gccrs: add test case to show our query-type system is working
[official-gcc.git] / gcc / tree-vrp.cc
blobbe7d06f565c5c605350903f0ff35f9473bbee217
1 /* Support routines for Value Range Propagation (VRP).
2 Copyright (C) 2005-2023 Free Software Foundation, Inc.
3 Contributed by Diego Novillo <dnovillo@redhat.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 "basic-block.h"
25 #include "bitmap.h"
26 #include "sbitmap.h"
27 #include "options.h"
28 #include "dominance.h"
29 #include "function.h"
30 #include "cfg.h"
31 #include "tree.h"
32 #include "gimple.h"
33 #include "tree-pass.h"
34 #include "ssa.h"
35 #include "gimple-pretty-print.h"
36 #include "fold-const.h"
37 #include "cfganal.h"
38 #include "gimple-iterator.h"
39 #include "tree-cfg.h"
40 #include "tree-ssa-loop-manip.h"
41 #include "tree-ssa-loop-niter.h"
42 #include "tree-into-ssa.h"
43 #include "cfgloop.h"
44 #include "tree-scalar-evolution.h"
45 #include "tree-ssa-propagate.h"
46 #include "domwalk.h"
47 #include "vr-values.h"
48 #include "gimple-array-bounds.h"
49 #include "gimple-range.h"
50 #include "gimple-range-path.h"
51 #include "value-pointer-equiv.h"
52 #include "gimple-fold.h"
53 #include "tree-dfa.h"
54 #include "tree-ssa-dce.h"
56 // This class is utilized by VRP and ranger to remove __builtin_unreachable
57 // calls, and reflect any resulting global ranges.
59 // maybe_register_block () is called on basic blocks, and if that block
60 // matches the pattern of one branch being a builtin_unreachable, register
61 // the resulting executable edge in a list.
63 // After all blocks have been processed, remove_and_update_globals() will
64 // - check all exports from registered blocks
65 // - ensure the cache entry of each export is set with the appropriate range
66 // - rewrite the conditions to take the executable edge
67 // - perform DCE on any feeding instructions to those rewritten conditions
69 // Then each of the immediate use chain of each export is walked, and a new
70 // global range created by unioning the ranges at all remaining use locations.
72 class remove_unreachable {
73 public:
74 remove_unreachable (gimple_ranger &r) : m_ranger (r) { m_list.create (30); }
75 ~remove_unreachable () { m_list.release (); }
76 void maybe_register_block (basic_block bb);
77 bool remove_and_update_globals (bool final_p);
78 vec<edge> m_list;
79 gimple_ranger &m_ranger;
82 // Check if block BB has a __builtin_unreachable () call on one arm, and
83 // register the executable edge if so.
85 void
86 remove_unreachable::maybe_register_block (basic_block bb)
88 gimple *s = gimple_outgoing_range_stmt_p (bb);
89 if (!s || gimple_code (s) != GIMPLE_COND)
90 return;
92 edge e0 = EDGE_SUCC (bb, 0);
93 basic_block bb0 = e0->dest;
94 bool un0 = EDGE_COUNT (bb0->succs) == 0
95 && gimple_seq_unreachable_p (bb_seq (bb0));
96 edge e1 = EDGE_SUCC (bb, 1);
97 basic_block bb1 = e1->dest;
98 bool un1 = EDGE_COUNT (bb1->succs) == 0
99 && gimple_seq_unreachable_p (bb_seq (bb1));
101 // If the 2 blocks are not different, ignore.
102 if (un0 == un1)
103 return;
105 if (un0)
106 m_list.safe_push (e1);
107 else
108 m_list.safe_push (e0);
111 // Process the edges in the list, change the conditions and removing any
112 // dead code feeding those conditions. Calculate the range of any
113 // names that may have been exported from those blocks, and determine if
114 // there is any updates to their global ranges..
115 // FINAL_P indicates all builtin_unreachable calls should be removed.
116 // Return true if any builtin_unreachables/globals eliminated/updated.
118 bool
119 remove_unreachable::remove_and_update_globals (bool final_p)
121 if (m_list.length () == 0)
122 return false;
124 // Ensure the cache in SCEV has been cleared before processing
125 // globals to be removed.
126 scev_reset ();
128 bool change = false;
129 tree name;
130 unsigned i;
131 bitmap_iterator bi;
132 auto_bitmap all_exports;
133 for (i = 0; i < m_list.length (); i++)
135 edge e = m_list[i];
136 gimple *s = gimple_outgoing_range_stmt_p (e->src);
137 gcc_checking_assert (gimple_code (s) == GIMPLE_COND);
138 bool lhs_p = TREE_CODE (gimple_cond_lhs (s)) == SSA_NAME;
139 bool rhs_p = TREE_CODE (gimple_cond_rhs (s)) == SSA_NAME;
140 // Do not remove __builtin_unreachable if it confers a relation, or
141 // that relation will be lost in subsequent passes. Unless its the
142 // final pass.
143 if (!final_p && lhs_p && rhs_p)
144 continue;
145 // If this is already a constant condition, don't look either
146 if (!lhs_p && !rhs_p)
147 continue;
149 bool dominate_exit_p = true;
150 FOR_EACH_GORI_EXPORT_NAME (m_ranger.gori (), e->src, name)
152 // Ensure the cache is set for NAME in the succ block.
153 Value_Range r(TREE_TYPE (name));
154 Value_Range ex(TREE_TYPE (name));
155 m_ranger.range_on_entry (r, e->dest, name);
156 m_ranger.range_on_entry (ex, EXIT_BLOCK_PTR_FOR_FN (cfun), name);
157 // If the range produced by this __builtin_unreachacble expression
158 // is not fully reflected in the range at exit, then it does not
159 // dominate the exit of the function.
160 if (ex.intersect (r))
161 dominate_exit_p = false;
164 // If the exit is dominated, add to the export list. Otherwise if this
165 // isn't the final VRP pass, leave the call in the IL.
166 if (dominate_exit_p)
167 bitmap_ior_into (all_exports, m_ranger.gori ().exports (e->src));
168 else if (!final_p)
169 continue;
171 change = true;
172 // Rewrite the condition.
173 if (e->flags & EDGE_TRUE_VALUE)
174 gimple_cond_make_true (as_a<gcond *> (s));
175 else
176 gimple_cond_make_false (as_a<gcond *> (s));
177 update_stmt (s);
180 if (bitmap_empty_p (all_exports))
181 return false;
182 // Invoke DCE on all exported names to eliminate dead feeding defs.
183 auto_bitmap dce;
184 bitmap_copy (dce, all_exports);
185 // Don't attempt to DCE parameters.
186 EXECUTE_IF_SET_IN_BITMAP (all_exports, 0, i, bi)
187 if (!ssa_name (i) || SSA_NAME_IS_DEFAULT_DEF (ssa_name (i)))
188 bitmap_clear_bit (dce, i);
189 simple_dce_from_worklist (dce);
191 // Loop over all uses of each name and find maximal range. This is the
192 // new global range.
193 use_operand_p use_p;
194 imm_use_iterator iter;
195 EXECUTE_IF_SET_IN_BITMAP (all_exports, 0, i, bi)
197 name = ssa_name (i);
198 if (!name || SSA_NAME_IN_FREE_LIST (name))
199 continue;
200 Value_Range r (TREE_TYPE (name));
201 Value_Range exp_range (TREE_TYPE (name));
202 r.set_undefined ();
203 FOR_EACH_IMM_USE_FAST (use_p, iter, name)
205 gimple *use_stmt = USE_STMT (use_p);
206 if (is_gimple_debug (use_stmt))
207 continue;
208 if (!m_ranger.range_of_expr (exp_range, name, use_stmt))
209 exp_range.set_varying (TREE_TYPE (name));
210 r.union_ (exp_range);
211 if (r.varying_p ())
212 break;
214 // Include the on-exit range to ensure non-dominated unreachables
215 // don't incorrectly impact the global range.
216 m_ranger.range_on_entry (exp_range, EXIT_BLOCK_PTR_FOR_FN (cfun), name);
217 r.union_ (exp_range);
218 if (r.varying_p () || r.undefined_p ())
219 continue;
220 if (!set_range_info (name, r))
221 continue;
222 change = true;
223 if (dump_file)
225 fprintf (dump_file, "Global Exported (via unreachable): ");
226 print_generic_expr (dump_file, name, TDF_SLIM);
227 fprintf (dump_file, " = ");
228 gimple_range_global (r, name);
229 r.dump (dump_file);
230 fputc ('\n', dump_file);
233 return change;
236 /* VR_TYPE describes a range with minimum value *MIN and maximum
237 value *MAX. Restrict the range to the set of values that have
238 no bits set outside NONZERO_BITS. Update *MIN and *MAX and
239 return the new range type.
241 SGN gives the sign of the values described by the range. */
243 enum value_range_kind
244 intersect_range_with_nonzero_bits (enum value_range_kind vr_type,
245 wide_int *min, wide_int *max,
246 const wide_int &nonzero_bits,
247 signop sgn)
249 if (vr_type == VR_ANTI_RANGE)
251 /* The VR_ANTI_RANGE is equivalent to the union of the ranges
252 A: [-INF, *MIN) and B: (*MAX, +INF]. First use NONZERO_BITS
253 to create an inclusive upper bound for A and an inclusive lower
254 bound for B. */
255 wide_int a_max = wi::round_down_for_mask (*min - 1, nonzero_bits);
256 wide_int b_min = wi::round_up_for_mask (*max + 1, nonzero_bits);
258 /* If the calculation of A_MAX wrapped, A is effectively empty
259 and A_MAX is the highest value that satisfies NONZERO_BITS.
260 Likewise if the calculation of B_MIN wrapped, B is effectively
261 empty and B_MIN is the lowest value that satisfies NONZERO_BITS. */
262 bool a_empty = wi::ge_p (a_max, *min, sgn);
263 bool b_empty = wi::le_p (b_min, *max, sgn);
265 /* If both A and B are empty, there are no valid values. */
266 if (a_empty && b_empty)
267 return VR_UNDEFINED;
269 /* If exactly one of A or B is empty, return a VR_RANGE for the
270 other one. */
271 if (a_empty || b_empty)
273 *min = b_min;
274 *max = a_max;
275 gcc_checking_assert (wi::le_p (*min, *max, sgn));
276 return VR_RANGE;
279 /* Update the VR_ANTI_RANGE bounds. */
280 *min = a_max + 1;
281 *max = b_min - 1;
282 gcc_checking_assert (wi::le_p (*min, *max, sgn));
284 /* Now check whether the excluded range includes any values that
285 satisfy NONZERO_BITS. If not, switch to a full VR_RANGE. */
286 if (wi::round_up_for_mask (*min, nonzero_bits) == b_min)
288 unsigned int precision = min->get_precision ();
289 *min = wi::min_value (precision, sgn);
290 *max = wi::max_value (precision, sgn);
291 vr_type = VR_RANGE;
294 if (vr_type == VR_RANGE || vr_type == VR_VARYING)
296 *max = wi::round_down_for_mask (*max, nonzero_bits);
298 /* Check that the range contains at least one valid value. */
299 if (wi::gt_p (*min, *max, sgn))
300 return VR_UNDEFINED;
302 *min = wi::round_up_for_mask (*min, nonzero_bits);
303 gcc_checking_assert (wi::le_p (*min, *max, sgn));
305 return vr_type;
308 /* Return true if max and min of VR are INTEGER_CST. It's not necessary
309 a singleton. */
311 bool
312 range_int_cst_p (const value_range *vr)
314 return (vr->kind () == VR_RANGE && range_has_numeric_bounds_p (vr));
317 /* Return the single symbol (an SSA_NAME) contained in T if any, or NULL_TREE
318 otherwise. We only handle additive operations and set NEG to true if the
319 symbol is negated and INV to the invariant part, if any. */
321 static tree
322 get_single_symbol (tree t, bool *neg, tree *inv)
324 bool neg_;
325 tree inv_;
327 *inv = NULL_TREE;
328 *neg = false;
330 if (TREE_CODE (t) == PLUS_EXPR
331 || TREE_CODE (t) == POINTER_PLUS_EXPR
332 || TREE_CODE (t) == MINUS_EXPR)
334 if (is_gimple_min_invariant (TREE_OPERAND (t, 0)))
336 neg_ = (TREE_CODE (t) == MINUS_EXPR);
337 inv_ = TREE_OPERAND (t, 0);
338 t = TREE_OPERAND (t, 1);
340 else if (is_gimple_min_invariant (TREE_OPERAND (t, 1)))
342 neg_ = false;
343 inv_ = TREE_OPERAND (t, 1);
344 t = TREE_OPERAND (t, 0);
346 else
347 return NULL_TREE;
349 else
351 neg_ = false;
352 inv_ = NULL_TREE;
355 if (TREE_CODE (t) == NEGATE_EXPR)
357 t = TREE_OPERAND (t, 0);
358 neg_ = !neg_;
361 if (TREE_CODE (t) != SSA_NAME)
362 return NULL_TREE;
364 if (inv_ && TREE_OVERFLOW_P (inv_))
365 inv_ = drop_tree_overflow (inv_);
367 *neg = neg_;
368 *inv = inv_;
369 return t;
372 /* Return
373 1 if VAL < VAL2
374 0 if !(VAL < VAL2)
375 -2 if those are incomparable. */
377 operand_less_p (tree val, tree val2)
379 /* LT is folded faster than GE and others. Inline the common case. */
380 if (TREE_CODE (val) == INTEGER_CST && TREE_CODE (val2) == INTEGER_CST)
381 return tree_int_cst_lt (val, val2);
382 else if (TREE_CODE (val) == SSA_NAME && TREE_CODE (val2) == SSA_NAME)
383 return val == val2 ? 0 : -2;
384 else
386 int cmp = compare_values (val, val2);
387 if (cmp == -1)
388 return 1;
389 else if (cmp == 0 || cmp == 1)
390 return 0;
391 else
392 return -2;
396 /* Compare two values VAL1 and VAL2. Return
398 -2 if VAL1 and VAL2 cannot be compared at compile-time,
399 -1 if VAL1 < VAL2,
400 0 if VAL1 == VAL2,
401 +1 if VAL1 > VAL2, and
402 +2 if VAL1 != VAL2
404 This is similar to tree_int_cst_compare but supports pointer values
405 and values that cannot be compared at compile time.
407 If STRICT_OVERFLOW_P is not NULL, then set *STRICT_OVERFLOW_P to
408 true if the return value is only valid if we assume that signed
409 overflow is undefined. */
412 compare_values_warnv (tree val1, tree val2, bool *strict_overflow_p)
414 if (val1 == val2)
415 return 0;
417 /* Below we rely on the fact that VAL1 and VAL2 are both pointers or
418 both integers. */
419 gcc_assert (POINTER_TYPE_P (TREE_TYPE (val1))
420 == POINTER_TYPE_P (TREE_TYPE (val2)));
422 /* Convert the two values into the same type. This is needed because
423 sizetype causes sign extension even for unsigned types. */
424 if (!useless_type_conversion_p (TREE_TYPE (val1), TREE_TYPE (val2)))
425 val2 = fold_convert (TREE_TYPE (val1), val2);
427 const bool overflow_undefined
428 = INTEGRAL_TYPE_P (TREE_TYPE (val1))
429 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1));
430 tree inv1, inv2;
431 bool neg1, neg2;
432 tree sym1 = get_single_symbol (val1, &neg1, &inv1);
433 tree sym2 = get_single_symbol (val2, &neg2, &inv2);
435 /* If VAL1 and VAL2 are of the form '[-]NAME [+ CST]', return -1 or +1
436 accordingly. If VAL1 and VAL2 don't use the same name, return -2. */
437 if (sym1 && sym2)
439 /* Both values must use the same name with the same sign. */
440 if (sym1 != sym2 || neg1 != neg2)
441 return -2;
443 /* [-]NAME + CST == [-]NAME + CST. */
444 if (inv1 == inv2)
445 return 0;
447 /* If overflow is defined we cannot simplify more. */
448 if (!overflow_undefined)
449 return -2;
451 if (strict_overflow_p != NULL
452 /* Symbolic range building sets the no-warning bit to declare
453 that overflow doesn't happen. */
454 && (!inv1 || !warning_suppressed_p (val1, OPT_Woverflow))
455 && (!inv2 || !warning_suppressed_p (val2, OPT_Woverflow)))
456 *strict_overflow_p = true;
458 if (!inv1)
459 inv1 = build_int_cst (TREE_TYPE (val1), 0);
460 if (!inv2)
461 inv2 = build_int_cst (TREE_TYPE (val2), 0);
463 return wi::cmp (wi::to_wide (inv1), wi::to_wide (inv2),
464 TYPE_SIGN (TREE_TYPE (val1)));
467 const bool cst1 = is_gimple_min_invariant (val1);
468 const bool cst2 = is_gimple_min_invariant (val2);
470 /* If one is of the form '[-]NAME + CST' and the other is constant, then
471 it might be possible to say something depending on the constants. */
472 if ((sym1 && inv1 && cst2) || (sym2 && inv2 && cst1))
474 if (!overflow_undefined)
475 return -2;
477 if (strict_overflow_p != NULL
478 /* Symbolic range building sets the no-warning bit to declare
479 that overflow doesn't happen. */
480 && (!sym1 || !warning_suppressed_p (val1, OPT_Woverflow))
481 && (!sym2 || !warning_suppressed_p (val2, OPT_Woverflow)))
482 *strict_overflow_p = true;
484 const signop sgn = TYPE_SIGN (TREE_TYPE (val1));
485 tree cst = cst1 ? val1 : val2;
486 tree inv = cst1 ? inv2 : inv1;
488 /* Compute the difference between the constants. If it overflows or
489 underflows, this means that we can trivially compare the NAME with
490 it and, consequently, the two values with each other. */
491 wide_int diff = wi::to_wide (cst) - wi::to_wide (inv);
492 if (wi::cmp (0, wi::to_wide (inv), sgn)
493 != wi::cmp (diff, wi::to_wide (cst), sgn))
495 const int res = wi::cmp (wi::to_wide (cst), wi::to_wide (inv), sgn);
496 return cst1 ? res : -res;
499 return -2;
502 /* We cannot say anything more for non-constants. */
503 if (!cst1 || !cst2)
504 return -2;
506 if (!POINTER_TYPE_P (TREE_TYPE (val1)))
508 /* We cannot compare overflowed values. */
509 if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
510 return -2;
512 if (TREE_CODE (val1) == INTEGER_CST
513 && TREE_CODE (val2) == INTEGER_CST)
514 return tree_int_cst_compare (val1, val2);
516 if (poly_int_tree_p (val1) && poly_int_tree_p (val2))
518 if (known_eq (wi::to_poly_widest (val1),
519 wi::to_poly_widest (val2)))
520 return 0;
521 if (known_lt (wi::to_poly_widest (val1),
522 wi::to_poly_widest (val2)))
523 return -1;
524 if (known_gt (wi::to_poly_widest (val1),
525 wi::to_poly_widest (val2)))
526 return 1;
529 return -2;
531 else
533 if (TREE_CODE (val1) == INTEGER_CST && TREE_CODE (val2) == INTEGER_CST)
535 /* We cannot compare overflowed values. */
536 if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
537 return -2;
539 return tree_int_cst_compare (val1, val2);
542 /* First see if VAL1 and VAL2 are not the same. */
543 if (operand_equal_p (val1, val2, 0))
544 return 0;
546 fold_defer_overflow_warnings ();
548 /* If VAL1 is a lower address than VAL2, return -1. */
549 tree t = fold_binary_to_constant (LT_EXPR, boolean_type_node, val1, val2);
550 if (t && integer_onep (t))
552 fold_undefer_and_ignore_overflow_warnings ();
553 return -1;
556 /* If VAL1 is a higher address than VAL2, return +1. */
557 t = fold_binary_to_constant (LT_EXPR, boolean_type_node, val2, val1);
558 if (t && integer_onep (t))
560 fold_undefer_and_ignore_overflow_warnings ();
561 return 1;
564 /* If VAL1 is different than VAL2, return +2. */
565 t = fold_binary_to_constant (NE_EXPR, boolean_type_node, val1, val2);
566 fold_undefer_and_ignore_overflow_warnings ();
567 if (t && integer_onep (t))
568 return 2;
570 return -2;
574 /* Compare values like compare_values_warnv. */
577 compare_values (tree val1, tree val2)
579 bool sop;
580 return compare_values_warnv (val1, val2, &sop);
583 /* If the types passed are supported, return TRUE, otherwise set VR to
584 VARYING and return FALSE. */
586 static bool
587 supported_types_p (value_range *vr,
588 tree type0,
589 tree = NULL)
591 if (!value_range::supports_p (type0))
593 vr->set_varying (type0);
594 return false;
596 return true;
599 /* If any of the ranges passed are defined, return TRUE, otherwise set
600 VR to UNDEFINED and return FALSE. */
602 static bool
603 defined_ranges_p (value_range *vr,
604 const value_range *vr0, const value_range *vr1 = NULL)
606 if (vr0->undefined_p () && (!vr1 || vr1->undefined_p ()))
608 vr->set_undefined ();
609 return false;
611 return true;
614 /* Perform a binary operation on a pair of ranges. */
616 void
617 range_fold_binary_expr (value_range *vr,
618 enum tree_code code,
619 tree expr_type,
620 const value_range *vr0_,
621 const value_range *vr1_)
623 if (!supported_types_p (vr, expr_type)
624 || !defined_ranges_p (vr, vr0_, vr1_))
625 return;
626 range_op_handler op (code, expr_type);
627 if (!op)
629 vr->set_varying (expr_type);
630 return;
633 value_range vr0 (*vr0_);
634 value_range vr1 (*vr1_);
635 if (vr0.undefined_p ())
636 vr0.set_varying (expr_type);
637 if (vr1.undefined_p ())
638 vr1.set_varying (expr_type);
639 vr0.normalize_addresses ();
640 vr1.normalize_addresses ();
641 if (!op.fold_range (*vr, expr_type, vr0, vr1))
642 vr->set_varying (expr_type);
645 /* Perform a unary operation on a range. */
647 void
648 range_fold_unary_expr (value_range *vr,
649 enum tree_code code, tree expr_type,
650 const value_range *vr0,
651 tree vr0_type)
653 if (!supported_types_p (vr, expr_type, vr0_type)
654 || !defined_ranges_p (vr, vr0))
655 return;
656 range_op_handler op (code, expr_type);
657 if (!op)
659 vr->set_varying (expr_type);
660 return;
663 value_range vr0_cst (*vr0);
664 vr0_cst.normalize_addresses ();
665 if (!op.fold_range (*vr, expr_type, vr0_cst, value_range (expr_type)))
666 vr->set_varying (expr_type);
669 /* Helper for overflow_comparison_p
671 OP0 CODE OP1 is a comparison. Examine the comparison and potentially
672 OP1's defining statement to see if it ultimately has the form
673 OP0 CODE (OP0 PLUS INTEGER_CST)
675 If so, return TRUE indicating this is an overflow test and store into
676 *NEW_CST an updated constant that can be used in a narrowed range test.
678 REVERSED indicates if the comparison was originally:
680 OP1 CODE' OP0.
682 This affects how we build the updated constant. */
684 static bool
685 overflow_comparison_p_1 (enum tree_code code, tree op0, tree op1,
686 bool reversed, tree *new_cst)
688 /* See if this is a relational operation between two SSA_NAMES with
689 unsigned, overflow wrapping values. If so, check it more deeply. */
690 if ((code == LT_EXPR || code == LE_EXPR
691 || code == GE_EXPR || code == GT_EXPR)
692 && TREE_CODE (op0) == SSA_NAME
693 && TREE_CODE (op1) == SSA_NAME
694 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
695 && TYPE_UNSIGNED (TREE_TYPE (op0))
696 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0)))
698 gimple *op1_def = SSA_NAME_DEF_STMT (op1);
700 /* Now look at the defining statement of OP1 to see if it adds
701 or subtracts a nonzero constant from another operand. */
702 if (op1_def
703 && is_gimple_assign (op1_def)
704 && gimple_assign_rhs_code (op1_def) == PLUS_EXPR
705 && TREE_CODE (gimple_assign_rhs2 (op1_def)) == INTEGER_CST
706 && !integer_zerop (gimple_assign_rhs2 (op1_def)))
708 tree target = gimple_assign_rhs1 (op1_def);
710 /* If we did not find our target SSA_NAME, then this is not
711 an overflow test. */
712 if (op0 != target)
713 return false;
715 tree type = TREE_TYPE (op0);
716 wide_int max = wi::max_value (TYPE_PRECISION (type), UNSIGNED);
717 tree inc = gimple_assign_rhs2 (op1_def);
718 if (reversed)
719 *new_cst = wide_int_to_tree (type, max + wi::to_wide (inc));
720 else
721 *new_cst = wide_int_to_tree (type, max - wi::to_wide (inc));
722 return true;
725 return false;
728 /* OP0 CODE OP1 is a comparison. Examine the comparison and potentially
729 OP1's defining statement to see if it ultimately has the form
730 OP0 CODE (OP0 PLUS INTEGER_CST)
732 If so, return TRUE indicating this is an overflow test and store into
733 *NEW_CST an updated constant that can be used in a narrowed range test.
735 These statements are left as-is in the IL to facilitate discovery of
736 {ADD,SUB}_OVERFLOW sequences later in the optimizer pipeline. But
737 the alternate range representation is often useful within VRP. */
739 bool
740 overflow_comparison_p (tree_code code, tree name, tree val, tree *new_cst)
742 if (overflow_comparison_p_1 (code, name, val, false, new_cst))
743 return true;
744 return overflow_comparison_p_1 (swap_tree_comparison (code), val, name,
745 true, new_cst);
748 /* Handle
749 _4 = x_3 & 31;
750 if (_4 != 0)
751 goto <bb 6>;
752 else
753 goto <bb 7>;
754 <bb 6>:
755 __builtin_unreachable ();
756 <bb 7>:
758 If x_3 has no other immediate uses (checked by caller), var is the
759 x_3 var, we can clear low 5 bits from the non-zero bitmask. */
761 void
762 maybe_set_nonzero_bits (edge e, tree var)
764 basic_block cond_bb = e->src;
765 gimple *stmt = last_stmt (cond_bb);
766 tree cst;
768 if (stmt == NULL
769 || gimple_code (stmt) != GIMPLE_COND
770 || gimple_cond_code (stmt) != ((e->flags & EDGE_TRUE_VALUE)
771 ? EQ_EXPR : NE_EXPR)
772 || TREE_CODE (gimple_cond_lhs (stmt)) != SSA_NAME
773 || !integer_zerop (gimple_cond_rhs (stmt)))
774 return;
776 stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt));
777 if (!is_gimple_assign (stmt)
778 || gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
779 || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
780 return;
781 if (gimple_assign_rhs1 (stmt) != var)
783 gimple *stmt2;
785 if (TREE_CODE (gimple_assign_rhs1 (stmt)) != SSA_NAME)
786 return;
787 stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
788 if (!gimple_assign_cast_p (stmt2)
789 || gimple_assign_rhs1 (stmt2) != var
790 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt2))
791 || (TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (stmt)))
792 != TYPE_PRECISION (TREE_TYPE (var))))
793 return;
795 cst = gimple_assign_rhs2 (stmt);
796 if (POINTER_TYPE_P (TREE_TYPE (var)))
798 struct ptr_info_def *pi = SSA_NAME_PTR_INFO (var);
799 if (pi && pi->misalign)
800 return;
801 wide_int w = wi::bit_not (wi::to_wide (cst));
802 unsigned int bits = wi::ctz (w);
803 if (bits == 0 || bits >= HOST_BITS_PER_INT)
804 return;
805 unsigned int align = 1U << bits;
806 if (pi == NULL || pi->align < align)
807 set_ptr_info_alignment (get_ptr_info (var), align, 0);
809 else
810 set_nonzero_bits (var, wi::bit_and_not (get_nonzero_bits (var),
811 wi::to_wide (cst)));
814 /* Searches the case label vector VEC for the index *IDX of the CASE_LABEL
815 that includes the value VAL. The search is restricted to the range
816 [START_IDX, n - 1] where n is the size of VEC.
818 If there is a CASE_LABEL for VAL, its index is placed in IDX and true is
819 returned.
821 If there is no CASE_LABEL for VAL and there is one that is larger than VAL,
822 it is placed in IDX and false is returned.
824 If VAL is larger than any CASE_LABEL, n is placed on IDX and false is
825 returned. */
827 bool
828 find_case_label_index (gswitch *stmt, size_t start_idx, tree val, size_t *idx)
830 size_t n = gimple_switch_num_labels (stmt);
831 size_t low, high;
833 /* Find case label for minimum of the value range or the next one.
834 At each iteration we are searching in [low, high - 1]. */
836 for (low = start_idx, high = n; high != low; )
838 tree t;
839 int cmp;
840 /* Note that i != high, so we never ask for n. */
841 size_t i = (high + low) / 2;
842 t = gimple_switch_label (stmt, i);
844 /* Cache the result of comparing CASE_LOW and val. */
845 cmp = tree_int_cst_compare (CASE_LOW (t), val);
847 if (cmp == 0)
849 /* Ranges cannot be empty. */
850 *idx = i;
851 return true;
853 else if (cmp > 0)
854 high = i;
855 else
857 low = i + 1;
858 if (CASE_HIGH (t) != NULL
859 && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
861 *idx = i;
862 return true;
867 *idx = high;
868 return false;
871 /* Searches the case label vector VEC for the range of CASE_LABELs that is used
872 for values between MIN and MAX. The first index is placed in MIN_IDX. The
873 last index is placed in MAX_IDX. If the range of CASE_LABELs is empty
874 then MAX_IDX < MIN_IDX.
875 Returns true if the default label is not needed. */
877 bool
878 find_case_label_range (gswitch *stmt, tree min, tree max, size_t *min_idx,
879 size_t *max_idx)
881 size_t i, j;
882 bool min_take_default = !find_case_label_index (stmt, 1, min, &i);
883 bool max_take_default = !find_case_label_index (stmt, i, max, &j);
885 if (i == j
886 && min_take_default
887 && max_take_default)
889 /* Only the default case label reached.
890 Return an empty range. */
891 *min_idx = 1;
892 *max_idx = 0;
893 return false;
895 else
897 bool take_default = min_take_default || max_take_default;
898 tree low, high;
899 size_t k;
901 if (max_take_default)
902 j--;
904 /* If the case label range is continuous, we do not need
905 the default case label. Verify that. */
906 high = CASE_LOW (gimple_switch_label (stmt, i));
907 if (CASE_HIGH (gimple_switch_label (stmt, i)))
908 high = CASE_HIGH (gimple_switch_label (stmt, i));
909 for (k = i + 1; k <= j; ++k)
911 low = CASE_LOW (gimple_switch_label (stmt, k));
912 if (!integer_onep (int_const_binop (MINUS_EXPR, low, high)))
914 take_default = true;
915 break;
917 high = low;
918 if (CASE_HIGH (gimple_switch_label (stmt, k)))
919 high = CASE_HIGH (gimple_switch_label (stmt, k));
922 *min_idx = i;
923 *max_idx = j;
924 return !take_default;
928 /* Given a SWITCH_STMT, return the case label that encompasses the
929 known possible values for the switch operand. RANGE_OF_OP is a
930 range for the known values of the switch operand. */
932 tree
933 find_case_label_range (gswitch *switch_stmt, const irange *range_of_op)
935 if (range_of_op->undefined_p ()
936 || range_of_op->varying_p ())
937 return NULL_TREE;
939 size_t i, j;
940 tree op = gimple_switch_index (switch_stmt);
941 tree type = TREE_TYPE (op);
942 tree tmin = wide_int_to_tree (type, range_of_op->lower_bound ());
943 tree tmax = wide_int_to_tree (type, range_of_op->upper_bound ());
944 find_case_label_range (switch_stmt, tmin, tmax, &i, &j);
945 if (i == j)
947 /* Look for exactly one label that encompasses the range of
948 the operand. */
949 tree label = gimple_switch_label (switch_stmt, i);
950 tree case_high
951 = CASE_HIGH (label) ? CASE_HIGH (label) : CASE_LOW (label);
952 int_range_max label_range (CASE_LOW (label), case_high);
953 if (!types_compatible_p (label_range.type (), range_of_op->type ()))
954 range_cast (label_range, range_of_op->type ());
955 label_range.intersect (*range_of_op);
956 if (label_range == *range_of_op)
957 return label;
959 else if (i > j)
961 /* If there are no labels at all, take the default. */
962 return gimple_switch_label (switch_stmt, 0);
964 else
966 /* Otherwise, there are various labels that can encompass
967 the range of operand. In which case, see if the range of
968 the operand is entirely *outside* the bounds of all the
969 (non-default) case labels. If so, take the default. */
970 unsigned n = gimple_switch_num_labels (switch_stmt);
971 tree min_label = gimple_switch_label (switch_stmt, 1);
972 tree max_label = gimple_switch_label (switch_stmt, n - 1);
973 tree case_high = CASE_HIGH (max_label);
974 if (!case_high)
975 case_high = CASE_LOW (max_label);
976 int_range_max label_range (CASE_LOW (min_label), case_high);
977 if (!types_compatible_p (label_range.type (), range_of_op->type ()))
978 range_cast (label_range, range_of_op->type ());
979 label_range.intersect (*range_of_op);
980 if (label_range.undefined_p ())
981 return gimple_switch_label (switch_stmt, 0);
983 return NULL_TREE;
986 struct case_info
988 tree expr;
989 basic_block bb;
992 // This is a ranger based folder which continues to use the dominator
993 // walk to access the substitute and fold machinery. Ranges are calculated
994 // on demand.
996 class rvrp_folder : public substitute_and_fold_engine
998 public:
1000 rvrp_folder (gimple_ranger *r) : substitute_and_fold_engine (),
1001 m_unreachable (*r),
1002 m_simplifier (r, r->non_executable_edge_flag)
1004 m_ranger = r;
1005 m_pta = new pointer_equiv_analyzer (m_ranger);
1006 m_last_bb_stmt = NULL;
1009 ~rvrp_folder ()
1011 delete m_pta;
1014 tree value_of_expr (tree name, gimple *s = NULL) override
1016 // Shortcircuit subst_and_fold callbacks for abnormal ssa_names.
1017 if (TREE_CODE (name) == SSA_NAME && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
1018 return NULL;
1019 tree ret = m_ranger->value_of_expr (name, s);
1020 if (!ret && supported_pointer_equiv_p (name))
1021 ret = m_pta->get_equiv (name);
1022 return ret;
1025 tree value_on_edge (edge e, tree name) override
1027 // Shortcircuit subst_and_fold callbacks for abnormal ssa_names.
1028 if (TREE_CODE (name) == SSA_NAME && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
1029 return NULL;
1030 tree ret = m_ranger->value_on_edge (e, name);
1031 if (!ret && supported_pointer_equiv_p (name))
1032 ret = m_pta->get_equiv (name);
1033 return ret;
1036 tree value_of_stmt (gimple *s, tree name = NULL) override
1038 // Shortcircuit subst_and_fold callbacks for abnormal ssa_names.
1039 if (TREE_CODE (name) == SSA_NAME && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
1040 return NULL;
1041 return m_ranger->value_of_stmt (s, name);
1044 void pre_fold_bb (basic_block bb) override
1046 m_pta->enter (bb);
1047 for (gphi_iterator gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
1048 gsi_next (&gsi))
1049 m_ranger->register_inferred_ranges (gsi.phi ());
1050 m_last_bb_stmt = last_stmt (bb);
1053 void post_fold_bb (basic_block bb) override
1055 m_pta->leave (bb);
1056 if (cfun->after_inlining)
1057 m_unreachable.maybe_register_block (bb);
1060 void pre_fold_stmt (gimple *stmt) override
1062 m_pta->visit_stmt (stmt);
1063 // If this is the last stmt and there are inferred ranges, reparse the
1064 // block for transitive inferred ranges that occur earlier in the block.
1065 if (stmt == m_last_bb_stmt)
1066 m_ranger->register_transitive_inferred_ranges (gimple_bb (stmt));
1069 bool fold_stmt (gimple_stmt_iterator *gsi) override
1071 bool ret = m_simplifier.simplify (gsi);
1072 if (!ret)
1073 ret = m_ranger->fold_stmt (gsi, follow_single_use_edges);
1074 m_ranger->register_inferred_ranges (gsi_stmt (*gsi));
1075 return ret;
1078 remove_unreachable m_unreachable;
1079 private:
1080 DISABLE_COPY_AND_ASSIGN (rvrp_folder);
1081 gimple_ranger *m_ranger;
1082 simplify_using_ranges m_simplifier;
1083 pointer_equiv_analyzer *m_pta;
1084 gimple *m_last_bb_stmt;
1087 /* Main entry point for a VRP pass using just ranger. This can be called
1088 from anywhere to perform a VRP pass, including from EVRP. */
1090 unsigned int
1091 execute_ranger_vrp (struct function *fun, bool warn_array_bounds_p,
1092 bool final_p)
1094 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
1095 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
1096 scev_initialize ();
1097 calculate_dominance_info (CDI_DOMINATORS);
1099 set_all_edges_as_executable (fun);
1100 gimple_ranger *ranger = enable_ranger (fun, false);
1101 rvrp_folder folder (ranger);
1102 folder.substitute_and_fold ();
1103 // Remove tagged builtin-unreachable and maybe update globals.
1104 folder.m_unreachable.remove_and_update_globals (final_p);
1105 if (dump_file && (dump_flags & TDF_DETAILS))
1106 ranger->dump (dump_file);
1108 if ((warn_array_bounds || warn_strict_flex_arrays) && warn_array_bounds_p)
1110 // Set all edges as executable, except those ranger says aren't.
1111 int non_exec_flag = ranger->non_executable_edge_flag;
1112 basic_block bb;
1113 FOR_ALL_BB_FN (bb, fun)
1115 edge_iterator ei;
1116 edge e;
1117 FOR_EACH_EDGE (e, ei, bb->succs)
1118 if (e->flags & non_exec_flag)
1119 e->flags &= ~EDGE_EXECUTABLE;
1120 else
1121 e->flags |= EDGE_EXECUTABLE;
1123 scev_reset ();
1124 array_bounds_checker array_checker (fun, ranger);
1125 array_checker.check ();
1128 disable_ranger (fun);
1129 scev_finalize ();
1130 loop_optimizer_finalize ();
1131 return 0;
1134 namespace {
1136 const pass_data pass_data_vrp =
1138 GIMPLE_PASS, /* type */
1139 "vrp", /* name */
1140 OPTGROUP_NONE, /* optinfo_flags */
1141 TV_TREE_VRP, /* tv_id */
1142 PROP_ssa, /* properties_required */
1143 0, /* properties_provided */
1144 0, /* properties_destroyed */
1145 0, /* todo_flags_start */
1146 ( TODO_cleanup_cfg | TODO_update_ssa ), /* todo_flags_finish */
1149 const pass_data pass_data_early_vrp =
1151 GIMPLE_PASS, /* type */
1152 "evrp", /* name */
1153 OPTGROUP_NONE, /* optinfo_flags */
1154 TV_TREE_EARLY_VRP, /* tv_id */
1155 PROP_ssa, /* properties_required */
1156 0, /* properties_provided */
1157 0, /* properties_destroyed */
1158 0, /* todo_flags_start */
1159 ( TODO_cleanup_cfg | TODO_update_ssa | TODO_verify_all ),
1162 static int vrp_pass_num = 0;
1163 class pass_vrp : public gimple_opt_pass
1165 public:
1166 pass_vrp (gcc::context *ctxt, const pass_data &data_)
1167 : gimple_opt_pass (data_, ctxt), data (data_), warn_array_bounds_p (false),
1168 my_pass (vrp_pass_num++)
1171 /* opt_pass methods: */
1172 opt_pass * clone () final override { return new pass_vrp (m_ctxt, data); }
1173 void set_pass_param (unsigned int n, bool param) final override
1175 gcc_assert (n == 0);
1176 warn_array_bounds_p = param;
1178 bool gate (function *) final override { return flag_tree_vrp != 0; }
1179 unsigned int execute (function *fun) final override
1181 // Early VRP pass.
1182 if (my_pass == 0)
1183 return execute_ranger_vrp (fun, /*warn_array_bounds_p=*/false, false);
1185 return execute_ranger_vrp (fun, warn_array_bounds_p, my_pass == 2);
1188 private:
1189 const pass_data &data;
1190 bool warn_array_bounds_p;
1191 int my_pass;
1192 }; // class pass_vrp
1194 const pass_data pass_data_assumptions =
1196 GIMPLE_PASS, /* type */
1197 "assumptions", /* name */
1198 OPTGROUP_NONE, /* optinfo_flags */
1199 TV_TREE_ASSUMPTIONS, /* tv_id */
1200 PROP_ssa, /* properties_required */
1201 PROP_assumptions_done, /* properties_provided */
1202 0, /* properties_destroyed */
1203 0, /* todo_flags_start */
1204 0, /* todo_flags_end */
1207 class pass_assumptions : public gimple_opt_pass
1209 public:
1210 pass_assumptions (gcc::context *ctxt)
1211 : gimple_opt_pass (pass_data_assumptions, ctxt)
1214 /* opt_pass methods: */
1215 bool gate (function *fun) final override { return fun->assume_function; }
1216 unsigned int execute (function *) final override
1218 assume_query query;
1219 if (dump_file)
1220 fprintf (dump_file, "Assumptions :\n--------------\n");
1222 for (tree arg = DECL_ARGUMENTS (cfun->decl); arg; arg = DECL_CHAIN (arg))
1224 tree name = ssa_default_def (cfun, arg);
1225 if (!name || !gimple_range_ssa_p (name))
1226 continue;
1227 tree type = TREE_TYPE (name);
1228 if (!Value_Range::supports_type_p (type))
1229 continue;
1230 Value_Range assume_range (type);
1231 if (query.assume_range_p (assume_range, name))
1233 // Set the global range of NAME to anything calculated.
1234 set_range_info (name, assume_range);
1235 if (dump_file)
1237 print_generic_expr (dump_file, name, TDF_SLIM);
1238 fprintf (dump_file, " -> ");
1239 assume_range.dump (dump_file);
1240 fputc ('\n', dump_file);
1244 if (dump_file)
1246 fputc ('\n', dump_file);
1247 gimple_dump_cfg (dump_file, dump_flags & ~TDF_DETAILS);
1248 if (dump_flags & TDF_DETAILS)
1249 query.dump (dump_file);
1251 return TODO_discard_function;
1254 }; // class pass_assumptions
1256 } // anon namespace
1258 gimple_opt_pass *
1259 make_pass_vrp (gcc::context *ctxt)
1261 return new pass_vrp (ctxt, pass_data_vrp);
1264 gimple_opt_pass *
1265 make_pass_early_vrp (gcc::context *ctxt)
1267 return new pass_vrp (ctxt, pass_data_early_vrp);
1270 gimple_opt_pass *
1271 make_pass_assumptions (gcc::context *ctx)
1273 return new pass_assumptions (ctx);