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