2017-02-20 Paul Thomas <pault@gcc.gnu.org>
[official-gcc.git] / gcc / tree-ssa-uninit.c
blob79208d6d1c0cb5beb058d78b1dd1500b771d3f15
1 /* Predicate aware uninitialized variable warning.
2 Copyright (C) 2001-2017 Free Software Foundation, Inc.
3 Contributed by Xinliang David Li <davidxl@google.com>
5 This file is part of GCC.
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.
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.
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/>. */
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "backend.h"
25 #include "tree.h"
26 #include "gimple.h"
27 #include "tree-pass.h"
28 #include "ssa.h"
29 #include "gimple-pretty-print.h"
30 #include "diagnostic-core.h"
31 #include "fold-const.h"
32 #include "gimple-iterator.h"
33 #include "tree-ssa.h"
34 #include "params.h"
35 #include "tree-cfg.h"
37 /* This implements the pass that does predicate aware warning on uses of
38 possibly uninitialized variables. The pass first collects the set of
39 possibly uninitialized SSA names. For each such name, it walks through
40 all its immediate uses. For each immediate use, it rebuilds the condition
41 expression (the predicate) that guards the use. The predicate is then
42 examined to see if the variable is always defined under that same condition.
43 This is done either by pruning the unrealizable paths that lead to the
44 default definitions or by checking if the predicate set that guards the
45 defining paths is a superset of the use predicate. */
47 /* Max PHI args we can handle in pass. */
48 const unsigned max_phi_args = 32;
50 /* Pointer set of potentially undefined ssa names, i.e.,
51 ssa names that are defined by phi with operands that
52 are not defined or potentially undefined. */
53 static hash_set<tree> *possibly_undefined_names = 0;
55 /* Bit mask handling macros. */
56 #define MASK_SET_BIT(mask, pos) mask |= (1 << pos)
57 #define MASK_TEST_BIT(mask, pos) (mask & (1 << pos))
58 #define MASK_EMPTY(mask) (mask == 0)
60 /* Returns the first bit position (starting from LSB)
61 in mask that is non zero. Returns -1 if the mask is empty. */
62 static int
63 get_mask_first_set_bit (unsigned mask)
65 int pos = 0;
66 if (mask == 0)
67 return -1;
69 while ((mask & (1 << pos)) == 0)
70 pos++;
72 return pos;
74 #define MASK_FIRST_SET_BIT(mask) get_mask_first_set_bit (mask)
76 /* Return true if T, an SSA_NAME, has an undefined value. */
77 static bool
78 has_undefined_value_p (tree t)
80 return (ssa_undefined_value_p (t)
81 || (possibly_undefined_names
82 && possibly_undefined_names->contains (t)));
85 /* Like has_undefined_value_p, but don't return true if TREE_NO_WARNING
86 is set on SSA_NAME_VAR. */
88 static inline bool
89 uninit_undefined_value_p (tree t)
91 if (!has_undefined_value_p (t))
92 return false;
93 if (SSA_NAME_VAR (t) && TREE_NO_WARNING (SSA_NAME_VAR (t)))
94 return false;
95 return true;
98 /* Emit warnings for uninitialized variables. This is done in two passes.
100 The first pass notices real uses of SSA names with undefined values.
101 Such uses are unconditionally uninitialized, and we can be certain that
102 such a use is a mistake. This pass is run before most optimizations,
103 so that we catch as many as we can.
105 The second pass follows PHI nodes to find uses that are potentially
106 uninitialized. In this case we can't necessarily prove that the use
107 is really uninitialized. This pass is run after most optimizations,
108 so that we thread as many jumps and possible, and delete as much dead
109 code as possible, in order to reduce false positives. We also look
110 again for plain uninitialized variables, since optimization may have
111 changed conditionally uninitialized to unconditionally uninitialized. */
113 /* Emit a warning for EXPR based on variable VAR at the point in the
114 program T, an SSA_NAME, is used being uninitialized. The exact
115 warning text is in MSGID and DATA is the gimple stmt with info about
116 the location in source code. When DATA is a GIMPLE_PHI, PHIARG_IDX
117 gives which argument of the phi node to take the location from. WC
118 is the warning code. */
120 static void
121 warn_uninit (enum opt_code wc, tree t, tree expr, tree var,
122 const char *gmsgid, void *data, location_t phiarg_loc)
124 gimple *context = (gimple *) data;
125 location_t location, cfun_loc;
126 expanded_location xloc, floc;
128 /* Ignore COMPLEX_EXPR as initializing only a part of a complex
129 turns in a COMPLEX_EXPR with the not initialized part being
130 set to its previous (undefined) value. */
131 if (is_gimple_assign (context)
132 && gimple_assign_rhs_code (context) == COMPLEX_EXPR)
133 return;
134 if (!has_undefined_value_p (t))
135 return;
137 /* Anonymous SSA_NAMEs shouldn't be uninitialized, but ssa_undefined_value_p
138 can return true if the def stmt of anonymous SSA_NAME is COMPLEX_EXPR
139 created for conversion from scalar to complex. Use the underlying var of
140 the COMPLEX_EXPRs real part in that case. See PR71581. */
141 if (expr == NULL_TREE
142 && var == NULL_TREE
143 && SSA_NAME_VAR (t) == NULL_TREE
144 && is_gimple_assign (SSA_NAME_DEF_STMT (t))
145 && gimple_assign_rhs_code (SSA_NAME_DEF_STMT (t)) == COMPLEX_EXPR)
147 tree v = gimple_assign_rhs1 (SSA_NAME_DEF_STMT (t));
148 if (TREE_CODE (v) == SSA_NAME
149 && has_undefined_value_p (v)
150 && zerop (gimple_assign_rhs2 (SSA_NAME_DEF_STMT (t))))
152 expr = SSA_NAME_VAR (v);
153 var = expr;
157 if (expr == NULL_TREE)
158 return;
160 /* TREE_NO_WARNING either means we already warned, or the front end
161 wishes to suppress the warning. */
162 if ((context
163 && (gimple_no_warning_p (context)
164 || (gimple_assign_single_p (context)
165 && TREE_NO_WARNING (gimple_assign_rhs1 (context)))))
166 || TREE_NO_WARNING (expr))
167 return;
169 if (context != NULL && gimple_has_location (context))
170 location = gimple_location (context);
171 else if (phiarg_loc != UNKNOWN_LOCATION)
172 location = phiarg_loc;
173 else
174 location = DECL_SOURCE_LOCATION (var);
175 location = linemap_resolve_location (line_table, location,
176 LRK_SPELLING_LOCATION, NULL);
177 cfun_loc = DECL_SOURCE_LOCATION (cfun->decl);
178 xloc = expand_location (location);
179 floc = expand_location (cfun_loc);
180 if (warning_at (location, wc, gmsgid, expr))
182 TREE_NO_WARNING (expr) = 1;
184 if (location == DECL_SOURCE_LOCATION (var))
185 return;
186 if (xloc.file != floc.file
187 || linemap_location_before_p (line_table, location, cfun_loc)
188 || linemap_location_before_p (line_table, cfun->function_end_locus,
189 location))
190 inform (DECL_SOURCE_LOCATION (var), "%qD was declared here", var);
194 static unsigned int
195 warn_uninitialized_vars (bool warn_possibly_uninitialized)
197 gimple_stmt_iterator gsi;
198 basic_block bb;
200 FOR_EACH_BB_FN (bb, cfun)
202 basic_block succ = single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun));
203 bool always_executed = dominated_by_p (CDI_POST_DOMINATORS, succ, bb);
204 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
206 gimple *stmt = gsi_stmt (gsi);
207 use_operand_p use_p;
208 ssa_op_iter op_iter;
209 tree use;
211 if (is_gimple_debug (stmt))
212 continue;
214 /* We only do data flow with SSA_NAMEs, so that's all we
215 can warn about. */
216 FOR_EACH_SSA_USE_OPERAND (use_p, stmt, op_iter, SSA_OP_USE)
218 /* BIT_INSERT_EXPR first operand should not be considered
219 a use for the purpose of uninit warnings. */
220 if (gassign *ass = dyn_cast <gassign *> (stmt))
222 if (gimple_assign_rhs_code (ass) == BIT_INSERT_EXPR
223 && use_p->use == gimple_assign_rhs1_ptr (ass))
224 continue;
226 use = USE_FROM_PTR (use_p);
227 if (always_executed)
228 warn_uninit (OPT_Wuninitialized, use, SSA_NAME_VAR (use),
229 SSA_NAME_VAR (use),
230 "%qD is used uninitialized in this function", stmt,
231 UNKNOWN_LOCATION);
232 else if (warn_possibly_uninitialized)
233 warn_uninit (OPT_Wmaybe_uninitialized, use, SSA_NAME_VAR (use),
234 SSA_NAME_VAR (use),
235 "%qD may be used uninitialized in this function",
236 stmt, UNKNOWN_LOCATION);
239 /* For memory the only cheap thing we can do is see if we
240 have a use of the default def of the virtual operand.
241 ??? Not so cheap would be to use the alias oracle via
242 walk_aliased_vdefs, if we don't find any aliasing vdef
243 warn as is-used-uninitialized, if we don't find an aliasing
244 vdef that kills our use (stmt_kills_ref_p), warn as
245 may-be-used-uninitialized. But this walk is quadratic and
246 so must be limited which means we would miss warning
247 opportunities. */
248 use = gimple_vuse (stmt);
249 if (use
250 && gimple_assign_single_p (stmt)
251 && !gimple_vdef (stmt)
252 && SSA_NAME_IS_DEFAULT_DEF (use))
254 tree rhs = gimple_assign_rhs1 (stmt);
255 tree base = get_base_address (rhs);
257 /* Do not warn if it can be initialized outside this function. */
258 if (!VAR_P (base)
259 || DECL_HARD_REGISTER (base)
260 || is_global_var (base))
261 continue;
263 if (always_executed)
264 warn_uninit (OPT_Wuninitialized, use, gimple_assign_rhs1 (stmt),
265 base, "%qE is used uninitialized in this function",
266 stmt, UNKNOWN_LOCATION);
267 else if (warn_possibly_uninitialized)
268 warn_uninit (OPT_Wmaybe_uninitialized, use,
269 gimple_assign_rhs1 (stmt), base,
270 "%qE may be used uninitialized in this function",
271 stmt, UNKNOWN_LOCATION);
276 return 0;
279 /* Checks if the operand OPND of PHI is defined by
280 another phi with one operand defined by this PHI,
281 but the rest operands are all defined. If yes,
282 returns true to skip this operand as being
283 redundant. Can be enhanced to be more general. */
285 static bool
286 can_skip_redundant_opnd (tree opnd, gimple *phi)
288 gimple *op_def;
289 tree phi_def;
290 int i, n;
292 phi_def = gimple_phi_result (phi);
293 op_def = SSA_NAME_DEF_STMT (opnd);
294 if (gimple_code (op_def) != GIMPLE_PHI)
295 return false;
296 n = gimple_phi_num_args (op_def);
297 for (i = 0; i < n; ++i)
299 tree op = gimple_phi_arg_def (op_def, i);
300 if (TREE_CODE (op) != SSA_NAME)
301 continue;
302 if (op != phi_def && uninit_undefined_value_p (op))
303 return false;
306 return true;
309 /* Returns a bit mask holding the positions of arguments in PHI
310 that have empty (or possibly empty) definitions. */
312 static unsigned
313 compute_uninit_opnds_pos (gphi *phi)
315 size_t i, n;
316 unsigned uninit_opnds = 0;
318 n = gimple_phi_num_args (phi);
319 /* Bail out for phi with too many args. */
320 if (n > max_phi_args)
321 return 0;
323 for (i = 0; i < n; ++i)
325 tree op = gimple_phi_arg_def (phi, i);
326 if (TREE_CODE (op) == SSA_NAME
327 && uninit_undefined_value_p (op)
328 && !can_skip_redundant_opnd (op, phi))
330 if (cfun->has_nonlocal_label || cfun->calls_setjmp)
332 /* Ignore SSA_NAMEs that appear on abnormal edges
333 somewhere. */
334 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
335 continue;
337 MASK_SET_BIT (uninit_opnds, i);
340 return uninit_opnds;
343 /* Find the immediate postdominator PDOM of the specified
344 basic block BLOCK. */
346 static inline basic_block
347 find_pdom (basic_block block)
349 if (block == EXIT_BLOCK_PTR_FOR_FN (cfun))
350 return EXIT_BLOCK_PTR_FOR_FN (cfun);
351 else
353 basic_block bb = get_immediate_dominator (CDI_POST_DOMINATORS, block);
354 if (!bb)
355 return EXIT_BLOCK_PTR_FOR_FN (cfun);
356 return bb;
360 /* Find the immediate DOM of the specified basic block BLOCK. */
362 static inline basic_block
363 find_dom (basic_block block)
365 if (block == ENTRY_BLOCK_PTR_FOR_FN (cfun))
366 return ENTRY_BLOCK_PTR_FOR_FN (cfun);
367 else
369 basic_block bb = get_immediate_dominator (CDI_DOMINATORS, block);
370 if (!bb)
371 return ENTRY_BLOCK_PTR_FOR_FN (cfun);
372 return bb;
376 /* Returns true if BB1 is postdominating BB2 and BB1 is
377 not a loop exit bb. The loop exit bb check is simple and does
378 not cover all cases. */
380 static bool
381 is_non_loop_exit_postdominating (basic_block bb1, basic_block bb2)
383 if (!dominated_by_p (CDI_POST_DOMINATORS, bb2, bb1))
384 return false;
386 if (single_pred_p (bb1) && !single_succ_p (bb2))
387 return false;
389 return true;
392 /* Find the closest postdominator of a specified BB, which is control
393 equivalent to BB. */
395 static inline basic_block
396 find_control_equiv_block (basic_block bb)
398 basic_block pdom;
400 pdom = find_pdom (bb);
402 /* Skip the postdominating bb that is also loop exit. */
403 if (!is_non_loop_exit_postdominating (pdom, bb))
404 return NULL;
406 if (dominated_by_p (CDI_DOMINATORS, pdom, bb))
407 return pdom;
409 return NULL;
412 #define MAX_NUM_CHAINS 8
413 #define MAX_CHAIN_LEN 5
414 #define MAX_POSTDOM_CHECK 8
415 #define MAX_SWITCH_CASES 40
417 /* Computes the control dependence chains (paths of edges)
418 for DEP_BB up to the dominating basic block BB (the head node of a
419 chain should be dominated by it). CD_CHAINS is pointer to an
420 array holding the result chains. CUR_CD_CHAIN is the current
421 chain being computed. *NUM_CHAINS is total number of chains. The
422 function returns true if the information is successfully computed,
423 return false if there is no control dependence or not computed. */
425 static bool
426 compute_control_dep_chain (basic_block bb, basic_block dep_bb,
427 vec<edge> *cd_chains,
428 size_t *num_chains,
429 vec<edge> *cur_cd_chain,
430 int *num_calls)
432 edge_iterator ei;
433 edge e;
434 size_t i;
435 bool found_cd_chain = false;
436 size_t cur_chain_len = 0;
438 if (EDGE_COUNT (bb->succs) < 2)
439 return false;
441 if (*num_calls > PARAM_VALUE (PARAM_UNINIT_CONTROL_DEP_ATTEMPTS))
442 return false;
443 ++*num_calls;
445 /* Could use a set instead. */
446 cur_chain_len = cur_cd_chain->length ();
447 if (cur_chain_len > MAX_CHAIN_LEN)
448 return false;
450 for (i = 0; i < cur_chain_len; i++)
452 edge e = (*cur_cd_chain)[i];
453 /* Cycle detected. */
454 if (e->src == bb)
455 return false;
458 FOR_EACH_EDGE (e, ei, bb->succs)
460 basic_block cd_bb;
461 int post_dom_check = 0;
462 if (e->flags & (EDGE_FAKE | EDGE_ABNORMAL))
463 continue;
465 cd_bb = e->dest;
466 cur_cd_chain->safe_push (e);
467 while (!is_non_loop_exit_postdominating (cd_bb, bb))
469 if (cd_bb == dep_bb)
471 /* Found a direct control dependence. */
472 if (*num_chains < MAX_NUM_CHAINS)
474 cd_chains[*num_chains] = cur_cd_chain->copy ();
475 (*num_chains)++;
477 found_cd_chain = true;
478 /* Check path from next edge. */
479 break;
482 /* Now check if DEP_BB is indirectly control dependent on BB. */
483 if (compute_control_dep_chain (cd_bb, dep_bb, cd_chains, num_chains,
484 cur_cd_chain, num_calls))
486 found_cd_chain = true;
487 break;
490 cd_bb = find_pdom (cd_bb);
491 post_dom_check++;
492 if (cd_bb == EXIT_BLOCK_PTR_FOR_FN (cfun)
493 || post_dom_check > MAX_POSTDOM_CHECK)
494 break;
496 cur_cd_chain->pop ();
497 gcc_assert (cur_cd_chain->length () == cur_chain_len);
499 gcc_assert (cur_cd_chain->length () == cur_chain_len);
501 return found_cd_chain;
504 /* The type to represent a simple predicate. */
506 struct pred_info
508 tree pred_lhs;
509 tree pred_rhs;
510 enum tree_code cond_code;
511 bool invert;
514 /* The type to represent a sequence of predicates grouped
515 with .AND. operation. */
517 typedef vec<pred_info, va_heap, vl_ptr> pred_chain;
519 /* The type to represent a sequence of pred_chains grouped
520 with .OR. operation. */
522 typedef vec<pred_chain, va_heap, vl_ptr> pred_chain_union;
524 /* Converts the chains of control dependence edges into a set of
525 predicates. A control dependence chain is represented by a vector
526 edges. DEP_CHAINS points to an array of dependence chains.
527 NUM_CHAINS is the size of the chain array. One edge in a dependence
528 chain is mapped to predicate expression represented by pred_info
529 type. One dependence chain is converted to a composite predicate that
530 is the result of AND operation of pred_info mapped to each edge.
531 A composite predicate is presented by a vector of pred_info. On
532 return, *PREDS points to the resulting array of composite predicates.
533 *NUM_PREDS is the number of composite predictes. */
535 static bool
536 convert_control_dep_chain_into_preds (vec<edge> *dep_chains,
537 size_t num_chains,
538 pred_chain_union *preds)
540 bool has_valid_pred = false;
541 size_t i, j;
542 if (num_chains == 0 || num_chains >= MAX_NUM_CHAINS)
543 return false;
545 /* Now convert the control dep chain into a set
546 of predicates. */
547 preds->reserve (num_chains);
549 for (i = 0; i < num_chains; i++)
551 vec<edge> one_cd_chain = dep_chains[i];
553 has_valid_pred = false;
554 pred_chain t_chain = vNULL;
555 for (j = 0; j < one_cd_chain.length (); j++)
557 gimple *cond_stmt;
558 gimple_stmt_iterator gsi;
559 basic_block guard_bb;
560 pred_info one_pred;
561 edge e;
563 e = one_cd_chain[j];
564 guard_bb = e->src;
565 gsi = gsi_last_bb (guard_bb);
566 if (gsi_end_p (gsi))
568 has_valid_pred = false;
569 break;
571 cond_stmt = gsi_stmt (gsi);
572 if (is_gimple_call (cond_stmt) && EDGE_COUNT (e->src->succs) >= 2)
573 /* Ignore EH edge. Can add assertion on the other edge's flag. */
574 continue;
575 /* Skip if there is essentially one succesor. */
576 if (EDGE_COUNT (e->src->succs) == 2)
578 edge e1;
579 edge_iterator ei1;
580 bool skip = false;
582 FOR_EACH_EDGE (e1, ei1, e->src->succs)
584 if (EDGE_COUNT (e1->dest->succs) == 0)
586 skip = true;
587 break;
590 if (skip)
591 continue;
593 if (gimple_code (cond_stmt) == GIMPLE_COND)
595 one_pred.pred_lhs = gimple_cond_lhs (cond_stmt);
596 one_pred.pred_rhs = gimple_cond_rhs (cond_stmt);
597 one_pred.cond_code = gimple_cond_code (cond_stmt);
598 one_pred.invert = !!(e->flags & EDGE_FALSE_VALUE);
599 t_chain.safe_push (one_pred);
600 has_valid_pred = true;
602 else if (gswitch *gs = dyn_cast<gswitch *> (cond_stmt))
604 /* Avoid quadratic behavior. */
605 if (gimple_switch_num_labels (gs) > MAX_SWITCH_CASES)
607 has_valid_pred = false;
608 break;
610 /* Find the case label. */
611 tree l = NULL_TREE;
612 unsigned idx;
613 for (idx = 0; idx < gimple_switch_num_labels (gs); ++idx)
615 tree tl = gimple_switch_label (gs, idx);
616 if (e->dest == label_to_block (CASE_LABEL (tl)))
618 if (!l)
619 l = tl;
620 else
622 l = NULL_TREE;
623 break;
627 /* If more than one label reaches this block or the case
628 label doesn't have a single value (like the default one)
629 fail. */
630 if (!l
631 || !CASE_LOW (l)
632 || (CASE_HIGH (l)
633 && !operand_equal_p (CASE_LOW (l), CASE_HIGH (l), 0)))
635 has_valid_pred = false;
636 break;
638 one_pred.pred_lhs = gimple_switch_index (gs);
639 one_pred.pred_rhs = CASE_LOW (l);
640 one_pred.cond_code = EQ_EXPR;
641 one_pred.invert = false;
642 t_chain.safe_push (one_pred);
643 has_valid_pred = true;
645 else
647 has_valid_pred = false;
648 break;
652 if (!has_valid_pred)
653 break;
654 else
655 preds->safe_push (t_chain);
657 return has_valid_pred;
660 /* Computes all control dependence chains for USE_BB. The control
661 dependence chains are then converted to an array of composite
662 predicates pointed to by PREDS. PHI_BB is the basic block of
663 the phi whose result is used in USE_BB. */
665 static bool
666 find_predicates (pred_chain_union *preds,
667 basic_block phi_bb,
668 basic_block use_bb)
670 size_t num_chains = 0, i;
671 int num_calls = 0;
672 vec<edge> dep_chains[MAX_NUM_CHAINS];
673 auto_vec<edge, MAX_CHAIN_LEN + 1> cur_chain;
674 bool has_valid_pred = false;
675 basic_block cd_root = 0;
677 /* First find the closest bb that is control equivalent to PHI_BB
678 that also dominates USE_BB. */
679 cd_root = phi_bb;
680 while (dominated_by_p (CDI_DOMINATORS, use_bb, cd_root))
682 basic_block ctrl_eq_bb = find_control_equiv_block (cd_root);
683 if (ctrl_eq_bb && dominated_by_p (CDI_DOMINATORS, use_bb, ctrl_eq_bb))
684 cd_root = ctrl_eq_bb;
685 else
686 break;
689 compute_control_dep_chain (cd_root, use_bb, dep_chains, &num_chains,
690 &cur_chain, &num_calls);
692 has_valid_pred
693 = convert_control_dep_chain_into_preds (dep_chains, num_chains, preds);
694 for (i = 0; i < num_chains; i++)
695 dep_chains[i].release ();
696 return has_valid_pred;
699 /* Computes the set of incoming edges of PHI that have non empty
700 definitions of a phi chain. The collection will be done
701 recursively on operands that are defined by phis. CD_ROOT
702 is the control dependence root. *EDGES holds the result, and
703 VISITED_PHIS is a pointer set for detecting cycles. */
705 static void
706 collect_phi_def_edges (gphi *phi, basic_block cd_root,
707 auto_vec<edge> *edges,
708 hash_set<gimple *> *visited_phis)
710 size_t i, n;
711 edge opnd_edge;
712 tree opnd;
714 if (visited_phis->add (phi))
715 return;
717 n = gimple_phi_num_args (phi);
718 for (i = 0; i < n; i++)
720 opnd_edge = gimple_phi_arg_edge (phi, i);
721 opnd = gimple_phi_arg_def (phi, i);
723 if (TREE_CODE (opnd) != SSA_NAME)
725 if (dump_file && (dump_flags & TDF_DETAILS))
727 fprintf (dump_file, "\n[CHECK] Found def edge %d in ", (int) i);
728 print_gimple_stmt (dump_file, phi, 0, 0);
730 edges->safe_push (opnd_edge);
732 else
734 gimple *def = SSA_NAME_DEF_STMT (opnd);
736 if (gimple_code (def) == GIMPLE_PHI
737 && dominated_by_p (CDI_DOMINATORS, gimple_bb (def), cd_root))
738 collect_phi_def_edges (as_a<gphi *> (def), cd_root, edges,
739 visited_phis);
740 else if (!uninit_undefined_value_p (opnd))
742 if (dump_file && (dump_flags & TDF_DETAILS))
744 fprintf (dump_file, "\n[CHECK] Found def edge %d in ",
745 (int) i);
746 print_gimple_stmt (dump_file, phi, 0, 0);
748 edges->safe_push (opnd_edge);
754 /* For each use edge of PHI, computes all control dependence chains.
755 The control dependence chains are then converted to an array of
756 composite predicates pointed to by PREDS. */
758 static bool
759 find_def_preds (pred_chain_union *preds, gphi *phi)
761 size_t num_chains = 0, i, n;
762 vec<edge> dep_chains[MAX_NUM_CHAINS];
763 auto_vec<edge, MAX_CHAIN_LEN + 1> cur_chain;
764 auto_vec<edge> def_edges;
765 bool has_valid_pred = false;
766 basic_block phi_bb, cd_root = 0;
768 phi_bb = gimple_bb (phi);
769 /* First find the closest dominating bb to be
770 the control dependence root. */
771 cd_root = find_dom (phi_bb);
772 if (!cd_root)
773 return false;
775 hash_set<gimple *> visited_phis;
776 collect_phi_def_edges (phi, cd_root, &def_edges, &visited_phis);
778 n = def_edges.length ();
779 if (n == 0)
780 return false;
782 for (i = 0; i < n; i++)
784 size_t prev_nc, j;
785 int num_calls = 0;
786 edge opnd_edge;
788 opnd_edge = def_edges[i];
789 prev_nc = num_chains;
790 compute_control_dep_chain (cd_root, opnd_edge->src, dep_chains,
791 &num_chains, &cur_chain, &num_calls);
793 /* Now update the newly added chains with
794 the phi operand edge: */
795 if (EDGE_COUNT (opnd_edge->src->succs) > 1)
797 if (prev_nc == num_chains && num_chains < MAX_NUM_CHAINS)
798 dep_chains[num_chains++] = vNULL;
799 for (j = prev_nc; j < num_chains; j++)
800 dep_chains[j].safe_push (opnd_edge);
804 has_valid_pred
805 = convert_control_dep_chain_into_preds (dep_chains, num_chains, preds);
806 for (i = 0; i < num_chains; i++)
807 dep_chains[i].release ();
808 return has_valid_pred;
811 /* Dumps the predicates (PREDS) for USESTMT. */
813 static void
814 dump_predicates (gimple *usestmt, pred_chain_union preds, const char *msg)
816 size_t i, j;
817 pred_chain one_pred_chain = vNULL;
818 fprintf (dump_file, "%s", msg);
819 print_gimple_stmt (dump_file, usestmt, 0, 0);
820 fprintf (dump_file, "is guarded by :\n\n");
821 size_t num_preds = preds.length ();
822 /* Do some dumping here: */
823 for (i = 0; i < num_preds; i++)
825 size_t np;
827 one_pred_chain = preds[i];
828 np = one_pred_chain.length ();
830 for (j = 0; j < np; j++)
832 pred_info one_pred = one_pred_chain[j];
833 if (one_pred.invert)
834 fprintf (dump_file, " (.NOT.) ");
835 print_generic_expr (dump_file, one_pred.pred_lhs, 0);
836 fprintf (dump_file, " %s ", op_symbol_code (one_pred.cond_code));
837 print_generic_expr (dump_file, one_pred.pred_rhs, 0);
838 if (j < np - 1)
839 fprintf (dump_file, " (.AND.) ");
840 else
841 fprintf (dump_file, "\n");
843 if (i < num_preds - 1)
844 fprintf (dump_file, "(.OR.)\n");
845 else
846 fprintf (dump_file, "\n\n");
850 /* Destroys the predicate set *PREDS. */
852 static void
853 destroy_predicate_vecs (pred_chain_union *preds)
855 size_t i;
857 size_t n = preds->length ();
858 for (i = 0; i < n; i++)
859 (*preds)[i].release ();
860 preds->release ();
863 /* Computes the 'normalized' conditional code with operand
864 swapping and condition inversion. */
866 static enum tree_code
867 get_cmp_code (enum tree_code orig_cmp_code, bool swap_cond, bool invert)
869 enum tree_code tc = orig_cmp_code;
871 if (swap_cond)
872 tc = swap_tree_comparison (orig_cmp_code);
873 if (invert)
874 tc = invert_tree_comparison (tc, false);
876 switch (tc)
878 case LT_EXPR:
879 case LE_EXPR:
880 case GT_EXPR:
881 case GE_EXPR:
882 case EQ_EXPR:
883 case NE_EXPR:
884 break;
885 default:
886 return ERROR_MARK;
888 return tc;
891 /* Returns true if VAL falls in the range defined by BOUNDARY and CMPC, i.e.
892 all values in the range satisfies (x CMPC BOUNDARY) == true. */
894 static bool
895 is_value_included_in (tree val, tree boundary, enum tree_code cmpc)
897 bool inverted = false;
898 bool is_unsigned;
899 bool result;
901 /* Only handle integer constant here. */
902 if (TREE_CODE (val) != INTEGER_CST || TREE_CODE (boundary) != INTEGER_CST)
903 return true;
905 is_unsigned = TYPE_UNSIGNED (TREE_TYPE (val));
907 if (cmpc == GE_EXPR || cmpc == GT_EXPR || cmpc == NE_EXPR)
909 cmpc = invert_tree_comparison (cmpc, false);
910 inverted = true;
913 if (is_unsigned)
915 if (cmpc == EQ_EXPR)
916 result = tree_int_cst_equal (val, boundary);
917 else if (cmpc == LT_EXPR)
918 result = tree_int_cst_lt (val, boundary);
919 else
921 gcc_assert (cmpc == LE_EXPR);
922 result = tree_int_cst_le (val, boundary);
925 else
927 if (cmpc == EQ_EXPR)
928 result = tree_int_cst_equal (val, boundary);
929 else if (cmpc == LT_EXPR)
930 result = tree_int_cst_lt (val, boundary);
931 else
933 gcc_assert (cmpc == LE_EXPR);
934 result = (tree_int_cst_equal (val, boundary)
935 || tree_int_cst_lt (val, boundary));
939 if (inverted)
940 result ^= 1;
942 return result;
945 /* Returns true if PRED is common among all the predicate
946 chains (PREDS) (and therefore can be factored out).
947 NUM_PRED_CHAIN is the size of array PREDS. */
949 static bool
950 find_matching_predicate_in_rest_chains (pred_info pred,
951 pred_chain_union preds,
952 size_t num_pred_chains)
954 size_t i, j, n;
956 /* Trival case. */
957 if (num_pred_chains == 1)
958 return true;
960 for (i = 1; i < num_pred_chains; i++)
962 bool found = false;
963 pred_chain one_chain = preds[i];
964 n = one_chain.length ();
965 for (j = 0; j < n; j++)
967 pred_info pred2 = one_chain[j];
968 /* Can relax the condition comparison to not
969 use address comparison. However, the most common
970 case is that multiple control dependent paths share
971 a common path prefix, so address comparison should
972 be ok. */
974 if (operand_equal_p (pred2.pred_lhs, pred.pred_lhs, 0)
975 && operand_equal_p (pred2.pred_rhs, pred.pred_rhs, 0)
976 && pred2.invert == pred.invert)
978 found = true;
979 break;
982 if (!found)
983 return false;
985 return true;
988 /* Forward declaration. */
989 static bool is_use_properly_guarded (gimple *use_stmt,
990 basic_block use_bb,
991 gphi *phi,
992 unsigned uninit_opnds,
993 pred_chain_union *def_preds,
994 hash_set<gphi *> *visited_phis);
996 /* Returns true if all uninitialized opnds are pruned. Returns false
997 otherwise. PHI is the phi node with uninitialized operands,
998 UNINIT_OPNDS is the bitmap of the uninitialize operand positions,
999 FLAG_DEF is the statement defining the flag guarding the use of the
1000 PHI output, BOUNDARY_CST is the const value used in the predicate
1001 associated with the flag, CMP_CODE is the comparison code used in
1002 the predicate, VISITED_PHIS is the pointer set of phis visited, and
1003 VISITED_FLAG_PHIS is the pointer to the pointer set of flag definitions
1004 that are also phis.
1006 Example scenario:
1008 BB1:
1009 flag_1 = phi <0, 1> // (1)
1010 var_1 = phi <undef, some_val>
1013 BB2:
1014 flag_2 = phi <0, flag_1, flag_1> // (2)
1015 var_2 = phi <undef, var_1, var_1>
1016 if (flag_2 == 1)
1017 goto BB3;
1019 BB3:
1020 use of var_2 // (3)
1022 Because some flag arg in (1) is not constant, if we do not look into the
1023 flag phis recursively, it is conservatively treated as unknown and var_1
1024 is thought to be flowed into use at (3). Since var_1 is potentially
1025 uninitialized a false warning will be emitted.
1026 Checking recursively into (1), the compiler can find out that only some_val
1027 (which is defined) can flow into (3) which is OK. */
1029 static bool
1030 prune_uninit_phi_opnds (gphi *phi, unsigned uninit_opnds, gphi *flag_def,
1031 tree boundary_cst, enum tree_code cmp_code,
1032 hash_set<gphi *> *visited_phis,
1033 bitmap *visited_flag_phis)
1035 unsigned i;
1037 for (i = 0; i < MIN (max_phi_args, gimple_phi_num_args (flag_def)); i++)
1039 tree flag_arg;
1041 if (!MASK_TEST_BIT (uninit_opnds, i))
1042 continue;
1044 flag_arg = gimple_phi_arg_def (flag_def, i);
1045 if (!is_gimple_constant (flag_arg))
1047 gphi *flag_arg_def, *phi_arg_def;
1048 tree phi_arg;
1049 unsigned uninit_opnds_arg_phi;
1051 if (TREE_CODE (flag_arg) != SSA_NAME)
1052 return false;
1053 flag_arg_def = dyn_cast<gphi *> (SSA_NAME_DEF_STMT (flag_arg));
1054 if (!flag_arg_def)
1055 return false;
1057 phi_arg = gimple_phi_arg_def (phi, i);
1058 if (TREE_CODE (phi_arg) != SSA_NAME)
1059 return false;
1061 phi_arg_def = dyn_cast<gphi *> (SSA_NAME_DEF_STMT (phi_arg));
1062 if (!phi_arg_def)
1063 return false;
1065 if (gimple_bb (phi_arg_def) != gimple_bb (flag_arg_def))
1066 return false;
1068 if (!*visited_flag_phis)
1069 *visited_flag_phis = BITMAP_ALLOC (NULL);
1071 tree phi_result = gimple_phi_result (flag_arg_def);
1072 if (bitmap_bit_p (*visited_flag_phis, SSA_NAME_VERSION (phi_result)))
1073 return false;
1075 bitmap_set_bit (*visited_flag_phis,
1076 SSA_NAME_VERSION (gimple_phi_result (flag_arg_def)));
1078 /* Now recursively prune the uninitialized phi args. */
1079 uninit_opnds_arg_phi = compute_uninit_opnds_pos (phi_arg_def);
1080 if (!prune_uninit_phi_opnds
1081 (phi_arg_def, uninit_opnds_arg_phi, flag_arg_def, boundary_cst,
1082 cmp_code, visited_phis, visited_flag_phis))
1083 return false;
1085 phi_result = gimple_phi_result (flag_arg_def);
1086 bitmap_clear_bit (*visited_flag_phis, SSA_NAME_VERSION (phi_result));
1087 continue;
1090 /* Now check if the constant is in the guarded range. */
1091 if (is_value_included_in (flag_arg, boundary_cst, cmp_code))
1093 tree opnd;
1094 gimple *opnd_def;
1096 /* Now that we know that this undefined edge is not
1097 pruned. If the operand is defined by another phi,
1098 we can further prune the incoming edges of that
1099 phi by checking the predicates of this operands. */
1101 opnd = gimple_phi_arg_def (phi, i);
1102 opnd_def = SSA_NAME_DEF_STMT (opnd);
1103 if (gphi *opnd_def_phi = dyn_cast <gphi *> (opnd_def))
1105 edge opnd_edge;
1106 unsigned uninit_opnds2 = compute_uninit_opnds_pos (opnd_def_phi);
1107 if (!MASK_EMPTY (uninit_opnds2))
1109 pred_chain_union def_preds = vNULL;
1110 bool ok;
1111 opnd_edge = gimple_phi_arg_edge (phi, i);
1112 ok = is_use_properly_guarded (phi,
1113 opnd_edge->src,
1114 opnd_def_phi,
1115 uninit_opnds2,
1116 &def_preds,
1117 visited_phis);
1118 destroy_predicate_vecs (&def_preds);
1119 if (!ok)
1120 return false;
1123 else
1124 return false;
1128 return true;
1131 /* A helper function that determines if the predicate set
1132 of the use is not overlapping with that of the uninit paths.
1133 The most common senario of guarded use is in Example 1:
1134 Example 1:
1135 if (some_cond)
1137 x = ...;
1138 flag = true;
1141 ... some code ...
1143 if (flag)
1144 use (x);
1146 The real world examples are usually more complicated, but similar
1147 and usually result from inlining:
1149 bool init_func (int * x)
1151 if (some_cond)
1152 return false;
1153 *x = ..
1154 return true;
1157 void foo (..)
1159 int x;
1161 if (!init_func (&x))
1162 return;
1164 .. some_code ...
1165 use (x);
1168 Another possible use scenario is in the following trivial example:
1170 Example 2:
1171 if (n > 0)
1172 x = 1;
1174 if (n > 0)
1176 if (m < 2)
1177 .. = x;
1180 Predicate analysis needs to compute the composite predicate:
1182 1) 'x' use predicate: (n > 0) .AND. (m < 2)
1183 2) 'x' default value (non-def) predicate: .NOT. (n > 0)
1184 (the predicate chain for phi operand defs can be computed
1185 starting from a bb that is control equivalent to the phi's
1186 bb and is dominating the operand def.)
1188 and check overlapping:
1189 (n > 0) .AND. (m < 2) .AND. (.NOT. (n > 0))
1190 <==> false
1192 This implementation provides framework that can handle
1193 scenarios. (Note that many simple cases are handled properly
1194 without the predicate analysis -- this is due to jump threading
1195 transformation which eliminates the merge point thus makes
1196 path sensitive analysis unnecessary.)
1198 PHI is the phi node whose incoming (undefined) paths need to be
1199 pruned, and UNINIT_OPNDS is the bitmap holding uninit operand
1200 positions. VISITED_PHIS is the pointer set of phi stmts being
1201 checked. */
1203 static bool
1204 use_pred_not_overlap_with_undef_path_pred (pred_chain_union preds,
1205 gphi *phi, unsigned uninit_opnds,
1206 hash_set<gphi *> *visited_phis)
1208 unsigned int i, n;
1209 gimple *flag_def = 0;
1210 tree boundary_cst = 0;
1211 enum tree_code cmp_code;
1212 bool swap_cond = false;
1213 bool invert = false;
1214 pred_chain the_pred_chain = vNULL;
1215 bitmap visited_flag_phis = NULL;
1216 bool all_pruned = false;
1217 size_t num_preds = preds.length ();
1219 gcc_assert (num_preds > 0);
1220 /* Find within the common prefix of multiple predicate chains
1221 a predicate that is a comparison of a flag variable against
1222 a constant. */
1223 the_pred_chain = preds[0];
1224 n = the_pred_chain.length ();
1225 for (i = 0; i < n; i++)
1227 tree cond_lhs, cond_rhs, flag = 0;
1229 pred_info the_pred = the_pred_chain[i];
1231 invert = the_pred.invert;
1232 cond_lhs = the_pred.pred_lhs;
1233 cond_rhs = the_pred.pred_rhs;
1234 cmp_code = the_pred.cond_code;
1236 if (cond_lhs != NULL_TREE && TREE_CODE (cond_lhs) == SSA_NAME
1237 && cond_rhs != NULL_TREE && is_gimple_constant (cond_rhs))
1239 boundary_cst = cond_rhs;
1240 flag = cond_lhs;
1242 else if (cond_rhs != NULL_TREE && TREE_CODE (cond_rhs) == SSA_NAME
1243 && cond_lhs != NULL_TREE && is_gimple_constant (cond_lhs))
1245 boundary_cst = cond_lhs;
1246 flag = cond_rhs;
1247 swap_cond = true;
1250 if (!flag)
1251 continue;
1253 flag_def = SSA_NAME_DEF_STMT (flag);
1255 if (!flag_def)
1256 continue;
1258 if ((gimple_code (flag_def) == GIMPLE_PHI)
1259 && (gimple_bb (flag_def) == gimple_bb (phi))
1260 && find_matching_predicate_in_rest_chains (the_pred, preds,
1261 num_preds))
1262 break;
1264 flag_def = 0;
1267 if (!flag_def)
1268 return false;
1270 /* Now check all the uninit incoming edge has a constant flag value
1271 that is in conflict with the use guard/predicate. */
1272 cmp_code = get_cmp_code (cmp_code, swap_cond, invert);
1274 if (cmp_code == ERROR_MARK)
1275 return false;
1277 all_pruned = prune_uninit_phi_opnds
1278 (phi, uninit_opnds, as_a<gphi *> (flag_def), boundary_cst, cmp_code,
1279 visited_phis, &visited_flag_phis);
1281 if (visited_flag_phis)
1282 BITMAP_FREE (visited_flag_phis);
1284 return all_pruned;
1287 /* The helper function returns true if two predicates X1 and X2
1288 are equivalent. It assumes the expressions have already
1289 properly re-associated. */
1291 static inline bool
1292 pred_equal_p (pred_info x1, pred_info x2)
1294 enum tree_code c1, c2;
1295 if (!operand_equal_p (x1.pred_lhs, x2.pred_lhs, 0)
1296 || !operand_equal_p (x1.pred_rhs, x2.pred_rhs, 0))
1297 return false;
1299 c1 = x1.cond_code;
1300 if (x1.invert != x2.invert
1301 && TREE_CODE_CLASS (x2.cond_code) == tcc_comparison)
1302 c2 = invert_tree_comparison (x2.cond_code, false);
1303 else
1304 c2 = x2.cond_code;
1306 return c1 == c2;
1309 /* Returns true if the predication is testing !=. */
1311 static inline bool
1312 is_neq_relop_p (pred_info pred)
1315 return ((pred.cond_code == NE_EXPR && !pred.invert)
1316 || (pred.cond_code == EQ_EXPR && pred.invert));
1319 /* Returns true if pred is of the form X != 0. */
1321 static inline bool
1322 is_neq_zero_form_p (pred_info pred)
1324 if (!is_neq_relop_p (pred) || !integer_zerop (pred.pred_rhs)
1325 || TREE_CODE (pred.pred_lhs) != SSA_NAME)
1326 return false;
1327 return true;
1330 /* The helper function returns true if two predicates X1
1331 is equivalent to X2 != 0. */
1333 static inline bool
1334 pred_expr_equal_p (pred_info x1, tree x2)
1336 if (!is_neq_zero_form_p (x1))
1337 return false;
1339 return operand_equal_p (x1.pred_lhs, x2, 0);
1342 /* Returns true of the domain of single predicate expression
1343 EXPR1 is a subset of that of EXPR2. Returns false if it
1344 can not be proved. */
1346 static bool
1347 is_pred_expr_subset_of (pred_info expr1, pred_info expr2)
1349 enum tree_code code1, code2;
1351 if (pred_equal_p (expr1, expr2))
1352 return true;
1354 if ((TREE_CODE (expr1.pred_rhs) != INTEGER_CST)
1355 || (TREE_CODE (expr2.pred_rhs) != INTEGER_CST))
1356 return false;
1358 if (!operand_equal_p (expr1.pred_lhs, expr2.pred_lhs, 0))
1359 return false;
1361 code1 = expr1.cond_code;
1362 if (expr1.invert)
1363 code1 = invert_tree_comparison (code1, false);
1364 code2 = expr2.cond_code;
1365 if (expr2.invert)
1366 code2 = invert_tree_comparison (code2, false);
1368 if ((code1 == EQ_EXPR || code1 == BIT_AND_EXPR) && code2 == BIT_AND_EXPR)
1369 return wi::eq_p (expr1.pred_rhs,
1370 wi::bit_and (expr1.pred_rhs, expr2.pred_rhs));
1372 if (code1 != code2 && code2 != NE_EXPR)
1373 return false;
1375 if (is_value_included_in (expr1.pred_rhs, expr2.pred_rhs, code2))
1376 return true;
1378 return false;
1381 /* Returns true if the domain of PRED1 is a subset
1382 of that of PRED2. Returns false if it can not be proved so. */
1384 static bool
1385 is_pred_chain_subset_of (pred_chain pred1, pred_chain pred2)
1387 size_t np1, np2, i1, i2;
1389 np1 = pred1.length ();
1390 np2 = pred2.length ();
1392 for (i2 = 0; i2 < np2; i2++)
1394 bool found = false;
1395 pred_info info2 = pred2[i2];
1396 for (i1 = 0; i1 < np1; i1++)
1398 pred_info info1 = pred1[i1];
1399 if (is_pred_expr_subset_of (info1, info2))
1401 found = true;
1402 break;
1405 if (!found)
1406 return false;
1408 return true;
1411 /* Returns true if the domain defined by
1412 one pred chain ONE_PRED is a subset of the domain
1413 of *PREDS. It returns false if ONE_PRED's domain is
1414 not a subset of any of the sub-domains of PREDS
1415 (corresponding to each individual chains in it), even
1416 though it may be still be a subset of whole domain
1417 of PREDS which is the union (ORed) of all its subdomains.
1418 In other words, the result is conservative. */
1420 static bool
1421 is_included_in (pred_chain one_pred, pred_chain_union preds)
1423 size_t i;
1424 size_t n = preds.length ();
1426 for (i = 0; i < n; i++)
1428 if (is_pred_chain_subset_of (one_pred, preds[i]))
1429 return true;
1432 return false;
1435 /* Compares two predicate sets PREDS1 and PREDS2 and returns
1436 true if the domain defined by PREDS1 is a superset
1437 of PREDS2's domain. N1 and N2 are array sizes of PREDS1 and
1438 PREDS2 respectively. The implementation chooses not to build
1439 generic trees (and relying on the folding capability of the
1440 compiler), but instead performs brute force comparison of
1441 individual predicate chains (won't be a compile time problem
1442 as the chains are pretty short). When the function returns
1443 false, it does not necessarily mean *PREDS1 is not a superset
1444 of *PREDS2, but mean it may not be so since the analysis can
1445 not prove it. In such cases, false warnings may still be
1446 emitted. */
1448 static bool
1449 is_superset_of (pred_chain_union preds1, pred_chain_union preds2)
1451 size_t i, n2;
1452 pred_chain one_pred_chain = vNULL;
1454 n2 = preds2.length ();
1456 for (i = 0; i < n2; i++)
1458 one_pred_chain = preds2[i];
1459 if (!is_included_in (one_pred_chain, preds1))
1460 return false;
1463 return true;
1466 /* Returns true if TC is AND or OR. */
1468 static inline bool
1469 is_and_or_or_p (enum tree_code tc, tree type)
1471 return (tc == BIT_IOR_EXPR
1472 || (tc == BIT_AND_EXPR
1473 && (type == 0 || TREE_CODE (type) == BOOLEAN_TYPE)));
1476 /* Returns true if X1 is the negate of X2. */
1478 static inline bool
1479 pred_neg_p (pred_info x1, pred_info x2)
1481 enum tree_code c1, c2;
1482 if (!operand_equal_p (x1.pred_lhs, x2.pred_lhs, 0)
1483 || !operand_equal_p (x1.pred_rhs, x2.pred_rhs, 0))
1484 return false;
1486 c1 = x1.cond_code;
1487 if (x1.invert == x2.invert)
1488 c2 = invert_tree_comparison (x2.cond_code, false);
1489 else
1490 c2 = x2.cond_code;
1492 return c1 == c2;
1495 /* 1) ((x IOR y) != 0) AND (x != 0) is equivalent to (x != 0);
1496 2) (X AND Y) OR (!X AND Y) is equivalent to Y;
1497 3) X OR (!X AND Y) is equivalent to (X OR Y);
1498 4) ((x IAND y) != 0) || (x != 0 AND y != 0)) is equivalent to
1499 (x != 0 AND y != 0)
1500 5) (X AND Y) OR (!X AND Z) OR (!Y AND Z) is equivalent to
1501 (X AND Y) OR Z
1503 PREDS is the predicate chains, and N is the number of chains. */
1505 /* Helper function to implement rule 1 above. ONE_CHAIN is
1506 the AND predication to be simplified. */
1508 static void
1509 simplify_pred (pred_chain *one_chain)
1511 size_t i, j, n;
1512 bool simplified = false;
1513 pred_chain s_chain = vNULL;
1515 n = one_chain->length ();
1517 for (i = 0; i < n; i++)
1519 pred_info *a_pred = &(*one_chain)[i];
1521 if (!a_pred->pred_lhs)
1522 continue;
1523 if (!is_neq_zero_form_p (*a_pred))
1524 continue;
1526 gimple *def_stmt = SSA_NAME_DEF_STMT (a_pred->pred_lhs);
1527 if (gimple_code (def_stmt) != GIMPLE_ASSIGN)
1528 continue;
1529 if (gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR)
1531 for (j = 0; j < n; j++)
1533 pred_info *b_pred = &(*one_chain)[j];
1535 if (!b_pred->pred_lhs)
1536 continue;
1537 if (!is_neq_zero_form_p (*b_pred))
1538 continue;
1540 if (pred_expr_equal_p (*b_pred, gimple_assign_rhs1 (def_stmt))
1541 || pred_expr_equal_p (*b_pred, gimple_assign_rhs2 (def_stmt)))
1543 /* Mark a_pred for removal. */
1544 a_pred->pred_lhs = NULL;
1545 a_pred->pred_rhs = NULL;
1546 simplified = true;
1547 break;
1553 if (!simplified)
1554 return;
1556 for (i = 0; i < n; i++)
1558 pred_info *a_pred = &(*one_chain)[i];
1559 if (!a_pred->pred_lhs)
1560 continue;
1561 s_chain.safe_push (*a_pred);
1564 one_chain->release ();
1565 *one_chain = s_chain;
1568 /* The helper function implements the rule 2 for the
1569 OR predicate PREDS.
1571 2) (X AND Y) OR (!X AND Y) is equivalent to Y. */
1573 static bool
1574 simplify_preds_2 (pred_chain_union *preds)
1576 size_t i, j, n;
1577 bool simplified = false;
1578 pred_chain_union s_preds = vNULL;
1580 /* (X AND Y) OR (!X AND Y) is equivalent to Y.
1581 (X AND Y) OR (X AND !Y) is equivalent to X. */
1583 n = preds->length ();
1584 for (i = 0; i < n; i++)
1586 pred_info x, y;
1587 pred_chain *a_chain = &(*preds)[i];
1589 if (a_chain->length () != 2)
1590 continue;
1592 x = (*a_chain)[0];
1593 y = (*a_chain)[1];
1595 for (j = 0; j < n; j++)
1597 pred_chain *b_chain;
1598 pred_info x2, y2;
1600 if (j == i)
1601 continue;
1603 b_chain = &(*preds)[j];
1604 if (b_chain->length () != 2)
1605 continue;
1607 x2 = (*b_chain)[0];
1608 y2 = (*b_chain)[1];
1610 if (pred_equal_p (x, x2) && pred_neg_p (y, y2))
1612 /* Kill a_chain. */
1613 a_chain->release ();
1614 b_chain->release ();
1615 b_chain->safe_push (x);
1616 simplified = true;
1617 break;
1619 if (pred_neg_p (x, x2) && pred_equal_p (y, y2))
1621 /* Kill a_chain. */
1622 a_chain->release ();
1623 b_chain->release ();
1624 b_chain->safe_push (y);
1625 simplified = true;
1626 break;
1630 /* Now clean up the chain. */
1631 if (simplified)
1633 for (i = 0; i < n; i++)
1635 if ((*preds)[i].is_empty ())
1636 continue;
1637 s_preds.safe_push ((*preds)[i]);
1639 preds->release ();
1640 (*preds) = s_preds;
1641 s_preds = vNULL;
1644 return simplified;
1647 /* The helper function implements the rule 2 for the
1648 OR predicate PREDS.
1650 3) x OR (!x AND y) is equivalent to x OR y. */
1652 static bool
1653 simplify_preds_3 (pred_chain_union *preds)
1655 size_t i, j, n;
1656 bool simplified = false;
1658 /* Now iteratively simplify X OR (!X AND Z ..)
1659 into X OR (Z ...). */
1661 n = preds->length ();
1662 if (n < 2)
1663 return false;
1665 for (i = 0; i < n; i++)
1667 pred_info x;
1668 pred_chain *a_chain = &(*preds)[i];
1670 if (a_chain->length () != 1)
1671 continue;
1673 x = (*a_chain)[0];
1675 for (j = 0; j < n; j++)
1677 pred_chain *b_chain;
1678 pred_info x2;
1679 size_t k;
1681 if (j == i)
1682 continue;
1684 b_chain = &(*preds)[j];
1685 if (b_chain->length () < 2)
1686 continue;
1688 for (k = 0; k < b_chain->length (); k++)
1690 x2 = (*b_chain)[k];
1691 if (pred_neg_p (x, x2))
1693 b_chain->unordered_remove (k);
1694 simplified = true;
1695 break;
1700 return simplified;
1703 /* The helper function implements the rule 4 for the
1704 OR predicate PREDS.
1706 2) ((x AND y) != 0) OR (x != 0 AND y != 0) is equivalent to
1707 (x != 0 ANd y != 0). */
1709 static bool
1710 simplify_preds_4 (pred_chain_union *preds)
1712 size_t i, j, n;
1713 bool simplified = false;
1714 pred_chain_union s_preds = vNULL;
1715 gimple *def_stmt;
1717 n = preds->length ();
1718 for (i = 0; i < n; i++)
1720 pred_info z;
1721 pred_chain *a_chain = &(*preds)[i];
1723 if (a_chain->length () != 1)
1724 continue;
1726 z = (*a_chain)[0];
1728 if (!is_neq_zero_form_p (z))
1729 continue;
1731 def_stmt = SSA_NAME_DEF_STMT (z.pred_lhs);
1732 if (gimple_code (def_stmt) != GIMPLE_ASSIGN)
1733 continue;
1735 if (gimple_assign_rhs_code (def_stmt) != BIT_AND_EXPR)
1736 continue;
1738 for (j = 0; j < n; j++)
1740 pred_chain *b_chain;
1741 pred_info x2, y2;
1743 if (j == i)
1744 continue;
1746 b_chain = &(*preds)[j];
1747 if (b_chain->length () != 2)
1748 continue;
1750 x2 = (*b_chain)[0];
1751 y2 = (*b_chain)[1];
1752 if (!is_neq_zero_form_p (x2) || !is_neq_zero_form_p (y2))
1753 continue;
1755 if ((pred_expr_equal_p (x2, gimple_assign_rhs1 (def_stmt))
1756 && pred_expr_equal_p (y2, gimple_assign_rhs2 (def_stmt)))
1757 || (pred_expr_equal_p (x2, gimple_assign_rhs2 (def_stmt))
1758 && pred_expr_equal_p (y2, gimple_assign_rhs1 (def_stmt))))
1760 /* Kill a_chain. */
1761 a_chain->release ();
1762 simplified = true;
1763 break;
1767 /* Now clean up the chain. */
1768 if (simplified)
1770 for (i = 0; i < n; i++)
1772 if ((*preds)[i].is_empty ())
1773 continue;
1774 s_preds.safe_push ((*preds)[i]);
1777 preds->release ();
1778 (*preds) = s_preds;
1779 s_preds = vNULL;
1782 return simplified;
1785 /* This function simplifies predicates in PREDS. */
1787 static void
1788 simplify_preds (pred_chain_union *preds, gimple *use_or_def, bool is_use)
1790 size_t i, n;
1791 bool changed = false;
1793 if (dump_file && dump_flags & TDF_DETAILS)
1795 fprintf (dump_file, "[BEFORE SIMPLICATION -- ");
1796 dump_predicates (use_or_def, *preds, is_use ? "[USE]:\n" : "[DEF]:\n");
1799 for (i = 0; i < preds->length (); i++)
1800 simplify_pred (&(*preds)[i]);
1802 n = preds->length ();
1803 if (n < 2)
1804 return;
1808 changed = false;
1809 if (simplify_preds_2 (preds))
1810 changed = true;
1812 /* Now iteratively simplify X OR (!X AND Z ..)
1813 into X OR (Z ...). */
1814 if (simplify_preds_3 (preds))
1815 changed = true;
1817 if (simplify_preds_4 (preds))
1818 changed = true;
1820 while (changed);
1822 return;
1825 /* This is a helper function which attempts to normalize predicate chains
1826 by following UD chains. It basically builds up a big tree of either IOR
1827 operations or AND operations, and convert the IOR tree into a
1828 pred_chain_union or BIT_AND tree into a pred_chain.
1829 Example:
1831 _3 = _2 RELOP1 _1;
1832 _6 = _5 RELOP2 _4;
1833 _9 = _8 RELOP3 _7;
1834 _10 = _3 | _6;
1835 _12 = _9 | _0;
1836 _t = _10 | _12;
1838 then _t != 0 will be normalized into a pred_chain_union
1840 (_2 RELOP1 _1) OR (_5 RELOP2 _4) OR (_8 RELOP3 _7) OR (_0 != 0)
1842 Similarly given,
1844 _3 = _2 RELOP1 _1;
1845 _6 = _5 RELOP2 _4;
1846 _9 = _8 RELOP3 _7;
1847 _10 = _3 & _6;
1848 _12 = _9 & _0;
1850 then _t != 0 will be normalized into a pred_chain:
1851 (_2 RELOP1 _1) AND (_5 RELOP2 _4) AND (_8 RELOP3 _7) AND (_0 != 0)
1855 /* This is a helper function that stores a PRED into NORM_PREDS. */
1857 inline static void
1858 push_pred (pred_chain_union *norm_preds, pred_info pred)
1860 pred_chain pred_chain = vNULL;
1861 pred_chain.safe_push (pred);
1862 norm_preds->safe_push (pred_chain);
1865 /* A helper function that creates a predicate of the form
1866 OP != 0 and push it WORK_LIST. */
1868 inline static void
1869 push_to_worklist (tree op, vec<pred_info, va_heap, vl_ptr> *work_list,
1870 hash_set<tree> *mark_set)
1872 if (mark_set->contains (op))
1873 return;
1874 mark_set->add (op);
1876 pred_info arg_pred;
1877 arg_pred.pred_lhs = op;
1878 arg_pred.pred_rhs = integer_zero_node;
1879 arg_pred.cond_code = NE_EXPR;
1880 arg_pred.invert = false;
1881 work_list->safe_push (arg_pred);
1884 /* A helper that generates a pred_info from a gimple assignment
1885 CMP_ASSIGN with comparison rhs. */
1887 static pred_info
1888 get_pred_info_from_cmp (gimple *cmp_assign)
1890 pred_info n_pred;
1891 n_pred.pred_lhs = gimple_assign_rhs1 (cmp_assign);
1892 n_pred.pred_rhs = gimple_assign_rhs2 (cmp_assign);
1893 n_pred.cond_code = gimple_assign_rhs_code (cmp_assign);
1894 n_pred.invert = false;
1895 return n_pred;
1898 /* Returns true if the PHI is a degenerated phi with
1899 all args with the same value (relop). In that case, *PRED
1900 will be updated to that value. */
1902 static bool
1903 is_degenerated_phi (gimple *phi, pred_info *pred_p)
1905 int i, n;
1906 tree op0;
1907 gimple *def0;
1908 pred_info pred0;
1910 n = gimple_phi_num_args (phi);
1911 op0 = gimple_phi_arg_def (phi, 0);
1913 if (TREE_CODE (op0) != SSA_NAME)
1914 return false;
1916 def0 = SSA_NAME_DEF_STMT (op0);
1917 if (gimple_code (def0) != GIMPLE_ASSIGN)
1918 return false;
1919 if (TREE_CODE_CLASS (gimple_assign_rhs_code (def0)) != tcc_comparison)
1920 return false;
1921 pred0 = get_pred_info_from_cmp (def0);
1923 for (i = 1; i < n; ++i)
1925 gimple *def;
1926 pred_info pred;
1927 tree op = gimple_phi_arg_def (phi, i);
1929 if (TREE_CODE (op) != SSA_NAME)
1930 return false;
1932 def = SSA_NAME_DEF_STMT (op);
1933 if (gimple_code (def) != GIMPLE_ASSIGN)
1934 return false;
1935 if (TREE_CODE_CLASS (gimple_assign_rhs_code (def)) != tcc_comparison)
1936 return false;
1937 pred = get_pred_info_from_cmp (def);
1938 if (!pred_equal_p (pred, pred0))
1939 return false;
1942 *pred_p = pred0;
1943 return true;
1946 /* Normalize one predicate PRED
1947 1) if PRED can no longer be normlized, put it into NORM_PREDS.
1948 2) otherwise if PRED is of the form x != 0, follow x's definition
1949 and put normalized predicates into WORK_LIST. */
1951 static void
1952 normalize_one_pred_1 (pred_chain_union *norm_preds,
1953 pred_chain *norm_chain,
1954 pred_info pred,
1955 enum tree_code and_or_code,
1956 vec<pred_info, va_heap, vl_ptr> *work_list,
1957 hash_set<tree> *mark_set)
1959 if (!is_neq_zero_form_p (pred))
1961 if (and_or_code == BIT_IOR_EXPR)
1962 push_pred (norm_preds, pred);
1963 else
1964 norm_chain->safe_push (pred);
1965 return;
1968 gimple *def_stmt = SSA_NAME_DEF_STMT (pred.pred_lhs);
1970 if (gimple_code (def_stmt) == GIMPLE_PHI
1971 && is_degenerated_phi (def_stmt, &pred))
1972 work_list->safe_push (pred);
1973 else if (gimple_code (def_stmt) == GIMPLE_PHI && and_or_code == BIT_IOR_EXPR)
1975 int i, n;
1976 n = gimple_phi_num_args (def_stmt);
1978 /* If we see non zero constant, we should punt. The predicate
1979 * should be one guarding the phi edge. */
1980 for (i = 0; i < n; ++i)
1982 tree op = gimple_phi_arg_def (def_stmt, i);
1983 if (TREE_CODE (op) == INTEGER_CST && !integer_zerop (op))
1985 push_pred (norm_preds, pred);
1986 return;
1990 for (i = 0; i < n; ++i)
1992 tree op = gimple_phi_arg_def (def_stmt, i);
1993 if (integer_zerop (op))
1994 continue;
1996 push_to_worklist (op, work_list, mark_set);
1999 else if (gimple_code (def_stmt) != GIMPLE_ASSIGN)
2001 if (and_or_code == BIT_IOR_EXPR)
2002 push_pred (norm_preds, pred);
2003 else
2004 norm_chain->safe_push (pred);
2006 else if (gimple_assign_rhs_code (def_stmt) == and_or_code)
2008 /* Avoid splitting up bit manipulations like x & 3 or y | 1. */
2009 if (is_gimple_min_invariant (gimple_assign_rhs2 (def_stmt)))
2011 /* But treat x & 3 as condition. */
2012 if (and_or_code == BIT_AND_EXPR)
2014 pred_info n_pred;
2015 n_pred.pred_lhs = gimple_assign_rhs1 (def_stmt);
2016 n_pred.pred_rhs = gimple_assign_rhs2 (def_stmt);
2017 n_pred.cond_code = and_or_code;
2018 n_pred.invert = false;
2019 norm_chain->safe_push (n_pred);
2022 else
2024 push_to_worklist (gimple_assign_rhs1 (def_stmt), work_list, mark_set);
2025 push_to_worklist (gimple_assign_rhs2 (def_stmt), work_list, mark_set);
2028 else if (TREE_CODE_CLASS (gimple_assign_rhs_code (def_stmt))
2029 == tcc_comparison)
2031 pred_info n_pred = get_pred_info_from_cmp (def_stmt);
2032 if (and_or_code == BIT_IOR_EXPR)
2033 push_pred (norm_preds, n_pred);
2034 else
2035 norm_chain->safe_push (n_pred);
2037 else
2039 if (and_or_code == BIT_IOR_EXPR)
2040 push_pred (norm_preds, pred);
2041 else
2042 norm_chain->safe_push (pred);
2046 /* Normalize PRED and store the normalized predicates into NORM_PREDS. */
2048 static void
2049 normalize_one_pred (pred_chain_union *norm_preds, pred_info pred)
2051 vec<pred_info, va_heap, vl_ptr> work_list = vNULL;
2052 enum tree_code and_or_code = ERROR_MARK;
2053 pred_chain norm_chain = vNULL;
2055 if (!is_neq_zero_form_p (pred))
2057 push_pred (norm_preds, pred);
2058 return;
2061 gimple *def_stmt = SSA_NAME_DEF_STMT (pred.pred_lhs);
2062 if (gimple_code (def_stmt) == GIMPLE_ASSIGN)
2063 and_or_code = gimple_assign_rhs_code (def_stmt);
2064 if (and_or_code != BIT_IOR_EXPR && and_or_code != BIT_AND_EXPR)
2066 if (TREE_CODE_CLASS (and_or_code) == tcc_comparison)
2068 pred_info n_pred = get_pred_info_from_cmp (def_stmt);
2069 push_pred (norm_preds, n_pred);
2071 else
2072 push_pred (norm_preds, pred);
2073 return;
2076 work_list.safe_push (pred);
2077 hash_set<tree> mark_set;
2079 while (!work_list.is_empty ())
2081 pred_info a_pred = work_list.pop ();
2082 normalize_one_pred_1 (norm_preds, &norm_chain, a_pred, and_or_code,
2083 &work_list, &mark_set);
2085 if (and_or_code == BIT_AND_EXPR)
2086 norm_preds->safe_push (norm_chain);
2088 work_list.release ();
2091 static void
2092 normalize_one_pred_chain (pred_chain_union *norm_preds, pred_chain one_chain)
2094 vec<pred_info, va_heap, vl_ptr> work_list = vNULL;
2095 hash_set<tree> mark_set;
2096 pred_chain norm_chain = vNULL;
2097 size_t i;
2099 for (i = 0; i < one_chain.length (); i++)
2101 work_list.safe_push (one_chain[i]);
2102 mark_set.add (one_chain[i].pred_lhs);
2105 while (!work_list.is_empty ())
2107 pred_info a_pred = work_list.pop ();
2108 normalize_one_pred_1 (0, &norm_chain, a_pred, BIT_AND_EXPR, &work_list,
2109 &mark_set);
2112 norm_preds->safe_push (norm_chain);
2113 work_list.release ();
2116 /* Normalize predicate chains PREDS and returns the normalized one. */
2118 static pred_chain_union
2119 normalize_preds (pred_chain_union preds, gimple *use_or_def, bool is_use)
2121 pred_chain_union norm_preds = vNULL;
2122 size_t n = preds.length ();
2123 size_t i;
2125 if (dump_file && dump_flags & TDF_DETAILS)
2127 fprintf (dump_file, "[BEFORE NORMALIZATION --");
2128 dump_predicates (use_or_def, preds, is_use ? "[USE]:\n" : "[DEF]:\n");
2131 for (i = 0; i < n; i++)
2133 if (preds[i].length () != 1)
2134 normalize_one_pred_chain (&norm_preds, preds[i]);
2135 else
2137 normalize_one_pred (&norm_preds, preds[i][0]);
2138 preds[i].release ();
2142 if (dump_file)
2144 fprintf (dump_file, "[AFTER NORMALIZATION -- ");
2145 dump_predicates (use_or_def, norm_preds,
2146 is_use ? "[USE]:\n" : "[DEF]:\n");
2149 destroy_predicate_vecs (&preds);
2150 return norm_preds;
2153 /* Return TRUE if PREDICATE can be invalidated by any individual
2154 predicate in WORKLIST. */
2156 static bool
2157 can_one_predicate_be_invalidated_p (pred_info predicate,
2158 pred_chain use_guard)
2160 for (size_t i = 0; i < use_guard.length (); ++i)
2162 /* NOTE: This is a very simple check, and only understands an
2163 exact opposite. So, [i == 0] is currently only invalidated
2164 by [.NOT. i == 0] or [i != 0]. Ideally we should also
2165 invalidate with say [i > 5] or [i == 8]. There is certainly
2166 room for improvement here. */
2167 if (pred_neg_p (predicate, use_guard[i]))
2168 return true;
2170 return false;
2173 /* Return TRUE if all predicates in UNINIT_PRED are invalidated by
2174 USE_GUARD being true. */
2176 static bool
2177 can_chain_union_be_invalidated_p (pred_chain_union uninit_pred,
2178 pred_chain use_guard)
2180 if (uninit_pred.is_empty ())
2181 return false;
2182 for (size_t i = 0; i < uninit_pred.length (); ++i)
2184 pred_chain c = uninit_pred[i];
2185 for (size_t j = 0; j < c.length (); ++j)
2186 if (!can_one_predicate_be_invalidated_p (c[j], use_guard))
2187 return false;
2189 return true;
2192 /* Return TRUE if none of the uninitialized operands in UNINT_OPNDS
2193 can actually happen if we arrived at a use for PHI.
2195 PHI_USE_GUARDS are the guard conditions for the use of the PHI. */
2197 static bool
2198 uninit_uses_cannot_happen (gphi *phi, unsigned uninit_opnds,
2199 pred_chain_union phi_use_guards)
2201 unsigned phi_args = gimple_phi_num_args (phi);
2202 if (phi_args > max_phi_args)
2203 return false;
2205 /* PHI_USE_GUARDS are OR'ed together. If we have more than one
2206 possible guard, there's no way of knowing which guard was true.
2207 Since we need to be absolutely sure that the uninitialized
2208 operands will be invalidated, bail. */
2209 if (phi_use_guards.length () != 1)
2210 return false;
2212 /* Look for the control dependencies of all the uninitialized
2213 operands and build guard predicates describing them. */
2214 pred_chain_union uninit_preds;
2215 bool ret = true;
2216 for (unsigned i = 0; i < phi_args; ++i)
2218 if (!MASK_TEST_BIT (uninit_opnds, i))
2219 continue;
2221 edge e = gimple_phi_arg_edge (phi, i);
2222 vec<edge> dep_chains[MAX_NUM_CHAINS];
2223 auto_vec<edge, MAX_CHAIN_LEN + 1> cur_chain;
2224 size_t num_chains = 0;
2225 int num_calls = 0;
2227 /* Build the control dependency chain for uninit operand `i'... */
2228 uninit_preds = vNULL;
2229 if (!compute_control_dep_chain (find_dom (e->src),
2230 e->src, dep_chains, &num_chains,
2231 &cur_chain, &num_calls))
2233 ret = false;
2234 break;
2236 /* ...and convert it into a set of predicates. */
2237 convert_control_dep_chain_into_preds (dep_chains, num_chains,
2238 &uninit_preds);
2239 for (size_t j = 0; j < num_chains; ++j)
2240 dep_chains[j].release ();
2241 simplify_preds (&uninit_preds, NULL, false);
2242 uninit_preds = normalize_preds (uninit_preds, NULL, false);
2244 /* Can the guard for this uninitialized operand be invalidated
2245 by the PHI use? */
2246 if (!can_chain_union_be_invalidated_p (uninit_preds, phi_use_guards[0]))
2248 ret = false;
2249 break;
2252 destroy_predicate_vecs (&uninit_preds);
2253 return ret;
2256 /* Computes the predicates that guard the use and checks
2257 if the incoming paths that have empty (or possibly
2258 empty) definition can be pruned/filtered. The function returns
2259 true if it can be determined that the use of PHI's def in
2260 USE_STMT is guarded with a predicate set not overlapping with
2261 predicate sets of all runtime paths that do not have a definition.
2263 Returns false if it is not or it can not be determined. USE_BB is
2264 the bb of the use (for phi operand use, the bb is not the bb of
2265 the phi stmt, but the src bb of the operand edge).
2267 UNINIT_OPNDS is a bit vector. If an operand of PHI is uninitialized, the
2268 corresponding bit in the vector is 1. VISITED_PHIS is a pointer
2269 set of phis being visited.
2271 *DEF_PREDS contains the (memoized) defining predicate chains of PHI.
2272 If *DEF_PREDS is the empty vector, the defining predicate chains of
2273 PHI will be computed and stored into *DEF_PREDS as needed.
2275 VISITED_PHIS is a pointer set of phis being visited. */
2277 static bool
2278 is_use_properly_guarded (gimple *use_stmt,
2279 basic_block use_bb,
2280 gphi *phi,
2281 unsigned uninit_opnds,
2282 pred_chain_union *def_preds,
2283 hash_set<gphi *> *visited_phis)
2285 basic_block phi_bb;
2286 pred_chain_union preds = vNULL;
2287 bool has_valid_preds = false;
2288 bool is_properly_guarded = false;
2290 if (visited_phis->add (phi))
2291 return false;
2293 phi_bb = gimple_bb (phi);
2295 if (is_non_loop_exit_postdominating (use_bb, phi_bb))
2296 return false;
2298 has_valid_preds = find_predicates (&preds, phi_bb, use_bb);
2300 if (!has_valid_preds)
2302 destroy_predicate_vecs (&preds);
2303 return false;
2306 /* Try to prune the dead incoming phi edges. */
2307 is_properly_guarded
2308 = use_pred_not_overlap_with_undef_path_pred (preds, phi, uninit_opnds,
2309 visited_phis);
2311 /* We might be able to prove that if the control dependencies
2312 for UNINIT_OPNDS are true, that the control dependencies for
2313 USE_STMT can never be true. */
2314 if (!is_properly_guarded)
2315 is_properly_guarded |= uninit_uses_cannot_happen (phi, uninit_opnds,
2316 preds);
2318 if (is_properly_guarded)
2320 destroy_predicate_vecs (&preds);
2321 return true;
2324 if (def_preds->is_empty ())
2326 has_valid_preds = find_def_preds (def_preds, phi);
2328 if (!has_valid_preds)
2330 destroy_predicate_vecs (&preds);
2331 return false;
2334 simplify_preds (def_preds, phi, false);
2335 *def_preds = normalize_preds (*def_preds, phi, false);
2338 simplify_preds (&preds, use_stmt, true);
2339 preds = normalize_preds (preds, use_stmt, true);
2341 is_properly_guarded = is_superset_of (*def_preds, preds);
2343 destroy_predicate_vecs (&preds);
2344 return is_properly_guarded;
2347 /* Searches through all uses of a potentially
2348 uninitialized variable defined by PHI and returns a use
2349 statement if the use is not properly guarded. It returns
2350 NULL if all uses are guarded. UNINIT_OPNDS is a bitvector
2351 holding the position(s) of uninit PHI operands. WORKLIST
2352 is the vector of candidate phis that may be updated by this
2353 function. ADDED_TO_WORKLIST is the pointer set tracking
2354 if the new phi is already in the worklist. */
2356 static gimple *
2357 find_uninit_use (gphi *phi, unsigned uninit_opnds,
2358 vec<gphi *> *worklist,
2359 hash_set<gphi *> *added_to_worklist)
2361 tree phi_result;
2362 use_operand_p use_p;
2363 gimple *use_stmt;
2364 imm_use_iterator iter;
2365 pred_chain_union def_preds = vNULL;
2366 gimple *ret = NULL;
2368 phi_result = gimple_phi_result (phi);
2370 FOR_EACH_IMM_USE_FAST (use_p, iter, phi_result)
2372 basic_block use_bb;
2374 use_stmt = USE_STMT (use_p);
2375 if (is_gimple_debug (use_stmt))
2376 continue;
2378 if (gphi *use_phi = dyn_cast<gphi *> (use_stmt))
2379 use_bb = gimple_phi_arg_edge (use_phi,
2380 PHI_ARG_INDEX_FROM_USE (use_p))->src;
2381 else
2382 use_bb = gimple_bb (use_stmt);
2384 hash_set<gphi *> visited_phis;
2385 if (is_use_properly_guarded (use_stmt, use_bb, phi, uninit_opnds,
2386 &def_preds, &visited_phis))
2387 continue;
2389 if (dump_file && (dump_flags & TDF_DETAILS))
2391 fprintf (dump_file, "[CHECK]: Found unguarded use: ");
2392 print_gimple_stmt (dump_file, use_stmt, 0, 0);
2394 /* Found one real use, return. */
2395 if (gimple_code (use_stmt) != GIMPLE_PHI)
2397 ret = use_stmt;
2398 break;
2401 /* Found a phi use that is not guarded,
2402 add the phi to the worklist. */
2403 if (!added_to_worklist->add (as_a<gphi *> (use_stmt)))
2405 if (dump_file && (dump_flags & TDF_DETAILS))
2407 fprintf (dump_file, "[WORKLIST]: Update worklist with phi: ");
2408 print_gimple_stmt (dump_file, use_stmt, 0, 0);
2411 worklist->safe_push (as_a<gphi *> (use_stmt));
2412 possibly_undefined_names->add (phi_result);
2416 destroy_predicate_vecs (&def_preds);
2417 return ret;
2420 /* Look for inputs to PHI that are SSA_NAMEs that have empty definitions
2421 and gives warning if there exists a runtime path from the entry to a
2422 use of the PHI def that does not contain a definition. In other words,
2423 the warning is on the real use. The more dead paths that can be pruned
2424 by the compiler, the fewer false positives the warning is. WORKLIST
2425 is a vector of candidate phis to be examined. ADDED_TO_WORKLIST is
2426 a pointer set tracking if the new phi is added to the worklist or not. */
2428 static void
2429 warn_uninitialized_phi (gphi *phi, vec<gphi *> *worklist,
2430 hash_set<gphi *> *added_to_worklist)
2432 unsigned uninit_opnds;
2433 gimple *uninit_use_stmt = 0;
2434 tree uninit_op;
2435 int phiarg_index;
2436 location_t loc;
2438 /* Don't look at virtual operands. */
2439 if (virtual_operand_p (gimple_phi_result (phi)))
2440 return;
2442 uninit_opnds = compute_uninit_opnds_pos (phi);
2444 if (MASK_EMPTY (uninit_opnds))
2445 return;
2447 if (dump_file && (dump_flags & TDF_DETAILS))
2449 fprintf (dump_file, "[CHECK]: examining phi: ");
2450 print_gimple_stmt (dump_file, phi, 0, 0);
2453 /* Now check if we have any use of the value without proper guard. */
2454 uninit_use_stmt = find_uninit_use (phi, uninit_opnds,
2455 worklist, added_to_worklist);
2457 /* All uses are properly guarded. */
2458 if (!uninit_use_stmt)
2459 return;
2461 phiarg_index = MASK_FIRST_SET_BIT (uninit_opnds);
2462 uninit_op = gimple_phi_arg_def (phi, phiarg_index);
2463 if (SSA_NAME_VAR (uninit_op) == NULL_TREE)
2464 return;
2465 if (gimple_phi_arg_has_location (phi, phiarg_index))
2466 loc = gimple_phi_arg_location (phi, phiarg_index);
2467 else
2468 loc = UNKNOWN_LOCATION;
2469 warn_uninit (OPT_Wmaybe_uninitialized, uninit_op, SSA_NAME_VAR (uninit_op),
2470 SSA_NAME_VAR (uninit_op),
2471 "%qD may be used uninitialized in this function",
2472 uninit_use_stmt, loc);
2475 static bool
2476 gate_warn_uninitialized (void)
2478 return warn_uninitialized || warn_maybe_uninitialized;
2481 namespace {
2483 const pass_data pass_data_late_warn_uninitialized =
2485 GIMPLE_PASS, /* type */
2486 "uninit", /* name */
2487 OPTGROUP_NONE, /* optinfo_flags */
2488 TV_NONE, /* tv_id */
2489 PROP_ssa, /* properties_required */
2490 0, /* properties_provided */
2491 0, /* properties_destroyed */
2492 0, /* todo_flags_start */
2493 0, /* todo_flags_finish */
2496 class pass_late_warn_uninitialized : public gimple_opt_pass
2498 public:
2499 pass_late_warn_uninitialized (gcc::context *ctxt)
2500 : gimple_opt_pass (pass_data_late_warn_uninitialized, ctxt)
2503 /* opt_pass methods: */
2504 opt_pass *clone () { return new pass_late_warn_uninitialized (m_ctxt); }
2505 virtual bool gate (function *) { return gate_warn_uninitialized (); }
2506 virtual unsigned int execute (function *);
2508 }; // class pass_late_warn_uninitialized
2510 unsigned int
2511 pass_late_warn_uninitialized::execute (function *fun)
2513 basic_block bb;
2514 gphi_iterator gsi;
2515 vec<gphi *> worklist = vNULL;
2517 calculate_dominance_info (CDI_DOMINATORS);
2518 calculate_dominance_info (CDI_POST_DOMINATORS);
2519 /* Re-do the plain uninitialized variable check, as optimization may have
2520 straightened control flow. Do this first so that we don't accidentally
2521 get a "may be" warning when we'd have seen an "is" warning later. */
2522 warn_uninitialized_vars (/*warn_possibly_uninitialized=*/1);
2524 timevar_push (TV_TREE_UNINIT);
2526 possibly_undefined_names = new hash_set<tree>;
2527 hash_set<gphi *> added_to_worklist;
2529 /* Initialize worklist */
2530 FOR_EACH_BB_FN (bb, fun)
2531 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2533 gphi *phi = gsi.phi ();
2534 size_t n, i;
2536 n = gimple_phi_num_args (phi);
2538 /* Don't look at virtual operands. */
2539 if (virtual_operand_p (gimple_phi_result (phi)))
2540 continue;
2542 for (i = 0; i < n; ++i)
2544 tree op = gimple_phi_arg_def (phi, i);
2545 if (TREE_CODE (op) == SSA_NAME && uninit_undefined_value_p (op))
2547 worklist.safe_push (phi);
2548 added_to_worklist.add (phi);
2549 if (dump_file && (dump_flags & TDF_DETAILS))
2551 fprintf (dump_file, "[WORKLIST]: add to initial list: ");
2552 print_gimple_stmt (dump_file, phi, 0, 0);
2554 break;
2559 while (worklist.length () != 0)
2561 gphi *cur_phi = 0;
2562 cur_phi = worklist.pop ();
2563 warn_uninitialized_phi (cur_phi, &worklist, &added_to_worklist);
2566 worklist.release ();
2567 delete possibly_undefined_names;
2568 possibly_undefined_names = NULL;
2569 free_dominance_info (CDI_POST_DOMINATORS);
2570 timevar_pop (TV_TREE_UNINIT);
2571 return 0;
2574 } // anon namespace
2576 gimple_opt_pass *
2577 make_pass_late_warn_uninitialized (gcc::context *ctxt)
2579 return new pass_late_warn_uninitialized (ctxt);
2582 static unsigned int
2583 execute_early_warn_uninitialized (void)
2585 /* Currently, this pass runs always but
2586 execute_late_warn_uninitialized only runs with optimization. With
2587 optimization we want to warn about possible uninitialized as late
2588 as possible, thus don't do it here. However, without
2589 optimization we need to warn here about "may be uninitialized". */
2590 calculate_dominance_info (CDI_POST_DOMINATORS);
2592 warn_uninitialized_vars (/*warn_possibly_uninitialized=*/!optimize);
2594 /* Post-dominator information can not be reliably updated. Free it
2595 after the use. */
2597 free_dominance_info (CDI_POST_DOMINATORS);
2598 return 0;
2601 namespace {
2603 const pass_data pass_data_early_warn_uninitialized =
2605 GIMPLE_PASS, /* type */
2606 "*early_warn_uninitialized", /* name */
2607 OPTGROUP_NONE, /* optinfo_flags */
2608 TV_TREE_UNINIT, /* tv_id */
2609 PROP_ssa, /* properties_required */
2610 0, /* properties_provided */
2611 0, /* properties_destroyed */
2612 0, /* todo_flags_start */
2613 0, /* todo_flags_finish */
2616 class pass_early_warn_uninitialized : public gimple_opt_pass
2618 public:
2619 pass_early_warn_uninitialized (gcc::context *ctxt)
2620 : gimple_opt_pass (pass_data_early_warn_uninitialized, ctxt)
2623 /* opt_pass methods: */
2624 virtual bool gate (function *) { return gate_warn_uninitialized (); }
2625 virtual unsigned int execute (function *)
2627 return execute_early_warn_uninitialized ();
2630 }; // class pass_early_warn_uninitialized
2632 } // anon namespace
2634 gimple_opt_pass *
2635 make_pass_early_warn_uninitialized (gcc::context *ctxt)
2637 return new pass_early_warn_uninitialized (ctxt);