]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/tree-ssa-uninit.c
Avoid -Wuninitialized false negatives with sanitization and VLAs.
[thirdparty/gcc.git] / gcc / tree-ssa-uninit.c
1 /* Predicate aware uninitialized variable warning.
2 Copyright (C) 2001-2021 Free Software Foundation, Inc.
3 Contributed by Xinliang David Li <davidxl@google.com>
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
11
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
20
21 #define INCLUDE_STRING
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "backend.h"
26 #include "tree.h"
27 #include "gimple.h"
28 #include "tree-pass.h"
29 #include "ssa.h"
30 #include "gimple-pretty-print.h"
31 #include "diagnostic-core.h"
32 #include "fold-const.h"
33 #include "gimple-iterator.h"
34 #include "tree-ssa.h"
35 #include "tree-cfg.h"
36 #include "cfghooks.h"
37 #include "attribs.h"
38 #include "builtins.h"
39 #include "calls.h"
40
41 /* This implements the pass that does predicate aware warning on uses of
42 possibly uninitialized variables. The pass first collects the set of
43 possibly uninitialized SSA names. For each such name, it walks through
44 all its immediate uses. For each immediate use, it rebuilds the condition
45 expression (the predicate) that guards the use. The predicate is then
46 examined to see if the variable is always defined under that same condition.
47 This is done either by pruning the unrealizable paths that lead to the
48 default definitions or by checking if the predicate set that guards the
49 defining paths is a superset of the use predicate. */
50
51 /* Max PHI args we can handle in pass. */
52 const unsigned max_phi_args = 32;
53
54 /* Pointer set of potentially undefined ssa names, i.e.,
55 ssa names that are defined by phi with operands that
56 are not defined or potentially undefined. */
57 static hash_set<tree> *possibly_undefined_names = 0;
58
59 /* Bit mask handling macros. */
60 #define MASK_SET_BIT(mask, pos) mask |= (1 << pos)
61 #define MASK_TEST_BIT(mask, pos) (mask & (1 << pos))
62 #define MASK_EMPTY(mask) (mask == 0)
63
64 /* Returns the first bit position (starting from LSB)
65 in mask that is non zero. Returns -1 if the mask is empty. */
66 static int
67 get_mask_first_set_bit (unsigned mask)
68 {
69 int pos = 0;
70 if (mask == 0)
71 return -1;
72
73 while ((mask & (1 << pos)) == 0)
74 pos++;
75
76 return pos;
77 }
78 #define MASK_FIRST_SET_BIT(mask) get_mask_first_set_bit (mask)
79
80 /* Return true if T, an SSA_NAME, has an undefined value. */
81 static bool
82 has_undefined_value_p (tree t)
83 {
84 return (ssa_undefined_value_p (t)
85 || (possibly_undefined_names
86 && possibly_undefined_names->contains (t)));
87 }
88
89 /* Like has_undefined_value_p, but don't return true if TREE_NO_WARNING
90 is set on SSA_NAME_VAR. */
91
92 static inline bool
93 uninit_undefined_value_p (tree t)
94 {
95 if (!has_undefined_value_p (t))
96 return false;
97 if (SSA_NAME_VAR (t) && TREE_NO_WARNING (SSA_NAME_VAR (t)))
98 return false;
99 return true;
100 }
101
102 /* Emit warnings for uninitialized variables. This is done in two passes.
103
104 The first pass notices real uses of SSA names with undefined values.
105 Such uses are unconditionally uninitialized, and we can be certain that
106 such a use is a mistake. This pass is run before most optimizations,
107 so that we catch as many as we can.
108
109 The second pass follows PHI nodes to find uses that are potentially
110 uninitialized. In this case we can't necessarily prove that the use
111 is really uninitialized. This pass is run after most optimizations,
112 so that we thread as many jumps and possible, and delete as much dead
113 code as possible, in order to reduce false positives. We also look
114 again for plain uninitialized variables, since optimization may have
115 changed conditionally uninitialized to unconditionally uninitialized. */
116
117 /* Emit a warning for EXPR based on variable VAR at the point in the
118 program T, an SSA_NAME, is used being uninitialized. The exact
119 warning text is in MSGID and DATA is the gimple stmt with info about
120 the location in source code. When DATA is a GIMPLE_PHI, PHIARG_IDX
121 gives which argument of the phi node to take the location from. WC
122 is the warning code. */
123
124 static void
125 warn_uninit (enum opt_code wc, tree t, tree expr, tree var,
126 const char *gmsgid, void *data, location_t phiarg_loc)
127 {
128 gimple *context = (gimple *) data;
129 location_t location, cfun_loc;
130 expanded_location xloc, floc;
131
132 /* Ignore COMPLEX_EXPR as initializing only a part of a complex
133 turns in a COMPLEX_EXPR with the not initialized part being
134 set to its previous (undefined) value. */
135 if (is_gimple_assign (context)
136 && gimple_assign_rhs_code (context) == COMPLEX_EXPR)
137 return;
138 if (!has_undefined_value_p (t))
139 return;
140
141 /* Anonymous SSA_NAMEs shouldn't be uninitialized, but ssa_undefined_value_p
142 can return true if the def stmt of anonymous SSA_NAME is COMPLEX_EXPR
143 created for conversion from scalar to complex. Use the underlying var of
144 the COMPLEX_EXPRs real part in that case. See PR71581. */
145 if (expr == NULL_TREE
146 && var == NULL_TREE
147 && SSA_NAME_VAR (t) == NULL_TREE
148 && is_gimple_assign (SSA_NAME_DEF_STMT (t))
149 && gimple_assign_rhs_code (SSA_NAME_DEF_STMT (t)) == COMPLEX_EXPR)
150 {
151 tree v = gimple_assign_rhs1 (SSA_NAME_DEF_STMT (t));
152 if (TREE_CODE (v) == SSA_NAME
153 && has_undefined_value_p (v)
154 && zerop (gimple_assign_rhs2 (SSA_NAME_DEF_STMT (t))))
155 {
156 expr = SSA_NAME_VAR (v);
157 var = expr;
158 }
159 }
160
161 if (expr == NULL_TREE)
162 return;
163
164 /* TREE_NO_WARNING either means we already warned, or the front end
165 wishes to suppress the warning. */
166 if ((context
167 && (gimple_no_warning_p (context)
168 || (gimple_assign_single_p (context)
169 && TREE_NO_WARNING (gimple_assign_rhs1 (context)))))
170 || TREE_NO_WARNING (expr))
171 return;
172
173 if (context != NULL && gimple_has_location (context))
174 location = gimple_location (context);
175 else if (phiarg_loc != UNKNOWN_LOCATION)
176 location = phiarg_loc;
177 else
178 location = DECL_SOURCE_LOCATION (var);
179 location = linemap_resolve_location (line_table, location,
180 LRK_SPELLING_LOCATION, NULL);
181 cfun_loc = DECL_SOURCE_LOCATION (cfun->decl);
182 xloc = expand_location (location);
183 floc = expand_location (cfun_loc);
184 auto_diagnostic_group d;
185 if (warning_at (location, wc, gmsgid, expr))
186 {
187 TREE_NO_WARNING (expr) = 1;
188
189 if (location == DECL_SOURCE_LOCATION (var))
190 return;
191 if (xloc.file != floc.file
192 || linemap_location_before_p (line_table, location, cfun_loc)
193 || linemap_location_before_p (line_table, cfun->function_end_locus,
194 location))
195 inform (DECL_SOURCE_LOCATION (var), "%qD was declared here", var);
196 }
197 }
198
199 struct check_defs_data
200 {
201 /* If we found any may-defs besides must-def clobbers. */
202 bool found_may_defs;
203 };
204
205 /* Callback for walk_aliased_vdefs. */
206
207 static bool
208 check_defs (ao_ref *ref, tree vdef, void *data_)
209 {
210 check_defs_data *data = (check_defs_data *)data_;
211 gimple *def_stmt = SSA_NAME_DEF_STMT (vdef);
212
213 /* The ASAN_MARK intrinsic doesn't modify the variable. */
214 if (is_gimple_call (def_stmt)
215 && gimple_call_internal_p (def_stmt, IFN_ASAN_MARK))
216 return false;
217
218 /* End of VLA scope is not a kill. */
219 if (gimple_call_builtin_p (def_stmt, BUILT_IN_STACK_RESTORE))
220 return false;
221
222 /* If this is a clobber then if it is not a kill walk past it. */
223 if (gimple_clobber_p (def_stmt))
224 {
225 if (stmt_kills_ref_p (def_stmt, ref))
226 return true;
227 return false;
228 }
229
230 /* Found a may-def on this path. */
231 data->found_may_defs = true;
232 return true;
233 }
234
235 /* Counters and limits controlling the the depth of analysis and
236 strictness of the warning. */
237 struct wlimits
238 {
239 /* Number of VDEFs encountered. */
240 unsigned int vdef_cnt;
241 /* Number of statements examined by walk_aliased_vdefs. */
242 unsigned int oracle_cnt;
243 /* Limit on the number of statements visited by walk_aliased_vdefs. */
244 unsigned limit;
245 /* Set when basic block with statement is executed unconditionally. */
246 bool always_executed;
247 /* Set to issue -Wmaybe-uninitialized. */
248 bool wmaybe_uninit;
249 };
250
251 /* Determine if REF references an uninitialized operand and diagnose
252 it if so. */
253
254 static tree
255 maybe_warn_operand (ao_ref &ref, gimple *stmt, tree lhs, tree rhs,
256 wlimits &wlims)
257 {
258 bool has_bit_insert = false;
259 use_operand_p luse_p;
260 imm_use_iterator liter;
261
262 if (TREE_NO_WARNING (rhs))
263 return NULL_TREE;
264
265 /* Do not warn if the base was marked so or this is a
266 hard register var. */
267 tree base = ao_ref_base (&ref);
268 if ((VAR_P (base)
269 && DECL_HARD_REGISTER (base))
270 || TREE_NO_WARNING (base))
271 return NULL_TREE;
272
273 /* Do not warn if the access is fully outside of the variable. */
274 poly_int64 decl_size;
275 if (DECL_P (base)
276 && ((known_size_p (ref.size)
277 && known_eq (ref.max_size, ref.size)
278 && known_le (ref.offset + ref.size, 0))
279 || (known_ge (ref.offset, 0)
280 && DECL_SIZE (base)
281 && poly_int_tree_p (DECL_SIZE (base), &decl_size)
282 && known_le (decl_size, ref.offset))))
283 return NULL_TREE;
284
285 /* Do not warn if the result of the access is then used for
286 a BIT_INSERT_EXPR. */
287 if (lhs && TREE_CODE (lhs) == SSA_NAME)
288 FOR_EACH_IMM_USE_FAST (luse_p, liter, lhs)
289 {
290 gimple *use_stmt = USE_STMT (luse_p);
291 /* BIT_INSERT_EXPR first operand should not be considered
292 a use for the purpose of uninit warnings. */
293 if (gassign *ass = dyn_cast <gassign *> (use_stmt))
294 {
295 if (gimple_assign_rhs_code (ass) == BIT_INSERT_EXPR
296 && luse_p->use == gimple_assign_rhs1_ptr (ass))
297 {
298 has_bit_insert = true;
299 break;
300 }
301 }
302 }
303
304 if (has_bit_insert)
305 return NULL_TREE;
306
307 /* Limit the walking to a constant number of stmts after
308 we overcommit quadratic behavior for small functions
309 and O(n) behavior. */
310 if (wlims.oracle_cnt > 128 * 128
311 && wlims.oracle_cnt > wlims.vdef_cnt * 2)
312 wlims.limit = 32;
313
314 check_defs_data data;
315 bool fentry_reached = false;
316 data.found_may_defs = false;
317 tree use = gimple_vuse (stmt);
318 if (!use)
319 return NULL_TREE;
320 int res = walk_aliased_vdefs (&ref, use,
321 check_defs, &data, NULL,
322 &fentry_reached, wlims.limit);
323 if (res == -1)
324 {
325 wlims.oracle_cnt += wlims.limit;
326 return NULL_TREE;
327 }
328
329 wlims.oracle_cnt += res;
330 if (data.found_may_defs)
331 return NULL_TREE;
332
333 bool found_alloc = false;
334
335 if (fentry_reached)
336 {
337 if (TREE_CODE (base) == MEM_REF)
338 base = TREE_OPERAND (base, 0);
339
340 /* Follow the chain of SSA_NAME assignments looking for an alloca
341 call (or VLA) or malloc/realloc, or for decls. If any is found
342 (and in the latter case, the operand is a local variable) issue
343 a warning. */
344 while (TREE_CODE (base) == SSA_NAME)
345 {
346 gimple *def_stmt = SSA_NAME_DEF_STMT (base);
347
348 if (is_gimple_call (def_stmt)
349 && gimple_call_builtin_p (def_stmt))
350 {
351 /* Detect uses of uninitialized alloca/VLAs. */
352 tree fndecl = gimple_call_fndecl (def_stmt);
353 const built_in_function fncode = DECL_FUNCTION_CODE (fndecl);
354 if (fncode == BUILT_IN_ALLOCA
355 || fncode == BUILT_IN_ALLOCA_WITH_ALIGN
356 || fncode == BUILT_IN_MALLOC)
357 found_alloc = true;
358 break;
359 }
360
361 if (!is_gimple_assign (def_stmt))
362 break;
363
364 tree_code code = gimple_assign_rhs_code (def_stmt);
365 if (code != ADDR_EXPR && code != POINTER_PLUS_EXPR)
366 break;
367
368 base = gimple_assign_rhs1 (def_stmt);
369 if (TREE_CODE (base) == ADDR_EXPR)
370 base = TREE_OPERAND (base, 0);
371
372 if (DECL_P (base)
373 || TREE_CODE (base) == COMPONENT_REF)
374 rhs = base;
375
376 if (TREE_CODE (base) == MEM_REF)
377 base = TREE_OPERAND (base, 0);
378
379 if (tree ba = get_base_address (base))
380 base = ba;
381 }
382
383 /* Replace the RHS expression with BASE so that it
384 refers to it in the diagnostic (instead of to
385 '<unknown>'). */
386 if (DECL_P (base)
387 && EXPR_P (rhs)
388 && TREE_CODE (rhs) != COMPONENT_REF)
389 rhs = base;
390 }
391
392 /* Do not warn if it can be initialized outside this function.
393 If we did not reach function entry then we found killing
394 clobbers on all paths to entry. */
395 if (!found_alloc
396 && fentry_reached
397 /* ??? We'd like to use ref_may_alias_global_p but that
398 excludes global readonly memory and thus we get bogus
399 warnings from p = cond ? "a" : "b" for example. */
400 && (!VAR_P (base)
401 || is_global_var (base)))
402 return NULL_TREE;
403
404 /* Strip the address-of expression from arrays passed to functions. */
405 if (TREE_CODE (rhs) == ADDR_EXPR)
406 rhs = TREE_OPERAND (rhs, 0);
407
408 /* Check again since RHS may have changed above. */
409 if (TREE_NO_WARNING (rhs))
410 return NULL_TREE;
411
412 /* Avoid warning about empty types such as structs with no members.
413 The first_field() test is important for C++ where the predicate
414 alone isn't always sufficient. */
415 tree rhstype = TREE_TYPE (rhs);
416 if (POINTER_TYPE_P (rhstype))
417 rhstype = TREE_TYPE (rhstype);
418 if (is_empty_type (rhstype))
419 return NULL_TREE;
420
421 bool warned = false;
422 /* We didn't find any may-defs so on all paths either
423 reached function entry or a killing clobber. */
424 location_t location
425 = linemap_resolve_location (line_table, gimple_location (stmt),
426 LRK_SPELLING_LOCATION, NULL);
427 if (wlims.always_executed)
428 {
429 if (warning_at (location, OPT_Wuninitialized,
430 "%G%qE is used uninitialized", stmt, rhs))
431 {
432 /* ??? This is only effective for decls as in
433 gcc.dg/uninit-B-O0.c. Avoid doing this for maybe-uninit
434 uses or accesses by functions as it may hide important
435 locations. */
436 if (lhs)
437 TREE_NO_WARNING (rhs) = 1;
438 warned = true;
439 }
440 }
441 else if (wlims.wmaybe_uninit)
442 warned = warning_at (location, OPT_Wmaybe_uninitialized,
443 "%G%qE may be used uninitialized", stmt, rhs);
444
445 return warned ? base : NULL_TREE;
446 }
447
448
449 /* Diagnose passing addresses of uninitialized objects to either const
450 pointer arguments to functions, or to functions declared with attribute
451 access implying read access to those objects. */
452
453 static void
454 maybe_warn_pass_by_reference (gcall *stmt, wlimits &wlims)
455 {
456 if (!wlims.wmaybe_uninit)
457 return;
458
459 unsigned nargs = gimple_call_num_args (stmt);
460 if (!nargs)
461 return;
462
463 tree fndecl = gimple_call_fndecl (stmt);
464 tree fntype = gimple_call_fntype (stmt);
465 if (!fntype)
466 return;
467
468 /* Const function do not read their arguments. */
469 if (gimple_call_flags (stmt) & ECF_CONST)
470 return;
471
472 const built_in_function fncode
473 = (fndecl && gimple_call_builtin_p (stmt, BUILT_IN_NORMAL)
474 ? DECL_FUNCTION_CODE (fndecl) : (built_in_function)BUILT_IN_LAST);
475
476 if (fncode == BUILT_IN_MEMCPY || fncode == BUILT_IN_MEMMOVE)
477 /* Avoid diagnosing calls to raw memory functions (this is overly
478 permissive; consider tightening it up). */
479 return;
480
481 /* Save the current warning setting and replace it either a "maybe"
482 when passing addresses of uninitialized variables to const-qualified
483 pointers or arguments declared with attribute read_write, or with
484 a "certain" when passing them to arguments declared with attribute
485 read_only. */
486 const bool save_always_executed = wlims.always_executed;
487
488 /* Initialize a map of attribute access specifications for arguments
489 to the function function call. */
490 rdwr_map rdwr_idx;
491 init_attr_rdwr_indices (&rdwr_idx, TYPE_ATTRIBUTES (fntype));
492
493 tree argtype;
494 unsigned argno = 0;
495 function_args_iterator it;
496
497 FOREACH_FUNCTION_ARGS (fntype, argtype, it)
498 {
499 ++argno;
500
501 if (!POINTER_TYPE_P (argtype))
502 continue;
503
504 tree access_size = NULL_TREE;
505 const attr_access* access = rdwr_idx.get (argno - 1);
506 if (access)
507 {
508 if (access->mode == access_none
509 || access->mode == access_write_only)
510 continue;
511
512 if (access->mode == access_deferred
513 && !TYPE_READONLY (TREE_TYPE (argtype)))
514 continue;
515
516 if (save_always_executed && access->mode == access_read_only)
517 /* Attribute read_only arguments imply read access. */
518 wlims.always_executed = true;
519 else
520 /* Attribute read_write arguments are documented as requiring
521 initialized objects but it's expected that aggregates may
522 be only partially initialized regardless. */
523 wlims.always_executed = false;
524
525 if (access->sizarg < nargs)
526 access_size = gimple_call_arg (stmt, access->sizarg);
527 }
528 else if (!TYPE_READONLY (TREE_TYPE (argtype)))
529 continue;
530 else if (save_always_executed && fncode != BUILT_IN_LAST)
531 /* Const-qualified arguments to built-ins imply read access. */
532 wlims.always_executed = true;
533 else
534 /* Const-qualified arguments to ordinary functions imply a likely
535 (but not definitive) read access. */
536 wlims.always_executed = false;
537
538 /* Ignore args we are not going to read from. */
539 if (gimple_call_arg_flags (stmt, argno - 1) & EAF_UNUSED)
540 continue;
541
542 tree arg = gimple_call_arg (stmt, argno - 1);
543
544 ao_ref ref;
545 ao_ref_init_from_ptr_and_size (&ref, arg, access_size);
546 tree argbase = maybe_warn_operand (ref, stmt, NULL_TREE, arg, wlims);
547 if (!argbase)
548 continue;
549
550 if (access && access->mode != access_deferred)
551 {
552 const char* const access_str =
553 TREE_STRING_POINTER (access->to_external_string ());
554
555 if (fndecl)
556 {
557 location_t loc = DECL_SOURCE_LOCATION (fndecl);
558 inform (loc, "in a call to %qD declared with "
559 "attribute %<%s%> here", fndecl, access_str);
560 }
561 else
562 {
563 /* Handle calls through function pointers. */
564 location_t loc = gimple_location (stmt);
565 inform (loc, "in a call to %qT declared with "
566 "attribute %<%s%>", fntype, access_str);
567 }
568 }
569 else
570 {
571 /* For a declaration with no relevant attribute access create
572 a dummy object and use the formatting function to avoid
573 having to complicate things here. */
574 attr_access ptr_access = { };
575 if (!access)
576 access = &ptr_access;
577 const std::string argtypestr = access->array_as_string (argtype);
578 if (fndecl)
579 {
580 location_t loc (DECL_SOURCE_LOCATION (fndecl));
581 inform (loc, "by argument %u of type %s to %qD "
582 "declared here",
583 argno, argtypestr.c_str (), fndecl);
584 }
585 else
586 {
587 /* Handle calls through function pointers. */
588 location_t loc (gimple_location (stmt));
589 inform (loc, "by argument %u of type %s to %qT",
590 argno, argtypestr.c_str (), fntype);
591 }
592 }
593
594 if (DECL_P (argbase))
595 {
596 location_t loc = DECL_SOURCE_LOCATION (argbase);
597 inform (loc, "%qD declared here", argbase);
598 }
599 }
600
601 wlims.always_executed = save_always_executed;
602 }
603
604
605 static unsigned int
606 warn_uninitialized_vars (bool wmaybe_uninit)
607 {
608 /* Counters and limits controlling the the depth of the warning. */
609 wlimits wlims = { };
610 wlims.wmaybe_uninit = wmaybe_uninit;
611
612 gimple_stmt_iterator gsi;
613 basic_block bb;
614 FOR_EACH_BB_FN (bb, cfun)
615 {
616 basic_block succ = single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun));
617 wlims.always_executed = dominated_by_p (CDI_POST_DOMINATORS, succ, bb);
618 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
619 {
620 gimple *stmt = gsi_stmt (gsi);
621 use_operand_p use_p;
622 ssa_op_iter op_iter;
623 tree use;
624
625 if (is_gimple_debug (stmt))
626 continue;
627
628 /* We only do data flow with SSA_NAMEs, so that's all we
629 can warn about. */
630 FOR_EACH_SSA_USE_OPERAND (use_p, stmt, op_iter, SSA_OP_USE)
631 {
632 /* BIT_INSERT_EXPR first operand should not be considered
633 a use for the purpose of uninit warnings. */
634 if (gassign *ass = dyn_cast <gassign *> (stmt))
635 {
636 if (gimple_assign_rhs_code (ass) == BIT_INSERT_EXPR
637 && use_p->use == gimple_assign_rhs1_ptr (ass))
638 continue;
639 }
640 use = USE_FROM_PTR (use_p);
641 if (wlims.always_executed)
642 warn_uninit (OPT_Wuninitialized, use, SSA_NAME_VAR (use),
643 SSA_NAME_VAR (use),
644 "%qD is used uninitialized", stmt,
645 UNKNOWN_LOCATION);
646 else if (wmaybe_uninit)
647 warn_uninit (OPT_Wmaybe_uninitialized, use, SSA_NAME_VAR (use),
648 SSA_NAME_VAR (use),
649 "%qD may be used uninitialized",
650 stmt, UNKNOWN_LOCATION);
651 }
652
653 /* For limiting the alias walk below we count all
654 vdefs in the function. */
655 if (gimple_vdef (stmt))
656 wlims.vdef_cnt++;
657
658 if (gcall *call = dyn_cast <gcall *> (stmt))
659 maybe_warn_pass_by_reference (call, wlims);
660 else if (gimple_assign_load_p (stmt)
661 && gimple_has_location (stmt))
662 {
663 tree rhs = gimple_assign_rhs1 (stmt);
664 tree lhs = gimple_assign_lhs (stmt);
665
666 ao_ref ref;
667 ao_ref_init (&ref, rhs);
668 tree var = maybe_warn_operand (ref, stmt, lhs, rhs, wlims);
669 if (!var)
670 continue;
671
672 if (DECL_P (var))
673 {
674 location_t loc = DECL_SOURCE_LOCATION (var);
675 inform (loc, "%qD declared here", var);
676 }
677 }
678 }
679 }
680
681 return 0;
682 }
683
684 /* Checks if the operand OPND of PHI is defined by
685 another phi with one operand defined by this PHI,
686 but the rest operands are all defined. If yes,
687 returns true to skip this operand as being
688 redundant. Can be enhanced to be more general. */
689
690 static bool
691 can_skip_redundant_opnd (tree opnd, gimple *phi)
692 {
693 gimple *op_def;
694 tree phi_def;
695 int i, n;
696
697 phi_def = gimple_phi_result (phi);
698 op_def = SSA_NAME_DEF_STMT (opnd);
699 if (gimple_code (op_def) != GIMPLE_PHI)
700 return false;
701 n = gimple_phi_num_args (op_def);
702 for (i = 0; i < n; ++i)
703 {
704 tree op = gimple_phi_arg_def (op_def, i);
705 if (TREE_CODE (op) != SSA_NAME)
706 continue;
707 if (op != phi_def && uninit_undefined_value_p (op))
708 return false;
709 }
710
711 return true;
712 }
713
714 /* Returns a bit mask holding the positions of arguments in PHI
715 that have empty (or possibly empty) definitions. */
716
717 static unsigned
718 compute_uninit_opnds_pos (gphi *phi)
719 {
720 size_t i, n;
721 unsigned uninit_opnds = 0;
722
723 n = gimple_phi_num_args (phi);
724 /* Bail out for phi with too many args. */
725 if (n > max_phi_args)
726 return 0;
727
728 for (i = 0; i < n; ++i)
729 {
730 tree op = gimple_phi_arg_def (phi, i);
731 if (TREE_CODE (op) == SSA_NAME
732 && uninit_undefined_value_p (op)
733 && !can_skip_redundant_opnd (op, phi))
734 {
735 if (cfun->has_nonlocal_label || cfun->calls_setjmp)
736 {
737 /* Ignore SSA_NAMEs that appear on abnormal edges
738 somewhere. */
739 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
740 continue;
741 }
742 MASK_SET_BIT (uninit_opnds, i);
743 }
744 }
745 return uninit_opnds;
746 }
747
748 /* Find the immediate postdominator PDOM of the specified
749 basic block BLOCK. */
750
751 static inline basic_block
752 find_pdom (basic_block block)
753 {
754 if (block == EXIT_BLOCK_PTR_FOR_FN (cfun))
755 return EXIT_BLOCK_PTR_FOR_FN (cfun);
756 else
757 {
758 basic_block bb = get_immediate_dominator (CDI_POST_DOMINATORS, block);
759 if (!bb)
760 return EXIT_BLOCK_PTR_FOR_FN (cfun);
761 return bb;
762 }
763 }
764
765 /* Find the immediate DOM of the specified basic block BLOCK. */
766
767 static inline basic_block
768 find_dom (basic_block block)
769 {
770 if (block == ENTRY_BLOCK_PTR_FOR_FN (cfun))
771 return ENTRY_BLOCK_PTR_FOR_FN (cfun);
772 else
773 {
774 basic_block bb = get_immediate_dominator (CDI_DOMINATORS, block);
775 if (!bb)
776 return ENTRY_BLOCK_PTR_FOR_FN (cfun);
777 return bb;
778 }
779 }
780
781 /* Returns true if BB1 is postdominating BB2 and BB1 is
782 not a loop exit bb. The loop exit bb check is simple and does
783 not cover all cases. */
784
785 static bool
786 is_non_loop_exit_postdominating (basic_block bb1, basic_block bb2)
787 {
788 if (!dominated_by_p (CDI_POST_DOMINATORS, bb2, bb1))
789 return false;
790
791 if (single_pred_p (bb1) && !single_succ_p (bb2))
792 return false;
793
794 return true;
795 }
796
797 /* Find the closest postdominator of a specified BB, which is control
798 equivalent to BB. */
799
800 static inline basic_block
801 find_control_equiv_block (basic_block bb)
802 {
803 basic_block pdom;
804
805 pdom = find_pdom (bb);
806
807 /* Skip the postdominating bb that is also loop exit. */
808 if (!is_non_loop_exit_postdominating (pdom, bb))
809 return NULL;
810
811 if (dominated_by_p (CDI_DOMINATORS, pdom, bb))
812 return pdom;
813
814 return NULL;
815 }
816
817 #define MAX_NUM_CHAINS 8
818 #define MAX_CHAIN_LEN 5
819 #define MAX_POSTDOM_CHECK 8
820 #define MAX_SWITCH_CASES 40
821
822 /* Computes the control dependence chains (paths of edges)
823 for DEP_BB up to the dominating basic block BB (the head node of a
824 chain should be dominated by it). CD_CHAINS is pointer to an
825 array holding the result chains. CUR_CD_CHAIN is the current
826 chain being computed. *NUM_CHAINS is total number of chains. The
827 function returns true if the information is successfully computed,
828 return false if there is no control dependence or not computed. */
829
830 static bool
831 compute_control_dep_chain (basic_block bb, basic_block dep_bb,
832 vec<edge> *cd_chains,
833 size_t *num_chains,
834 vec<edge> *cur_cd_chain,
835 int *num_calls)
836 {
837 edge_iterator ei;
838 edge e;
839 size_t i;
840 bool found_cd_chain = false;
841 size_t cur_chain_len = 0;
842
843 if (*num_calls > param_uninit_control_dep_attempts)
844 return false;
845 ++*num_calls;
846
847 /* Could use a set instead. */
848 cur_chain_len = cur_cd_chain->length ();
849 if (cur_chain_len > MAX_CHAIN_LEN)
850 return false;
851
852 for (i = 0; i < cur_chain_len; i++)
853 {
854 edge e = (*cur_cd_chain)[i];
855 /* Cycle detected. */
856 if (e->src == bb)
857 return false;
858 }
859
860 FOR_EACH_EDGE (e, ei, bb->succs)
861 {
862 basic_block cd_bb;
863 int post_dom_check = 0;
864 if (e->flags & (EDGE_FAKE | EDGE_ABNORMAL))
865 continue;
866
867 cd_bb = e->dest;
868 cur_cd_chain->safe_push (e);
869 while (!is_non_loop_exit_postdominating (cd_bb, bb))
870 {
871 if (cd_bb == dep_bb)
872 {
873 /* Found a direct control dependence. */
874 if (*num_chains < MAX_NUM_CHAINS)
875 {
876 cd_chains[*num_chains] = cur_cd_chain->copy ();
877 (*num_chains)++;
878 }
879 found_cd_chain = true;
880 /* Check path from next edge. */
881 break;
882 }
883
884 /* Now check if DEP_BB is indirectly control dependent on BB. */
885 if (compute_control_dep_chain (cd_bb, dep_bb, cd_chains, num_chains,
886 cur_cd_chain, num_calls))
887 {
888 found_cd_chain = true;
889 break;
890 }
891
892 cd_bb = find_pdom (cd_bb);
893 post_dom_check++;
894 if (cd_bb == EXIT_BLOCK_PTR_FOR_FN (cfun)
895 || post_dom_check > MAX_POSTDOM_CHECK)
896 break;
897 }
898 cur_cd_chain->pop ();
899 gcc_assert (cur_cd_chain->length () == cur_chain_len);
900 }
901 gcc_assert (cur_cd_chain->length () == cur_chain_len);
902
903 return found_cd_chain;
904 }
905
906 /* The type to represent a simple predicate. */
907
908 struct pred_info
909 {
910 tree pred_lhs;
911 tree pred_rhs;
912 enum tree_code cond_code;
913 bool invert;
914 };
915
916 /* The type to represent a sequence of predicates grouped
917 with .AND. operation. */
918
919 typedef vec<pred_info, va_heap, vl_ptr> pred_chain;
920
921 /* The type to represent a sequence of pred_chains grouped
922 with .OR. operation. */
923
924 typedef vec<pred_chain, va_heap, vl_ptr> pred_chain_union;
925
926 /* Converts the chains of control dependence edges into a set of
927 predicates. A control dependence chain is represented by a vector
928 edges. DEP_CHAINS points to an array of dependence chains.
929 NUM_CHAINS is the size of the chain array. One edge in a dependence
930 chain is mapped to predicate expression represented by pred_info
931 type. One dependence chain is converted to a composite predicate that
932 is the result of AND operation of pred_info mapped to each edge.
933 A composite predicate is presented by a vector of pred_info. On
934 return, *PREDS points to the resulting array of composite predicates.
935 *NUM_PREDS is the number of composite predictes. */
936
937 static bool
938 convert_control_dep_chain_into_preds (vec<edge> *dep_chains,
939 size_t num_chains,
940 pred_chain_union *preds)
941 {
942 bool has_valid_pred = false;
943 size_t i, j;
944 if (num_chains == 0 || num_chains >= MAX_NUM_CHAINS)
945 return false;
946
947 /* Now convert the control dep chain into a set
948 of predicates. */
949 preds->reserve (num_chains);
950
951 for (i = 0; i < num_chains; i++)
952 {
953 vec<edge> one_cd_chain = dep_chains[i];
954
955 has_valid_pred = false;
956 pred_chain t_chain = vNULL;
957 for (j = 0; j < one_cd_chain.length (); j++)
958 {
959 gimple *cond_stmt;
960 gimple_stmt_iterator gsi;
961 basic_block guard_bb;
962 pred_info one_pred;
963 edge e;
964
965 e = one_cd_chain[j];
966 guard_bb = e->src;
967 gsi = gsi_last_bb (guard_bb);
968 /* Ignore empty forwarder blocks. */
969 if (empty_block_p (guard_bb) && single_succ_p (guard_bb))
970 continue;
971 /* An empty basic block here is likely a PHI, and is not one
972 of the cases we handle below. */
973 if (gsi_end_p (gsi))
974 {
975 has_valid_pred = false;
976 break;
977 }
978 cond_stmt = gsi_stmt (gsi);
979 if (is_gimple_call (cond_stmt) && EDGE_COUNT (e->src->succs) >= 2)
980 /* Ignore EH edge. Can add assertion on the other edge's flag. */
981 continue;
982 /* Skip if there is essentially one succesor. */
983 if (EDGE_COUNT (e->src->succs) == 2)
984 {
985 edge e1;
986 edge_iterator ei1;
987 bool skip = false;
988
989 FOR_EACH_EDGE (e1, ei1, e->src->succs)
990 {
991 if (EDGE_COUNT (e1->dest->succs) == 0)
992 {
993 skip = true;
994 break;
995 }
996 }
997 if (skip)
998 continue;
999 }
1000 if (gimple_code (cond_stmt) == GIMPLE_COND)
1001 {
1002 one_pred.pred_lhs = gimple_cond_lhs (cond_stmt);
1003 one_pred.pred_rhs = gimple_cond_rhs (cond_stmt);
1004 one_pred.cond_code = gimple_cond_code (cond_stmt);
1005 one_pred.invert = !!(e->flags & EDGE_FALSE_VALUE);
1006 t_chain.safe_push (one_pred);
1007 has_valid_pred = true;
1008 }
1009 else if (gswitch *gs = dyn_cast<gswitch *> (cond_stmt))
1010 {
1011 /* Avoid quadratic behavior. */
1012 if (gimple_switch_num_labels (gs) > MAX_SWITCH_CASES)
1013 {
1014 has_valid_pred = false;
1015 break;
1016 }
1017 /* Find the case label. */
1018 tree l = NULL_TREE;
1019 unsigned idx;
1020 for (idx = 0; idx < gimple_switch_num_labels (gs); ++idx)
1021 {
1022 tree tl = gimple_switch_label (gs, idx);
1023 if (e->dest == label_to_block (cfun, CASE_LABEL (tl)))
1024 {
1025 if (!l)
1026 l = tl;
1027 else
1028 {
1029 l = NULL_TREE;
1030 break;
1031 }
1032 }
1033 }
1034 /* If more than one label reaches this block or the case
1035 label doesn't have a single value (like the default one)
1036 fail. */
1037 if (!l
1038 || !CASE_LOW (l)
1039 || (CASE_HIGH (l)
1040 && !operand_equal_p (CASE_LOW (l), CASE_HIGH (l), 0)))
1041 {
1042 has_valid_pred = false;
1043 break;
1044 }
1045 one_pred.pred_lhs = gimple_switch_index (gs);
1046 one_pred.pred_rhs = CASE_LOW (l);
1047 one_pred.cond_code = EQ_EXPR;
1048 one_pred.invert = false;
1049 t_chain.safe_push (one_pred);
1050 has_valid_pred = true;
1051 }
1052 else
1053 {
1054 has_valid_pred = false;
1055 break;
1056 }
1057 }
1058
1059 if (!has_valid_pred)
1060 break;
1061 else
1062 preds->safe_push (t_chain);
1063 }
1064 return has_valid_pred;
1065 }
1066
1067 /* Computes all control dependence chains for USE_BB. The control
1068 dependence chains are then converted to an array of composite
1069 predicates pointed to by PREDS. PHI_BB is the basic block of
1070 the phi whose result is used in USE_BB. */
1071
1072 static bool
1073 find_predicates (pred_chain_union *preds,
1074 basic_block phi_bb,
1075 basic_block use_bb)
1076 {
1077 size_t num_chains = 0, i;
1078 int num_calls = 0;
1079 vec<edge> dep_chains[MAX_NUM_CHAINS];
1080 auto_vec<edge, MAX_CHAIN_LEN + 1> cur_chain;
1081 bool has_valid_pred = false;
1082 basic_block cd_root = 0;
1083
1084 /* First find the closest bb that is control equivalent to PHI_BB
1085 that also dominates USE_BB. */
1086 cd_root = phi_bb;
1087 while (dominated_by_p (CDI_DOMINATORS, use_bb, cd_root))
1088 {
1089 basic_block ctrl_eq_bb = find_control_equiv_block (cd_root);
1090 if (ctrl_eq_bb && dominated_by_p (CDI_DOMINATORS, use_bb, ctrl_eq_bb))
1091 cd_root = ctrl_eq_bb;
1092 else
1093 break;
1094 }
1095
1096 compute_control_dep_chain (cd_root, use_bb, dep_chains, &num_chains,
1097 &cur_chain, &num_calls);
1098
1099 has_valid_pred
1100 = convert_control_dep_chain_into_preds (dep_chains, num_chains, preds);
1101 for (i = 0; i < num_chains; i++)
1102 dep_chains[i].release ();
1103 return has_valid_pred;
1104 }
1105
1106 /* Computes the set of incoming edges of PHI that have non empty
1107 definitions of a phi chain. The collection will be done
1108 recursively on operands that are defined by phis. CD_ROOT
1109 is the control dependence root. *EDGES holds the result, and
1110 VISITED_PHIS is a pointer set for detecting cycles. */
1111
1112 static void
1113 collect_phi_def_edges (gphi *phi, basic_block cd_root,
1114 auto_vec<edge> *edges,
1115 hash_set<gimple *> *visited_phis)
1116 {
1117 size_t i, n;
1118 edge opnd_edge;
1119 tree opnd;
1120
1121 if (visited_phis->add (phi))
1122 return;
1123
1124 n = gimple_phi_num_args (phi);
1125 for (i = 0; i < n; i++)
1126 {
1127 opnd_edge = gimple_phi_arg_edge (phi, i);
1128 opnd = gimple_phi_arg_def (phi, i);
1129
1130 if (TREE_CODE (opnd) != SSA_NAME)
1131 {
1132 if (dump_file && (dump_flags & TDF_DETAILS))
1133 {
1134 fprintf (dump_file, "\n[CHECK] Found def edge %d in ", (int) i);
1135 print_gimple_stmt (dump_file, phi, 0);
1136 }
1137 edges->safe_push (opnd_edge);
1138 }
1139 else
1140 {
1141 gimple *def = SSA_NAME_DEF_STMT (opnd);
1142
1143 if (gimple_code (def) == GIMPLE_PHI
1144 && dominated_by_p (CDI_DOMINATORS, gimple_bb (def), cd_root))
1145 collect_phi_def_edges (as_a<gphi *> (def), cd_root, edges,
1146 visited_phis);
1147 else if (!uninit_undefined_value_p (opnd))
1148 {
1149 if (dump_file && (dump_flags & TDF_DETAILS))
1150 {
1151 fprintf (dump_file, "\n[CHECK] Found def edge %d in ",
1152 (int) i);
1153 print_gimple_stmt (dump_file, phi, 0);
1154 }
1155 edges->safe_push (opnd_edge);
1156 }
1157 }
1158 }
1159 }
1160
1161 /* For each use edge of PHI, computes all control dependence chains.
1162 The control dependence chains are then converted to an array of
1163 composite predicates pointed to by PREDS. */
1164
1165 static bool
1166 find_def_preds (pred_chain_union *preds, gphi *phi)
1167 {
1168 size_t num_chains = 0, i, n;
1169 vec<edge> dep_chains[MAX_NUM_CHAINS];
1170 auto_vec<edge, MAX_CHAIN_LEN + 1> cur_chain;
1171 auto_vec<edge> def_edges;
1172 bool has_valid_pred = false;
1173 basic_block phi_bb, cd_root = 0;
1174
1175 phi_bb = gimple_bb (phi);
1176 /* First find the closest dominating bb to be
1177 the control dependence root. */
1178 cd_root = find_dom (phi_bb);
1179 if (!cd_root)
1180 return false;
1181
1182 hash_set<gimple *> visited_phis;
1183 collect_phi_def_edges (phi, cd_root, &def_edges, &visited_phis);
1184
1185 n = def_edges.length ();
1186 if (n == 0)
1187 return false;
1188
1189 for (i = 0; i < n; i++)
1190 {
1191 size_t prev_nc, j;
1192 int num_calls = 0;
1193 edge opnd_edge;
1194
1195 opnd_edge = def_edges[i];
1196 prev_nc = num_chains;
1197 compute_control_dep_chain (cd_root, opnd_edge->src, dep_chains,
1198 &num_chains, &cur_chain, &num_calls);
1199
1200 /* Now update the newly added chains with
1201 the phi operand edge: */
1202 if (EDGE_COUNT (opnd_edge->src->succs) > 1)
1203 {
1204 if (prev_nc == num_chains && num_chains < MAX_NUM_CHAINS)
1205 dep_chains[num_chains++] = vNULL;
1206 for (j = prev_nc; j < num_chains; j++)
1207 dep_chains[j].safe_push (opnd_edge);
1208 }
1209 }
1210
1211 has_valid_pred
1212 = convert_control_dep_chain_into_preds (dep_chains, num_chains, preds);
1213 for (i = 0; i < num_chains; i++)
1214 dep_chains[i].release ();
1215 return has_valid_pred;
1216 }
1217
1218 /* Dump a pred_info. */
1219
1220 static void
1221 dump_pred_info (pred_info one_pred)
1222 {
1223 if (one_pred.invert)
1224 fprintf (dump_file, " (.NOT.) ");
1225 print_generic_expr (dump_file, one_pred.pred_lhs);
1226 fprintf (dump_file, " %s ", op_symbol_code (one_pred.cond_code));
1227 print_generic_expr (dump_file, one_pred.pred_rhs);
1228 }
1229
1230 /* Dump a pred_chain. */
1231
1232 static void
1233 dump_pred_chain (pred_chain one_pred_chain)
1234 {
1235 size_t np = one_pred_chain.length ();
1236 for (size_t j = 0; j < np; j++)
1237 {
1238 dump_pred_info (one_pred_chain[j]);
1239 if (j < np - 1)
1240 fprintf (dump_file, " (.AND.) ");
1241 else
1242 fprintf (dump_file, "\n");
1243 }
1244 }
1245
1246 /* Dumps the predicates (PREDS) for USESTMT. */
1247
1248 static void
1249 dump_predicates (gimple *usestmt, pred_chain_union preds, const char *msg)
1250 {
1251 fprintf (dump_file, "%s", msg);
1252 if (usestmt)
1253 {
1254 print_gimple_stmt (dump_file, usestmt, 0);
1255 fprintf (dump_file, "is guarded by :\n\n");
1256 }
1257 size_t num_preds = preds.length ();
1258 for (size_t i = 0; i < num_preds; i++)
1259 {
1260 dump_pred_chain (preds[i]);
1261 if (i < num_preds - 1)
1262 fprintf (dump_file, "(.OR.)\n");
1263 else
1264 fprintf (dump_file, "\n\n");
1265 }
1266 }
1267
1268 /* Destroys the predicate set *PREDS. */
1269
1270 static void
1271 destroy_predicate_vecs (pred_chain_union *preds)
1272 {
1273 size_t i;
1274
1275 size_t n = preds->length ();
1276 for (i = 0; i < n; i++)
1277 (*preds)[i].release ();
1278 preds->release ();
1279 }
1280
1281 /* Computes the 'normalized' conditional code with operand
1282 swapping and condition inversion. */
1283
1284 static enum tree_code
1285 get_cmp_code (enum tree_code orig_cmp_code, bool swap_cond, bool invert)
1286 {
1287 enum tree_code tc = orig_cmp_code;
1288
1289 if (swap_cond)
1290 tc = swap_tree_comparison (orig_cmp_code);
1291 if (invert)
1292 tc = invert_tree_comparison (tc, false);
1293
1294 switch (tc)
1295 {
1296 case LT_EXPR:
1297 case LE_EXPR:
1298 case GT_EXPR:
1299 case GE_EXPR:
1300 case EQ_EXPR:
1301 case NE_EXPR:
1302 break;
1303 default:
1304 return ERROR_MARK;
1305 }
1306 return tc;
1307 }
1308
1309 /* Returns whether VAL CMPC BOUNDARY is true. */
1310
1311 static bool
1312 is_value_included_in (tree val, tree boundary, enum tree_code cmpc)
1313 {
1314 bool inverted = false;
1315 bool result;
1316
1317 /* Only handle integer constant here. */
1318 if (TREE_CODE (val) != INTEGER_CST || TREE_CODE (boundary) != INTEGER_CST)
1319 return true;
1320
1321 if (cmpc == GE_EXPR || cmpc == GT_EXPR || cmpc == NE_EXPR)
1322 {
1323 cmpc = invert_tree_comparison (cmpc, false);
1324 inverted = true;
1325 }
1326
1327 if (cmpc == EQ_EXPR)
1328 result = tree_int_cst_equal (val, boundary);
1329 else if (cmpc == LT_EXPR)
1330 result = tree_int_cst_lt (val, boundary);
1331 else
1332 {
1333 gcc_assert (cmpc == LE_EXPR);
1334 result = tree_int_cst_le (val, boundary);
1335 }
1336
1337 if (inverted)
1338 result ^= 1;
1339
1340 return result;
1341 }
1342
1343 /* Returns whether VAL satisfies (x CMPC BOUNDARY) predicate. CMPC can be
1344 either one of the range comparison codes ({GE,LT,EQ,NE}_EXPR and the like),
1345 or BIT_AND_EXPR. EXACT_P is only meaningful for the latter. It modifies the
1346 question from whether VAL & BOUNDARY != 0 to whether VAL & BOUNDARY == VAL.
1347 For other values of CMPC, EXACT_P is ignored. */
1348
1349 static bool
1350 value_sat_pred_p (tree val, tree boundary, enum tree_code cmpc,
1351 bool exact_p = false)
1352 {
1353 if (cmpc != BIT_AND_EXPR)
1354 return is_value_included_in (val, boundary, cmpc);
1355
1356 wide_int andw = wi::to_wide (val) & wi::to_wide (boundary);
1357 if (exact_p)
1358 return andw == wi::to_wide (val);
1359 else
1360 return andw.to_uhwi ();
1361 }
1362
1363 /* Returns true if PRED is common among all the predicate
1364 chains (PREDS) (and therefore can be factored out). */
1365
1366 static bool
1367 find_matching_predicate_in_rest_chains (pred_info pred, pred_chain_union preds)
1368 {
1369 size_t i, j, n;
1370
1371 /* Trival case. */
1372 if (preds.length () == 1)
1373 return true;
1374
1375 for (i = 1; i < preds.length (); i++)
1376 {
1377 bool found = false;
1378 pred_chain one_chain = preds[i];
1379 n = one_chain.length ();
1380 for (j = 0; j < n; j++)
1381 {
1382 pred_info pred2 = one_chain[j];
1383 /* Can relax the condition comparison to not
1384 use address comparison. However, the most common
1385 case is that multiple control dependent paths share
1386 a common path prefix, so address comparison should
1387 be ok. */
1388
1389 if (operand_equal_p (pred2.pred_lhs, pred.pred_lhs, 0)
1390 && operand_equal_p (pred2.pred_rhs, pred.pred_rhs, 0)
1391 && pred2.invert == pred.invert)
1392 {
1393 found = true;
1394 break;
1395 }
1396 }
1397 if (!found)
1398 return false;
1399 }
1400 return true;
1401 }
1402
1403 /* Forward declaration. */
1404 static bool is_use_properly_guarded (gimple *use_stmt,
1405 basic_block use_bb,
1406 gphi *phi,
1407 unsigned uninit_opnds,
1408 pred_chain_union *def_preds,
1409 hash_set<gphi *> *visited_phis);
1410
1411 /* Returns true if all uninitialized opnds are pruned. Returns false
1412 otherwise. PHI is the phi node with uninitialized operands,
1413 UNINIT_OPNDS is the bitmap of the uninitialize operand positions,
1414 FLAG_DEF is the statement defining the flag guarding the use of the
1415 PHI output, BOUNDARY_CST is the const value used in the predicate
1416 associated with the flag, CMP_CODE is the comparison code used in
1417 the predicate, VISITED_PHIS is the pointer set of phis visited, and
1418 VISITED_FLAG_PHIS is the pointer to the pointer set of flag definitions
1419 that are also phis.
1420
1421 Example scenario:
1422
1423 BB1:
1424 flag_1 = phi <0, 1> // (1)
1425 var_1 = phi <undef, some_val>
1426
1427
1428 BB2:
1429 flag_2 = phi <0, flag_1, flag_1> // (2)
1430 var_2 = phi <undef, var_1, var_1>
1431 if (flag_2 == 1)
1432 goto BB3;
1433
1434 BB3:
1435 use of var_2 // (3)
1436
1437 Because some flag arg in (1) is not constant, if we do not look into the
1438 flag phis recursively, it is conservatively treated as unknown and var_1
1439 is thought to be flowed into use at (3). Since var_1 is potentially
1440 uninitialized a false warning will be emitted.
1441 Checking recursively into (1), the compiler can find out that only some_val
1442 (which is defined) can flow into (3) which is OK. */
1443
1444 static bool
1445 prune_uninit_phi_opnds (gphi *phi, unsigned uninit_opnds, gphi *flag_def,
1446 tree boundary_cst, enum tree_code cmp_code,
1447 hash_set<gphi *> *visited_phis,
1448 bitmap *visited_flag_phis)
1449 {
1450 unsigned i;
1451
1452 for (i = 0; i < MIN (max_phi_args, gimple_phi_num_args (flag_def)); i++)
1453 {
1454 tree flag_arg;
1455
1456 if (!MASK_TEST_BIT (uninit_opnds, i))
1457 continue;
1458
1459 flag_arg = gimple_phi_arg_def (flag_def, i);
1460 if (!is_gimple_constant (flag_arg))
1461 {
1462 gphi *flag_arg_def, *phi_arg_def;
1463 tree phi_arg;
1464 unsigned uninit_opnds_arg_phi;
1465
1466 if (TREE_CODE (flag_arg) != SSA_NAME)
1467 return false;
1468 flag_arg_def = dyn_cast<gphi *> (SSA_NAME_DEF_STMT (flag_arg));
1469 if (!flag_arg_def)
1470 return false;
1471
1472 phi_arg = gimple_phi_arg_def (phi, i);
1473 if (TREE_CODE (phi_arg) != SSA_NAME)
1474 return false;
1475
1476 phi_arg_def = dyn_cast<gphi *> (SSA_NAME_DEF_STMT (phi_arg));
1477 if (!phi_arg_def)
1478 return false;
1479
1480 if (gimple_bb (phi_arg_def) != gimple_bb (flag_arg_def))
1481 return false;
1482
1483 if (!*visited_flag_phis)
1484 *visited_flag_phis = BITMAP_ALLOC (NULL);
1485
1486 tree phi_result = gimple_phi_result (flag_arg_def);
1487 if (bitmap_bit_p (*visited_flag_phis, SSA_NAME_VERSION (phi_result)))
1488 return false;
1489
1490 bitmap_set_bit (*visited_flag_phis,
1491 SSA_NAME_VERSION (gimple_phi_result (flag_arg_def)));
1492
1493 /* Now recursively prune the uninitialized phi args. */
1494 uninit_opnds_arg_phi = compute_uninit_opnds_pos (phi_arg_def);
1495 if (!prune_uninit_phi_opnds
1496 (phi_arg_def, uninit_opnds_arg_phi, flag_arg_def, boundary_cst,
1497 cmp_code, visited_phis, visited_flag_phis))
1498 return false;
1499
1500 phi_result = gimple_phi_result (flag_arg_def);
1501 bitmap_clear_bit (*visited_flag_phis, SSA_NAME_VERSION (phi_result));
1502 continue;
1503 }
1504
1505 /* Now check if the constant is in the guarded range. */
1506 if (is_value_included_in (flag_arg, boundary_cst, cmp_code))
1507 {
1508 tree opnd;
1509 gimple *opnd_def;
1510
1511 /* Now that we know that this undefined edge is not
1512 pruned. If the operand is defined by another phi,
1513 we can further prune the incoming edges of that
1514 phi by checking the predicates of this operands. */
1515
1516 opnd = gimple_phi_arg_def (phi, i);
1517 opnd_def = SSA_NAME_DEF_STMT (opnd);
1518 if (gphi *opnd_def_phi = dyn_cast <gphi *> (opnd_def))
1519 {
1520 edge opnd_edge;
1521 unsigned uninit_opnds2 = compute_uninit_opnds_pos (opnd_def_phi);
1522 if (!MASK_EMPTY (uninit_opnds2))
1523 {
1524 pred_chain_union def_preds = vNULL;
1525 bool ok;
1526 opnd_edge = gimple_phi_arg_edge (phi, i);
1527 ok = is_use_properly_guarded (phi,
1528 opnd_edge->src,
1529 opnd_def_phi,
1530 uninit_opnds2,
1531 &def_preds,
1532 visited_phis);
1533 destroy_predicate_vecs (&def_preds);
1534 if (!ok)
1535 return false;
1536 }
1537 }
1538 else
1539 return false;
1540 }
1541 }
1542
1543 return true;
1544 }
1545
1546 /* A helper function finds predicate which will be examined against uninit
1547 paths. If there is no "flag_var cmp const" form predicate, the function
1548 tries to find predicate of form like "flag_var cmp flag_var" with value
1549 range info. PHI is the phi node whose incoming (undefined) paths need to
1550 be examined. On success, the function returns the comparsion code, sets
1551 defintion gimple of the flag_var to FLAG_DEF, sets boundary_cst to
1552 BOUNDARY_CST. On fail, the function returns ERROR_MARK. */
1553
1554 static enum tree_code
1555 find_var_cmp_const (pred_chain_union preds, gphi *phi, gimple **flag_def,
1556 tree *boundary_cst)
1557 {
1558 enum tree_code vrinfo_code = ERROR_MARK, code;
1559 gimple *vrinfo_def = NULL;
1560 tree vrinfo_cst = NULL, cond_lhs, cond_rhs;
1561
1562 gcc_assert (preds.length () > 0);
1563 pred_chain the_pred_chain = preds[0];
1564 for (unsigned i = 0; i < the_pred_chain.length (); i++)
1565 {
1566 bool use_vrinfo_p = false;
1567 pred_info the_pred = the_pred_chain[i];
1568 cond_lhs = the_pred.pred_lhs;
1569 cond_rhs = the_pred.pred_rhs;
1570 if (cond_lhs == NULL_TREE || cond_rhs == NULL_TREE)
1571 continue;
1572
1573 code = get_cmp_code (the_pred.cond_code, false, the_pred.invert);
1574 if (code == ERROR_MARK)
1575 continue;
1576
1577 if (TREE_CODE (cond_lhs) == SSA_NAME && is_gimple_constant (cond_rhs))
1578 ;
1579 else if (TREE_CODE (cond_rhs) == SSA_NAME
1580 && is_gimple_constant (cond_lhs))
1581 {
1582 std::swap (cond_lhs, cond_rhs);
1583 if ((code = get_cmp_code (code, true, false)) == ERROR_MARK)
1584 continue;
1585 }
1586 /* Check if we can take advantage of "flag_var comp flag_var" predicate
1587 with value range info. Note only first of such case is handled. */
1588 else if (vrinfo_code == ERROR_MARK
1589 && TREE_CODE (cond_lhs) == SSA_NAME
1590 && TREE_CODE (cond_rhs) == SSA_NAME)
1591 {
1592 gimple* lhs_def = SSA_NAME_DEF_STMT (cond_lhs);
1593 if (!lhs_def || gimple_code (lhs_def) != GIMPLE_PHI
1594 || gimple_bb (lhs_def) != gimple_bb (phi))
1595 {
1596 std::swap (cond_lhs, cond_rhs);
1597 if ((code = get_cmp_code (code, true, false)) == ERROR_MARK)
1598 continue;
1599 }
1600
1601 /* Check value range info of rhs, do following transforms:
1602 flag_var < [min, max] -> flag_var < max
1603 flag_var > [min, max] -> flag_var > min
1604
1605 We can also transform LE_EXPR/GE_EXPR to LT_EXPR/GT_EXPR:
1606 flag_var <= [min, max] -> flag_var < [min, max+1]
1607 flag_var >= [min, max] -> flag_var > [min-1, max]
1608 if no overflow/wrap. */
1609 wide_int min, max;
1610 tree type = TREE_TYPE (cond_lhs);
1611 if (!INTEGRAL_TYPE_P (type)
1612 || get_range_info (cond_rhs, &min, &max) != VR_RANGE)
1613 continue;
1614 if (code == LE_EXPR
1615 && max != wi::max_value (TYPE_PRECISION (type), TYPE_SIGN (type)))
1616 {
1617 code = LT_EXPR;
1618 max = max + 1;
1619 }
1620 if (code == GE_EXPR
1621 && min != wi::min_value (TYPE_PRECISION (type), TYPE_SIGN (type)))
1622 {
1623 code = GT_EXPR;
1624 min = min - 1;
1625 }
1626 if (code == LT_EXPR)
1627 cond_rhs = wide_int_to_tree (type, max);
1628 else if (code == GT_EXPR)
1629 cond_rhs = wide_int_to_tree (type, min);
1630 else
1631 continue;
1632
1633 use_vrinfo_p = true;
1634 }
1635 else
1636 continue;
1637
1638 if ((*flag_def = SSA_NAME_DEF_STMT (cond_lhs)) == NULL)
1639 continue;
1640
1641 if (gimple_code (*flag_def) != GIMPLE_PHI
1642 || gimple_bb (*flag_def) != gimple_bb (phi)
1643 || !find_matching_predicate_in_rest_chains (the_pred, preds))
1644 continue;
1645
1646 /* Return if any "flag_var comp const" predicate is found. */
1647 if (!use_vrinfo_p)
1648 {
1649 *boundary_cst = cond_rhs;
1650 return code;
1651 }
1652 /* Record if any "flag_var comp flag_var[vinfo]" predicate is found. */
1653 else if (vrinfo_code == ERROR_MARK)
1654 {
1655 vrinfo_code = code;
1656 vrinfo_def = *flag_def;
1657 vrinfo_cst = cond_rhs;
1658 }
1659 }
1660 /* Return the "flag_var cmp flag_var[vinfo]" predicate we found. */
1661 if (vrinfo_code != ERROR_MARK)
1662 {
1663 *flag_def = vrinfo_def;
1664 *boundary_cst = vrinfo_cst;
1665 }
1666 return vrinfo_code;
1667 }
1668
1669 /* A helper function that determines if the predicate set
1670 of the use is not overlapping with that of the uninit paths.
1671 The most common senario of guarded use is in Example 1:
1672 Example 1:
1673 if (some_cond)
1674 {
1675 x = ...;
1676 flag = true;
1677 }
1678
1679 ... some code ...
1680
1681 if (flag)
1682 use (x);
1683
1684 The real world examples are usually more complicated, but similar
1685 and usually result from inlining:
1686
1687 bool init_func (int * x)
1688 {
1689 if (some_cond)
1690 return false;
1691 *x = ..
1692 return true;
1693 }
1694
1695 void foo (..)
1696 {
1697 int x;
1698
1699 if (!init_func (&x))
1700 return;
1701
1702 .. some_code ...
1703 use (x);
1704 }
1705
1706 Another possible use scenario is in the following trivial example:
1707
1708 Example 2:
1709 if (n > 0)
1710 x = 1;
1711 ...
1712 if (n > 0)
1713 {
1714 if (m < 2)
1715 .. = x;
1716 }
1717
1718 Predicate analysis needs to compute the composite predicate:
1719
1720 1) 'x' use predicate: (n > 0) .AND. (m < 2)
1721 2) 'x' default value (non-def) predicate: .NOT. (n > 0)
1722 (the predicate chain for phi operand defs can be computed
1723 starting from a bb that is control equivalent to the phi's
1724 bb and is dominating the operand def.)
1725
1726 and check overlapping:
1727 (n > 0) .AND. (m < 2) .AND. (.NOT. (n > 0))
1728 <==> false
1729
1730 This implementation provides framework that can handle
1731 scenarios. (Note that many simple cases are handled properly
1732 without the predicate analysis -- this is due to jump threading
1733 transformation which eliminates the merge point thus makes
1734 path sensitive analysis unnecessary.)
1735
1736 PHI is the phi node whose incoming (undefined) paths need to be
1737 pruned, and UNINIT_OPNDS is the bitmap holding uninit operand
1738 positions. VISITED_PHIS is the pointer set of phi stmts being
1739 checked. */
1740
1741 static bool
1742 use_pred_not_overlap_with_undef_path_pred (pred_chain_union preds,
1743 gphi *phi, unsigned uninit_opnds,
1744 hash_set<gphi *> *visited_phis)
1745 {
1746 gimple *flag_def = 0;
1747 tree boundary_cst = 0;
1748 enum tree_code cmp_code;
1749 bitmap visited_flag_phis = NULL;
1750 bool all_pruned = false;
1751
1752 /* Find within the common prefix of multiple predicate chains
1753 a predicate that is a comparison of a flag variable against
1754 a constant. */
1755 cmp_code = find_var_cmp_const (preds, phi, &flag_def, &boundary_cst);
1756 if (cmp_code == ERROR_MARK)
1757 return false;
1758
1759 /* Now check all the uninit incoming edge has a constant flag value
1760 that is in conflict with the use guard/predicate. */
1761 all_pruned = prune_uninit_phi_opnds
1762 (phi, uninit_opnds, as_a<gphi *> (flag_def), boundary_cst, cmp_code,
1763 visited_phis, &visited_flag_phis);
1764
1765 if (visited_flag_phis)
1766 BITMAP_FREE (visited_flag_phis);
1767
1768 return all_pruned;
1769 }
1770
1771 /* The helper function returns true if two predicates X1 and X2
1772 are equivalent. It assumes the expressions have already
1773 properly re-associated. */
1774
1775 static inline bool
1776 pred_equal_p (pred_info x1, pred_info x2)
1777 {
1778 enum tree_code c1, c2;
1779 if (!operand_equal_p (x1.pred_lhs, x2.pred_lhs, 0)
1780 || !operand_equal_p (x1.pred_rhs, x2.pred_rhs, 0))
1781 return false;
1782
1783 c1 = x1.cond_code;
1784 if (x1.invert != x2.invert
1785 && TREE_CODE_CLASS (x2.cond_code) == tcc_comparison)
1786 c2 = invert_tree_comparison (x2.cond_code, false);
1787 else
1788 c2 = x2.cond_code;
1789
1790 return c1 == c2;
1791 }
1792
1793 /* Returns true if the predication is testing !=. */
1794
1795 static inline bool
1796 is_neq_relop_p (pred_info pred)
1797 {
1798
1799 return ((pred.cond_code == NE_EXPR && !pred.invert)
1800 || (pred.cond_code == EQ_EXPR && pred.invert));
1801 }
1802
1803 /* Returns true if pred is of the form X != 0. */
1804
1805 static inline bool
1806 is_neq_zero_form_p (pred_info pred)
1807 {
1808 if (!is_neq_relop_p (pred) || !integer_zerop (pred.pred_rhs)
1809 || TREE_CODE (pred.pred_lhs) != SSA_NAME)
1810 return false;
1811 return true;
1812 }
1813
1814 /* The helper function returns true if two predicates X1
1815 is equivalent to X2 != 0. */
1816
1817 static inline bool
1818 pred_expr_equal_p (pred_info x1, tree x2)
1819 {
1820 if (!is_neq_zero_form_p (x1))
1821 return false;
1822
1823 return operand_equal_p (x1.pred_lhs, x2, 0);
1824 }
1825
1826 /* Returns true of the domain of single predicate expression
1827 EXPR1 is a subset of that of EXPR2. Returns false if it
1828 cannot be proved. */
1829
1830 static bool
1831 is_pred_expr_subset_of (pred_info expr1, pred_info expr2)
1832 {
1833 enum tree_code code1, code2;
1834
1835 if (pred_equal_p (expr1, expr2))
1836 return true;
1837
1838 if ((TREE_CODE (expr1.pred_rhs) != INTEGER_CST)
1839 || (TREE_CODE (expr2.pred_rhs) != INTEGER_CST))
1840 return false;
1841
1842 if (!operand_equal_p (expr1.pred_lhs, expr2.pred_lhs, 0))
1843 return false;
1844
1845 code1 = expr1.cond_code;
1846 if (expr1.invert)
1847 code1 = invert_tree_comparison (code1, false);
1848 code2 = expr2.cond_code;
1849 if (expr2.invert)
1850 code2 = invert_tree_comparison (code2, false);
1851
1852 if (code2 == NE_EXPR && code1 == NE_EXPR)
1853 return false;
1854
1855 if (code2 == NE_EXPR)
1856 return !value_sat_pred_p (expr2.pred_rhs, expr1.pred_rhs, code1);
1857
1858 if (code1 == EQ_EXPR)
1859 return value_sat_pred_p (expr1.pred_rhs, expr2.pred_rhs, code2);
1860
1861 if (code1 == code2)
1862 return value_sat_pred_p (expr1.pred_rhs, expr2.pred_rhs, code2,
1863 code1 == BIT_AND_EXPR);
1864
1865 return false;
1866 }
1867
1868 /* Returns true if the domain of PRED1 is a subset
1869 of that of PRED2. Returns false if it cannot be proved so. */
1870
1871 static bool
1872 is_pred_chain_subset_of (pred_chain pred1, pred_chain pred2)
1873 {
1874 size_t np1, np2, i1, i2;
1875
1876 np1 = pred1.length ();
1877 np2 = pred2.length ();
1878
1879 for (i2 = 0; i2 < np2; i2++)
1880 {
1881 bool found = false;
1882 pred_info info2 = pred2[i2];
1883 for (i1 = 0; i1 < np1; i1++)
1884 {
1885 pred_info info1 = pred1[i1];
1886 if (is_pred_expr_subset_of (info1, info2))
1887 {
1888 found = true;
1889 break;
1890 }
1891 }
1892 if (!found)
1893 return false;
1894 }
1895 return true;
1896 }
1897
1898 /* Returns true if the domain defined by
1899 one pred chain ONE_PRED is a subset of the domain
1900 of *PREDS. It returns false if ONE_PRED's domain is
1901 not a subset of any of the sub-domains of PREDS
1902 (corresponding to each individual chains in it), even
1903 though it may be still be a subset of whole domain
1904 of PREDS which is the union (ORed) of all its subdomains.
1905 In other words, the result is conservative. */
1906
1907 static bool
1908 is_included_in (pred_chain one_pred, pred_chain_union preds)
1909 {
1910 size_t i;
1911 size_t n = preds.length ();
1912
1913 for (i = 0; i < n; i++)
1914 {
1915 if (is_pred_chain_subset_of (one_pred, preds[i]))
1916 return true;
1917 }
1918
1919 return false;
1920 }
1921
1922 /* Compares two predicate sets PREDS1 and PREDS2 and returns
1923 true if the domain defined by PREDS1 is a superset
1924 of PREDS2's domain. N1 and N2 are array sizes of PREDS1 and
1925 PREDS2 respectively. The implementation chooses not to build
1926 generic trees (and relying on the folding capability of the
1927 compiler), but instead performs brute force comparison of
1928 individual predicate chains (won't be a compile time problem
1929 as the chains are pretty short). When the function returns
1930 false, it does not necessarily mean *PREDS1 is not a superset
1931 of *PREDS2, but mean it may not be so since the analysis cannot
1932 prove it. In such cases, false warnings may still be
1933 emitted. */
1934
1935 static bool
1936 is_superset_of (pred_chain_union preds1, pred_chain_union preds2)
1937 {
1938 size_t i, n2;
1939 pred_chain one_pred_chain = vNULL;
1940
1941 n2 = preds2.length ();
1942
1943 for (i = 0; i < n2; i++)
1944 {
1945 one_pred_chain = preds2[i];
1946 if (!is_included_in (one_pred_chain, preds1))
1947 return false;
1948 }
1949
1950 return true;
1951 }
1952
1953 /* Returns true if X1 is the negate of X2. */
1954
1955 static inline bool
1956 pred_neg_p (pred_info x1, pred_info x2)
1957 {
1958 enum tree_code c1, c2;
1959 if (!operand_equal_p (x1.pred_lhs, x2.pred_lhs, 0)
1960 || !operand_equal_p (x1.pred_rhs, x2.pred_rhs, 0))
1961 return false;
1962
1963 c1 = x1.cond_code;
1964 if (x1.invert == x2.invert)
1965 c2 = invert_tree_comparison (x2.cond_code, false);
1966 else
1967 c2 = x2.cond_code;
1968
1969 return c1 == c2;
1970 }
1971
1972 /* 1) ((x IOR y) != 0) AND (x != 0) is equivalent to (x != 0);
1973 2) (X AND Y) OR (!X AND Y) is equivalent to Y;
1974 3) X OR (!X AND Y) is equivalent to (X OR Y);
1975 4) ((x IAND y) != 0) || (x != 0 AND y != 0)) is equivalent to
1976 (x != 0 AND y != 0)
1977 5) (X AND Y) OR (!X AND Z) OR (!Y AND Z) is equivalent to
1978 (X AND Y) OR Z
1979
1980 PREDS is the predicate chains, and N is the number of chains. */
1981
1982 /* Helper function to implement rule 1 above. ONE_CHAIN is
1983 the AND predication to be simplified. */
1984
1985 static void
1986 simplify_pred (pred_chain *one_chain)
1987 {
1988 size_t i, j, n;
1989 bool simplified = false;
1990 pred_chain s_chain = vNULL;
1991
1992 n = one_chain->length ();
1993
1994 for (i = 0; i < n; i++)
1995 {
1996 pred_info *a_pred = &(*one_chain)[i];
1997
1998 if (!a_pred->pred_lhs)
1999 continue;
2000 if (!is_neq_zero_form_p (*a_pred))
2001 continue;
2002
2003 gimple *def_stmt = SSA_NAME_DEF_STMT (a_pred->pred_lhs);
2004 if (gimple_code (def_stmt) != GIMPLE_ASSIGN)
2005 continue;
2006 if (gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR)
2007 {
2008 for (j = 0; j < n; j++)
2009 {
2010 pred_info *b_pred = &(*one_chain)[j];
2011
2012 if (!b_pred->pred_lhs)
2013 continue;
2014 if (!is_neq_zero_form_p (*b_pred))
2015 continue;
2016
2017 if (pred_expr_equal_p (*b_pred, gimple_assign_rhs1 (def_stmt))
2018 || pred_expr_equal_p (*b_pred, gimple_assign_rhs2 (def_stmt)))
2019 {
2020 /* Mark a_pred for removal. */
2021 a_pred->pred_lhs = NULL;
2022 a_pred->pred_rhs = NULL;
2023 simplified = true;
2024 break;
2025 }
2026 }
2027 }
2028 }
2029
2030 if (!simplified)
2031 return;
2032
2033 for (i = 0; i < n; i++)
2034 {
2035 pred_info *a_pred = &(*one_chain)[i];
2036 if (!a_pred->pred_lhs)
2037 continue;
2038 s_chain.safe_push (*a_pred);
2039 }
2040
2041 one_chain->release ();
2042 *one_chain = s_chain;
2043 }
2044
2045 /* The helper function implements the rule 2 for the
2046 OR predicate PREDS.
2047
2048 2) (X AND Y) OR (!X AND Y) is equivalent to Y. */
2049
2050 static bool
2051 simplify_preds_2 (pred_chain_union *preds)
2052 {
2053 size_t i, j, n;
2054 bool simplified = false;
2055 pred_chain_union s_preds = vNULL;
2056
2057 /* (X AND Y) OR (!X AND Y) is equivalent to Y.
2058 (X AND Y) OR (X AND !Y) is equivalent to X. */
2059
2060 n = preds->length ();
2061 for (i = 0; i < n; i++)
2062 {
2063 pred_info x, y;
2064 pred_chain *a_chain = &(*preds)[i];
2065
2066 if (a_chain->length () != 2)
2067 continue;
2068
2069 x = (*a_chain)[0];
2070 y = (*a_chain)[1];
2071
2072 for (j = 0; j < n; j++)
2073 {
2074 pred_chain *b_chain;
2075 pred_info x2, y2;
2076
2077 if (j == i)
2078 continue;
2079
2080 b_chain = &(*preds)[j];
2081 if (b_chain->length () != 2)
2082 continue;
2083
2084 x2 = (*b_chain)[0];
2085 y2 = (*b_chain)[1];
2086
2087 if (pred_equal_p (x, x2) && pred_neg_p (y, y2))
2088 {
2089 /* Kill a_chain. */
2090 a_chain->release ();
2091 b_chain->release ();
2092 b_chain->safe_push (x);
2093 simplified = true;
2094 break;
2095 }
2096 if (pred_neg_p (x, x2) && pred_equal_p (y, y2))
2097 {
2098 /* Kill a_chain. */
2099 a_chain->release ();
2100 b_chain->release ();
2101 b_chain->safe_push (y);
2102 simplified = true;
2103 break;
2104 }
2105 }
2106 }
2107 /* Now clean up the chain. */
2108 if (simplified)
2109 {
2110 for (i = 0; i < n; i++)
2111 {
2112 if ((*preds)[i].is_empty ())
2113 continue;
2114 s_preds.safe_push ((*preds)[i]);
2115 }
2116 preds->release ();
2117 (*preds) = s_preds;
2118 s_preds = vNULL;
2119 }
2120
2121 return simplified;
2122 }
2123
2124 /* The helper function implements the rule 2 for the
2125 OR predicate PREDS.
2126
2127 3) x OR (!x AND y) is equivalent to x OR y. */
2128
2129 static bool
2130 simplify_preds_3 (pred_chain_union *preds)
2131 {
2132 size_t i, j, n;
2133 bool simplified = false;
2134
2135 /* Now iteratively simplify X OR (!X AND Z ..)
2136 into X OR (Z ...). */
2137
2138 n = preds->length ();
2139 if (n < 2)
2140 return false;
2141
2142 for (i = 0; i < n; i++)
2143 {
2144 pred_info x;
2145 pred_chain *a_chain = &(*preds)[i];
2146
2147 if (a_chain->length () != 1)
2148 continue;
2149
2150 x = (*a_chain)[0];
2151
2152 for (j = 0; j < n; j++)
2153 {
2154 pred_chain *b_chain;
2155 pred_info x2;
2156 size_t k;
2157
2158 if (j == i)
2159 continue;
2160
2161 b_chain = &(*preds)[j];
2162 if (b_chain->length () < 2)
2163 continue;
2164
2165 for (k = 0; k < b_chain->length (); k++)
2166 {
2167 x2 = (*b_chain)[k];
2168 if (pred_neg_p (x, x2))
2169 {
2170 b_chain->unordered_remove (k);
2171 simplified = true;
2172 break;
2173 }
2174 }
2175 }
2176 }
2177 return simplified;
2178 }
2179
2180 /* The helper function implements the rule 4 for the
2181 OR predicate PREDS.
2182
2183 2) ((x AND y) != 0) OR (x != 0 AND y != 0) is equivalent to
2184 (x != 0 ANd y != 0). */
2185
2186 static bool
2187 simplify_preds_4 (pred_chain_union *preds)
2188 {
2189 size_t i, j, n;
2190 bool simplified = false;
2191 pred_chain_union s_preds = vNULL;
2192 gimple *def_stmt;
2193
2194 n = preds->length ();
2195 for (i = 0; i < n; i++)
2196 {
2197 pred_info z;
2198 pred_chain *a_chain = &(*preds)[i];
2199
2200 if (a_chain->length () != 1)
2201 continue;
2202
2203 z = (*a_chain)[0];
2204
2205 if (!is_neq_zero_form_p (z))
2206 continue;
2207
2208 def_stmt = SSA_NAME_DEF_STMT (z.pred_lhs);
2209 if (gimple_code (def_stmt) != GIMPLE_ASSIGN)
2210 continue;
2211
2212 if (gimple_assign_rhs_code (def_stmt) != BIT_AND_EXPR)
2213 continue;
2214
2215 for (j = 0; j < n; j++)
2216 {
2217 pred_chain *b_chain;
2218 pred_info x2, y2;
2219
2220 if (j == i)
2221 continue;
2222
2223 b_chain = &(*preds)[j];
2224 if (b_chain->length () != 2)
2225 continue;
2226
2227 x2 = (*b_chain)[0];
2228 y2 = (*b_chain)[1];
2229 if (!is_neq_zero_form_p (x2) || !is_neq_zero_form_p (y2))
2230 continue;
2231
2232 if ((pred_expr_equal_p (x2, gimple_assign_rhs1 (def_stmt))
2233 && pred_expr_equal_p (y2, gimple_assign_rhs2 (def_stmt)))
2234 || (pred_expr_equal_p (x2, gimple_assign_rhs2 (def_stmt))
2235 && pred_expr_equal_p (y2, gimple_assign_rhs1 (def_stmt))))
2236 {
2237 /* Kill a_chain. */
2238 a_chain->release ();
2239 simplified = true;
2240 break;
2241 }
2242 }
2243 }
2244 /* Now clean up the chain. */
2245 if (simplified)
2246 {
2247 for (i = 0; i < n; i++)
2248 {
2249 if ((*preds)[i].is_empty ())
2250 continue;
2251 s_preds.safe_push ((*preds)[i]);
2252 }
2253
2254 preds->release ();
2255 (*preds) = s_preds;
2256 s_preds = vNULL;
2257 }
2258
2259 return simplified;
2260 }
2261
2262 /* This function simplifies predicates in PREDS. */
2263
2264 static void
2265 simplify_preds (pred_chain_union *preds, gimple *use_or_def, bool is_use)
2266 {
2267 size_t i, n;
2268 bool changed = false;
2269
2270 if (dump_file && dump_flags & TDF_DETAILS)
2271 {
2272 fprintf (dump_file, "[BEFORE SIMPLICATION -- ");
2273 dump_predicates (use_or_def, *preds, is_use ? "[USE]:\n" : "[DEF]:\n");
2274 }
2275
2276 for (i = 0; i < preds->length (); i++)
2277 simplify_pred (&(*preds)[i]);
2278
2279 n = preds->length ();
2280 if (n < 2)
2281 return;
2282
2283 do
2284 {
2285 changed = false;
2286 if (simplify_preds_2 (preds))
2287 changed = true;
2288
2289 /* Now iteratively simplify X OR (!X AND Z ..)
2290 into X OR (Z ...). */
2291 if (simplify_preds_3 (preds))
2292 changed = true;
2293
2294 if (simplify_preds_4 (preds))
2295 changed = true;
2296 }
2297 while (changed);
2298
2299 return;
2300 }
2301
2302 /* This is a helper function which attempts to normalize predicate chains
2303 by following UD chains. It basically builds up a big tree of either IOR
2304 operations or AND operations, and convert the IOR tree into a
2305 pred_chain_union or BIT_AND tree into a pred_chain.
2306 Example:
2307
2308 _3 = _2 RELOP1 _1;
2309 _6 = _5 RELOP2 _4;
2310 _9 = _8 RELOP3 _7;
2311 _10 = _3 | _6;
2312 _12 = _9 | _0;
2313 _t = _10 | _12;
2314
2315 then _t != 0 will be normalized into a pred_chain_union
2316
2317 (_2 RELOP1 _1) OR (_5 RELOP2 _4) OR (_8 RELOP3 _7) OR (_0 != 0)
2318
2319 Similarly given,
2320
2321 _3 = _2 RELOP1 _1;
2322 _6 = _5 RELOP2 _4;
2323 _9 = _8 RELOP3 _7;
2324 _10 = _3 & _6;
2325 _12 = _9 & _0;
2326
2327 then _t != 0 will be normalized into a pred_chain:
2328 (_2 RELOP1 _1) AND (_5 RELOP2 _4) AND (_8 RELOP3 _7) AND (_0 != 0)
2329
2330 */
2331
2332 /* This is a helper function that stores a PRED into NORM_PREDS. */
2333
2334 inline static void
2335 push_pred (pred_chain_union *norm_preds, pred_info pred)
2336 {
2337 pred_chain pred_chain = vNULL;
2338 pred_chain.safe_push (pred);
2339 norm_preds->safe_push (pred_chain);
2340 }
2341
2342 /* A helper function that creates a predicate of the form
2343 OP != 0 and push it WORK_LIST. */
2344
2345 inline static void
2346 push_to_worklist (tree op, vec<pred_info, va_heap, vl_ptr> *work_list,
2347 hash_set<tree> *mark_set)
2348 {
2349 if (mark_set->contains (op))
2350 return;
2351 mark_set->add (op);
2352
2353 pred_info arg_pred;
2354 arg_pred.pred_lhs = op;
2355 arg_pred.pred_rhs = integer_zero_node;
2356 arg_pred.cond_code = NE_EXPR;
2357 arg_pred.invert = false;
2358 work_list->safe_push (arg_pred);
2359 }
2360
2361 /* A helper that generates a pred_info from a gimple assignment
2362 CMP_ASSIGN with comparison rhs. */
2363
2364 static pred_info
2365 get_pred_info_from_cmp (gimple *cmp_assign)
2366 {
2367 pred_info n_pred;
2368 n_pred.pred_lhs = gimple_assign_rhs1 (cmp_assign);
2369 n_pred.pred_rhs = gimple_assign_rhs2 (cmp_assign);
2370 n_pred.cond_code = gimple_assign_rhs_code (cmp_assign);
2371 n_pred.invert = false;
2372 return n_pred;
2373 }
2374
2375 /* Returns true if the PHI is a degenerated phi with
2376 all args with the same value (relop). In that case, *PRED
2377 will be updated to that value. */
2378
2379 static bool
2380 is_degenerated_phi (gimple *phi, pred_info *pred_p)
2381 {
2382 int i, n;
2383 tree op0;
2384 gimple *def0;
2385 pred_info pred0;
2386
2387 n = gimple_phi_num_args (phi);
2388 op0 = gimple_phi_arg_def (phi, 0);
2389
2390 if (TREE_CODE (op0) != SSA_NAME)
2391 return false;
2392
2393 def0 = SSA_NAME_DEF_STMT (op0);
2394 if (gimple_code (def0) != GIMPLE_ASSIGN)
2395 return false;
2396 if (TREE_CODE_CLASS (gimple_assign_rhs_code (def0)) != tcc_comparison)
2397 return false;
2398 pred0 = get_pred_info_from_cmp (def0);
2399
2400 for (i = 1; i < n; ++i)
2401 {
2402 gimple *def;
2403 pred_info pred;
2404 tree op = gimple_phi_arg_def (phi, i);
2405
2406 if (TREE_CODE (op) != SSA_NAME)
2407 return false;
2408
2409 def = SSA_NAME_DEF_STMT (op);
2410 if (gimple_code (def) != GIMPLE_ASSIGN)
2411 return false;
2412 if (TREE_CODE_CLASS (gimple_assign_rhs_code (def)) != tcc_comparison)
2413 return false;
2414 pred = get_pred_info_from_cmp (def);
2415 if (!pred_equal_p (pred, pred0))
2416 return false;
2417 }
2418
2419 *pred_p = pred0;
2420 return true;
2421 }
2422
2423 /* Normalize one predicate PRED
2424 1) if PRED can no longer be normlized, put it into NORM_PREDS.
2425 2) otherwise if PRED is of the form x != 0, follow x's definition
2426 and put normalized predicates into WORK_LIST. */
2427
2428 static void
2429 normalize_one_pred_1 (pred_chain_union *norm_preds,
2430 pred_chain *norm_chain,
2431 pred_info pred,
2432 enum tree_code and_or_code,
2433 vec<pred_info, va_heap, vl_ptr> *work_list,
2434 hash_set<tree> *mark_set)
2435 {
2436 if (!is_neq_zero_form_p (pred))
2437 {
2438 if (and_or_code == BIT_IOR_EXPR)
2439 push_pred (norm_preds, pred);
2440 else
2441 norm_chain->safe_push (pred);
2442 return;
2443 }
2444
2445 gimple *def_stmt = SSA_NAME_DEF_STMT (pred.pred_lhs);
2446
2447 if (gimple_code (def_stmt) == GIMPLE_PHI
2448 && is_degenerated_phi (def_stmt, &pred))
2449 work_list->safe_push (pred);
2450 else if (gimple_code (def_stmt) == GIMPLE_PHI && and_or_code == BIT_IOR_EXPR)
2451 {
2452 int i, n;
2453 n = gimple_phi_num_args (def_stmt);
2454
2455 /* If we see non zero constant, we should punt. The predicate
2456 * should be one guarding the phi edge. */
2457 for (i = 0; i < n; ++i)
2458 {
2459 tree op = gimple_phi_arg_def (def_stmt, i);
2460 if (TREE_CODE (op) == INTEGER_CST && !integer_zerop (op))
2461 {
2462 push_pred (norm_preds, pred);
2463 return;
2464 }
2465 }
2466
2467 for (i = 0; i < n; ++i)
2468 {
2469 tree op = gimple_phi_arg_def (def_stmt, i);
2470 if (integer_zerop (op))
2471 continue;
2472
2473 push_to_worklist (op, work_list, mark_set);
2474 }
2475 }
2476 else if (gimple_code (def_stmt) != GIMPLE_ASSIGN)
2477 {
2478 if (and_or_code == BIT_IOR_EXPR)
2479 push_pred (norm_preds, pred);
2480 else
2481 norm_chain->safe_push (pred);
2482 }
2483 else if (gimple_assign_rhs_code (def_stmt) == and_or_code)
2484 {
2485 /* Avoid splitting up bit manipulations like x & 3 or y | 1. */
2486 if (is_gimple_min_invariant (gimple_assign_rhs2 (def_stmt)))
2487 {
2488 /* But treat x & 3 as condition. */
2489 if (and_or_code == BIT_AND_EXPR)
2490 {
2491 pred_info n_pred;
2492 n_pred.pred_lhs = gimple_assign_rhs1 (def_stmt);
2493 n_pred.pred_rhs = gimple_assign_rhs2 (def_stmt);
2494 n_pred.cond_code = and_or_code;
2495 n_pred.invert = false;
2496 norm_chain->safe_push (n_pred);
2497 }
2498 }
2499 else
2500 {
2501 push_to_worklist (gimple_assign_rhs1 (def_stmt), work_list, mark_set);
2502 push_to_worklist (gimple_assign_rhs2 (def_stmt), work_list, mark_set);
2503 }
2504 }
2505 else if (TREE_CODE_CLASS (gimple_assign_rhs_code (def_stmt))
2506 == tcc_comparison)
2507 {
2508 pred_info n_pred = get_pred_info_from_cmp (def_stmt);
2509 if (and_or_code == BIT_IOR_EXPR)
2510 push_pred (norm_preds, n_pred);
2511 else
2512 norm_chain->safe_push (n_pred);
2513 }
2514 else
2515 {
2516 if (and_or_code == BIT_IOR_EXPR)
2517 push_pred (norm_preds, pred);
2518 else
2519 norm_chain->safe_push (pred);
2520 }
2521 }
2522
2523 /* Normalize PRED and store the normalized predicates into NORM_PREDS. */
2524
2525 static void
2526 normalize_one_pred (pred_chain_union *norm_preds, pred_info pred)
2527 {
2528 vec<pred_info, va_heap, vl_ptr> work_list = vNULL;
2529 enum tree_code and_or_code = ERROR_MARK;
2530 pred_chain norm_chain = vNULL;
2531
2532 if (!is_neq_zero_form_p (pred))
2533 {
2534 push_pred (norm_preds, pred);
2535 return;
2536 }
2537
2538 gimple *def_stmt = SSA_NAME_DEF_STMT (pred.pred_lhs);
2539 if (gimple_code (def_stmt) == GIMPLE_ASSIGN)
2540 and_or_code = gimple_assign_rhs_code (def_stmt);
2541 if (and_or_code != BIT_IOR_EXPR && and_or_code != BIT_AND_EXPR)
2542 {
2543 if (TREE_CODE_CLASS (and_or_code) == tcc_comparison)
2544 {
2545 pred_info n_pred = get_pred_info_from_cmp (def_stmt);
2546 push_pred (norm_preds, n_pred);
2547 }
2548 else
2549 push_pred (norm_preds, pred);
2550 return;
2551 }
2552
2553 work_list.safe_push (pred);
2554 hash_set<tree> mark_set;
2555
2556 while (!work_list.is_empty ())
2557 {
2558 pred_info a_pred = work_list.pop ();
2559 normalize_one_pred_1 (norm_preds, &norm_chain, a_pred, and_or_code,
2560 &work_list, &mark_set);
2561 }
2562 if (and_or_code == BIT_AND_EXPR)
2563 norm_preds->safe_push (norm_chain);
2564
2565 work_list.release ();
2566 }
2567
2568 static void
2569 normalize_one_pred_chain (pred_chain_union *norm_preds, pred_chain one_chain)
2570 {
2571 vec<pred_info, va_heap, vl_ptr> work_list = vNULL;
2572 hash_set<tree> mark_set;
2573 pred_chain norm_chain = vNULL;
2574 size_t i;
2575
2576 for (i = 0; i < one_chain.length (); i++)
2577 {
2578 work_list.safe_push (one_chain[i]);
2579 mark_set.add (one_chain[i].pred_lhs);
2580 }
2581
2582 while (!work_list.is_empty ())
2583 {
2584 pred_info a_pred = work_list.pop ();
2585 normalize_one_pred_1 (0, &norm_chain, a_pred, BIT_AND_EXPR, &work_list,
2586 &mark_set);
2587 }
2588
2589 norm_preds->safe_push (norm_chain);
2590 work_list.release ();
2591 }
2592
2593 /* Normalize predicate chains PREDS and returns the normalized one. */
2594
2595 static pred_chain_union
2596 normalize_preds (pred_chain_union preds, gimple *use_or_def, bool is_use)
2597 {
2598 pred_chain_union norm_preds = vNULL;
2599 size_t n = preds.length ();
2600 size_t i;
2601
2602 if (dump_file && dump_flags & TDF_DETAILS)
2603 {
2604 fprintf (dump_file, "[BEFORE NORMALIZATION --");
2605 dump_predicates (use_or_def, preds, is_use ? "[USE]:\n" : "[DEF]:\n");
2606 }
2607
2608 for (i = 0; i < n; i++)
2609 {
2610 if (preds[i].length () != 1)
2611 normalize_one_pred_chain (&norm_preds, preds[i]);
2612 else
2613 {
2614 normalize_one_pred (&norm_preds, preds[i][0]);
2615 preds[i].release ();
2616 }
2617 }
2618
2619 if (dump_file)
2620 {
2621 fprintf (dump_file, "[AFTER NORMALIZATION -- ");
2622 dump_predicates (use_or_def, norm_preds,
2623 is_use ? "[USE]:\n" : "[DEF]:\n");
2624 }
2625
2626 destroy_predicate_vecs (&preds);
2627 return norm_preds;
2628 }
2629
2630 /* Return TRUE if PREDICATE can be invalidated by any individual
2631 predicate in USE_GUARD. */
2632
2633 static bool
2634 can_one_predicate_be_invalidated_p (pred_info predicate,
2635 pred_chain use_guard)
2636 {
2637 if (dump_file && dump_flags & TDF_DETAILS)
2638 {
2639 fprintf (dump_file, "Testing if this predicate: ");
2640 dump_pred_info (predicate);
2641 fprintf (dump_file, "\n...can be invalidated by a USE guard of: ");
2642 dump_pred_chain (use_guard);
2643 }
2644 for (size_t i = 0; i < use_guard.length (); ++i)
2645 {
2646 /* NOTE: This is a very simple check, and only understands an
2647 exact opposite. So, [i == 0] is currently only invalidated
2648 by [.NOT. i == 0] or [i != 0]. Ideally we should also
2649 invalidate with say [i > 5] or [i == 8]. There is certainly
2650 room for improvement here. */
2651 if (pred_neg_p (predicate, use_guard[i]))
2652 {
2653 if (dump_file && dump_flags & TDF_DETAILS)
2654 {
2655 fprintf (dump_file, " Predicate was invalidated by: ");
2656 dump_pred_info (use_guard[i]);
2657 fputc ('\n', dump_file);
2658 }
2659 return true;
2660 }
2661 }
2662 return false;
2663 }
2664
2665 /* Return TRUE if all predicates in UNINIT_PRED are invalidated by
2666 USE_GUARD being true. */
2667
2668 static bool
2669 can_chain_union_be_invalidated_p (pred_chain_union uninit_pred,
2670 pred_chain use_guard)
2671 {
2672 if (uninit_pred.is_empty ())
2673 return false;
2674 if (dump_file && dump_flags & TDF_DETAILS)
2675 dump_predicates (NULL, uninit_pred,
2676 "Testing if anything here can be invalidated: ");
2677 for (size_t i = 0; i < uninit_pred.length (); ++i)
2678 {
2679 pred_chain c = uninit_pred[i];
2680 size_t j;
2681 for (j = 0; j < c.length (); ++j)
2682 if (can_one_predicate_be_invalidated_p (c[j], use_guard))
2683 break;
2684
2685 /* If we were unable to invalidate any predicate in C, then there
2686 is a viable path from entry to the PHI where the PHI takes
2687 an uninitialized value and continues to a use of the PHI. */
2688 if (j == c.length ())
2689 return false;
2690 }
2691 return true;
2692 }
2693
2694 /* Return TRUE if none of the uninitialized operands in UNINT_OPNDS
2695 can actually happen if we arrived at a use for PHI.
2696
2697 PHI_USE_GUARDS are the guard conditions for the use of the PHI. */
2698
2699 static bool
2700 uninit_uses_cannot_happen (gphi *phi, unsigned uninit_opnds,
2701 pred_chain_union phi_use_guards)
2702 {
2703 unsigned phi_args = gimple_phi_num_args (phi);
2704 if (phi_args > max_phi_args)
2705 return false;
2706
2707 /* PHI_USE_GUARDS are OR'ed together. If we have more than one
2708 possible guard, there's no way of knowing which guard was true.
2709 Since we need to be absolutely sure that the uninitialized
2710 operands will be invalidated, bail. */
2711 if (phi_use_guards.length () != 1)
2712 return false;
2713
2714 /* Look for the control dependencies of all the uninitialized
2715 operands and build guard predicates describing them. */
2716 pred_chain_union uninit_preds;
2717 bool ret = true;
2718 for (unsigned i = 0; i < phi_args; ++i)
2719 {
2720 if (!MASK_TEST_BIT (uninit_opnds, i))
2721 continue;
2722
2723 edge e = gimple_phi_arg_edge (phi, i);
2724 vec<edge> dep_chains[MAX_NUM_CHAINS];
2725 auto_vec<edge, MAX_CHAIN_LEN + 1> cur_chain;
2726 size_t num_chains = 0;
2727 int num_calls = 0;
2728
2729 /* Build the control dependency chain for uninit operand `i'... */
2730 uninit_preds = vNULL;
2731 if (!compute_control_dep_chain (ENTRY_BLOCK_PTR_FOR_FN (cfun),
2732 e->src, dep_chains, &num_chains,
2733 &cur_chain, &num_calls))
2734 {
2735 ret = false;
2736 break;
2737 }
2738 /* ...and convert it into a set of predicates. */
2739 bool has_valid_preds
2740 = convert_control_dep_chain_into_preds (dep_chains, num_chains,
2741 &uninit_preds);
2742 for (size_t j = 0; j < num_chains; ++j)
2743 dep_chains[j].release ();
2744 if (!has_valid_preds)
2745 {
2746 ret = false;
2747 break;
2748 }
2749 simplify_preds (&uninit_preds, NULL, false);
2750 uninit_preds = normalize_preds (uninit_preds, NULL, false);
2751
2752 /* Can the guard for this uninitialized operand be invalidated
2753 by the PHI use? */
2754 if (!can_chain_union_be_invalidated_p (uninit_preds, phi_use_guards[0]))
2755 {
2756 ret = false;
2757 break;
2758 }
2759 }
2760 destroy_predicate_vecs (&uninit_preds);
2761 return ret;
2762 }
2763
2764 /* Computes the predicates that guard the use and checks
2765 if the incoming paths that have empty (or possibly
2766 empty) definition can be pruned/filtered. The function returns
2767 true if it can be determined that the use of PHI's def in
2768 USE_STMT is guarded with a predicate set not overlapping with
2769 predicate sets of all runtime paths that do not have a definition.
2770
2771 Returns false if it is not or it cannot be determined. USE_BB is
2772 the bb of the use (for phi operand use, the bb is not the bb of
2773 the phi stmt, but the src bb of the operand edge).
2774
2775 UNINIT_OPNDS is a bit vector. If an operand of PHI is uninitialized, the
2776 corresponding bit in the vector is 1. VISITED_PHIS is a pointer
2777 set of phis being visited.
2778
2779 *DEF_PREDS contains the (memoized) defining predicate chains of PHI.
2780 If *DEF_PREDS is the empty vector, the defining predicate chains of
2781 PHI will be computed and stored into *DEF_PREDS as needed.
2782
2783 VISITED_PHIS is a pointer set of phis being visited. */
2784
2785 static bool
2786 is_use_properly_guarded (gimple *use_stmt,
2787 basic_block use_bb,
2788 gphi *phi,
2789 unsigned uninit_opnds,
2790 pred_chain_union *def_preds,
2791 hash_set<gphi *> *visited_phis)
2792 {
2793 basic_block phi_bb;
2794 pred_chain_union preds = vNULL;
2795 bool has_valid_preds = false;
2796 bool is_properly_guarded = false;
2797
2798 if (visited_phis->add (phi))
2799 return false;
2800
2801 phi_bb = gimple_bb (phi);
2802
2803 if (is_non_loop_exit_postdominating (use_bb, phi_bb))
2804 return false;
2805
2806 has_valid_preds = find_predicates (&preds, phi_bb, use_bb);
2807
2808 if (!has_valid_preds)
2809 {
2810 destroy_predicate_vecs (&preds);
2811 return false;
2812 }
2813
2814 /* Try to prune the dead incoming phi edges. */
2815 is_properly_guarded
2816 = use_pred_not_overlap_with_undef_path_pred (preds, phi, uninit_opnds,
2817 visited_phis);
2818
2819 /* We might be able to prove that if the control dependencies
2820 for UNINIT_OPNDS are true, that the control dependencies for
2821 USE_STMT can never be true. */
2822 if (!is_properly_guarded)
2823 is_properly_guarded |= uninit_uses_cannot_happen (phi, uninit_opnds,
2824 preds);
2825
2826 if (is_properly_guarded)
2827 {
2828 destroy_predicate_vecs (&preds);
2829 return true;
2830 }
2831
2832 if (def_preds->is_empty ())
2833 {
2834 has_valid_preds = find_def_preds (def_preds, phi);
2835
2836 if (!has_valid_preds)
2837 {
2838 destroy_predicate_vecs (&preds);
2839 return false;
2840 }
2841
2842 simplify_preds (def_preds, phi, false);
2843 *def_preds = normalize_preds (*def_preds, phi, false);
2844 }
2845
2846 simplify_preds (&preds, use_stmt, true);
2847 preds = normalize_preds (preds, use_stmt, true);
2848
2849 is_properly_guarded = is_superset_of (*def_preds, preds);
2850
2851 destroy_predicate_vecs (&preds);
2852 return is_properly_guarded;
2853 }
2854
2855 /* Searches through all uses of a potentially
2856 uninitialized variable defined by PHI and returns a use
2857 statement if the use is not properly guarded. It returns
2858 NULL if all uses are guarded. UNINIT_OPNDS is a bitvector
2859 holding the position(s) of uninit PHI operands. WORKLIST
2860 is the vector of candidate phis that may be updated by this
2861 function. ADDED_TO_WORKLIST is the pointer set tracking
2862 if the new phi is already in the worklist. */
2863
2864 static gimple *
2865 find_uninit_use (gphi *phi, unsigned uninit_opnds,
2866 vec<gphi *> *worklist,
2867 hash_set<gphi *> *added_to_worklist)
2868 {
2869 tree phi_result;
2870 use_operand_p use_p;
2871 gimple *use_stmt;
2872 imm_use_iterator iter;
2873 pred_chain_union def_preds = vNULL;
2874 gimple *ret = NULL;
2875
2876 phi_result = gimple_phi_result (phi);
2877
2878 FOR_EACH_IMM_USE_FAST (use_p, iter, phi_result)
2879 {
2880 basic_block use_bb;
2881
2882 use_stmt = USE_STMT (use_p);
2883 if (is_gimple_debug (use_stmt))
2884 continue;
2885
2886 if (gphi *use_phi = dyn_cast<gphi *> (use_stmt))
2887 use_bb = gimple_phi_arg_edge (use_phi,
2888 PHI_ARG_INDEX_FROM_USE (use_p))->src;
2889 else
2890 use_bb = gimple_bb (use_stmt);
2891
2892 hash_set<gphi *> visited_phis;
2893 if (is_use_properly_guarded (use_stmt, use_bb, phi, uninit_opnds,
2894 &def_preds, &visited_phis))
2895 continue;
2896
2897 if (dump_file && (dump_flags & TDF_DETAILS))
2898 {
2899 fprintf (dump_file, "[CHECK]: Found unguarded use: ");
2900 print_gimple_stmt (dump_file, use_stmt, 0);
2901 }
2902 /* Found one real use, return. */
2903 if (gimple_code (use_stmt) != GIMPLE_PHI)
2904 {
2905 ret = use_stmt;
2906 break;
2907 }
2908
2909 /* Found a phi use that is not guarded,
2910 add the phi to the worklist. */
2911 if (!added_to_worklist->add (as_a<gphi *> (use_stmt)))
2912 {
2913 if (dump_file && (dump_flags & TDF_DETAILS))
2914 {
2915 fprintf (dump_file, "[WORKLIST]: Update worklist with phi: ");
2916 print_gimple_stmt (dump_file, use_stmt, 0);
2917 }
2918
2919 worklist->safe_push (as_a<gphi *> (use_stmt));
2920 possibly_undefined_names->add (phi_result);
2921 }
2922 }
2923
2924 destroy_predicate_vecs (&def_preds);
2925 return ret;
2926 }
2927
2928 /* Look for inputs to PHI that are SSA_NAMEs that have empty definitions
2929 and gives warning if there exists a runtime path from the entry to a
2930 use of the PHI def that does not contain a definition. In other words,
2931 the warning is on the real use. The more dead paths that can be pruned
2932 by the compiler, the fewer false positives the warning is. WORKLIST
2933 is a vector of candidate phis to be examined. ADDED_TO_WORKLIST is
2934 a pointer set tracking if the new phi is added to the worklist or not. */
2935
2936 static void
2937 warn_uninitialized_phi (gphi *phi, vec<gphi *> *worklist,
2938 hash_set<gphi *> *added_to_worklist)
2939 {
2940 unsigned uninit_opnds;
2941 gimple *uninit_use_stmt = 0;
2942 tree uninit_op;
2943 int phiarg_index;
2944 location_t loc;
2945
2946 /* Don't look at virtual operands. */
2947 if (virtual_operand_p (gimple_phi_result (phi)))
2948 return;
2949
2950 uninit_opnds = compute_uninit_opnds_pos (phi);
2951
2952 if (MASK_EMPTY (uninit_opnds))
2953 return;
2954
2955 if (dump_file && (dump_flags & TDF_DETAILS))
2956 {
2957 fprintf (dump_file, "[CHECK]: examining phi: ");
2958 print_gimple_stmt (dump_file, phi, 0);
2959 }
2960
2961 /* Now check if we have any use of the value without proper guard. */
2962 uninit_use_stmt = find_uninit_use (phi, uninit_opnds,
2963 worklist, added_to_worklist);
2964
2965 /* All uses are properly guarded. */
2966 if (!uninit_use_stmt)
2967 return;
2968
2969 phiarg_index = MASK_FIRST_SET_BIT (uninit_opnds);
2970 uninit_op = gimple_phi_arg_def (phi, phiarg_index);
2971 if (SSA_NAME_VAR (uninit_op) == NULL_TREE)
2972 return;
2973 if (gimple_phi_arg_has_location (phi, phiarg_index))
2974 loc = gimple_phi_arg_location (phi, phiarg_index);
2975 else
2976 loc = UNKNOWN_LOCATION;
2977 warn_uninit (OPT_Wmaybe_uninitialized, uninit_op, SSA_NAME_VAR (uninit_op),
2978 SSA_NAME_VAR (uninit_op),
2979 "%qD may be used uninitialized in this function",
2980 uninit_use_stmt, loc);
2981 }
2982
2983 static bool
2984 gate_warn_uninitialized (void)
2985 {
2986 return warn_uninitialized || warn_maybe_uninitialized;
2987 }
2988
2989 namespace {
2990
2991 const pass_data pass_data_late_warn_uninitialized =
2992 {
2993 GIMPLE_PASS, /* type */
2994 "uninit", /* name */
2995 OPTGROUP_NONE, /* optinfo_flags */
2996 TV_NONE, /* tv_id */
2997 PROP_ssa, /* properties_required */
2998 0, /* properties_provided */
2999 0, /* properties_destroyed */
3000 0, /* todo_flags_start */
3001 0, /* todo_flags_finish */
3002 };
3003
3004 class pass_late_warn_uninitialized : public gimple_opt_pass
3005 {
3006 public:
3007 pass_late_warn_uninitialized (gcc::context *ctxt)
3008 : gimple_opt_pass (pass_data_late_warn_uninitialized, ctxt)
3009 {}
3010
3011 /* opt_pass methods: */
3012 opt_pass *clone () { return new pass_late_warn_uninitialized (m_ctxt); }
3013 virtual bool gate (function *) { return gate_warn_uninitialized (); }
3014 virtual unsigned int execute (function *);
3015
3016 }; // class pass_late_warn_uninitialized
3017
3018 unsigned int
3019 pass_late_warn_uninitialized::execute (function *fun)
3020 {
3021 basic_block bb;
3022 gphi_iterator gsi;
3023 vec<gphi *> worklist = vNULL;
3024
3025 calculate_dominance_info (CDI_DOMINATORS);
3026 calculate_dominance_info (CDI_POST_DOMINATORS);
3027 /* Re-do the plain uninitialized variable check, as optimization may have
3028 straightened control flow. Do this first so that we don't accidentally
3029 get a "may be" warning when we'd have seen an "is" warning later. */
3030 warn_uninitialized_vars (/*warn_maybe_uninitialized=*/1);
3031
3032 timevar_push (TV_TREE_UNINIT);
3033
3034 possibly_undefined_names = new hash_set<tree>;
3035 hash_set<gphi *> added_to_worklist;
3036
3037 /* Initialize worklist */
3038 FOR_EACH_BB_FN (bb, fun)
3039 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3040 {
3041 gphi *phi = gsi.phi ();
3042 size_t n, i;
3043
3044 n = gimple_phi_num_args (phi);
3045
3046 /* Don't look at virtual operands. */
3047 if (virtual_operand_p (gimple_phi_result (phi)))
3048 continue;
3049
3050 for (i = 0; i < n; ++i)
3051 {
3052 tree op = gimple_phi_arg_def (phi, i);
3053 if (TREE_CODE (op) == SSA_NAME && uninit_undefined_value_p (op))
3054 {
3055 worklist.safe_push (phi);
3056 added_to_worklist.add (phi);
3057 if (dump_file && (dump_flags & TDF_DETAILS))
3058 {
3059 fprintf (dump_file, "[WORKLIST]: add to initial list: ");
3060 print_gimple_stmt (dump_file, phi, 0);
3061 }
3062 break;
3063 }
3064 }
3065 }
3066
3067 while (worklist.length () != 0)
3068 {
3069 gphi *cur_phi = 0;
3070 cur_phi = worklist.pop ();
3071 warn_uninitialized_phi (cur_phi, &worklist, &added_to_worklist);
3072 }
3073
3074 worklist.release ();
3075 delete possibly_undefined_names;
3076 possibly_undefined_names = NULL;
3077 free_dominance_info (CDI_POST_DOMINATORS);
3078 timevar_pop (TV_TREE_UNINIT);
3079 return 0;
3080 }
3081
3082 } // anon namespace
3083
3084 gimple_opt_pass *
3085 make_pass_late_warn_uninitialized (gcc::context *ctxt)
3086 {
3087 return new pass_late_warn_uninitialized (ctxt);
3088 }
3089
3090 static unsigned int
3091 execute_early_warn_uninitialized (void)
3092 {
3093 /* Currently, this pass runs always but
3094 execute_late_warn_uninitialized only runs with optimization. With
3095 optimization we want to warn about possible uninitialized as late
3096 as possible, thus don't do it here. However, without
3097 optimization we need to warn here about "may be uninitialized". */
3098 calculate_dominance_info (CDI_POST_DOMINATORS);
3099
3100 warn_uninitialized_vars (/*warn_maybe_uninitialized=*/!optimize);
3101
3102 /* Post-dominator information cannot be reliably updated. Free it
3103 after the use. */
3104
3105 free_dominance_info (CDI_POST_DOMINATORS);
3106 return 0;
3107 }
3108
3109 namespace {
3110
3111 const pass_data pass_data_early_warn_uninitialized =
3112 {
3113 GIMPLE_PASS, /* type */
3114 "*early_warn_uninitialized", /* name */
3115 OPTGROUP_NONE, /* optinfo_flags */
3116 TV_TREE_UNINIT, /* tv_id */
3117 PROP_ssa, /* properties_required */
3118 0, /* properties_provided */
3119 0, /* properties_destroyed */
3120 0, /* todo_flags_start */
3121 0, /* todo_flags_finish */
3122 };
3123
3124 class pass_early_warn_uninitialized : public gimple_opt_pass
3125 {
3126 public:
3127 pass_early_warn_uninitialized (gcc::context *ctxt)
3128 : gimple_opt_pass (pass_data_early_warn_uninitialized, ctxt)
3129 {}
3130
3131 /* opt_pass methods: */
3132 virtual bool gate (function *) { return gate_warn_uninitialized (); }
3133 virtual unsigned int execute (function *)
3134 {
3135 return execute_early_warn_uninitialized ();
3136 }
3137
3138 }; // class pass_early_warn_uninitialized
3139
3140 } // anon namespace
3141
3142 gimple_opt_pass *
3143 make_pass_early_warn_uninitialized (gcc::context *ctxt)
3144 {
3145 return new pass_early_warn_uninitialized (ctxt);
3146 }