Avoid is_constant calls in vectorizable_bswap
[official-gcc.git] / gcc / tree-vrp.c
blob735b3646e815600d677c337ddd8309373ef25aa4
1 /* Support routines for Value Range Propagation (VRP).
2 Copyright (C) 2005-2018 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 "backend.h"
25 #include "insn-codes.h"
26 #include "rtl.h"
27 #include "tree.h"
28 #include "gimple.h"
29 #include "cfghooks.h"
30 #include "tree-pass.h"
31 #include "ssa.h"
32 #include "optabs-tree.h"
33 #include "gimple-pretty-print.h"
34 #include "diagnostic-core.h"
35 #include "flags.h"
36 #include "fold-const.h"
37 #include "stor-layout.h"
38 #include "calls.h"
39 #include "cfganal.h"
40 #include "gimple-fold.h"
41 #include "tree-eh.h"
42 #include "gimple-iterator.h"
43 #include "gimple-walk.h"
44 #include "tree-cfg.h"
45 #include "tree-dfa.h"
46 #include "tree-ssa-loop-manip.h"
47 #include "tree-ssa-loop-niter.h"
48 #include "tree-ssa-loop.h"
49 #include "tree-into-ssa.h"
50 #include "tree-ssa.h"
51 #include "intl.h"
52 #include "cfgloop.h"
53 #include "tree-scalar-evolution.h"
54 #include "tree-ssa-propagate.h"
55 #include "tree-chrec.h"
56 #include "tree-ssa-threadupdate.h"
57 #include "tree-ssa-scopedtables.h"
58 #include "tree-ssa-threadedge.h"
59 #include "omp-general.h"
60 #include "target.h"
61 #include "case-cfn-macros.h"
62 #include "params.h"
63 #include "alloc-pool.h"
64 #include "domwalk.h"
65 #include "tree-cfgcleanup.h"
66 #include "stringpool.h"
67 #include "attribs.h"
68 #include "vr-values.h"
69 #include "builtins.h"
70 #include "wide-int-range.h"
72 /* Set of SSA names found live during the RPO traversal of the function
73 for still active basic-blocks. */
74 static sbitmap *live;
76 /* Return true if the SSA name NAME is live on the edge E. */
78 static bool
79 live_on_edge (edge e, tree name)
81 return (live[e->dest->index]
82 && bitmap_bit_p (live[e->dest->index], SSA_NAME_VERSION (name)));
85 /* Location information for ASSERT_EXPRs. Each instance of this
86 structure describes an ASSERT_EXPR for an SSA name. Since a single
87 SSA name may have more than one assertion associated with it, these
88 locations are kept in a linked list attached to the corresponding
89 SSA name. */
90 struct assert_locus
92 /* Basic block where the assertion would be inserted. */
93 basic_block bb;
95 /* Some assertions need to be inserted on an edge (e.g., assertions
96 generated by COND_EXPRs). In those cases, BB will be NULL. */
97 edge e;
99 /* Pointer to the statement that generated this assertion. */
100 gimple_stmt_iterator si;
102 /* Predicate code for the ASSERT_EXPR. Must be COMPARISON_CLASS_P. */
103 enum tree_code comp_code;
105 /* Value being compared against. */
106 tree val;
108 /* Expression to compare. */
109 tree expr;
111 /* Next node in the linked list. */
112 assert_locus *next;
115 /* If bit I is present, it means that SSA name N_i has a list of
116 assertions that should be inserted in the IL. */
117 static bitmap need_assert_for;
119 /* Array of locations lists where to insert assertions. ASSERTS_FOR[I]
120 holds a list of ASSERT_LOCUS_T nodes that describe where
121 ASSERT_EXPRs for SSA name N_I should be inserted. */
122 static assert_locus **asserts_for;
124 vec<edge> to_remove_edges;
125 vec<switch_update> to_update_switch_stmts;
128 /* Return the maximum value for TYPE. */
130 tree
131 vrp_val_max (const_tree type)
133 if (!INTEGRAL_TYPE_P (type))
134 return NULL_TREE;
136 return TYPE_MAX_VALUE (type);
139 /* Return the minimum value for TYPE. */
141 tree
142 vrp_val_min (const_tree type)
144 if (!INTEGRAL_TYPE_P (type))
145 return NULL_TREE;
147 return TYPE_MIN_VALUE (type);
150 /* Return whether VAL is equal to the maximum value of its type.
151 We can't do a simple equality comparison with TYPE_MAX_VALUE because
152 C typedefs and Ada subtypes can produce types whose TYPE_MAX_VALUE
153 is not == to the integer constant with the same value in the type. */
155 bool
156 vrp_val_is_max (const_tree val)
158 tree type_max = vrp_val_max (TREE_TYPE (val));
159 return (val == type_max
160 || (type_max != NULL_TREE
161 && operand_equal_p (val, type_max, 0)));
164 /* Return whether VAL is equal to the minimum value of its type. */
166 bool
167 vrp_val_is_min (const_tree val)
169 tree type_min = vrp_val_min (TREE_TYPE (val));
170 return (val == type_min
171 || (type_min != NULL_TREE
172 && operand_equal_p (val, type_min, 0)));
175 /* VR_TYPE describes a range with mininum value *MIN and maximum
176 value *MAX. Restrict the range to the set of values that have
177 no bits set outside NONZERO_BITS. Update *MIN and *MAX and
178 return the new range type.
180 SGN gives the sign of the values described by the range. */
182 enum value_range_type
183 intersect_range_with_nonzero_bits (enum value_range_type vr_type,
184 wide_int *min, wide_int *max,
185 const wide_int &nonzero_bits,
186 signop sgn)
188 if (vr_type == VR_ANTI_RANGE)
190 /* The VR_ANTI_RANGE is equivalent to the union of the ranges
191 A: [-INF, *MIN) and B: (*MAX, +INF]. First use NONZERO_BITS
192 to create an inclusive upper bound for A and an inclusive lower
193 bound for B. */
194 wide_int a_max = wi::round_down_for_mask (*min - 1, nonzero_bits);
195 wide_int b_min = wi::round_up_for_mask (*max + 1, nonzero_bits);
197 /* If the calculation of A_MAX wrapped, A is effectively empty
198 and A_MAX is the highest value that satisfies NONZERO_BITS.
199 Likewise if the calculation of B_MIN wrapped, B is effectively
200 empty and B_MIN is the lowest value that satisfies NONZERO_BITS. */
201 bool a_empty = wi::ge_p (a_max, *min, sgn);
202 bool b_empty = wi::le_p (b_min, *max, sgn);
204 /* If both A and B are empty, there are no valid values. */
205 if (a_empty && b_empty)
206 return VR_UNDEFINED;
208 /* If exactly one of A or B is empty, return a VR_RANGE for the
209 other one. */
210 if (a_empty || b_empty)
212 *min = b_min;
213 *max = a_max;
214 gcc_checking_assert (wi::le_p (*min, *max, sgn));
215 return VR_RANGE;
218 /* Update the VR_ANTI_RANGE bounds. */
219 *min = a_max + 1;
220 *max = b_min - 1;
221 gcc_checking_assert (wi::le_p (*min, *max, sgn));
223 /* Now check whether the excluded range includes any values that
224 satisfy NONZERO_BITS. If not, switch to a full VR_RANGE. */
225 if (wi::round_up_for_mask (*min, nonzero_bits) == b_min)
227 unsigned int precision = min->get_precision ();
228 *min = wi::min_value (precision, sgn);
229 *max = wi::max_value (precision, sgn);
230 vr_type = VR_RANGE;
233 if (vr_type == VR_RANGE)
235 *max = wi::round_down_for_mask (*max, nonzero_bits);
237 /* Check that the range contains at least one valid value. */
238 if (wi::gt_p (*min, *max, sgn))
239 return VR_UNDEFINED;
241 *min = wi::round_up_for_mask (*min, nonzero_bits);
242 gcc_checking_assert (wi::le_p (*min, *max, sgn));
244 return vr_type;
247 /* Set value range VR to VR_UNDEFINED. */
249 static inline void
250 set_value_range_to_undefined (value_range *vr)
252 vr->type = VR_UNDEFINED;
253 vr->min = vr->max = NULL_TREE;
254 if (vr->equiv)
255 bitmap_clear (vr->equiv);
258 /* Set value range VR to VR_VARYING. */
260 void
261 set_value_range_to_varying (value_range *vr)
263 vr->type = VR_VARYING;
264 vr->min = vr->max = NULL_TREE;
265 if (vr->equiv)
266 bitmap_clear (vr->equiv);
269 /* Set value range VR to {T, MIN, MAX, EQUIV}. */
271 void
272 set_value_range (value_range *vr, enum value_range_type t, tree min,
273 tree max, bitmap equiv)
275 /* Check the validity of the range. */
276 if (flag_checking
277 && (t == VR_RANGE || t == VR_ANTI_RANGE))
279 int cmp;
281 gcc_assert (min && max);
283 gcc_assert (!TREE_OVERFLOW_P (min) && !TREE_OVERFLOW_P (max));
285 if (INTEGRAL_TYPE_P (TREE_TYPE (min)) && t == VR_ANTI_RANGE)
286 gcc_assert (!vrp_val_is_min (min) || !vrp_val_is_max (max));
288 cmp = compare_values (min, max);
289 gcc_assert (cmp == 0 || cmp == -1 || cmp == -2);
292 if (flag_checking
293 && (t == VR_UNDEFINED || t == VR_VARYING))
295 gcc_assert (min == NULL_TREE && max == NULL_TREE);
296 gcc_assert (equiv == NULL || bitmap_empty_p (equiv));
299 vr->type = t;
300 vr->min = min;
301 vr->max = max;
303 /* Since updating the equivalence set involves deep copying the
304 bitmaps, only do it if absolutely necessary.
306 All equivalence bitmaps are allocated from the same obstack. So
307 we can use the obstack associated with EQUIV to allocate vr->equiv. */
308 if (vr->equiv == NULL
309 && equiv != NULL)
310 vr->equiv = BITMAP_ALLOC (equiv->obstack);
312 if (equiv != vr->equiv)
314 if (equiv && !bitmap_empty_p (equiv))
315 bitmap_copy (vr->equiv, equiv);
316 else
317 bitmap_clear (vr->equiv);
322 /* Set value range VR to the canonical form of {T, MIN, MAX, EQUIV}.
323 This means adjusting T, MIN and MAX representing the case of a
324 wrapping range with MAX < MIN covering [MIN, type_max] U [type_min, MAX]
325 as anti-rage ~[MAX+1, MIN-1]. Likewise for wrapping anti-ranges.
326 In corner cases where MAX+1 or MIN-1 wraps this will fall back
327 to varying.
328 This routine exists to ease canonicalization in the case where we
329 extract ranges from var + CST op limit. */
331 void
332 set_and_canonicalize_value_range (value_range *vr, enum value_range_type t,
333 tree min, tree max, bitmap equiv)
335 /* Use the canonical setters for VR_UNDEFINED and VR_VARYING. */
336 if (t == VR_UNDEFINED)
338 set_value_range_to_undefined (vr);
339 return;
341 else if (t == VR_VARYING)
343 set_value_range_to_varying (vr);
344 return;
347 /* Nothing to canonicalize for symbolic ranges. */
348 if (TREE_CODE (min) != INTEGER_CST
349 || TREE_CODE (max) != INTEGER_CST)
351 set_value_range (vr, t, min, max, equiv);
352 return;
355 /* Wrong order for min and max, to swap them and the VR type we need
356 to adjust them. */
357 if (tree_int_cst_lt (max, min))
359 tree one, tmp;
361 /* For one bit precision if max < min, then the swapped
362 range covers all values, so for VR_RANGE it is varying and
363 for VR_ANTI_RANGE empty range, so drop to varying as well. */
364 if (TYPE_PRECISION (TREE_TYPE (min)) == 1)
366 set_value_range_to_varying (vr);
367 return;
370 one = build_int_cst (TREE_TYPE (min), 1);
371 tmp = int_const_binop (PLUS_EXPR, max, one);
372 max = int_const_binop (MINUS_EXPR, min, one);
373 min = tmp;
375 /* There's one corner case, if we had [C+1, C] before we now have
376 that again. But this represents an empty value range, so drop
377 to varying in this case. */
378 if (tree_int_cst_lt (max, min))
380 set_value_range_to_varying (vr);
381 return;
384 t = t == VR_RANGE ? VR_ANTI_RANGE : VR_RANGE;
387 /* Anti-ranges that can be represented as ranges should be so. */
388 if (t == VR_ANTI_RANGE)
390 /* For -fstrict-enums we may receive out-of-range ranges so consider
391 values < -INF and values > INF as -INF/INF as well. */
392 tree type = TREE_TYPE (min);
393 bool is_min = (INTEGRAL_TYPE_P (type)
394 && tree_int_cst_compare (min, TYPE_MIN_VALUE (type)) <= 0);
395 bool is_max = (INTEGRAL_TYPE_P (type)
396 && tree_int_cst_compare (max, TYPE_MAX_VALUE (type)) >= 0);
398 if (is_min && is_max)
400 /* We cannot deal with empty ranges, drop to varying.
401 ??? This could be VR_UNDEFINED instead. */
402 set_value_range_to_varying (vr);
403 return;
405 else if (TYPE_PRECISION (TREE_TYPE (min)) == 1
406 && (is_min || is_max))
408 /* Non-empty boolean ranges can always be represented
409 as a singleton range. */
410 if (is_min)
411 min = max = vrp_val_max (TREE_TYPE (min));
412 else
413 min = max = vrp_val_min (TREE_TYPE (min));
414 t = VR_RANGE;
416 else if (is_min
417 /* As a special exception preserve non-null ranges. */
418 && !(TYPE_UNSIGNED (TREE_TYPE (min))
419 && integer_zerop (max)))
421 tree one = build_int_cst (TREE_TYPE (max), 1);
422 min = int_const_binop (PLUS_EXPR, max, one);
423 max = vrp_val_max (TREE_TYPE (max));
424 t = VR_RANGE;
426 else if (is_max)
428 tree one = build_int_cst (TREE_TYPE (min), 1);
429 max = int_const_binop (MINUS_EXPR, min, one);
430 min = vrp_val_min (TREE_TYPE (min));
431 t = VR_RANGE;
435 /* Do not drop [-INF(OVF), +INF(OVF)] to varying. (OVF) has to be sticky
436 to make sure VRP iteration terminates, otherwise we can get into
437 oscillations. */
439 set_value_range (vr, t, min, max, equiv);
442 /* Copy value range FROM into value range TO. */
444 void
445 copy_value_range (value_range *to, value_range *from)
447 set_value_range (to, from->type, from->min, from->max, from->equiv);
450 /* Set value range VR to a single value. This function is only called
451 with values we get from statements, and exists to clear the
452 TREE_OVERFLOW flag. */
454 void
455 set_value_range_to_value (value_range *vr, tree val, bitmap equiv)
457 gcc_assert (is_gimple_min_invariant (val));
458 if (TREE_OVERFLOW_P (val))
459 val = drop_tree_overflow (val);
460 set_value_range (vr, VR_RANGE, val, val, equiv);
463 /* Set value range VR to a non-NULL range of type TYPE. */
465 void
466 set_value_range_to_nonnull (value_range *vr, tree type)
468 tree zero = build_int_cst (type, 0);
469 set_value_range (vr, VR_ANTI_RANGE, zero, zero, vr->equiv);
473 /* Set value range VR to a NULL range of type TYPE. */
475 void
476 set_value_range_to_null (value_range *vr, tree type)
478 set_value_range_to_value (vr, build_int_cst (type, 0), vr->equiv);
481 /* Return true, if VAL1 and VAL2 are equal values for VRP purposes. */
483 bool
484 vrp_operand_equal_p (const_tree val1, const_tree val2)
486 if (val1 == val2)
487 return true;
488 if (!val1 || !val2 || !operand_equal_p (val1, val2, 0))
489 return false;
490 return true;
493 /* Return true, if the bitmaps B1 and B2 are equal. */
495 bool
496 vrp_bitmap_equal_p (const_bitmap b1, const_bitmap b2)
498 return (b1 == b2
499 || ((!b1 || bitmap_empty_p (b1))
500 && (!b2 || bitmap_empty_p (b2)))
501 || (b1 && b2
502 && bitmap_equal_p (b1, b2)));
505 /* Return true if VR is ~[0, 0]. */
507 bool
508 range_is_nonnull (value_range *vr)
510 return vr->type == VR_ANTI_RANGE
511 && integer_zerop (vr->min)
512 && integer_zerop (vr->max);
516 /* Return true if VR is [0, 0]. */
518 static inline bool
519 range_is_null (value_range *vr)
521 return vr->type == VR_RANGE
522 && integer_zerop (vr->min)
523 && integer_zerop (vr->max);
526 /* Return true if max and min of VR are INTEGER_CST. It's not necessary
527 a singleton. */
529 bool
530 range_int_cst_p (value_range *vr)
532 return (vr->type == VR_RANGE
533 && TREE_CODE (vr->max) == INTEGER_CST
534 && TREE_CODE (vr->min) == INTEGER_CST);
537 /* Return true if VR is a INTEGER_CST singleton. */
539 bool
540 range_int_cst_singleton_p (value_range *vr)
542 return (range_int_cst_p (vr)
543 && tree_int_cst_equal (vr->min, vr->max));
546 /* Return true if value range VR involves at least one symbol. */
548 bool
549 symbolic_range_p (value_range *vr)
551 return (!is_gimple_min_invariant (vr->min)
552 || !is_gimple_min_invariant (vr->max));
555 /* Return the single symbol (an SSA_NAME) contained in T if any, or NULL_TREE
556 otherwise. We only handle additive operations and set NEG to true if the
557 symbol is negated and INV to the invariant part, if any. */
559 tree
560 get_single_symbol (tree t, bool *neg, tree *inv)
562 bool neg_;
563 tree inv_;
565 *inv = NULL_TREE;
566 *neg = false;
568 if (TREE_CODE (t) == PLUS_EXPR
569 || TREE_CODE (t) == POINTER_PLUS_EXPR
570 || TREE_CODE (t) == MINUS_EXPR)
572 if (is_gimple_min_invariant (TREE_OPERAND (t, 0)))
574 neg_ = (TREE_CODE (t) == MINUS_EXPR);
575 inv_ = TREE_OPERAND (t, 0);
576 t = TREE_OPERAND (t, 1);
578 else if (is_gimple_min_invariant (TREE_OPERAND (t, 1)))
580 neg_ = false;
581 inv_ = TREE_OPERAND (t, 1);
582 t = TREE_OPERAND (t, 0);
584 else
585 return NULL_TREE;
587 else
589 neg_ = false;
590 inv_ = NULL_TREE;
593 if (TREE_CODE (t) == NEGATE_EXPR)
595 t = TREE_OPERAND (t, 0);
596 neg_ = !neg_;
599 if (TREE_CODE (t) != SSA_NAME)
600 return NULL_TREE;
602 if (inv_ && TREE_OVERFLOW_P (inv_))
603 inv_ = drop_tree_overflow (inv_);
605 *neg = neg_;
606 *inv = inv_;
607 return t;
610 /* The reverse operation: build a symbolic expression with TYPE
611 from symbol SYM, negated according to NEG, and invariant INV. */
613 static tree
614 build_symbolic_expr (tree type, tree sym, bool neg, tree inv)
616 const bool pointer_p = POINTER_TYPE_P (type);
617 tree t = sym;
619 if (neg)
620 t = build1 (NEGATE_EXPR, type, t);
622 if (integer_zerop (inv))
623 return t;
625 return build2 (pointer_p ? POINTER_PLUS_EXPR : PLUS_EXPR, type, t, inv);
628 /* Return
629 1 if VAL < VAL2
630 0 if !(VAL < VAL2)
631 -2 if those are incomparable. */
633 operand_less_p (tree val, tree val2)
635 /* LT is folded faster than GE and others. Inline the common case. */
636 if (TREE_CODE (val) == INTEGER_CST && TREE_CODE (val2) == INTEGER_CST)
637 return tree_int_cst_lt (val, val2);
638 else
640 tree tcmp;
642 fold_defer_overflow_warnings ();
644 tcmp = fold_binary_to_constant (LT_EXPR, boolean_type_node, val, val2);
646 fold_undefer_and_ignore_overflow_warnings ();
648 if (!tcmp
649 || TREE_CODE (tcmp) != INTEGER_CST)
650 return -2;
652 if (!integer_zerop (tcmp))
653 return 1;
656 return 0;
659 /* Compare two values VAL1 and VAL2. Return
661 -2 if VAL1 and VAL2 cannot be compared at compile-time,
662 -1 if VAL1 < VAL2,
663 0 if VAL1 == VAL2,
664 +1 if VAL1 > VAL2, and
665 +2 if VAL1 != VAL2
667 This is similar to tree_int_cst_compare but supports pointer values
668 and values that cannot be compared at compile time.
670 If STRICT_OVERFLOW_P is not NULL, then set *STRICT_OVERFLOW_P to
671 true if the return value is only valid if we assume that signed
672 overflow is undefined. */
675 compare_values_warnv (tree val1, tree val2, bool *strict_overflow_p)
677 if (val1 == val2)
678 return 0;
680 /* Below we rely on the fact that VAL1 and VAL2 are both pointers or
681 both integers. */
682 gcc_assert (POINTER_TYPE_P (TREE_TYPE (val1))
683 == POINTER_TYPE_P (TREE_TYPE (val2)));
685 /* Convert the two values into the same type. This is needed because
686 sizetype causes sign extension even for unsigned types. */
687 val2 = fold_convert (TREE_TYPE (val1), val2);
688 STRIP_USELESS_TYPE_CONVERSION (val2);
690 const bool overflow_undefined
691 = INTEGRAL_TYPE_P (TREE_TYPE (val1))
692 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1));
693 tree inv1, inv2;
694 bool neg1, neg2;
695 tree sym1 = get_single_symbol (val1, &neg1, &inv1);
696 tree sym2 = get_single_symbol (val2, &neg2, &inv2);
698 /* If VAL1 and VAL2 are of the form '[-]NAME [+ CST]', return -1 or +1
699 accordingly. If VAL1 and VAL2 don't use the same name, return -2. */
700 if (sym1 && sym2)
702 /* Both values must use the same name with the same sign. */
703 if (sym1 != sym2 || neg1 != neg2)
704 return -2;
706 /* [-]NAME + CST == [-]NAME + CST. */
707 if (inv1 == inv2)
708 return 0;
710 /* If overflow is defined we cannot simplify more. */
711 if (!overflow_undefined)
712 return -2;
714 if (strict_overflow_p != NULL
715 /* Symbolic range building sets TREE_NO_WARNING to declare
716 that overflow doesn't happen. */
717 && (!inv1 || !TREE_NO_WARNING (val1))
718 && (!inv2 || !TREE_NO_WARNING (val2)))
719 *strict_overflow_p = true;
721 if (!inv1)
722 inv1 = build_int_cst (TREE_TYPE (val1), 0);
723 if (!inv2)
724 inv2 = build_int_cst (TREE_TYPE (val2), 0);
726 return wi::cmp (wi::to_wide (inv1), wi::to_wide (inv2),
727 TYPE_SIGN (TREE_TYPE (val1)));
730 const bool cst1 = is_gimple_min_invariant (val1);
731 const bool cst2 = is_gimple_min_invariant (val2);
733 /* If one is of the form '[-]NAME + CST' and the other is constant, then
734 it might be possible to say something depending on the constants. */
735 if ((sym1 && inv1 && cst2) || (sym2 && inv2 && cst1))
737 if (!overflow_undefined)
738 return -2;
740 if (strict_overflow_p != NULL
741 /* Symbolic range building sets TREE_NO_WARNING to declare
742 that overflow doesn't happen. */
743 && (!sym1 || !TREE_NO_WARNING (val1))
744 && (!sym2 || !TREE_NO_WARNING (val2)))
745 *strict_overflow_p = true;
747 const signop sgn = TYPE_SIGN (TREE_TYPE (val1));
748 tree cst = cst1 ? val1 : val2;
749 tree inv = cst1 ? inv2 : inv1;
751 /* Compute the difference between the constants. If it overflows or
752 underflows, this means that we can trivially compare the NAME with
753 it and, consequently, the two values with each other. */
754 wide_int diff = wi::to_wide (cst) - wi::to_wide (inv);
755 if (wi::cmp (0, wi::to_wide (inv), sgn)
756 != wi::cmp (diff, wi::to_wide (cst), sgn))
758 const int res = wi::cmp (wi::to_wide (cst), wi::to_wide (inv), sgn);
759 return cst1 ? res : -res;
762 return -2;
765 /* We cannot say anything more for non-constants. */
766 if (!cst1 || !cst2)
767 return -2;
769 if (!POINTER_TYPE_P (TREE_TYPE (val1)))
771 /* We cannot compare overflowed values. */
772 if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
773 return -2;
775 if (TREE_CODE (val1) == INTEGER_CST
776 && TREE_CODE (val2) == INTEGER_CST)
777 return tree_int_cst_compare (val1, val2);
779 if (poly_int_tree_p (val1) && poly_int_tree_p (val2))
781 if (known_eq (wi::to_poly_widest (val1),
782 wi::to_poly_widest (val2)))
783 return 0;
784 if (known_lt (wi::to_poly_widest (val1),
785 wi::to_poly_widest (val2)))
786 return -1;
787 if (known_gt (wi::to_poly_widest (val1),
788 wi::to_poly_widest (val2)))
789 return 1;
792 return -2;
794 else
796 tree t;
798 /* First see if VAL1 and VAL2 are not the same. */
799 if (val1 == val2 || operand_equal_p (val1, val2, 0))
800 return 0;
802 /* If VAL1 is a lower address than VAL2, return -1. */
803 if (operand_less_p (val1, val2) == 1)
804 return -1;
806 /* If VAL1 is a higher address than VAL2, return +1. */
807 if (operand_less_p (val2, val1) == 1)
808 return 1;
810 /* If VAL1 is different than VAL2, return +2.
811 For integer constants we either have already returned -1 or 1
812 or they are equivalent. We still might succeed in proving
813 something about non-trivial operands. */
814 if (TREE_CODE (val1) != INTEGER_CST
815 || TREE_CODE (val2) != INTEGER_CST)
817 t = fold_binary_to_constant (NE_EXPR, boolean_type_node, val1, val2);
818 if (t && integer_onep (t))
819 return 2;
822 return -2;
826 /* Compare values like compare_values_warnv. */
829 compare_values (tree val1, tree val2)
831 bool sop;
832 return compare_values_warnv (val1, val2, &sop);
836 /* Return 1 if VAL is inside value range MIN <= VAL <= MAX,
837 0 if VAL is not inside [MIN, MAX],
838 -2 if we cannot tell either way.
840 Benchmark compile/20001226-1.c compilation time after changing this
841 function. */
844 value_inside_range (tree val, tree min, tree max)
846 int cmp1, cmp2;
848 cmp1 = operand_less_p (val, min);
849 if (cmp1 == -2)
850 return -2;
851 if (cmp1 == 1)
852 return 0;
854 cmp2 = operand_less_p (max, val);
855 if (cmp2 == -2)
856 return -2;
858 return !cmp2;
862 /* Return true if value ranges VR0 and VR1 have a non-empty
863 intersection.
865 Benchmark compile/20001226-1.c compilation time after changing this
866 function.
869 static inline bool
870 value_ranges_intersect_p (value_range *vr0, value_range *vr1)
872 /* The value ranges do not intersect if the maximum of the first range is
873 less than the minimum of the second range or vice versa.
874 When those relations are unknown, we can't do any better. */
875 if (operand_less_p (vr0->max, vr1->min) != 0)
876 return false;
877 if (operand_less_p (vr1->max, vr0->min) != 0)
878 return false;
879 return true;
883 /* Return 1 if [MIN, MAX] includes the value zero, 0 if it does not
884 include the value zero, -2 if we cannot tell. */
887 range_includes_zero_p (tree min, tree max)
889 tree zero = build_int_cst (TREE_TYPE (min), 0);
890 return value_inside_range (zero, min, max);
893 /* Return true if *VR is know to only contain nonnegative values. */
895 static inline bool
896 value_range_nonnegative_p (value_range *vr)
898 /* Testing for VR_ANTI_RANGE is not useful here as any anti-range
899 which would return a useful value should be encoded as a
900 VR_RANGE. */
901 if (vr->type == VR_RANGE)
903 int result = compare_values (vr->min, integer_zero_node);
904 return (result == 0 || result == 1);
907 return false;
910 /* If *VR has a value rante that is a single constant value return that,
911 otherwise return NULL_TREE. */
913 tree
914 value_range_constant_singleton (value_range *vr)
916 if (vr->type == VR_RANGE
917 && vrp_operand_equal_p (vr->min, vr->max)
918 && is_gimple_min_invariant (vr->min))
919 return vr->min;
921 return NULL_TREE;
924 /* Value range wrapper for wide_int_range_set_zero_nonzero_bits.
926 Compute MAY_BE_NONZERO and MUST_BE_NONZERO bit masks for range in VR.
928 Return TRUE if VR was a constant range and we were able to compute
929 the bit masks. */
931 bool
932 vrp_set_zero_nonzero_bits (const tree expr_type,
933 value_range *vr,
934 wide_int *may_be_nonzero,
935 wide_int *must_be_nonzero)
937 if (!range_int_cst_p (vr))
939 *may_be_nonzero = wi::minus_one (TYPE_PRECISION (expr_type));
940 *must_be_nonzero = wi::zero (TYPE_PRECISION (expr_type));
941 return false;
943 wide_int_range_set_zero_nonzero_bits (TYPE_SIGN (expr_type),
944 wi::to_wide (vr->min),
945 wi::to_wide (vr->max),
946 *may_be_nonzero, *must_be_nonzero);
947 return true;
950 /* Create two value-ranges in *VR0 and *VR1 from the anti-range *AR
951 so that *VR0 U *VR1 == *AR. Returns true if that is possible,
952 false otherwise. If *AR can be represented with a single range
953 *VR1 will be VR_UNDEFINED. */
955 static bool
956 ranges_from_anti_range (value_range *ar,
957 value_range *vr0, value_range *vr1)
959 tree type = TREE_TYPE (ar->min);
961 vr0->type = VR_UNDEFINED;
962 vr1->type = VR_UNDEFINED;
964 /* As a future improvement, we could handle ~[0, A] as: [-INF, -1] U
965 [A+1, +INF]. Not sure if this helps in practice, though. */
967 if (ar->type != VR_ANTI_RANGE
968 || TREE_CODE (ar->min) != INTEGER_CST
969 || TREE_CODE (ar->max) != INTEGER_CST
970 || !vrp_val_min (type)
971 || !vrp_val_max (type))
972 return false;
974 if (!vrp_val_is_min (ar->min))
976 vr0->type = VR_RANGE;
977 vr0->min = vrp_val_min (type);
978 vr0->max = wide_int_to_tree (type, wi::to_wide (ar->min) - 1);
980 if (!vrp_val_is_max (ar->max))
982 vr1->type = VR_RANGE;
983 vr1->min = wide_int_to_tree (type, wi::to_wide (ar->max) + 1);
984 vr1->max = vrp_val_max (type);
986 if (vr0->type == VR_UNDEFINED)
988 *vr0 = *vr1;
989 vr1->type = VR_UNDEFINED;
992 return vr0->type != VR_UNDEFINED;
995 /* Extract the components of a value range into a pair of wide ints in
996 [WMIN, WMAX].
998 If the value range is anything but a VR_RANGE of constants, the
999 resulting wide ints are set to [-MIN, +MAX] for the type. */
1001 static void inline
1002 extract_range_into_wide_ints (value_range *vr,
1003 signop sign, unsigned prec,
1004 wide_int &wmin, wide_int &wmax)
1006 if (range_int_cst_p (vr))
1008 wmin = wi::to_wide (vr->min);
1009 wmax = wi::to_wide (vr->max);
1011 else
1013 wmin = wi::min_value (prec, sign);
1014 wmax = wi::max_value (prec, sign);
1018 /* Value range wrapper for wide_int_range_shift_undefined_p. */
1020 static inline bool
1021 vrp_shift_undefined_p (const value_range &shifter, unsigned prec)
1023 tree type = TREE_TYPE (shifter.min);
1024 return wide_int_range_shift_undefined_p (TYPE_SIGN (type), prec,
1025 wi::to_wide (shifter.min),
1026 wi::to_wide (shifter.max));
1029 /* Value range wrapper for wide_int_range_multiplicative_op:
1031 *VR = *VR0 .CODE. *VR1. */
1033 static void
1034 extract_range_from_multiplicative_op (value_range *vr,
1035 enum tree_code code,
1036 value_range *vr0, value_range *vr1)
1038 gcc_assert (code == MULT_EXPR
1039 || code == TRUNC_DIV_EXPR
1040 || code == FLOOR_DIV_EXPR
1041 || code == CEIL_DIV_EXPR
1042 || code == EXACT_DIV_EXPR
1043 || code == ROUND_DIV_EXPR
1044 || code == RSHIFT_EXPR
1045 || code == LSHIFT_EXPR);
1046 gcc_assert (vr0->type == VR_RANGE && vr0->type == vr1->type);
1048 tree type = TREE_TYPE (vr0->min);
1049 wide_int res_lb, res_ub;
1050 wide_int vr0_lb = wi::to_wide (vr0->min);
1051 wide_int vr0_ub = wi::to_wide (vr0->max);
1052 wide_int vr1_lb = wi::to_wide (vr1->min);
1053 wide_int vr1_ub = wi::to_wide (vr1->max);
1054 bool overflow_undefined = TYPE_OVERFLOW_UNDEFINED (type);
1055 bool overflow_wraps = TYPE_OVERFLOW_WRAPS (type);
1056 unsigned prec = TYPE_PRECISION (type);
1058 if (wide_int_range_multiplicative_op (res_lb, res_ub,
1059 code, TYPE_SIGN (type), prec,
1060 vr0_lb, vr0_ub, vr1_lb, vr1_ub,
1061 overflow_undefined, overflow_wraps))
1062 set_and_canonicalize_value_range (vr, VR_RANGE,
1063 wide_int_to_tree (type, res_lb),
1064 wide_int_to_tree (type, res_ub), NULL);
1065 else
1066 set_value_range_to_varying (vr);
1069 /* Value range wrapper for wide_int_range_can_optimize_bit_op.
1071 If a bit operation on two ranges can be easily optimized in terms
1072 of a mask, store the optimized new range in VR and return TRUE. */
1074 static bool
1075 vrp_can_optimize_bit_op (value_range *vr, enum tree_code code,
1076 value_range *vr0, value_range *vr1)
1078 tree lower_bound, upper_bound, mask;
1079 if (code != BIT_AND_EXPR && code != BIT_IOR_EXPR)
1080 return false;
1081 if (range_int_cst_singleton_p (vr1))
1083 if (!range_int_cst_p (vr0))
1084 return false;
1085 mask = vr1->min;
1086 lower_bound = vr0->min;
1087 upper_bound = vr0->max;
1089 else if (range_int_cst_singleton_p (vr0))
1091 if (!range_int_cst_p (vr1))
1092 return false;
1093 mask = vr0->min;
1094 lower_bound = vr1->min;
1095 upper_bound = vr1->max;
1097 else
1098 return false;
1099 if (wide_int_range_can_optimize_bit_op (code,
1100 wi::to_wide (lower_bound),
1101 wi::to_wide (upper_bound),
1102 wi::to_wide (mask)))
1104 tree min = int_const_binop (code, lower_bound, mask);
1105 tree max = int_const_binop (code, upper_bound, mask);
1106 set_value_range (vr, VR_RANGE, min, max, NULL);
1107 return true;
1109 return false;
1112 /* If BOUND will include a symbolic bound, adjust it accordingly,
1113 otherwise leave it as is.
1115 CODE is the original operation that combined the bounds (PLUS_EXPR
1116 or MINUS_EXPR).
1118 TYPE is the type of the original operation.
1120 SYM_OPn is the symbolic for OPn if it has a symbolic.
1122 NEG_OPn is TRUE if the OPn was negated. */
1124 static void
1125 adjust_symbolic_bound (tree &bound, enum tree_code code, tree type,
1126 tree sym_op0, tree sym_op1,
1127 bool neg_op0, bool neg_op1)
1129 bool minus_p = (code == MINUS_EXPR);
1130 /* If the result bound is constant, we're done; otherwise, build the
1131 symbolic lower bound. */
1132 if (sym_op0 == sym_op1)
1134 else if (sym_op0)
1135 bound = build_symbolic_expr (type, sym_op0,
1136 neg_op0, bound);
1137 else if (sym_op1)
1139 /* We may not negate if that might introduce
1140 undefined overflow. */
1141 if (!minus_p
1142 || neg_op1
1143 || TYPE_OVERFLOW_WRAPS (type))
1144 bound = build_symbolic_expr (type, sym_op1,
1145 neg_op1 ^ minus_p, bound);
1146 else
1147 bound = NULL_TREE;
1151 /* Combine OP1 and OP1, which are two parts of a bound, into one wide
1152 int bound according to CODE. CODE is the operation combining the
1153 bound (either a PLUS_EXPR or a MINUS_EXPR).
1155 TYPE is the type of the combine operation.
1157 WI is the wide int to store the result.
1159 OVF is -1 if an underflow occurred, +1 if an overflow occurred or 0
1160 if over/underflow occurred. */
1162 static void
1163 combine_bound (enum tree_code code, wide_int &wi, wi::overflow_type &ovf,
1164 tree type, tree op0, tree op1)
1166 bool minus_p = (code == MINUS_EXPR);
1167 const signop sgn = TYPE_SIGN (type);
1168 const unsigned int prec = TYPE_PRECISION (type);
1170 /* Combine the bounds, if any. */
1171 if (op0 && op1)
1173 if (minus_p)
1174 wi = wi::sub (wi::to_wide (op0), wi::to_wide (op1), sgn, &ovf);
1175 else
1176 wi = wi::add (wi::to_wide (op0), wi::to_wide (op1), sgn, &ovf);
1178 else if (op0)
1179 wi = wi::to_wide (op0);
1180 else if (op1)
1182 if (minus_p)
1183 wi = wi::neg (wi::to_wide (op1), &ovf);
1184 else
1185 wi = wi::to_wide (op1);
1187 else
1188 wi = wi::shwi (0, prec);
1191 /* Given a range in [WMIN, WMAX], adjust it for possible overflow and
1192 put the result in VR.
1194 TYPE is the type of the range.
1196 MIN_OVF and MAX_OVF indicate what type of overflow, if any,
1197 occurred while originally calculating WMIN or WMAX. -1 indicates
1198 underflow. +1 indicates overflow. 0 indicates neither. */
1200 static void
1201 set_value_range_with_overflow (value_range &vr,
1202 tree type,
1203 const wide_int &wmin, const wide_int &wmax,
1204 wi::overflow_type min_ovf,
1205 wi::overflow_type max_ovf)
1207 const signop sgn = TYPE_SIGN (type);
1208 const unsigned int prec = TYPE_PRECISION (type);
1209 vr.type = VR_RANGE;
1210 vr.equiv = NULL;
1211 if (TYPE_OVERFLOW_WRAPS (type))
1213 /* If overflow wraps, truncate the values and adjust the
1214 range kind and bounds appropriately. */
1215 wide_int tmin = wide_int::from (wmin, prec, sgn);
1216 wide_int tmax = wide_int::from (wmax, prec, sgn);
1217 if ((min_ovf != wi::OVF_NONE) == (max_ovf != wi::OVF_NONE))
1219 /* No overflow or both overflow or underflow. The
1220 range kind stays VR_RANGE. */
1221 vr.min = wide_int_to_tree (type, tmin);
1222 vr.max = wide_int_to_tree (type, tmax);
1224 else if ((min_ovf == wi::OVF_UNDERFLOW && max_ovf == wi::OVF_NONE)
1225 || (max_ovf == wi::OVF_OVERFLOW && min_ovf == wi::OVF_NONE))
1227 /* Min underflow or max overflow. The range kind
1228 changes to VR_ANTI_RANGE. */
1229 bool covers = false;
1230 wide_int tem = tmin;
1231 vr.type = VR_ANTI_RANGE;
1232 tmin = tmax + 1;
1233 if (wi::cmp (tmin, tmax, sgn) < 0)
1234 covers = true;
1235 tmax = tem - 1;
1236 if (wi::cmp (tmax, tem, sgn) > 0)
1237 covers = true;
1238 /* If the anti-range would cover nothing, drop to varying.
1239 Likewise if the anti-range bounds are outside of the
1240 types values. */
1241 if (covers || wi::cmp (tmin, tmax, sgn) > 0)
1243 set_value_range_to_varying (&vr);
1244 return;
1246 vr.min = wide_int_to_tree (type, tmin);
1247 vr.max = wide_int_to_tree (type, tmax);
1249 else
1251 /* Other underflow and/or overflow, drop to VR_VARYING. */
1252 set_value_range_to_varying (&vr);
1253 return;
1256 else
1258 /* If overflow does not wrap, saturate to the types min/max
1259 value. */
1260 wide_int type_min = wi::min_value (prec, sgn);
1261 wide_int type_max = wi::max_value (prec, sgn);
1262 if (min_ovf == wi::OVF_UNDERFLOW)
1263 vr.min = wide_int_to_tree (type, type_min);
1264 else if (min_ovf == wi::OVF_OVERFLOW)
1265 vr.min = wide_int_to_tree (type, type_max);
1266 else
1267 vr.min = wide_int_to_tree (type, wmin);
1269 if (max_ovf == wi::OVF_UNDERFLOW)
1270 vr.max = wide_int_to_tree (type, type_min);
1271 else if (max_ovf == wi::OVF_OVERFLOW)
1272 vr.max = wide_int_to_tree (type, type_max);
1273 else
1274 vr.max = wide_int_to_tree (type, wmax);
1278 /* Extract range information from a binary operation CODE based on
1279 the ranges of each of its operands *VR0 and *VR1 with resulting
1280 type EXPR_TYPE. The resulting range is stored in *VR. */
1282 void
1283 extract_range_from_binary_expr_1 (value_range *vr,
1284 enum tree_code code, tree expr_type,
1285 value_range *vr0_, value_range *vr1_)
1287 signop sign = TYPE_SIGN (expr_type);
1288 unsigned int prec = TYPE_PRECISION (expr_type);
1289 value_range vr0 = *vr0_, vr1 = *vr1_;
1290 value_range vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
1291 enum value_range_type type;
1292 tree min = NULL_TREE, max = NULL_TREE;
1293 int cmp;
1295 if (!INTEGRAL_TYPE_P (expr_type)
1296 && !POINTER_TYPE_P (expr_type))
1298 set_value_range_to_varying (vr);
1299 return;
1302 /* Not all binary expressions can be applied to ranges in a
1303 meaningful way. Handle only arithmetic operations. */
1304 if (code != PLUS_EXPR
1305 && code != MINUS_EXPR
1306 && code != POINTER_PLUS_EXPR
1307 && code != MULT_EXPR
1308 && code != TRUNC_DIV_EXPR
1309 && code != FLOOR_DIV_EXPR
1310 && code != CEIL_DIV_EXPR
1311 && code != EXACT_DIV_EXPR
1312 && code != ROUND_DIV_EXPR
1313 && code != TRUNC_MOD_EXPR
1314 && code != RSHIFT_EXPR
1315 && code != LSHIFT_EXPR
1316 && code != MIN_EXPR
1317 && code != MAX_EXPR
1318 && code != BIT_AND_EXPR
1319 && code != BIT_IOR_EXPR
1320 && code != BIT_XOR_EXPR)
1322 set_value_range_to_varying (vr);
1323 return;
1326 /* If both ranges are UNDEFINED, so is the result. */
1327 if (vr0.type == VR_UNDEFINED && vr1.type == VR_UNDEFINED)
1329 set_value_range_to_undefined (vr);
1330 return;
1332 /* If one of the ranges is UNDEFINED drop it to VARYING for the following
1333 code. At some point we may want to special-case operations that
1334 have UNDEFINED result for all or some value-ranges of the not UNDEFINED
1335 operand. */
1336 else if (vr0.type == VR_UNDEFINED)
1337 set_value_range_to_varying (&vr0);
1338 else if (vr1.type == VR_UNDEFINED)
1339 set_value_range_to_varying (&vr1);
1341 /* We get imprecise results from ranges_from_anti_range when
1342 code is EXACT_DIV_EXPR. We could mask out bits in the resulting
1343 range, but then we also need to hack up vrp_meet. It's just
1344 easier to special case when vr0 is ~[0,0] for EXACT_DIV_EXPR. */
1345 if (code == EXACT_DIV_EXPR
1346 && vr0.type == VR_ANTI_RANGE
1347 && vr0.min == vr0.max
1348 && integer_zerop (vr0.min))
1350 set_value_range_to_nonnull (vr, expr_type);
1351 return;
1354 /* Now canonicalize anti-ranges to ranges when they are not symbolic
1355 and express ~[] op X as ([]' op X) U ([]'' op X). */
1356 if (vr0.type == VR_ANTI_RANGE
1357 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
1359 extract_range_from_binary_expr_1 (vr, code, expr_type, &vrtem0, vr1_);
1360 if (vrtem1.type != VR_UNDEFINED)
1362 value_range vrres = VR_INITIALIZER;
1363 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
1364 &vrtem1, vr1_);
1365 vrp_meet (vr, &vrres);
1367 return;
1369 /* Likewise for X op ~[]. */
1370 if (vr1.type == VR_ANTI_RANGE
1371 && ranges_from_anti_range (&vr1, &vrtem0, &vrtem1))
1373 extract_range_from_binary_expr_1 (vr, code, expr_type, vr0_, &vrtem0);
1374 if (vrtem1.type != VR_UNDEFINED)
1376 value_range vrres = VR_INITIALIZER;
1377 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
1378 vr0_, &vrtem1);
1379 vrp_meet (vr, &vrres);
1381 return;
1384 /* The type of the resulting value range defaults to VR0.TYPE. */
1385 type = vr0.type;
1387 /* Refuse to operate on VARYING ranges, ranges of different kinds
1388 and symbolic ranges. As an exception, we allow BIT_{AND,IOR}
1389 because we may be able to derive a useful range even if one of
1390 the operands is VR_VARYING or symbolic range. Similarly for
1391 divisions, MIN/MAX and PLUS/MINUS.
1393 TODO, we may be able to derive anti-ranges in some cases. */
1394 if (code != BIT_AND_EXPR
1395 && code != BIT_IOR_EXPR
1396 && code != TRUNC_DIV_EXPR
1397 && code != FLOOR_DIV_EXPR
1398 && code != CEIL_DIV_EXPR
1399 && code != EXACT_DIV_EXPR
1400 && code != ROUND_DIV_EXPR
1401 && code != TRUNC_MOD_EXPR
1402 && code != MIN_EXPR
1403 && code != MAX_EXPR
1404 && code != PLUS_EXPR
1405 && code != MINUS_EXPR
1406 && code != RSHIFT_EXPR
1407 && code != POINTER_PLUS_EXPR
1408 && (vr0.type == VR_VARYING
1409 || vr1.type == VR_VARYING
1410 || vr0.type != vr1.type
1411 || symbolic_range_p (&vr0)
1412 || symbolic_range_p (&vr1)))
1414 set_value_range_to_varying (vr);
1415 return;
1418 /* Now evaluate the expression to determine the new range. */
1419 if (POINTER_TYPE_P (expr_type))
1421 if (code == MIN_EXPR || code == MAX_EXPR)
1423 /* For MIN/MAX expressions with pointers, we only care about
1424 nullness, if both are non null, then the result is nonnull.
1425 If both are null, then the result is null. Otherwise they
1426 are varying. */
1427 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
1428 set_value_range_to_nonnull (vr, expr_type);
1429 else if (range_is_null (&vr0) && range_is_null (&vr1))
1430 set_value_range_to_null (vr, expr_type);
1431 else
1432 set_value_range_to_varying (vr);
1434 else if (code == POINTER_PLUS_EXPR)
1436 /* For pointer types, we are really only interested in asserting
1437 whether the expression evaluates to non-NULL. */
1438 if (range_is_nonnull (&vr0)
1439 || range_is_nonnull (&vr1)
1440 || (vr1.type == VR_RANGE
1441 && !symbolic_range_p (&vr1)
1442 && !range_includes_zero_p (vr1.min, vr1.max)))
1443 set_value_range_to_nonnull (vr, expr_type);
1444 else if (range_is_null (&vr0) && range_is_null (&vr1))
1445 set_value_range_to_null (vr, expr_type);
1446 else
1447 set_value_range_to_varying (vr);
1449 else if (code == BIT_AND_EXPR)
1451 /* For pointer types, we are really only interested in asserting
1452 whether the expression evaluates to non-NULL. */
1453 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
1454 set_value_range_to_nonnull (vr, expr_type);
1455 else if (range_is_null (&vr0) || range_is_null (&vr1))
1456 set_value_range_to_null (vr, expr_type);
1457 else
1458 set_value_range_to_varying (vr);
1460 else
1461 set_value_range_to_varying (vr);
1463 return;
1466 /* For integer ranges, apply the operation to each end of the
1467 range and see what we end up with. */
1468 if (code == PLUS_EXPR || code == MINUS_EXPR)
1470 const bool minus_p = (code == MINUS_EXPR);
1471 tree min_op0 = vr0.min;
1472 tree min_op1 = minus_p ? vr1.max : vr1.min;
1473 tree max_op0 = vr0.max;
1474 tree max_op1 = minus_p ? vr1.min : vr1.max;
1475 tree sym_min_op0 = NULL_TREE;
1476 tree sym_min_op1 = NULL_TREE;
1477 tree sym_max_op0 = NULL_TREE;
1478 tree sym_max_op1 = NULL_TREE;
1479 bool neg_min_op0, neg_min_op1, neg_max_op0, neg_max_op1;
1481 neg_min_op0 = neg_min_op1 = neg_max_op0 = neg_max_op1 = false;
1483 /* If we have a PLUS or MINUS with two VR_RANGEs, either constant or
1484 single-symbolic ranges, try to compute the precise resulting range,
1485 but only if we know that this resulting range will also be constant
1486 or single-symbolic. */
1487 if (vr0.type == VR_RANGE && vr1.type == VR_RANGE
1488 && (TREE_CODE (min_op0) == INTEGER_CST
1489 || (sym_min_op0
1490 = get_single_symbol (min_op0, &neg_min_op0, &min_op0)))
1491 && (TREE_CODE (min_op1) == INTEGER_CST
1492 || (sym_min_op1
1493 = get_single_symbol (min_op1, &neg_min_op1, &min_op1)))
1494 && (!(sym_min_op0 && sym_min_op1)
1495 || (sym_min_op0 == sym_min_op1
1496 && neg_min_op0 == (minus_p ? neg_min_op1 : !neg_min_op1)))
1497 && (TREE_CODE (max_op0) == INTEGER_CST
1498 || (sym_max_op0
1499 = get_single_symbol (max_op0, &neg_max_op0, &max_op0)))
1500 && (TREE_CODE (max_op1) == INTEGER_CST
1501 || (sym_max_op1
1502 = get_single_symbol (max_op1, &neg_max_op1, &max_op1)))
1503 && (!(sym_max_op0 && sym_max_op1)
1504 || (sym_max_op0 == sym_max_op1
1505 && neg_max_op0 == (minus_p ? neg_max_op1 : !neg_max_op1))))
1507 wide_int wmin, wmax;
1508 wi::overflow_type min_ovf = wi::OVF_NONE;
1509 wi::overflow_type max_ovf = wi::OVF_NONE;
1511 /* Build the bounds. */
1512 combine_bound (code, wmin, min_ovf, expr_type, min_op0, min_op1);
1513 combine_bound (code, wmax, max_ovf, expr_type, max_op0, max_op1);
1515 /* If we have overflow for the constant part and the resulting
1516 range will be symbolic, drop to VR_VARYING. */
1517 if (((bool)min_ovf && sym_min_op0 != sym_min_op1)
1518 || ((bool)max_ovf && sym_max_op0 != sym_max_op1))
1520 set_value_range_to_varying (vr);
1521 return;
1524 /* Adjust the range for possible overflow. */
1525 set_value_range_with_overflow (*vr, expr_type,
1526 wmin, wmax, min_ovf, max_ovf);
1527 if (vr->type == VR_VARYING)
1528 return;
1530 /* Build the symbolic bounds if needed. */
1531 adjust_symbolic_bound (vr->min, code, expr_type,
1532 sym_min_op0, sym_min_op1,
1533 neg_min_op0, neg_min_op1);
1534 adjust_symbolic_bound (vr->max, code, expr_type,
1535 sym_max_op0, sym_max_op1,
1536 neg_max_op0, neg_max_op1);
1537 /* ?? It would probably be cleaner to eliminate min/max/type
1538 entirely and hold these values in VR directly. */
1539 min = vr->min;
1540 max = vr->max;
1541 type = vr->type;
1543 else
1545 /* For other cases, for example if we have a PLUS_EXPR with two
1546 VR_ANTI_RANGEs, drop to VR_VARYING. It would take more effort
1547 to compute a precise range for such a case.
1548 ??? General even mixed range kind operations can be expressed
1549 by for example transforming ~[3, 5] + [1, 2] to range-only
1550 operations and a union primitive:
1551 [-INF, 2] + [1, 2] U [5, +INF] + [1, 2]
1552 [-INF+1, 4] U [6, +INF(OVF)]
1553 though usually the union is not exactly representable with
1554 a single range or anti-range as the above is
1555 [-INF+1, +INF(OVF)] intersected with ~[5, 5]
1556 but one could use a scheme similar to equivalences for this. */
1557 set_value_range_to_varying (vr);
1558 return;
1561 else if (code == MIN_EXPR
1562 || code == MAX_EXPR)
1564 wide_int wmin, wmax;
1565 wide_int vr0_min, vr0_max;
1566 wide_int vr1_min, vr1_max;
1567 extract_range_into_wide_ints (&vr0, sign, prec, vr0_min, vr0_max);
1568 extract_range_into_wide_ints (&vr1, sign, prec, vr1_min, vr1_max);
1569 if (wide_int_range_min_max (wmin, wmax, code, sign, prec,
1570 vr0_min, vr0_max, vr1_min, vr1_max))
1571 set_value_range (vr, VR_RANGE,
1572 wide_int_to_tree (expr_type, wmin),
1573 wide_int_to_tree (expr_type, wmax), NULL);
1574 else
1575 set_value_range_to_varying (vr);
1576 return;
1578 else if (code == MULT_EXPR)
1580 if (!range_int_cst_p (&vr0)
1581 || !range_int_cst_p (&vr1))
1583 set_value_range_to_varying (vr);
1584 return;
1586 extract_range_from_multiplicative_op (vr, code, &vr0, &vr1);
1587 return;
1589 else if (code == RSHIFT_EXPR
1590 || code == LSHIFT_EXPR)
1592 if (range_int_cst_p (&vr1)
1593 && !vrp_shift_undefined_p (vr1, prec))
1595 if (code == RSHIFT_EXPR)
1597 /* Even if vr0 is VARYING or otherwise not usable, we can derive
1598 useful ranges just from the shift count. E.g.
1599 x >> 63 for signed 64-bit x is always [-1, 0]. */
1600 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
1602 vr0.type = type = VR_RANGE;
1603 vr0.min = vrp_val_min (expr_type);
1604 vr0.max = vrp_val_max (expr_type);
1606 extract_range_from_multiplicative_op (vr, code, &vr0, &vr1);
1607 return;
1609 else if (code == LSHIFT_EXPR
1610 && range_int_cst_p (&vr0))
1612 wide_int res_lb, res_ub;
1613 if (wide_int_range_lshift (res_lb, res_ub, sign, prec,
1614 wi::to_wide (vr0.min),
1615 wi::to_wide (vr0.max),
1616 wi::to_wide (vr1.min),
1617 wi::to_wide (vr1.max),
1618 TYPE_OVERFLOW_UNDEFINED (expr_type),
1619 TYPE_OVERFLOW_WRAPS (expr_type)))
1621 min = wide_int_to_tree (expr_type, res_lb);
1622 max = wide_int_to_tree (expr_type, res_ub);
1623 set_and_canonicalize_value_range (vr, VR_RANGE,
1624 min, max, NULL);
1625 return;
1629 set_value_range_to_varying (vr);
1630 return;
1632 else if (code == TRUNC_DIV_EXPR
1633 || code == FLOOR_DIV_EXPR
1634 || code == CEIL_DIV_EXPR
1635 || code == EXACT_DIV_EXPR
1636 || code == ROUND_DIV_EXPR)
1638 wide_int dividend_min, dividend_max, divisor_min, divisor_max;
1639 wide_int wmin, wmax, extra_min, extra_max;
1640 bool extra_range_p;
1642 /* Special case explicit division by zero as undefined. */
1643 if (range_is_null (&vr1))
1645 /* However, we must not eliminate a division by zero if
1646 flag_non_call_exceptions. */
1647 if (cfun->can_throw_non_call_exceptions)
1648 set_value_range_to_varying (vr);
1649 else
1650 set_value_range_to_undefined (vr);
1651 return;
1654 /* First, normalize ranges into constants we can handle. Note
1655 that VR_ANTI_RANGE's of constants were already normalized
1656 before arriving here.
1658 NOTE: As a future improvement, we may be able to do better
1659 with mixed symbolic (anti-)ranges like [0, A]. See note in
1660 ranges_from_anti_range. */
1661 extract_range_into_wide_ints (&vr0, sign, prec,
1662 dividend_min, dividend_max);
1663 extract_range_into_wide_ints (&vr1, sign, prec,
1664 divisor_min, divisor_max);
1665 if (!wide_int_range_div (wmin, wmax, code, sign, prec,
1666 dividend_min, dividend_max,
1667 divisor_min, divisor_max,
1668 TYPE_OVERFLOW_UNDEFINED (expr_type),
1669 TYPE_OVERFLOW_WRAPS (expr_type),
1670 extra_range_p, extra_min, extra_max))
1672 set_value_range_to_varying (vr);
1673 return;
1675 set_value_range (vr, VR_RANGE,
1676 wide_int_to_tree (expr_type, wmin),
1677 wide_int_to_tree (expr_type, wmax), NULL);
1678 if (extra_range_p)
1680 value_range extra_range = VR_INITIALIZER;
1681 set_value_range (&extra_range, VR_RANGE,
1682 wide_int_to_tree (expr_type, extra_min),
1683 wide_int_to_tree (expr_type, extra_max), NULL);
1684 vrp_meet (vr, &extra_range);
1686 return;
1688 else if (code == TRUNC_MOD_EXPR)
1690 if (range_is_null (&vr1))
1692 set_value_range_to_undefined (vr);
1693 return;
1695 wide_int wmin, wmax, tmp;
1696 wide_int vr0_min, vr0_max, vr1_min, vr1_max;
1697 extract_range_into_wide_ints (&vr0, sign, prec, vr0_min, vr0_max);
1698 extract_range_into_wide_ints (&vr1, sign, prec, vr1_min, vr1_max);
1699 wide_int_range_trunc_mod (wmin, wmax, sign, prec,
1700 vr0_min, vr0_max, vr1_min, vr1_max);
1701 min = wide_int_to_tree (expr_type, wmin);
1702 max = wide_int_to_tree (expr_type, wmax);
1703 set_value_range (vr, VR_RANGE, min, max, NULL);
1704 return;
1706 else if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR || code == BIT_XOR_EXPR)
1708 if (vrp_can_optimize_bit_op (vr, code, &vr0, &vr1))
1709 return;
1711 wide_int may_be_nonzero0, may_be_nonzero1;
1712 wide_int must_be_nonzero0, must_be_nonzero1;
1713 wide_int wmin, wmax;
1714 wide_int vr0_min, vr0_max, vr1_min, vr1_max;
1715 vrp_set_zero_nonzero_bits (expr_type, &vr0,
1716 &may_be_nonzero0, &must_be_nonzero0);
1717 vrp_set_zero_nonzero_bits (expr_type, &vr1,
1718 &may_be_nonzero1, &must_be_nonzero1);
1719 extract_range_into_wide_ints (&vr0, sign, prec, vr0_min, vr0_max);
1720 extract_range_into_wide_ints (&vr1, sign, prec, vr1_min, vr1_max);
1721 if (code == BIT_AND_EXPR)
1723 if (wide_int_range_bit_and (wmin, wmax, sign, prec,
1724 vr0_min, vr0_max,
1725 vr1_min, vr1_max,
1726 must_be_nonzero0,
1727 may_be_nonzero0,
1728 must_be_nonzero1,
1729 may_be_nonzero1))
1731 min = wide_int_to_tree (expr_type, wmin);
1732 max = wide_int_to_tree (expr_type, wmax);
1733 set_value_range (vr, VR_RANGE, min, max, NULL);
1735 else
1736 set_value_range_to_varying (vr);
1737 return;
1739 else if (code == BIT_IOR_EXPR)
1741 if (wide_int_range_bit_ior (wmin, wmax, sign,
1742 vr0_min, vr0_max,
1743 vr1_min, vr1_max,
1744 must_be_nonzero0,
1745 may_be_nonzero0,
1746 must_be_nonzero1,
1747 may_be_nonzero1))
1749 min = wide_int_to_tree (expr_type, wmin);
1750 max = wide_int_to_tree (expr_type, wmax);
1751 set_value_range (vr, VR_RANGE, min, max, NULL);
1753 else
1754 set_value_range_to_varying (vr);
1755 return;
1757 else if (code == BIT_XOR_EXPR)
1759 if (wide_int_range_bit_xor (wmin, wmax, sign, prec,
1760 must_be_nonzero0,
1761 may_be_nonzero0,
1762 must_be_nonzero1,
1763 may_be_nonzero1))
1765 min = wide_int_to_tree (expr_type, wmin);
1766 max = wide_int_to_tree (expr_type, wmax);
1767 set_value_range (vr, VR_RANGE, min, max, NULL);
1769 else
1770 set_value_range_to_varying (vr);
1771 return;
1774 else
1775 gcc_unreachable ();
1777 /* If either MIN or MAX overflowed, then set the resulting range to
1778 VARYING. */
1779 if (min == NULL_TREE
1780 || TREE_OVERFLOW_P (min)
1781 || max == NULL_TREE
1782 || TREE_OVERFLOW_P (max))
1784 set_value_range_to_varying (vr);
1785 return;
1788 /* We punt for [-INF, +INF].
1789 We learn nothing when we have INF on both sides.
1790 Note that we do accept [-INF, -INF] and [+INF, +INF]. */
1791 if (vrp_val_is_min (min) && vrp_val_is_max (max))
1793 set_value_range_to_varying (vr);
1794 return;
1797 cmp = compare_values (min, max);
1798 if (cmp == -2 || cmp == 1)
1800 /* If the new range has its limits swapped around (MIN > MAX),
1801 then the operation caused one of them to wrap around, mark
1802 the new range VARYING. */
1803 set_value_range_to_varying (vr);
1805 else
1806 set_value_range (vr, type, min, max, NULL);
1809 /* Extract range information from a unary operation CODE based on
1810 the range of its operand *VR0 with type OP0_TYPE with resulting type TYPE.
1811 The resulting range is stored in *VR. */
1813 void
1814 extract_range_from_unary_expr (value_range *vr,
1815 enum tree_code code, tree type,
1816 value_range *vr0_, tree op0_type)
1818 signop sign = TYPE_SIGN (type);
1819 unsigned int prec = TYPE_PRECISION (type);
1820 value_range vr0 = *vr0_, vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
1822 /* VRP only operates on integral and pointer types. */
1823 if (!(INTEGRAL_TYPE_P (op0_type)
1824 || POINTER_TYPE_P (op0_type))
1825 || !(INTEGRAL_TYPE_P (type)
1826 || POINTER_TYPE_P (type)))
1828 set_value_range_to_varying (vr);
1829 return;
1832 /* If VR0 is UNDEFINED, so is the result. */
1833 if (vr0.type == VR_UNDEFINED)
1835 set_value_range_to_undefined (vr);
1836 return;
1839 /* Handle operations that we express in terms of others. */
1840 if (code == PAREN_EXPR || code == OBJ_TYPE_REF)
1842 /* PAREN_EXPR and OBJ_TYPE_REF are simple copies. */
1843 copy_value_range (vr, &vr0);
1844 return;
1846 else if (code == NEGATE_EXPR)
1848 /* -X is simply 0 - X, so re-use existing code that also handles
1849 anti-ranges fine. */
1850 value_range zero = VR_INITIALIZER;
1851 set_value_range_to_value (&zero, build_int_cst (type, 0), NULL);
1852 extract_range_from_binary_expr_1 (vr, MINUS_EXPR, type, &zero, &vr0);
1853 return;
1855 else if (code == BIT_NOT_EXPR)
1857 /* ~X is simply -1 - X, so re-use existing code that also handles
1858 anti-ranges fine. */
1859 value_range minusone = VR_INITIALIZER;
1860 set_value_range_to_value (&minusone, build_int_cst (type, -1), NULL);
1861 extract_range_from_binary_expr_1 (vr, MINUS_EXPR,
1862 type, &minusone, &vr0);
1863 return;
1866 /* Now canonicalize anti-ranges to ranges when they are not symbolic
1867 and express op ~[] as (op []') U (op []''). */
1868 if (vr0.type == VR_ANTI_RANGE
1869 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
1871 extract_range_from_unary_expr (vr, code, type, &vrtem0, op0_type);
1872 if (vrtem1.type != VR_UNDEFINED)
1874 value_range vrres = VR_INITIALIZER;
1875 extract_range_from_unary_expr (&vrres, code, type,
1876 &vrtem1, op0_type);
1877 vrp_meet (vr, &vrres);
1879 return;
1882 if (CONVERT_EXPR_CODE_P (code))
1884 tree inner_type = op0_type;
1885 tree outer_type = type;
1887 /* If the expression evaluates to a pointer, we are only interested in
1888 determining if it evaluates to NULL [0, 0] or non-NULL (~[0, 0]). */
1889 if (POINTER_TYPE_P (type))
1891 if (range_is_nonnull (&vr0))
1892 set_value_range_to_nonnull (vr, type);
1893 else if (range_is_null (&vr0))
1894 set_value_range_to_null (vr, type);
1895 else
1896 set_value_range_to_varying (vr);
1897 return;
1900 /* If VR0 is varying and we increase the type precision, assume
1901 a full range for the following transformation. */
1902 if (vr0.type == VR_VARYING
1903 && INTEGRAL_TYPE_P (inner_type)
1904 && TYPE_PRECISION (inner_type) < TYPE_PRECISION (outer_type))
1906 vr0.type = VR_RANGE;
1907 vr0.min = TYPE_MIN_VALUE (inner_type);
1908 vr0.max = TYPE_MAX_VALUE (inner_type);
1911 /* If VR0 is a constant range or anti-range and the conversion is
1912 not truncating we can convert the min and max values and
1913 canonicalize the resulting range. Otherwise we can do the
1914 conversion if the size of the range is less than what the
1915 precision of the target type can represent and the range is
1916 not an anti-range. */
1917 if ((vr0.type == VR_RANGE
1918 || vr0.type == VR_ANTI_RANGE)
1919 && TREE_CODE (vr0.min) == INTEGER_CST
1920 && TREE_CODE (vr0.max) == INTEGER_CST
1921 && (TYPE_PRECISION (outer_type) >= TYPE_PRECISION (inner_type)
1922 || (vr0.type == VR_RANGE
1923 && integer_zerop (int_const_binop (RSHIFT_EXPR,
1924 int_const_binop (MINUS_EXPR, vr0.max, vr0.min),
1925 size_int (TYPE_PRECISION (outer_type)))))))
1927 tree new_min, new_max;
1928 new_min = force_fit_type (outer_type, wi::to_widest (vr0.min),
1929 0, false);
1930 new_max = force_fit_type (outer_type, wi::to_widest (vr0.max),
1931 0, false);
1932 set_and_canonicalize_value_range (vr, vr0.type,
1933 new_min, new_max, NULL);
1934 return;
1937 set_value_range_to_varying (vr);
1938 return;
1940 else if (code == ABS_EXPR)
1942 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
1944 set_value_range_to_varying (vr);
1945 return;
1947 wide_int wmin, wmax;
1948 wide_int vr0_min, vr0_max;
1949 extract_range_into_wide_ints (&vr0, sign, prec, vr0_min, vr0_max);
1950 if (wide_int_range_abs (wmin, wmax, sign, prec, vr0_min, vr0_max,
1951 TYPE_OVERFLOW_UNDEFINED (type)))
1952 set_value_range (vr, VR_RANGE,
1953 wide_int_to_tree (type, wmin),
1954 wide_int_to_tree (type, wmax), NULL);
1955 else
1956 set_value_range_to_varying (vr);
1957 return;
1960 /* For unhandled operations fall back to varying. */
1961 set_value_range_to_varying (vr);
1962 return;
1965 /* Debugging dumps. */
1967 void dump_value_range (FILE *, const value_range *);
1968 void debug_value_range (value_range *);
1969 void dump_all_value_ranges (FILE *);
1970 void dump_vr_equiv (FILE *, bitmap);
1971 void debug_vr_equiv (bitmap);
1974 /* Dump value range VR to FILE. */
1976 void
1977 dump_value_range (FILE *file, const value_range *vr)
1979 if (vr == NULL)
1980 fprintf (file, "[]");
1981 else if (vr->type == VR_UNDEFINED)
1982 fprintf (file, "UNDEFINED");
1983 else if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
1985 tree type = TREE_TYPE (vr->min);
1987 fprintf (file, "%s[", (vr->type == VR_ANTI_RANGE) ? "~" : "");
1989 if (INTEGRAL_TYPE_P (type)
1990 && !TYPE_UNSIGNED (type)
1991 && vrp_val_is_min (vr->min))
1992 fprintf (file, "-INF");
1993 else
1994 print_generic_expr (file, vr->min);
1996 fprintf (file, ", ");
1998 if (INTEGRAL_TYPE_P (type)
1999 && vrp_val_is_max (vr->max))
2000 fprintf (file, "+INF");
2001 else
2002 print_generic_expr (file, vr->max);
2004 fprintf (file, "]");
2006 if (vr->equiv)
2008 bitmap_iterator bi;
2009 unsigned i, c = 0;
2011 fprintf (file, " EQUIVALENCES: { ");
2013 EXECUTE_IF_SET_IN_BITMAP (vr->equiv, 0, i, bi)
2015 print_generic_expr (file, ssa_name (i));
2016 fprintf (file, " ");
2017 c++;
2020 fprintf (file, "} (%u elements)", c);
2023 else if (vr->type == VR_VARYING)
2024 fprintf (file, "VARYING");
2025 else
2026 fprintf (file, "INVALID RANGE");
2030 /* Dump value range VR to stderr. */
2032 DEBUG_FUNCTION void
2033 debug_value_range (value_range *vr)
2035 dump_value_range (stderr, vr);
2036 fprintf (stderr, "\n");
2039 void
2040 value_range::dump ()
2042 debug_value_range (this);
2046 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
2047 create a new SSA name N and return the assertion assignment
2048 'N = ASSERT_EXPR <V, V OP W>'. */
2050 static gimple *
2051 build_assert_expr_for (tree cond, tree v)
2053 tree a;
2054 gassign *assertion;
2056 gcc_assert (TREE_CODE (v) == SSA_NAME
2057 && COMPARISON_CLASS_P (cond));
2059 a = build2 (ASSERT_EXPR, TREE_TYPE (v), v, cond);
2060 assertion = gimple_build_assign (NULL_TREE, a);
2062 /* The new ASSERT_EXPR, creates a new SSA name that replaces the
2063 operand of the ASSERT_EXPR. Create it so the new name and the old one
2064 are registered in the replacement table so that we can fix the SSA web
2065 after adding all the ASSERT_EXPRs. */
2066 tree new_def = create_new_def_for (v, assertion, NULL);
2067 /* Make sure we preserve abnormalness throughout an ASSERT_EXPR chain
2068 given we have to be able to fully propagate those out to re-create
2069 valid SSA when removing the asserts. */
2070 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (v))
2071 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_def) = 1;
2073 return assertion;
2077 /* Return false if EXPR is a predicate expression involving floating
2078 point values. */
2080 static inline bool
2081 fp_predicate (gimple *stmt)
2083 GIMPLE_CHECK (stmt, GIMPLE_COND);
2085 return FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)));
2088 /* If the range of values taken by OP can be inferred after STMT executes,
2089 return the comparison code (COMP_CODE_P) and value (VAL_P) that
2090 describes the inferred range. Return true if a range could be
2091 inferred. */
2093 bool
2094 infer_value_range (gimple *stmt, tree op, tree_code *comp_code_p, tree *val_p)
2096 *val_p = NULL_TREE;
2097 *comp_code_p = ERROR_MARK;
2099 /* Do not attempt to infer anything in names that flow through
2100 abnormal edges. */
2101 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
2102 return false;
2104 /* If STMT is the last statement of a basic block with no normal
2105 successors, there is no point inferring anything about any of its
2106 operands. We would not be able to find a proper insertion point
2107 for the assertion, anyway. */
2108 if (stmt_ends_bb_p (stmt))
2110 edge_iterator ei;
2111 edge e;
2113 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
2114 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
2115 break;
2116 if (e == NULL)
2117 return false;
2120 if (infer_nonnull_range (stmt, op))
2122 *val_p = build_int_cst (TREE_TYPE (op), 0);
2123 *comp_code_p = NE_EXPR;
2124 return true;
2127 return false;
2131 void dump_asserts_for (FILE *, tree);
2132 void debug_asserts_for (tree);
2133 void dump_all_asserts (FILE *);
2134 void debug_all_asserts (void);
2136 /* Dump all the registered assertions for NAME to FILE. */
2138 void
2139 dump_asserts_for (FILE *file, tree name)
2141 assert_locus *loc;
2143 fprintf (file, "Assertions to be inserted for ");
2144 print_generic_expr (file, name);
2145 fprintf (file, "\n");
2147 loc = asserts_for[SSA_NAME_VERSION (name)];
2148 while (loc)
2150 fprintf (file, "\t");
2151 print_gimple_stmt (file, gsi_stmt (loc->si), 0);
2152 fprintf (file, "\n\tBB #%d", loc->bb->index);
2153 if (loc->e)
2155 fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
2156 loc->e->dest->index);
2157 dump_edge_info (file, loc->e, dump_flags, 0);
2159 fprintf (file, "\n\tPREDICATE: ");
2160 print_generic_expr (file, loc->expr);
2161 fprintf (file, " %s ", get_tree_code_name (loc->comp_code));
2162 print_generic_expr (file, loc->val);
2163 fprintf (file, "\n\n");
2164 loc = loc->next;
2167 fprintf (file, "\n");
2171 /* Dump all the registered assertions for NAME to stderr. */
2173 DEBUG_FUNCTION void
2174 debug_asserts_for (tree name)
2176 dump_asserts_for (stderr, name);
2180 /* Dump all the registered assertions for all the names to FILE. */
2182 void
2183 dump_all_asserts (FILE *file)
2185 unsigned i;
2186 bitmap_iterator bi;
2188 fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
2189 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
2190 dump_asserts_for (file, ssa_name (i));
2191 fprintf (file, "\n");
2195 /* Dump all the registered assertions for all the names to stderr. */
2197 DEBUG_FUNCTION void
2198 debug_all_asserts (void)
2200 dump_all_asserts (stderr);
2203 /* Push the assert info for NAME, EXPR, COMP_CODE and VAL to ASSERTS. */
2205 static void
2206 add_assert_info (vec<assert_info> &asserts,
2207 tree name, tree expr, enum tree_code comp_code, tree val)
2209 assert_info info;
2210 info.comp_code = comp_code;
2211 info.name = name;
2212 if (TREE_OVERFLOW_P (val))
2213 val = drop_tree_overflow (val);
2214 info.val = val;
2215 info.expr = expr;
2216 asserts.safe_push (info);
2219 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
2220 'EXPR COMP_CODE VAL' at a location that dominates block BB or
2221 E->DEST, then register this location as a possible insertion point
2222 for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
2224 BB, E and SI provide the exact insertion point for the new
2225 ASSERT_EXPR. If BB is NULL, then the ASSERT_EXPR is to be inserted
2226 on edge E. Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
2227 BB. If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
2228 must not be NULL. */
2230 static void
2231 register_new_assert_for (tree name, tree expr,
2232 enum tree_code comp_code,
2233 tree val,
2234 basic_block bb,
2235 edge e,
2236 gimple_stmt_iterator si)
2238 assert_locus *n, *loc, *last_loc;
2239 basic_block dest_bb;
2241 gcc_checking_assert (bb == NULL || e == NULL);
2243 if (e == NULL)
2244 gcc_checking_assert (gimple_code (gsi_stmt (si)) != GIMPLE_COND
2245 && gimple_code (gsi_stmt (si)) != GIMPLE_SWITCH);
2247 /* Never build an assert comparing against an integer constant with
2248 TREE_OVERFLOW set. This confuses our undefined overflow warning
2249 machinery. */
2250 if (TREE_OVERFLOW_P (val))
2251 val = drop_tree_overflow (val);
2253 /* The new assertion A will be inserted at BB or E. We need to
2254 determine if the new location is dominated by a previously
2255 registered location for A. If we are doing an edge insertion,
2256 assume that A will be inserted at E->DEST. Note that this is not
2257 necessarily true.
2259 If E is a critical edge, it will be split. But even if E is
2260 split, the new block will dominate the same set of blocks that
2261 E->DEST dominates.
2263 The reverse, however, is not true, blocks dominated by E->DEST
2264 will not be dominated by the new block created to split E. So,
2265 if the insertion location is on a critical edge, we will not use
2266 the new location to move another assertion previously registered
2267 at a block dominated by E->DEST. */
2268 dest_bb = (bb) ? bb : e->dest;
2270 /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
2271 VAL at a block dominating DEST_BB, then we don't need to insert a new
2272 one. Similarly, if the same assertion already exists at a block
2273 dominated by DEST_BB and the new location is not on a critical
2274 edge, then update the existing location for the assertion (i.e.,
2275 move the assertion up in the dominance tree).
2277 Note, this is implemented as a simple linked list because there
2278 should not be more than a handful of assertions registered per
2279 name. If this becomes a performance problem, a table hashed by
2280 COMP_CODE and VAL could be implemented. */
2281 loc = asserts_for[SSA_NAME_VERSION (name)];
2282 last_loc = loc;
2283 while (loc)
2285 if (loc->comp_code == comp_code
2286 && (loc->val == val
2287 || operand_equal_p (loc->val, val, 0))
2288 && (loc->expr == expr
2289 || operand_equal_p (loc->expr, expr, 0)))
2291 /* If E is not a critical edge and DEST_BB
2292 dominates the existing location for the assertion, move
2293 the assertion up in the dominance tree by updating its
2294 location information. */
2295 if ((e == NULL || !EDGE_CRITICAL_P (e))
2296 && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
2298 loc->bb = dest_bb;
2299 loc->e = e;
2300 loc->si = si;
2301 return;
2305 /* Update the last node of the list and move to the next one. */
2306 last_loc = loc;
2307 loc = loc->next;
2310 /* If we didn't find an assertion already registered for
2311 NAME COMP_CODE VAL, add a new one at the end of the list of
2312 assertions associated with NAME. */
2313 n = XNEW (struct assert_locus);
2314 n->bb = dest_bb;
2315 n->e = e;
2316 n->si = si;
2317 n->comp_code = comp_code;
2318 n->val = val;
2319 n->expr = expr;
2320 n->next = NULL;
2322 if (last_loc)
2323 last_loc->next = n;
2324 else
2325 asserts_for[SSA_NAME_VERSION (name)] = n;
2327 bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
2330 /* (COND_OP0 COND_CODE COND_OP1) is a predicate which uses NAME.
2331 Extract a suitable test code and value and store them into *CODE_P and
2332 *VAL_P so the predicate is normalized to NAME *CODE_P *VAL_P.
2334 If no extraction was possible, return FALSE, otherwise return TRUE.
2336 If INVERT is true, then we invert the result stored into *CODE_P. */
2338 static bool
2339 extract_code_and_val_from_cond_with_ops (tree name, enum tree_code cond_code,
2340 tree cond_op0, tree cond_op1,
2341 bool invert, enum tree_code *code_p,
2342 tree *val_p)
2344 enum tree_code comp_code;
2345 tree val;
2347 /* Otherwise, we have a comparison of the form NAME COMP VAL
2348 or VAL COMP NAME. */
2349 if (name == cond_op1)
2351 /* If the predicate is of the form VAL COMP NAME, flip
2352 COMP around because we need to register NAME as the
2353 first operand in the predicate. */
2354 comp_code = swap_tree_comparison (cond_code);
2355 val = cond_op0;
2357 else if (name == cond_op0)
2359 /* The comparison is of the form NAME COMP VAL, so the
2360 comparison code remains unchanged. */
2361 comp_code = cond_code;
2362 val = cond_op1;
2364 else
2365 gcc_unreachable ();
2367 /* Invert the comparison code as necessary. */
2368 if (invert)
2369 comp_code = invert_tree_comparison (comp_code, 0);
2371 /* VRP only handles integral and pointer types. */
2372 if (! INTEGRAL_TYPE_P (TREE_TYPE (val))
2373 && ! POINTER_TYPE_P (TREE_TYPE (val)))
2374 return false;
2376 /* Do not register always-false predicates.
2377 FIXME: this works around a limitation in fold() when dealing with
2378 enumerations. Given 'enum { N1, N2 } x;', fold will not
2379 fold 'if (x > N2)' to 'if (0)'. */
2380 if ((comp_code == GT_EXPR || comp_code == LT_EXPR)
2381 && INTEGRAL_TYPE_P (TREE_TYPE (val)))
2383 tree min = TYPE_MIN_VALUE (TREE_TYPE (val));
2384 tree max = TYPE_MAX_VALUE (TREE_TYPE (val));
2386 if (comp_code == GT_EXPR
2387 && (!max
2388 || compare_values (val, max) == 0))
2389 return false;
2391 if (comp_code == LT_EXPR
2392 && (!min
2393 || compare_values (val, min) == 0))
2394 return false;
2396 *code_p = comp_code;
2397 *val_p = val;
2398 return true;
2401 /* Find out smallest RES where RES > VAL && (RES & MASK) == RES, if any
2402 (otherwise return VAL). VAL and MASK must be zero-extended for
2403 precision PREC. If SGNBIT is non-zero, first xor VAL with SGNBIT
2404 (to transform signed values into unsigned) and at the end xor
2405 SGNBIT back. */
2407 static wide_int
2408 masked_increment (const wide_int &val_in, const wide_int &mask,
2409 const wide_int &sgnbit, unsigned int prec)
2411 wide_int bit = wi::one (prec), res;
2412 unsigned int i;
2414 wide_int val = val_in ^ sgnbit;
2415 for (i = 0; i < prec; i++, bit += bit)
2417 res = mask;
2418 if ((res & bit) == 0)
2419 continue;
2420 res = bit - 1;
2421 res = wi::bit_and_not (val + bit, res);
2422 res &= mask;
2423 if (wi::gtu_p (res, val))
2424 return res ^ sgnbit;
2426 return val ^ sgnbit;
2429 /* Helper for overflow_comparison_p
2431 OP0 CODE OP1 is a comparison. Examine the comparison and potentially
2432 OP1's defining statement to see if it ultimately has the form
2433 OP0 CODE (OP0 PLUS INTEGER_CST)
2435 If so, return TRUE indicating this is an overflow test and store into
2436 *NEW_CST an updated constant that can be used in a narrowed range test.
2438 REVERSED indicates if the comparison was originally:
2440 OP1 CODE' OP0.
2442 This affects how we build the updated constant. */
2444 static bool
2445 overflow_comparison_p_1 (enum tree_code code, tree op0, tree op1,
2446 bool follow_assert_exprs, bool reversed, tree *new_cst)
2448 /* See if this is a relational operation between two SSA_NAMES with
2449 unsigned, overflow wrapping values. If so, check it more deeply. */
2450 if ((code == LT_EXPR || code == LE_EXPR
2451 || code == GE_EXPR || code == GT_EXPR)
2452 && TREE_CODE (op0) == SSA_NAME
2453 && TREE_CODE (op1) == SSA_NAME
2454 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
2455 && TYPE_UNSIGNED (TREE_TYPE (op0))
2456 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0)))
2458 gimple *op1_def = SSA_NAME_DEF_STMT (op1);
2460 /* If requested, follow any ASSERT_EXPRs backwards for OP1. */
2461 if (follow_assert_exprs)
2463 while (gimple_assign_single_p (op1_def)
2464 && TREE_CODE (gimple_assign_rhs1 (op1_def)) == ASSERT_EXPR)
2466 op1 = TREE_OPERAND (gimple_assign_rhs1 (op1_def), 0);
2467 if (TREE_CODE (op1) != SSA_NAME)
2468 break;
2469 op1_def = SSA_NAME_DEF_STMT (op1);
2473 /* Now look at the defining statement of OP1 to see if it adds
2474 or subtracts a nonzero constant from another operand. */
2475 if (op1_def
2476 && is_gimple_assign (op1_def)
2477 && gimple_assign_rhs_code (op1_def) == PLUS_EXPR
2478 && TREE_CODE (gimple_assign_rhs2 (op1_def)) == INTEGER_CST
2479 && !integer_zerop (gimple_assign_rhs2 (op1_def)))
2481 tree target = gimple_assign_rhs1 (op1_def);
2483 /* If requested, follow ASSERT_EXPRs backwards for op0 looking
2484 for one where TARGET appears on the RHS. */
2485 if (follow_assert_exprs)
2487 /* Now see if that "other operand" is op0, following the chain
2488 of ASSERT_EXPRs if necessary. */
2489 gimple *op0_def = SSA_NAME_DEF_STMT (op0);
2490 while (op0 != target
2491 && gimple_assign_single_p (op0_def)
2492 && TREE_CODE (gimple_assign_rhs1 (op0_def)) == ASSERT_EXPR)
2494 op0 = TREE_OPERAND (gimple_assign_rhs1 (op0_def), 0);
2495 if (TREE_CODE (op0) != SSA_NAME)
2496 break;
2497 op0_def = SSA_NAME_DEF_STMT (op0);
2501 /* If we did not find our target SSA_NAME, then this is not
2502 an overflow test. */
2503 if (op0 != target)
2504 return false;
2506 tree type = TREE_TYPE (op0);
2507 wide_int max = wi::max_value (TYPE_PRECISION (type), UNSIGNED);
2508 tree inc = gimple_assign_rhs2 (op1_def);
2509 if (reversed)
2510 *new_cst = wide_int_to_tree (type, max + wi::to_wide (inc));
2511 else
2512 *new_cst = wide_int_to_tree (type, max - wi::to_wide (inc));
2513 return true;
2516 return false;
2519 /* OP0 CODE OP1 is a comparison. Examine the comparison and potentially
2520 OP1's defining statement to see if it ultimately has the form
2521 OP0 CODE (OP0 PLUS INTEGER_CST)
2523 If so, return TRUE indicating this is an overflow test and store into
2524 *NEW_CST an updated constant that can be used in a narrowed range test.
2526 These statements are left as-is in the IL to facilitate discovery of
2527 {ADD,SUB}_OVERFLOW sequences later in the optimizer pipeline. But
2528 the alternate range representation is often useful within VRP. */
2530 bool
2531 overflow_comparison_p (tree_code code, tree name, tree val,
2532 bool use_equiv_p, tree *new_cst)
2534 if (overflow_comparison_p_1 (code, name, val, use_equiv_p, false, new_cst))
2535 return true;
2536 return overflow_comparison_p_1 (swap_tree_comparison (code), val, name,
2537 use_equiv_p, true, new_cst);
2541 /* Try to register an edge assertion for SSA name NAME on edge E for
2542 the condition COND contributing to the conditional jump pointed to by BSI.
2543 Invert the condition COND if INVERT is true. */
2545 static void
2546 register_edge_assert_for_2 (tree name, edge e,
2547 enum tree_code cond_code,
2548 tree cond_op0, tree cond_op1, bool invert,
2549 vec<assert_info> &asserts)
2551 tree val;
2552 enum tree_code comp_code;
2554 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
2555 cond_op0,
2556 cond_op1,
2557 invert, &comp_code, &val))
2558 return;
2560 /* Queue the assert. */
2561 tree x;
2562 if (overflow_comparison_p (comp_code, name, val, false, &x))
2564 enum tree_code new_code = ((comp_code == GT_EXPR || comp_code == GE_EXPR)
2565 ? GT_EXPR : LE_EXPR);
2566 add_assert_info (asserts, name, name, new_code, x);
2568 add_assert_info (asserts, name, name, comp_code, val);
2570 /* In the case of NAME <= CST and NAME being defined as
2571 NAME = (unsigned) NAME2 + CST2 we can assert NAME2 >= -CST2
2572 and NAME2 <= CST - CST2. We can do the same for NAME > CST.
2573 This catches range and anti-range tests. */
2574 if ((comp_code == LE_EXPR
2575 || comp_code == GT_EXPR)
2576 && TREE_CODE (val) == INTEGER_CST
2577 && TYPE_UNSIGNED (TREE_TYPE (val)))
2579 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
2580 tree cst2 = NULL_TREE, name2 = NULL_TREE, name3 = NULL_TREE;
2582 /* Extract CST2 from the (optional) addition. */
2583 if (is_gimple_assign (def_stmt)
2584 && gimple_assign_rhs_code (def_stmt) == PLUS_EXPR)
2586 name2 = gimple_assign_rhs1 (def_stmt);
2587 cst2 = gimple_assign_rhs2 (def_stmt);
2588 if (TREE_CODE (name2) == SSA_NAME
2589 && TREE_CODE (cst2) == INTEGER_CST)
2590 def_stmt = SSA_NAME_DEF_STMT (name2);
2593 /* Extract NAME2 from the (optional) sign-changing cast. */
2594 if (gimple_assign_cast_p (def_stmt))
2596 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt))
2597 && ! TYPE_UNSIGNED (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
2598 && (TYPE_PRECISION (gimple_expr_type (def_stmt))
2599 == TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))))
2600 name3 = gimple_assign_rhs1 (def_stmt);
2603 /* If name3 is used later, create an ASSERT_EXPR for it. */
2604 if (name3 != NULL_TREE
2605 && TREE_CODE (name3) == SSA_NAME
2606 && (cst2 == NULL_TREE
2607 || TREE_CODE (cst2) == INTEGER_CST)
2608 && INTEGRAL_TYPE_P (TREE_TYPE (name3)))
2610 tree tmp;
2612 /* Build an expression for the range test. */
2613 tmp = build1 (NOP_EXPR, TREE_TYPE (name), name3);
2614 if (cst2 != NULL_TREE)
2615 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
2617 if (dump_file)
2619 fprintf (dump_file, "Adding assert for ");
2620 print_generic_expr (dump_file, name3);
2621 fprintf (dump_file, " from ");
2622 print_generic_expr (dump_file, tmp);
2623 fprintf (dump_file, "\n");
2626 add_assert_info (asserts, name3, tmp, comp_code, val);
2629 /* If name2 is used later, create an ASSERT_EXPR for it. */
2630 if (name2 != NULL_TREE
2631 && TREE_CODE (name2) == SSA_NAME
2632 && TREE_CODE (cst2) == INTEGER_CST
2633 && INTEGRAL_TYPE_P (TREE_TYPE (name2)))
2635 tree tmp;
2637 /* Build an expression for the range test. */
2638 tmp = name2;
2639 if (TREE_TYPE (name) != TREE_TYPE (name2))
2640 tmp = build1 (NOP_EXPR, TREE_TYPE (name), tmp);
2641 if (cst2 != NULL_TREE)
2642 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
2644 if (dump_file)
2646 fprintf (dump_file, "Adding assert for ");
2647 print_generic_expr (dump_file, name2);
2648 fprintf (dump_file, " from ");
2649 print_generic_expr (dump_file, tmp);
2650 fprintf (dump_file, "\n");
2653 add_assert_info (asserts, name2, tmp, comp_code, val);
2657 /* In the case of post-in/decrement tests like if (i++) ... and uses
2658 of the in/decremented value on the edge the extra name we want to
2659 assert for is not on the def chain of the name compared. Instead
2660 it is in the set of use stmts.
2661 Similar cases happen for conversions that were simplified through
2662 fold_{sign_changed,widened}_comparison. */
2663 if ((comp_code == NE_EXPR
2664 || comp_code == EQ_EXPR)
2665 && TREE_CODE (val) == INTEGER_CST)
2667 imm_use_iterator ui;
2668 gimple *use_stmt;
2669 FOR_EACH_IMM_USE_STMT (use_stmt, ui, name)
2671 if (!is_gimple_assign (use_stmt))
2672 continue;
2674 /* Cut off to use-stmts that are dominating the predecessor. */
2675 if (!dominated_by_p (CDI_DOMINATORS, e->src, gimple_bb (use_stmt)))
2676 continue;
2678 tree name2 = gimple_assign_lhs (use_stmt);
2679 if (TREE_CODE (name2) != SSA_NAME)
2680 continue;
2682 enum tree_code code = gimple_assign_rhs_code (use_stmt);
2683 tree cst;
2684 if (code == PLUS_EXPR
2685 || code == MINUS_EXPR)
2687 cst = gimple_assign_rhs2 (use_stmt);
2688 if (TREE_CODE (cst) != INTEGER_CST)
2689 continue;
2690 cst = int_const_binop (code, val, cst);
2692 else if (CONVERT_EXPR_CODE_P (code))
2694 /* For truncating conversions we cannot record
2695 an inequality. */
2696 if (comp_code == NE_EXPR
2697 && (TYPE_PRECISION (TREE_TYPE (name2))
2698 < TYPE_PRECISION (TREE_TYPE (name))))
2699 continue;
2700 cst = fold_convert (TREE_TYPE (name2), val);
2702 else
2703 continue;
2705 if (TREE_OVERFLOW_P (cst))
2706 cst = drop_tree_overflow (cst);
2707 add_assert_info (asserts, name2, name2, comp_code, cst);
2711 if (TREE_CODE_CLASS (comp_code) == tcc_comparison
2712 && TREE_CODE (val) == INTEGER_CST)
2714 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
2715 tree name2 = NULL_TREE, names[2], cst2 = NULL_TREE;
2716 tree val2 = NULL_TREE;
2717 unsigned int prec = TYPE_PRECISION (TREE_TYPE (val));
2718 wide_int mask = wi::zero (prec);
2719 unsigned int nprec = prec;
2720 enum tree_code rhs_code = ERROR_MARK;
2722 if (is_gimple_assign (def_stmt))
2723 rhs_code = gimple_assign_rhs_code (def_stmt);
2725 /* In the case of NAME != CST1 where NAME = A +- CST2 we can
2726 assert that A != CST1 -+ CST2. */
2727 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
2728 && (rhs_code == PLUS_EXPR || rhs_code == MINUS_EXPR))
2730 tree op0 = gimple_assign_rhs1 (def_stmt);
2731 tree op1 = gimple_assign_rhs2 (def_stmt);
2732 if (TREE_CODE (op0) == SSA_NAME
2733 && TREE_CODE (op1) == INTEGER_CST)
2735 enum tree_code reverse_op = (rhs_code == PLUS_EXPR
2736 ? MINUS_EXPR : PLUS_EXPR);
2737 op1 = int_const_binop (reverse_op, val, op1);
2738 if (TREE_OVERFLOW (op1))
2739 op1 = drop_tree_overflow (op1);
2740 add_assert_info (asserts, op0, op0, comp_code, op1);
2744 /* Add asserts for NAME cmp CST and NAME being defined
2745 as NAME = (int) NAME2. */
2746 if (!TYPE_UNSIGNED (TREE_TYPE (val))
2747 && (comp_code == LE_EXPR || comp_code == LT_EXPR
2748 || comp_code == GT_EXPR || comp_code == GE_EXPR)
2749 && gimple_assign_cast_p (def_stmt))
2751 name2 = gimple_assign_rhs1 (def_stmt);
2752 if (CONVERT_EXPR_CODE_P (rhs_code)
2753 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
2754 && TYPE_UNSIGNED (TREE_TYPE (name2))
2755 && prec == TYPE_PRECISION (TREE_TYPE (name2))
2756 && (comp_code == LE_EXPR || comp_code == GT_EXPR
2757 || !tree_int_cst_equal (val,
2758 TYPE_MIN_VALUE (TREE_TYPE (val)))))
2760 tree tmp, cst;
2761 enum tree_code new_comp_code = comp_code;
2763 cst = fold_convert (TREE_TYPE (name2),
2764 TYPE_MIN_VALUE (TREE_TYPE (val)));
2765 /* Build an expression for the range test. */
2766 tmp = build2 (PLUS_EXPR, TREE_TYPE (name2), name2, cst);
2767 cst = fold_build2 (PLUS_EXPR, TREE_TYPE (name2), cst,
2768 fold_convert (TREE_TYPE (name2), val));
2769 if (comp_code == LT_EXPR || comp_code == GE_EXPR)
2771 new_comp_code = comp_code == LT_EXPR ? LE_EXPR : GT_EXPR;
2772 cst = fold_build2 (MINUS_EXPR, TREE_TYPE (name2), cst,
2773 build_int_cst (TREE_TYPE (name2), 1));
2776 if (dump_file)
2778 fprintf (dump_file, "Adding assert for ");
2779 print_generic_expr (dump_file, name2);
2780 fprintf (dump_file, " from ");
2781 print_generic_expr (dump_file, tmp);
2782 fprintf (dump_file, "\n");
2785 add_assert_info (asserts, name2, tmp, new_comp_code, cst);
2789 /* Add asserts for NAME cmp CST and NAME being defined as
2790 NAME = NAME2 >> CST2.
2792 Extract CST2 from the right shift. */
2793 if (rhs_code == RSHIFT_EXPR)
2795 name2 = gimple_assign_rhs1 (def_stmt);
2796 cst2 = gimple_assign_rhs2 (def_stmt);
2797 if (TREE_CODE (name2) == SSA_NAME
2798 && tree_fits_uhwi_p (cst2)
2799 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
2800 && IN_RANGE (tree_to_uhwi (cst2), 1, prec - 1)
2801 && type_has_mode_precision_p (TREE_TYPE (val)))
2803 mask = wi::mask (tree_to_uhwi (cst2), false, prec);
2804 val2 = fold_binary (LSHIFT_EXPR, TREE_TYPE (val), val, cst2);
2807 if (val2 != NULL_TREE
2808 && TREE_CODE (val2) == INTEGER_CST
2809 && simple_cst_equal (fold_build2 (RSHIFT_EXPR,
2810 TREE_TYPE (val),
2811 val2, cst2), val))
2813 enum tree_code new_comp_code = comp_code;
2814 tree tmp, new_val;
2816 tmp = name2;
2817 if (comp_code == EQ_EXPR || comp_code == NE_EXPR)
2819 if (!TYPE_UNSIGNED (TREE_TYPE (val)))
2821 tree type = build_nonstandard_integer_type (prec, 1);
2822 tmp = build1 (NOP_EXPR, type, name2);
2823 val2 = fold_convert (type, val2);
2825 tmp = fold_build2 (MINUS_EXPR, TREE_TYPE (tmp), tmp, val2);
2826 new_val = wide_int_to_tree (TREE_TYPE (tmp), mask);
2827 new_comp_code = comp_code == EQ_EXPR ? LE_EXPR : GT_EXPR;
2829 else if (comp_code == LT_EXPR || comp_code == GE_EXPR)
2831 wide_int minval
2832 = wi::min_value (prec, TYPE_SIGN (TREE_TYPE (val)));
2833 new_val = val2;
2834 if (minval == wi::to_wide (new_val))
2835 new_val = NULL_TREE;
2837 else
2839 wide_int maxval
2840 = wi::max_value (prec, TYPE_SIGN (TREE_TYPE (val)));
2841 mask |= wi::to_wide (val2);
2842 if (wi::eq_p (mask, maxval))
2843 new_val = NULL_TREE;
2844 else
2845 new_val = wide_int_to_tree (TREE_TYPE (val2), mask);
2848 if (new_val)
2850 if (dump_file)
2852 fprintf (dump_file, "Adding assert for ");
2853 print_generic_expr (dump_file, name2);
2854 fprintf (dump_file, " from ");
2855 print_generic_expr (dump_file, tmp);
2856 fprintf (dump_file, "\n");
2859 add_assert_info (asserts, name2, tmp, new_comp_code, new_val);
2863 /* Add asserts for NAME cmp CST and NAME being defined as
2864 NAME = NAME2 & CST2.
2866 Extract CST2 from the and.
2868 Also handle
2869 NAME = (unsigned) NAME2;
2870 casts where NAME's type is unsigned and has smaller precision
2871 than NAME2's type as if it was NAME = NAME2 & MASK. */
2872 names[0] = NULL_TREE;
2873 names[1] = NULL_TREE;
2874 cst2 = NULL_TREE;
2875 if (rhs_code == BIT_AND_EXPR
2876 || (CONVERT_EXPR_CODE_P (rhs_code)
2877 && INTEGRAL_TYPE_P (TREE_TYPE (val))
2878 && TYPE_UNSIGNED (TREE_TYPE (val))
2879 && TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
2880 > prec))
2882 name2 = gimple_assign_rhs1 (def_stmt);
2883 if (rhs_code == BIT_AND_EXPR)
2884 cst2 = gimple_assign_rhs2 (def_stmt);
2885 else
2887 cst2 = TYPE_MAX_VALUE (TREE_TYPE (val));
2888 nprec = TYPE_PRECISION (TREE_TYPE (name2));
2890 if (TREE_CODE (name2) == SSA_NAME
2891 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
2892 && TREE_CODE (cst2) == INTEGER_CST
2893 && !integer_zerop (cst2)
2894 && (nprec > 1
2895 || TYPE_UNSIGNED (TREE_TYPE (val))))
2897 gimple *def_stmt2 = SSA_NAME_DEF_STMT (name2);
2898 if (gimple_assign_cast_p (def_stmt2))
2900 names[1] = gimple_assign_rhs1 (def_stmt2);
2901 if (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt2))
2902 || !INTEGRAL_TYPE_P (TREE_TYPE (names[1]))
2903 || (TYPE_PRECISION (TREE_TYPE (name2))
2904 != TYPE_PRECISION (TREE_TYPE (names[1]))))
2905 names[1] = NULL_TREE;
2907 names[0] = name2;
2910 if (names[0] || names[1])
2912 wide_int minv, maxv, valv, cst2v;
2913 wide_int tem, sgnbit;
2914 bool valid_p = false, valn, cst2n;
2915 enum tree_code ccode = comp_code;
2917 valv = wide_int::from (wi::to_wide (val), nprec, UNSIGNED);
2918 cst2v = wide_int::from (wi::to_wide (cst2), nprec, UNSIGNED);
2919 valn = wi::neg_p (valv, TYPE_SIGN (TREE_TYPE (val)));
2920 cst2n = wi::neg_p (cst2v, TYPE_SIGN (TREE_TYPE (val)));
2921 /* If CST2 doesn't have most significant bit set,
2922 but VAL is negative, we have comparison like
2923 if ((x & 0x123) > -4) (always true). Just give up. */
2924 if (!cst2n && valn)
2925 ccode = ERROR_MARK;
2926 if (cst2n)
2927 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
2928 else
2929 sgnbit = wi::zero (nprec);
2930 minv = valv & cst2v;
2931 switch (ccode)
2933 case EQ_EXPR:
2934 /* Minimum unsigned value for equality is VAL & CST2
2935 (should be equal to VAL, otherwise we probably should
2936 have folded the comparison into false) and
2937 maximum unsigned value is VAL | ~CST2. */
2938 maxv = valv | ~cst2v;
2939 valid_p = true;
2940 break;
2942 case NE_EXPR:
2943 tem = valv | ~cst2v;
2944 /* If VAL is 0, handle (X & CST2) != 0 as (X & CST2) > 0U. */
2945 if (valv == 0)
2947 cst2n = false;
2948 sgnbit = wi::zero (nprec);
2949 goto gt_expr;
2951 /* If (VAL | ~CST2) is all ones, handle it as
2952 (X & CST2) < VAL. */
2953 if (tem == -1)
2955 cst2n = false;
2956 valn = false;
2957 sgnbit = wi::zero (nprec);
2958 goto lt_expr;
2960 if (!cst2n && wi::neg_p (cst2v))
2961 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
2962 if (sgnbit != 0)
2964 if (valv == sgnbit)
2966 cst2n = true;
2967 valn = true;
2968 goto gt_expr;
2970 if (tem == wi::mask (nprec - 1, false, nprec))
2972 cst2n = true;
2973 goto lt_expr;
2975 if (!cst2n)
2976 sgnbit = wi::zero (nprec);
2978 break;
2980 case GE_EXPR:
2981 /* Minimum unsigned value for >= if (VAL & CST2) == VAL
2982 is VAL and maximum unsigned value is ~0. For signed
2983 comparison, if CST2 doesn't have most significant bit
2984 set, handle it similarly. If CST2 has MSB set,
2985 the minimum is the same, and maximum is ~0U/2. */
2986 if (minv != valv)
2988 /* If (VAL & CST2) != VAL, X & CST2 can't be equal to
2989 VAL. */
2990 minv = masked_increment (valv, cst2v, sgnbit, nprec);
2991 if (minv == valv)
2992 break;
2994 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
2995 valid_p = true;
2996 break;
2998 case GT_EXPR:
2999 gt_expr:
3000 /* Find out smallest MINV where MINV > VAL
3001 && (MINV & CST2) == MINV, if any. If VAL is signed and
3002 CST2 has MSB set, compute it biased by 1 << (nprec - 1). */
3003 minv = masked_increment (valv, cst2v, sgnbit, nprec);
3004 if (minv == valv)
3005 break;
3006 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
3007 valid_p = true;
3008 break;
3010 case LE_EXPR:
3011 /* Minimum unsigned value for <= is 0 and maximum
3012 unsigned value is VAL | ~CST2 if (VAL & CST2) == VAL.
3013 Otherwise, find smallest VAL2 where VAL2 > VAL
3014 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
3015 as maximum.
3016 For signed comparison, if CST2 doesn't have most
3017 significant bit set, handle it similarly. If CST2 has
3018 MSB set, the maximum is the same and minimum is INT_MIN. */
3019 if (minv == valv)
3020 maxv = valv;
3021 else
3023 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
3024 if (maxv == valv)
3025 break;
3026 maxv -= 1;
3028 maxv |= ~cst2v;
3029 minv = sgnbit;
3030 valid_p = true;
3031 break;
3033 case LT_EXPR:
3034 lt_expr:
3035 /* Minimum unsigned value for < is 0 and maximum
3036 unsigned value is (VAL-1) | ~CST2 if (VAL & CST2) == VAL.
3037 Otherwise, find smallest VAL2 where VAL2 > VAL
3038 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
3039 as maximum.
3040 For signed comparison, if CST2 doesn't have most
3041 significant bit set, handle it similarly. If CST2 has
3042 MSB set, the maximum is the same and minimum is INT_MIN. */
3043 if (minv == valv)
3045 if (valv == sgnbit)
3046 break;
3047 maxv = valv;
3049 else
3051 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
3052 if (maxv == valv)
3053 break;
3055 maxv -= 1;
3056 maxv |= ~cst2v;
3057 minv = sgnbit;
3058 valid_p = true;
3059 break;
3061 default:
3062 break;
3064 if (valid_p
3065 && (maxv - minv) != -1)
3067 tree tmp, new_val, type;
3068 int i;
3070 for (i = 0; i < 2; i++)
3071 if (names[i])
3073 wide_int maxv2 = maxv;
3074 tmp = names[i];
3075 type = TREE_TYPE (names[i]);
3076 if (!TYPE_UNSIGNED (type))
3078 type = build_nonstandard_integer_type (nprec, 1);
3079 tmp = build1 (NOP_EXPR, type, names[i]);
3081 if (minv != 0)
3083 tmp = build2 (PLUS_EXPR, type, tmp,
3084 wide_int_to_tree (type, -minv));
3085 maxv2 = maxv - minv;
3087 new_val = wide_int_to_tree (type, maxv2);
3089 if (dump_file)
3091 fprintf (dump_file, "Adding assert for ");
3092 print_generic_expr (dump_file, names[i]);
3093 fprintf (dump_file, " from ");
3094 print_generic_expr (dump_file, tmp);
3095 fprintf (dump_file, "\n");
3098 add_assert_info (asserts, names[i], tmp, LE_EXPR, new_val);
3105 /* OP is an operand of a truth value expression which is known to have
3106 a particular value. Register any asserts for OP and for any
3107 operands in OP's defining statement.
3109 If CODE is EQ_EXPR, then we want to register OP is zero (false),
3110 if CODE is NE_EXPR, then we want to register OP is nonzero (true). */
3112 static void
3113 register_edge_assert_for_1 (tree op, enum tree_code code,
3114 edge e, vec<assert_info> &asserts)
3116 gimple *op_def;
3117 tree val;
3118 enum tree_code rhs_code;
3120 /* We only care about SSA_NAMEs. */
3121 if (TREE_CODE (op) != SSA_NAME)
3122 return;
3124 /* We know that OP will have a zero or nonzero value. */
3125 val = build_int_cst (TREE_TYPE (op), 0);
3126 add_assert_info (asserts, op, op, code, val);
3128 /* Now look at how OP is set. If it's set from a comparison,
3129 a truth operation or some bit operations, then we may be able
3130 to register information about the operands of that assignment. */
3131 op_def = SSA_NAME_DEF_STMT (op);
3132 if (gimple_code (op_def) != GIMPLE_ASSIGN)
3133 return;
3135 rhs_code = gimple_assign_rhs_code (op_def);
3137 if (TREE_CODE_CLASS (rhs_code) == tcc_comparison)
3139 bool invert = (code == EQ_EXPR ? true : false);
3140 tree op0 = gimple_assign_rhs1 (op_def);
3141 tree op1 = gimple_assign_rhs2 (op_def);
3143 if (TREE_CODE (op0) == SSA_NAME)
3144 register_edge_assert_for_2 (op0, e, rhs_code, op0, op1, invert, asserts);
3145 if (TREE_CODE (op1) == SSA_NAME)
3146 register_edge_assert_for_2 (op1, e, rhs_code, op0, op1, invert, asserts);
3148 else if ((code == NE_EXPR
3149 && gimple_assign_rhs_code (op_def) == BIT_AND_EXPR)
3150 || (code == EQ_EXPR
3151 && gimple_assign_rhs_code (op_def) == BIT_IOR_EXPR))
3153 /* Recurse on each operand. */
3154 tree op0 = gimple_assign_rhs1 (op_def);
3155 tree op1 = gimple_assign_rhs2 (op_def);
3156 if (TREE_CODE (op0) == SSA_NAME
3157 && has_single_use (op0))
3158 register_edge_assert_for_1 (op0, code, e, asserts);
3159 if (TREE_CODE (op1) == SSA_NAME
3160 && has_single_use (op1))
3161 register_edge_assert_for_1 (op1, code, e, asserts);
3163 else if (gimple_assign_rhs_code (op_def) == BIT_NOT_EXPR
3164 && TYPE_PRECISION (TREE_TYPE (gimple_assign_lhs (op_def))) == 1)
3166 /* Recurse, flipping CODE. */
3167 code = invert_tree_comparison (code, false);
3168 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
3170 else if (gimple_assign_rhs_code (op_def) == SSA_NAME)
3172 /* Recurse through the copy. */
3173 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
3175 else if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (op_def)))
3177 /* Recurse through the type conversion, unless it is a narrowing
3178 conversion or conversion from non-integral type. */
3179 tree rhs = gimple_assign_rhs1 (op_def);
3180 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs))
3181 && (TYPE_PRECISION (TREE_TYPE (rhs))
3182 <= TYPE_PRECISION (TREE_TYPE (op))))
3183 register_edge_assert_for_1 (rhs, code, e, asserts);
3187 /* Check if comparison
3188 NAME COND_OP INTEGER_CST
3189 has a form of
3190 (X & 11...100..0) COND_OP XX...X00...0
3191 Such comparison can yield assertions like
3192 X >= XX...X00...0
3193 X <= XX...X11...1
3194 in case of COND_OP being EQ_EXPR or
3195 X < XX...X00...0
3196 X > XX...X11...1
3197 in case of NE_EXPR. */
3199 static bool
3200 is_masked_range_test (tree name, tree valt, enum tree_code cond_code,
3201 tree *new_name, tree *low, enum tree_code *low_code,
3202 tree *high, enum tree_code *high_code)
3204 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3206 if (!is_gimple_assign (def_stmt)
3207 || gimple_assign_rhs_code (def_stmt) != BIT_AND_EXPR)
3208 return false;
3210 tree t = gimple_assign_rhs1 (def_stmt);
3211 tree maskt = gimple_assign_rhs2 (def_stmt);
3212 if (TREE_CODE (t) != SSA_NAME || TREE_CODE (maskt) != INTEGER_CST)
3213 return false;
3215 wi::tree_to_wide_ref mask = wi::to_wide (maskt);
3216 wide_int inv_mask = ~mask;
3217 /* Must have been removed by now so don't bother optimizing. */
3218 if (mask == 0 || inv_mask == 0)
3219 return false;
3221 /* Assume VALT is INTEGER_CST. */
3222 wi::tree_to_wide_ref val = wi::to_wide (valt);
3224 if ((inv_mask & (inv_mask + 1)) != 0
3225 || (val & mask) != val)
3226 return false;
3228 bool is_range = cond_code == EQ_EXPR;
3230 tree type = TREE_TYPE (t);
3231 wide_int min = wi::min_value (type),
3232 max = wi::max_value (type);
3234 if (is_range)
3236 *low_code = val == min ? ERROR_MARK : GE_EXPR;
3237 *high_code = val == max ? ERROR_MARK : LE_EXPR;
3239 else
3241 /* We can still generate assertion if one of alternatives
3242 is known to always be false. */
3243 if (val == min)
3245 *low_code = (enum tree_code) 0;
3246 *high_code = GT_EXPR;
3248 else if ((val | inv_mask) == max)
3250 *low_code = LT_EXPR;
3251 *high_code = (enum tree_code) 0;
3253 else
3254 return false;
3257 *new_name = t;
3258 *low = wide_int_to_tree (type, val);
3259 *high = wide_int_to_tree (type, val | inv_mask);
3261 return true;
3264 /* Try to register an edge assertion for SSA name NAME on edge E for
3265 the condition COND contributing to the conditional jump pointed to by
3266 SI. */
3268 void
3269 register_edge_assert_for (tree name, edge e,
3270 enum tree_code cond_code, tree cond_op0,
3271 tree cond_op1, vec<assert_info> &asserts)
3273 tree val;
3274 enum tree_code comp_code;
3275 bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
3277 /* Do not attempt to infer anything in names that flow through
3278 abnormal edges. */
3279 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
3280 return;
3282 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
3283 cond_op0, cond_op1,
3284 is_else_edge,
3285 &comp_code, &val))
3286 return;
3288 /* Register ASSERT_EXPRs for name. */
3289 register_edge_assert_for_2 (name, e, cond_code, cond_op0,
3290 cond_op1, is_else_edge, asserts);
3293 /* If COND is effectively an equality test of an SSA_NAME against
3294 the value zero or one, then we may be able to assert values
3295 for SSA_NAMEs which flow into COND. */
3297 /* In the case of NAME == 1 or NAME != 0, for BIT_AND_EXPR defining
3298 statement of NAME we can assert both operands of the BIT_AND_EXPR
3299 have nonzero value. */
3300 if (((comp_code == EQ_EXPR && integer_onep (val))
3301 || (comp_code == NE_EXPR && integer_zerop (val))))
3303 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3305 if (is_gimple_assign (def_stmt)
3306 && gimple_assign_rhs_code (def_stmt) == BIT_AND_EXPR)
3308 tree op0 = gimple_assign_rhs1 (def_stmt);
3309 tree op1 = gimple_assign_rhs2 (def_stmt);
3310 register_edge_assert_for_1 (op0, NE_EXPR, e, asserts);
3311 register_edge_assert_for_1 (op1, NE_EXPR, e, asserts);
3315 /* In the case of NAME == 0 or NAME != 1, for BIT_IOR_EXPR defining
3316 statement of NAME we can assert both operands of the BIT_IOR_EXPR
3317 have zero value. */
3318 if (((comp_code == EQ_EXPR && integer_zerop (val))
3319 || (comp_code == NE_EXPR && integer_onep (val))))
3321 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3323 /* For BIT_IOR_EXPR only if NAME == 0 both operands have
3324 necessarily zero value, or if type-precision is one. */
3325 if (is_gimple_assign (def_stmt)
3326 && (gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR
3327 && (TYPE_PRECISION (TREE_TYPE (name)) == 1
3328 || comp_code == EQ_EXPR)))
3330 tree op0 = gimple_assign_rhs1 (def_stmt);
3331 tree op1 = gimple_assign_rhs2 (def_stmt);
3332 register_edge_assert_for_1 (op0, EQ_EXPR, e, asserts);
3333 register_edge_assert_for_1 (op1, EQ_EXPR, e, asserts);
3337 /* Sometimes we can infer ranges from (NAME & MASK) == VALUE. */
3338 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
3339 && TREE_CODE (val) == INTEGER_CST)
3341 enum tree_code low_code, high_code;
3342 tree low, high;
3343 if (is_masked_range_test (name, val, comp_code, &name, &low,
3344 &low_code, &high, &high_code))
3346 if (low_code != ERROR_MARK)
3347 register_edge_assert_for_2 (name, e, low_code, name,
3348 low, /*invert*/false, asserts);
3349 if (high_code != ERROR_MARK)
3350 register_edge_assert_for_2 (name, e, high_code, name,
3351 high, /*invert*/false, asserts);
3356 /* Finish found ASSERTS for E and register them at GSI. */
3358 static void
3359 finish_register_edge_assert_for (edge e, gimple_stmt_iterator gsi,
3360 vec<assert_info> &asserts)
3362 for (unsigned i = 0; i < asserts.length (); ++i)
3363 /* Only register an ASSERT_EXPR if NAME was found in the sub-graph
3364 reachable from E. */
3365 if (live_on_edge (e, asserts[i].name))
3366 register_new_assert_for (asserts[i].name, asserts[i].expr,
3367 asserts[i].comp_code, asserts[i].val,
3368 NULL, e, gsi);
3373 /* Determine whether the outgoing edges of BB should receive an
3374 ASSERT_EXPR for each of the operands of BB's LAST statement.
3375 The last statement of BB must be a COND_EXPR.
3377 If any of the sub-graphs rooted at BB have an interesting use of
3378 the predicate operands, an assert location node is added to the
3379 list of assertions for the corresponding operands. */
3381 static void
3382 find_conditional_asserts (basic_block bb, gcond *last)
3384 gimple_stmt_iterator bsi;
3385 tree op;
3386 edge_iterator ei;
3387 edge e;
3388 ssa_op_iter iter;
3390 bsi = gsi_for_stmt (last);
3392 /* Look for uses of the operands in each of the sub-graphs
3393 rooted at BB. We need to check each of the outgoing edges
3394 separately, so that we know what kind of ASSERT_EXPR to
3395 insert. */
3396 FOR_EACH_EDGE (e, ei, bb->succs)
3398 if (e->dest == bb)
3399 continue;
3401 /* Register the necessary assertions for each operand in the
3402 conditional predicate. */
3403 auto_vec<assert_info, 8> asserts;
3404 FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
3405 register_edge_assert_for (op, e,
3406 gimple_cond_code (last),
3407 gimple_cond_lhs (last),
3408 gimple_cond_rhs (last), asserts);
3409 finish_register_edge_assert_for (e, bsi, asserts);
3413 struct case_info
3415 tree expr;
3416 basic_block bb;
3419 /* Compare two case labels sorting first by the destination bb index
3420 and then by the case value. */
3422 static int
3423 compare_case_labels (const void *p1, const void *p2)
3425 const struct case_info *ci1 = (const struct case_info *) p1;
3426 const struct case_info *ci2 = (const struct case_info *) p2;
3427 int idx1 = ci1->bb->index;
3428 int idx2 = ci2->bb->index;
3430 if (idx1 < idx2)
3431 return -1;
3432 else if (idx1 == idx2)
3434 /* Make sure the default label is first in a group. */
3435 if (!CASE_LOW (ci1->expr))
3436 return -1;
3437 else if (!CASE_LOW (ci2->expr))
3438 return 1;
3439 else
3440 return tree_int_cst_compare (CASE_LOW (ci1->expr),
3441 CASE_LOW (ci2->expr));
3443 else
3444 return 1;
3447 /* Determine whether the outgoing edges of BB should receive an
3448 ASSERT_EXPR for each of the operands of BB's LAST statement.
3449 The last statement of BB must be a SWITCH_EXPR.
3451 If any of the sub-graphs rooted at BB have an interesting use of
3452 the predicate operands, an assert location node is added to the
3453 list of assertions for the corresponding operands. */
3455 static void
3456 find_switch_asserts (basic_block bb, gswitch *last)
3458 gimple_stmt_iterator bsi;
3459 tree op;
3460 edge e;
3461 struct case_info *ci;
3462 size_t n = gimple_switch_num_labels (last);
3463 #if GCC_VERSION >= 4000
3464 unsigned int idx;
3465 #else
3466 /* Work around GCC 3.4 bug (PR 37086). */
3467 volatile unsigned int idx;
3468 #endif
3470 bsi = gsi_for_stmt (last);
3471 op = gimple_switch_index (last);
3472 if (TREE_CODE (op) != SSA_NAME)
3473 return;
3475 /* Build a vector of case labels sorted by destination label. */
3476 ci = XNEWVEC (struct case_info, n);
3477 for (idx = 0; idx < n; ++idx)
3479 ci[idx].expr = gimple_switch_label (last, idx);
3480 ci[idx].bb = label_to_block (CASE_LABEL (ci[idx].expr));
3482 edge default_edge = find_edge (bb, ci[0].bb);
3483 qsort (ci, n, sizeof (struct case_info), compare_case_labels);
3485 for (idx = 0; idx < n; ++idx)
3487 tree min, max;
3488 tree cl = ci[idx].expr;
3489 basic_block cbb = ci[idx].bb;
3491 min = CASE_LOW (cl);
3492 max = CASE_HIGH (cl);
3494 /* If there are multiple case labels with the same destination
3495 we need to combine them to a single value range for the edge. */
3496 if (idx + 1 < n && cbb == ci[idx + 1].bb)
3498 /* Skip labels until the last of the group. */
3499 do {
3500 ++idx;
3501 } while (idx < n && cbb == ci[idx].bb);
3502 --idx;
3504 /* Pick up the maximum of the case label range. */
3505 if (CASE_HIGH (ci[idx].expr))
3506 max = CASE_HIGH (ci[idx].expr);
3507 else
3508 max = CASE_LOW (ci[idx].expr);
3511 /* Can't extract a useful assertion out of a range that includes the
3512 default label. */
3513 if (min == NULL_TREE)
3514 continue;
3516 /* Find the edge to register the assert expr on. */
3517 e = find_edge (bb, cbb);
3519 /* Register the necessary assertions for the operand in the
3520 SWITCH_EXPR. */
3521 auto_vec<assert_info, 8> asserts;
3522 register_edge_assert_for (op, e,
3523 max ? GE_EXPR : EQ_EXPR,
3524 op, fold_convert (TREE_TYPE (op), min),
3525 asserts);
3526 if (max)
3527 register_edge_assert_for (op, e, LE_EXPR, op,
3528 fold_convert (TREE_TYPE (op), max),
3529 asserts);
3530 finish_register_edge_assert_for (e, bsi, asserts);
3533 XDELETEVEC (ci);
3535 if (!live_on_edge (default_edge, op))
3536 return;
3538 /* Now register along the default label assertions that correspond to the
3539 anti-range of each label. */
3540 int insertion_limit = PARAM_VALUE (PARAM_MAX_VRP_SWITCH_ASSERTIONS);
3541 if (insertion_limit == 0)
3542 return;
3544 /* We can't do this if the default case shares a label with another case. */
3545 tree default_cl = gimple_switch_default_label (last);
3546 for (idx = 1; idx < n; idx++)
3548 tree min, max;
3549 tree cl = gimple_switch_label (last, idx);
3550 if (CASE_LABEL (cl) == CASE_LABEL (default_cl))
3551 continue;
3553 min = CASE_LOW (cl);
3554 max = CASE_HIGH (cl);
3556 /* Combine contiguous case ranges to reduce the number of assertions
3557 to insert. */
3558 for (idx = idx + 1; idx < n; idx++)
3560 tree next_min, next_max;
3561 tree next_cl = gimple_switch_label (last, idx);
3562 if (CASE_LABEL (next_cl) == CASE_LABEL (default_cl))
3563 break;
3565 next_min = CASE_LOW (next_cl);
3566 next_max = CASE_HIGH (next_cl);
3568 wide_int difference = (wi::to_wide (next_min)
3569 - wi::to_wide (max ? max : min));
3570 if (wi::eq_p (difference, 1))
3571 max = next_max ? next_max : next_min;
3572 else
3573 break;
3575 idx--;
3577 if (max == NULL_TREE)
3579 /* Register the assertion OP != MIN. */
3580 auto_vec<assert_info, 8> asserts;
3581 min = fold_convert (TREE_TYPE (op), min);
3582 register_edge_assert_for (op, default_edge, NE_EXPR, op, min,
3583 asserts);
3584 finish_register_edge_assert_for (default_edge, bsi, asserts);
3586 else
3588 /* Register the assertion (unsigned)OP - MIN > (MAX - MIN),
3589 which will give OP the anti-range ~[MIN,MAX]. */
3590 tree uop = fold_convert (unsigned_type_for (TREE_TYPE (op)), op);
3591 min = fold_convert (TREE_TYPE (uop), min);
3592 max = fold_convert (TREE_TYPE (uop), max);
3594 tree lhs = fold_build2 (MINUS_EXPR, TREE_TYPE (uop), uop, min);
3595 tree rhs = int_const_binop (MINUS_EXPR, max, min);
3596 register_new_assert_for (op, lhs, GT_EXPR, rhs,
3597 NULL, default_edge, bsi);
3600 if (--insertion_limit == 0)
3601 break;
3606 /* Traverse all the statements in block BB looking for statements that
3607 may generate useful assertions for the SSA names in their operand.
3608 If a statement produces a useful assertion A for name N_i, then the
3609 list of assertions already generated for N_i is scanned to
3610 determine if A is actually needed.
3612 If N_i already had the assertion A at a location dominating the
3613 current location, then nothing needs to be done. Otherwise, the
3614 new location for A is recorded instead.
3616 1- For every statement S in BB, all the variables used by S are
3617 added to bitmap FOUND_IN_SUBGRAPH.
3619 2- If statement S uses an operand N in a way that exposes a known
3620 value range for N, then if N was not already generated by an
3621 ASSERT_EXPR, create a new assert location for N. For instance,
3622 if N is a pointer and the statement dereferences it, we can
3623 assume that N is not NULL.
3625 3- COND_EXPRs are a special case of #2. We can derive range
3626 information from the predicate but need to insert different
3627 ASSERT_EXPRs for each of the sub-graphs rooted at the
3628 conditional block. If the last statement of BB is a conditional
3629 expression of the form 'X op Y', then
3631 a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
3633 b) If the conditional is the only entry point to the sub-graph
3634 corresponding to the THEN_CLAUSE, recurse into it. On
3635 return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
3636 an ASSERT_EXPR is added for the corresponding variable.
3638 c) Repeat step (b) on the ELSE_CLAUSE.
3640 d) Mark X and Y in FOUND_IN_SUBGRAPH.
3642 For instance,
3644 if (a == 9)
3645 b = a;
3646 else
3647 b = c + 1;
3649 In this case, an assertion on the THEN clause is useful to
3650 determine that 'a' is always 9 on that edge. However, an assertion
3651 on the ELSE clause would be unnecessary.
3653 4- If BB does not end in a conditional expression, then we recurse
3654 into BB's dominator children.
3656 At the end of the recursive traversal, every SSA name will have a
3657 list of locations where ASSERT_EXPRs should be added. When a new
3658 location for name N is found, it is registered by calling
3659 register_new_assert_for. That function keeps track of all the
3660 registered assertions to prevent adding unnecessary assertions.
3661 For instance, if a pointer P_4 is dereferenced more than once in a
3662 dominator tree, only the location dominating all the dereference of
3663 P_4 will receive an ASSERT_EXPR. */
3665 static void
3666 find_assert_locations_1 (basic_block bb, sbitmap live)
3668 gimple *last;
3670 last = last_stmt (bb);
3672 /* If BB's last statement is a conditional statement involving integer
3673 operands, determine if we need to add ASSERT_EXPRs. */
3674 if (last
3675 && gimple_code (last) == GIMPLE_COND
3676 && !fp_predicate (last)
3677 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
3678 find_conditional_asserts (bb, as_a <gcond *> (last));
3680 /* If BB's last statement is a switch statement involving integer
3681 operands, determine if we need to add ASSERT_EXPRs. */
3682 if (last
3683 && gimple_code (last) == GIMPLE_SWITCH
3684 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
3685 find_switch_asserts (bb, as_a <gswitch *> (last));
3687 /* Traverse all the statements in BB marking used names and looking
3688 for statements that may infer assertions for their used operands. */
3689 for (gimple_stmt_iterator si = gsi_last_bb (bb); !gsi_end_p (si);
3690 gsi_prev (&si))
3692 gimple *stmt;
3693 tree op;
3694 ssa_op_iter i;
3696 stmt = gsi_stmt (si);
3698 if (is_gimple_debug (stmt))
3699 continue;
3701 /* See if we can derive an assertion for any of STMT's operands. */
3702 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
3704 tree value;
3705 enum tree_code comp_code;
3707 /* If op is not live beyond this stmt, do not bother to insert
3708 asserts for it. */
3709 if (!bitmap_bit_p (live, SSA_NAME_VERSION (op)))
3710 continue;
3712 /* If OP is used in such a way that we can infer a value
3713 range for it, and we don't find a previous assertion for
3714 it, create a new assertion location node for OP. */
3715 if (infer_value_range (stmt, op, &comp_code, &value))
3717 /* If we are able to infer a nonzero value range for OP,
3718 then walk backwards through the use-def chain to see if OP
3719 was set via a typecast.
3721 If so, then we can also infer a nonzero value range
3722 for the operand of the NOP_EXPR. */
3723 if (comp_code == NE_EXPR && integer_zerop (value))
3725 tree t = op;
3726 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
3728 while (is_gimple_assign (def_stmt)
3729 && CONVERT_EXPR_CODE_P
3730 (gimple_assign_rhs_code (def_stmt))
3731 && TREE_CODE
3732 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
3733 && POINTER_TYPE_P
3734 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
3736 t = gimple_assign_rhs1 (def_stmt);
3737 def_stmt = SSA_NAME_DEF_STMT (t);
3739 /* Note we want to register the assert for the
3740 operand of the NOP_EXPR after SI, not after the
3741 conversion. */
3742 if (bitmap_bit_p (live, SSA_NAME_VERSION (t)))
3743 register_new_assert_for (t, t, comp_code, value,
3744 bb, NULL, si);
3748 register_new_assert_for (op, op, comp_code, value, bb, NULL, si);
3752 /* Update live. */
3753 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
3754 bitmap_set_bit (live, SSA_NAME_VERSION (op));
3755 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_DEF)
3756 bitmap_clear_bit (live, SSA_NAME_VERSION (op));
3759 /* Traverse all PHI nodes in BB, updating live. */
3760 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
3761 gsi_next (&si))
3763 use_operand_p arg_p;
3764 ssa_op_iter i;
3765 gphi *phi = si.phi ();
3766 tree res = gimple_phi_result (phi);
3768 if (virtual_operand_p (res))
3769 continue;
3771 FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
3773 tree arg = USE_FROM_PTR (arg_p);
3774 if (TREE_CODE (arg) == SSA_NAME)
3775 bitmap_set_bit (live, SSA_NAME_VERSION (arg));
3778 bitmap_clear_bit (live, SSA_NAME_VERSION (res));
3782 /* Do an RPO walk over the function computing SSA name liveness
3783 on-the-fly and deciding on assert expressions to insert. */
3785 static void
3786 find_assert_locations (void)
3788 int *rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
3789 int *bb_rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
3790 int *last_rpo = XCNEWVEC (int, last_basic_block_for_fn (cfun));
3791 int rpo_cnt, i;
3793 live = XCNEWVEC (sbitmap, last_basic_block_for_fn (cfun));
3794 rpo_cnt = pre_and_rev_post_order_compute (NULL, rpo, false);
3795 for (i = 0; i < rpo_cnt; ++i)
3796 bb_rpo[rpo[i]] = i;
3798 /* Pre-seed loop latch liveness from loop header PHI nodes. Due to
3799 the order we compute liveness and insert asserts we otherwise
3800 fail to insert asserts into the loop latch. */
3801 loop_p loop;
3802 FOR_EACH_LOOP (loop, 0)
3804 i = loop->latch->index;
3805 unsigned int j = single_succ_edge (loop->latch)->dest_idx;
3806 for (gphi_iterator gsi = gsi_start_phis (loop->header);
3807 !gsi_end_p (gsi); gsi_next (&gsi))
3809 gphi *phi = gsi.phi ();
3810 if (virtual_operand_p (gimple_phi_result (phi)))
3811 continue;
3812 tree arg = gimple_phi_arg_def (phi, j);
3813 if (TREE_CODE (arg) == SSA_NAME)
3815 if (live[i] == NULL)
3817 live[i] = sbitmap_alloc (num_ssa_names);
3818 bitmap_clear (live[i]);
3820 bitmap_set_bit (live[i], SSA_NAME_VERSION (arg));
3825 for (i = rpo_cnt - 1; i >= 0; --i)
3827 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, rpo[i]);
3828 edge e;
3829 edge_iterator ei;
3831 if (!live[rpo[i]])
3833 live[rpo[i]] = sbitmap_alloc (num_ssa_names);
3834 bitmap_clear (live[rpo[i]]);
3837 /* Process BB and update the live information with uses in
3838 this block. */
3839 find_assert_locations_1 (bb, live[rpo[i]]);
3841 /* Merge liveness into the predecessor blocks and free it. */
3842 if (!bitmap_empty_p (live[rpo[i]]))
3844 int pred_rpo = i;
3845 FOR_EACH_EDGE (e, ei, bb->preds)
3847 int pred = e->src->index;
3848 if ((e->flags & EDGE_DFS_BACK) || pred == ENTRY_BLOCK)
3849 continue;
3851 if (!live[pred])
3853 live[pred] = sbitmap_alloc (num_ssa_names);
3854 bitmap_clear (live[pred]);
3856 bitmap_ior (live[pred], live[pred], live[rpo[i]]);
3858 if (bb_rpo[pred] < pred_rpo)
3859 pred_rpo = bb_rpo[pred];
3862 /* Record the RPO number of the last visited block that needs
3863 live information from this block. */
3864 last_rpo[rpo[i]] = pred_rpo;
3866 else
3868 sbitmap_free (live[rpo[i]]);
3869 live[rpo[i]] = NULL;
3872 /* We can free all successors live bitmaps if all their
3873 predecessors have been visited already. */
3874 FOR_EACH_EDGE (e, ei, bb->succs)
3875 if (last_rpo[e->dest->index] == i
3876 && live[e->dest->index])
3878 sbitmap_free (live[e->dest->index]);
3879 live[e->dest->index] = NULL;
3883 XDELETEVEC (rpo);
3884 XDELETEVEC (bb_rpo);
3885 XDELETEVEC (last_rpo);
3886 for (i = 0; i < last_basic_block_for_fn (cfun); ++i)
3887 if (live[i])
3888 sbitmap_free (live[i]);
3889 XDELETEVEC (live);
3892 /* Create an ASSERT_EXPR for NAME and insert it in the location
3893 indicated by LOC. Return true if we made any edge insertions. */
3895 static bool
3896 process_assert_insertions_for (tree name, assert_locus *loc)
3898 /* Build the comparison expression NAME_i COMP_CODE VAL. */
3899 gimple *stmt;
3900 tree cond;
3901 gimple *assert_stmt;
3902 edge_iterator ei;
3903 edge e;
3905 /* If we have X <=> X do not insert an assert expr for that. */
3906 if (loc->expr == loc->val)
3907 return false;
3909 cond = build2 (loc->comp_code, boolean_type_node, loc->expr, loc->val);
3910 assert_stmt = build_assert_expr_for (cond, name);
3911 if (loc->e)
3913 /* We have been asked to insert the assertion on an edge. This
3914 is used only by COND_EXPR and SWITCH_EXPR assertions. */
3915 gcc_checking_assert (gimple_code (gsi_stmt (loc->si)) == GIMPLE_COND
3916 || (gimple_code (gsi_stmt (loc->si))
3917 == GIMPLE_SWITCH));
3919 gsi_insert_on_edge (loc->e, assert_stmt);
3920 return true;
3923 /* If the stmt iterator points at the end then this is an insertion
3924 at the beginning of a block. */
3925 if (gsi_end_p (loc->si))
3927 gimple_stmt_iterator si = gsi_after_labels (loc->bb);
3928 gsi_insert_before (&si, assert_stmt, GSI_SAME_STMT);
3929 return false;
3932 /* Otherwise, we can insert right after LOC->SI iff the
3933 statement must not be the last statement in the block. */
3934 stmt = gsi_stmt (loc->si);
3935 if (!stmt_ends_bb_p (stmt))
3937 gsi_insert_after (&loc->si, assert_stmt, GSI_SAME_STMT);
3938 return false;
3941 /* If STMT must be the last statement in BB, we can only insert new
3942 assertions on the non-abnormal edge out of BB. Note that since
3943 STMT is not control flow, there may only be one non-abnormal/eh edge
3944 out of BB. */
3945 FOR_EACH_EDGE (e, ei, loc->bb->succs)
3946 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
3948 gsi_insert_on_edge (e, assert_stmt);
3949 return true;
3952 gcc_unreachable ();
3955 /* Qsort helper for sorting assert locations. If stable is true, don't
3956 use iterative_hash_expr because it can be unstable for -fcompare-debug,
3957 on the other side some pointers might be NULL. */
3959 template <bool stable>
3960 static int
3961 compare_assert_loc (const void *pa, const void *pb)
3963 assert_locus * const a = *(assert_locus * const *)pa;
3964 assert_locus * const b = *(assert_locus * const *)pb;
3966 /* If stable, some asserts might be optimized away already, sort
3967 them last. */
3968 if (stable)
3970 if (a == NULL)
3971 return b != NULL;
3972 else if (b == NULL)
3973 return -1;
3976 if (a->e == NULL && b->e != NULL)
3977 return 1;
3978 else if (a->e != NULL && b->e == NULL)
3979 return -1;
3981 /* After the above checks, we know that (a->e == NULL) == (b->e == NULL),
3982 no need to test both a->e and b->e. */
3984 /* Sort after destination index. */
3985 if (a->e == NULL)
3987 else if (a->e->dest->index > b->e->dest->index)
3988 return 1;
3989 else if (a->e->dest->index < b->e->dest->index)
3990 return -1;
3992 /* Sort after comp_code. */
3993 if (a->comp_code > b->comp_code)
3994 return 1;
3995 else if (a->comp_code < b->comp_code)
3996 return -1;
3998 hashval_t ha, hb;
4000 /* E.g. if a->val is ADDR_EXPR of a VAR_DECL, iterative_hash_expr
4001 uses DECL_UID of the VAR_DECL, so sorting might differ between
4002 -g and -g0. When doing the removal of redundant assert exprs
4003 and commonization to successors, this does not matter, but for
4004 the final sort needs to be stable. */
4005 if (stable)
4007 ha = 0;
4008 hb = 0;
4010 else
4012 ha = iterative_hash_expr (a->expr, iterative_hash_expr (a->val, 0));
4013 hb = iterative_hash_expr (b->expr, iterative_hash_expr (b->val, 0));
4016 /* Break the tie using hashing and source/bb index. */
4017 if (ha == hb)
4018 return (a->e != NULL
4019 ? a->e->src->index - b->e->src->index
4020 : a->bb->index - b->bb->index);
4021 return ha > hb ? 1 : -1;
4024 /* Process all the insertions registered for every name N_i registered
4025 in NEED_ASSERT_FOR. The list of assertions to be inserted are
4026 found in ASSERTS_FOR[i]. */
4028 static void
4029 process_assert_insertions (void)
4031 unsigned i;
4032 bitmap_iterator bi;
4033 bool update_edges_p = false;
4034 int num_asserts = 0;
4036 if (dump_file && (dump_flags & TDF_DETAILS))
4037 dump_all_asserts (dump_file);
4039 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
4041 assert_locus *loc = asserts_for[i];
4042 gcc_assert (loc);
4044 auto_vec<assert_locus *, 16> asserts;
4045 for (; loc; loc = loc->next)
4046 asserts.safe_push (loc);
4047 asserts.qsort (compare_assert_loc<false>);
4049 /* Push down common asserts to successors and remove redundant ones. */
4050 unsigned ecnt = 0;
4051 assert_locus *common = NULL;
4052 unsigned commonj = 0;
4053 for (unsigned j = 0; j < asserts.length (); ++j)
4055 loc = asserts[j];
4056 if (! loc->e)
4057 common = NULL;
4058 else if (! common
4059 || loc->e->dest != common->e->dest
4060 || loc->comp_code != common->comp_code
4061 || ! operand_equal_p (loc->val, common->val, 0)
4062 || ! operand_equal_p (loc->expr, common->expr, 0))
4064 commonj = j;
4065 common = loc;
4066 ecnt = 1;
4068 else if (loc->e == asserts[j-1]->e)
4070 /* Remove duplicate asserts. */
4071 if (commonj == j - 1)
4073 commonj = j;
4074 common = loc;
4076 free (asserts[j-1]);
4077 asserts[j-1] = NULL;
4079 else
4081 ecnt++;
4082 if (EDGE_COUNT (common->e->dest->preds) == ecnt)
4084 /* We have the same assertion on all incoming edges of a BB.
4085 Insert it at the beginning of that block. */
4086 loc->bb = loc->e->dest;
4087 loc->e = NULL;
4088 loc->si = gsi_none ();
4089 common = NULL;
4090 /* Clear asserts commoned. */
4091 for (; commonj != j; ++commonj)
4092 if (asserts[commonj])
4094 free (asserts[commonj]);
4095 asserts[commonj] = NULL;
4101 /* The asserts vector sorting above might be unstable for
4102 -fcompare-debug, sort again to ensure a stable sort. */
4103 asserts.qsort (compare_assert_loc<true>);
4104 for (unsigned j = 0; j < asserts.length (); ++j)
4106 loc = asserts[j];
4107 if (! loc)
4108 break;
4109 update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
4110 num_asserts++;
4111 free (loc);
4115 if (update_edges_p)
4116 gsi_commit_edge_inserts ();
4118 statistics_counter_event (cfun, "Number of ASSERT_EXPR expressions inserted",
4119 num_asserts);
4123 /* Traverse the flowgraph looking for conditional jumps to insert range
4124 expressions. These range expressions are meant to provide information
4125 to optimizations that need to reason in terms of value ranges. They
4126 will not be expanded into RTL. For instance, given:
4128 x = ...
4129 y = ...
4130 if (x < y)
4131 y = x - 2;
4132 else
4133 x = y + 3;
4135 this pass will transform the code into:
4137 x = ...
4138 y = ...
4139 if (x < y)
4141 x = ASSERT_EXPR <x, x < y>
4142 y = x - 2
4144 else
4146 y = ASSERT_EXPR <y, x >= y>
4147 x = y + 3
4150 The idea is that once copy and constant propagation have run, other
4151 optimizations will be able to determine what ranges of values can 'x'
4152 take in different paths of the code, simply by checking the reaching
4153 definition of 'x'. */
4155 static void
4156 insert_range_assertions (void)
4158 need_assert_for = BITMAP_ALLOC (NULL);
4159 asserts_for = XCNEWVEC (assert_locus *, num_ssa_names);
4161 calculate_dominance_info (CDI_DOMINATORS);
4163 find_assert_locations ();
4164 if (!bitmap_empty_p (need_assert_for))
4166 process_assert_insertions ();
4167 update_ssa (TODO_update_ssa_no_phi);
4170 if (dump_file && (dump_flags & TDF_DETAILS))
4172 fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
4173 dump_function_to_file (current_function_decl, dump_file, dump_flags);
4176 free (asserts_for);
4177 BITMAP_FREE (need_assert_for);
4180 class vrp_prop : public ssa_propagation_engine
4182 public:
4183 enum ssa_prop_result visit_stmt (gimple *, edge *, tree *) FINAL OVERRIDE;
4184 enum ssa_prop_result visit_phi (gphi *) FINAL OVERRIDE;
4186 void vrp_initialize (void);
4187 void vrp_finalize (bool);
4188 void check_all_array_refs (void);
4189 void check_array_ref (location_t, tree, bool);
4190 void check_mem_ref (location_t, tree, bool);
4191 void search_for_addr_array (tree, location_t);
4193 class vr_values vr_values;
4194 /* Temporary delegator to minimize code churn. */
4195 value_range *get_value_range (const_tree op)
4196 { return vr_values.get_value_range (op); }
4197 void set_defs_to_varying (gimple *stmt)
4198 { return vr_values.set_defs_to_varying (stmt); }
4199 void extract_range_from_stmt (gimple *stmt, edge *taken_edge_p,
4200 tree *output_p, value_range *vr)
4201 { vr_values.extract_range_from_stmt (stmt, taken_edge_p, output_p, vr); }
4202 bool update_value_range (const_tree op, value_range *vr)
4203 { return vr_values.update_value_range (op, vr); }
4204 void extract_range_basic (value_range *vr, gimple *stmt)
4205 { vr_values.extract_range_basic (vr, stmt); }
4206 void extract_range_from_phi_node (gphi *phi, value_range *vr)
4207 { vr_values.extract_range_from_phi_node (phi, vr); }
4209 /* Checks one ARRAY_REF in REF, located at LOCUS. Ignores flexible arrays
4210 and "struct" hacks. If VRP can determine that the
4211 array subscript is a constant, check if it is outside valid
4212 range. If the array subscript is a RANGE, warn if it is
4213 non-overlapping with valid range.
4214 IGNORE_OFF_BY_ONE is true if the ARRAY_REF is inside a ADDR_EXPR. */
4216 void
4217 vrp_prop::check_array_ref (location_t location, tree ref,
4218 bool ignore_off_by_one)
4220 value_range *vr = NULL;
4221 tree low_sub, up_sub;
4222 tree low_bound, up_bound, up_bound_p1;
4224 if (TREE_NO_WARNING (ref))
4225 return;
4227 low_sub = up_sub = TREE_OPERAND (ref, 1);
4228 up_bound = array_ref_up_bound (ref);
4230 if (!up_bound
4231 || TREE_CODE (up_bound) != INTEGER_CST
4232 || (warn_array_bounds < 2
4233 && array_at_struct_end_p (ref)))
4235 /* Accesses to trailing arrays via pointers may access storage
4236 beyond the types array bounds. For such arrays, or for flexible
4237 array members, as well as for other arrays of an unknown size,
4238 replace the upper bound with a more permissive one that assumes
4239 the size of the largest object is PTRDIFF_MAX. */
4240 tree eltsize = array_ref_element_size (ref);
4242 if (TREE_CODE (eltsize) != INTEGER_CST
4243 || integer_zerop (eltsize))
4245 up_bound = NULL_TREE;
4246 up_bound_p1 = NULL_TREE;
4248 else
4250 tree maxbound = TYPE_MAX_VALUE (ptrdiff_type_node);
4251 tree arg = TREE_OPERAND (ref, 0);
4252 poly_int64 off;
4254 if (get_addr_base_and_unit_offset (arg, &off) && known_gt (off, 0))
4255 maxbound = wide_int_to_tree (sizetype,
4256 wi::sub (wi::to_wide (maxbound),
4257 off));
4258 else
4259 maxbound = fold_convert (sizetype, maxbound);
4261 up_bound_p1 = int_const_binop (TRUNC_DIV_EXPR, maxbound, eltsize);
4263 up_bound = int_const_binop (MINUS_EXPR, up_bound_p1,
4264 build_int_cst (ptrdiff_type_node, 1));
4267 else
4268 up_bound_p1 = int_const_binop (PLUS_EXPR, up_bound,
4269 build_int_cst (TREE_TYPE (up_bound), 1));
4271 low_bound = array_ref_low_bound (ref);
4273 tree artype = TREE_TYPE (TREE_OPERAND (ref, 0));
4275 bool warned = false;
4277 /* Empty array. */
4278 if (up_bound && tree_int_cst_equal (low_bound, up_bound_p1))
4279 warned = warning_at (location, OPT_Warray_bounds,
4280 "array subscript %E is above array bounds of %qT",
4281 low_bound, artype);
4283 if (TREE_CODE (low_sub) == SSA_NAME)
4285 vr = get_value_range (low_sub);
4286 if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
4288 low_sub = vr->type == VR_RANGE ? vr->max : vr->min;
4289 up_sub = vr->type == VR_RANGE ? vr->min : vr->max;
4293 if (vr && vr->type == VR_ANTI_RANGE)
4295 if (up_bound
4296 && TREE_CODE (up_sub) == INTEGER_CST
4297 && (ignore_off_by_one
4298 ? tree_int_cst_lt (up_bound, up_sub)
4299 : tree_int_cst_le (up_bound, up_sub))
4300 && TREE_CODE (low_sub) == INTEGER_CST
4301 && tree_int_cst_le (low_sub, low_bound))
4302 warned = warning_at (location, OPT_Warray_bounds,
4303 "array subscript [%E, %E] is outside "
4304 "array bounds of %qT",
4305 low_sub, up_sub, artype);
4307 else if (up_bound
4308 && TREE_CODE (up_sub) == INTEGER_CST
4309 && (ignore_off_by_one
4310 ? !tree_int_cst_le (up_sub, up_bound_p1)
4311 : !tree_int_cst_le (up_sub, up_bound)))
4313 if (dump_file && (dump_flags & TDF_DETAILS))
4315 fprintf (dump_file, "Array bound warning for ");
4316 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
4317 fprintf (dump_file, "\n");
4319 warned = warning_at (location, OPT_Warray_bounds,
4320 "array subscript %E is above array bounds of %qT",
4321 up_sub, artype);
4323 else if (TREE_CODE (low_sub) == INTEGER_CST
4324 && tree_int_cst_lt (low_sub, low_bound))
4326 if (dump_file && (dump_flags & TDF_DETAILS))
4328 fprintf (dump_file, "Array bound warning for ");
4329 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
4330 fprintf (dump_file, "\n");
4332 warned = warning_at (location, OPT_Warray_bounds,
4333 "array subscript %E is below array bounds of %qT",
4334 low_sub, artype);
4337 if (warned)
4339 ref = TREE_OPERAND (ref, 0);
4341 if (DECL_P (ref))
4342 inform (DECL_SOURCE_LOCATION (ref), "while referencing %qD", ref);
4344 TREE_NO_WARNING (ref) = 1;
4348 /* Checks one MEM_REF in REF, located at LOCATION, for out-of-bounds
4349 references to string constants. If VRP can determine that the array
4350 subscript is a constant, check if it is outside valid range.
4351 If the array subscript is a RANGE, warn if it is non-overlapping
4352 with valid range.
4353 IGNORE_OFF_BY_ONE is true if the MEM_REF is inside an ADDR_EXPR
4354 (used to allow one-past-the-end indices for code that takes
4355 the address of the just-past-the-end element of an array). */
4357 void
4358 vrp_prop::check_mem_ref (location_t location, tree ref,
4359 bool ignore_off_by_one)
4361 if (TREE_NO_WARNING (ref))
4362 return;
4364 tree arg = TREE_OPERAND (ref, 0);
4365 /* The constant and variable offset of the reference. */
4366 tree cstoff = TREE_OPERAND (ref, 1);
4367 tree varoff = NULL_TREE;
4369 const offset_int maxobjsize = tree_to_shwi (max_object_size ());
4371 /* The array or string constant bounds in bytes. Initially set
4372 to [-MAXOBJSIZE - 1, MAXOBJSIZE] until a tighter bound is
4373 determined. */
4374 offset_int arrbounds[2] = { -maxobjsize - 1, maxobjsize };
4376 /* The minimum and maximum intermediate offset. For a reference
4377 to be valid, not only does the final offset/subscript must be
4378 in bounds but all intermediate offsets should be as well.
4379 GCC may be able to deal gracefully with such out-of-bounds
4380 offsets so the checking is only enbaled at -Warray-bounds=2
4381 where it may help detect bugs in uses of the intermediate
4382 offsets that could otherwise not be detectable. */
4383 offset_int ioff = wi::to_offset (fold_convert (ptrdiff_type_node, cstoff));
4384 offset_int extrema[2] = { 0, wi::abs (ioff) };
4386 /* The range of the byte offset into the reference. */
4387 offset_int offrange[2] = { 0, 0 };
4389 value_range *vr = NULL;
4391 /* Determine the offsets and increment OFFRANGE for the bounds of each.
4392 The loop computes the the range of the final offset for expressions
4393 such as (A + i0 + ... + iN)[CSTOFF] where i0 through iN are SSA_NAMEs
4394 in some range. */
4395 while (TREE_CODE (arg) == SSA_NAME)
4397 gimple *def = SSA_NAME_DEF_STMT (arg);
4398 if (!is_gimple_assign (def))
4399 break;
4401 tree_code code = gimple_assign_rhs_code (def);
4402 if (code == POINTER_PLUS_EXPR)
4404 arg = gimple_assign_rhs1 (def);
4405 varoff = gimple_assign_rhs2 (def);
4407 else if (code == ASSERT_EXPR)
4409 arg = TREE_OPERAND (gimple_assign_rhs1 (def), 0);
4410 continue;
4412 else
4413 return;
4415 /* VAROFF should always be a SSA_NAME here (and not even
4416 INTEGER_CST) but there's no point in taking chances. */
4417 if (TREE_CODE (varoff) != SSA_NAME)
4418 break;
4420 vr = get_value_range (varoff);
4421 if (!vr || vr->type == VR_UNDEFINED || !vr->min || !vr->max)
4422 break;
4424 if (TREE_CODE (vr->min) != INTEGER_CST
4425 || TREE_CODE (vr->max) != INTEGER_CST)
4426 break;
4428 if (vr->type == VR_RANGE)
4430 if (tree_int_cst_lt (vr->min, vr->max))
4432 offset_int min
4433 = wi::to_offset (fold_convert (ptrdiff_type_node, vr->min));
4434 offset_int max
4435 = wi::to_offset (fold_convert (ptrdiff_type_node, vr->max));
4436 if (min < max)
4438 offrange[0] += min;
4439 offrange[1] += max;
4441 else
4443 offrange[0] += max;
4444 offrange[1] += min;
4447 else
4449 /* Conservatively add [-MAXOBJSIZE -1, MAXOBJSIZE]
4450 to OFFRANGE. */
4451 offrange[0] += arrbounds[0];
4452 offrange[1] += arrbounds[1];
4455 else
4457 /* For an anti-range, analogously to the above, conservatively
4458 add [-MAXOBJSIZE -1, MAXOBJSIZE] to OFFRANGE. */
4459 offrange[0] += arrbounds[0];
4460 offrange[1] += arrbounds[1];
4463 /* Keep track of the minimum and maximum offset. */
4464 if (offrange[1] < 0 && offrange[1] < extrema[0])
4465 extrema[0] = offrange[1];
4466 if (offrange[0] > 0 && offrange[0] > extrema[1])
4467 extrema[1] = offrange[0];
4469 if (offrange[0] < arrbounds[0])
4470 offrange[0] = arrbounds[0];
4472 if (offrange[1] > arrbounds[1])
4473 offrange[1] = arrbounds[1];
4476 if (TREE_CODE (arg) == ADDR_EXPR)
4478 arg = TREE_OPERAND (arg, 0);
4479 if (TREE_CODE (arg) != STRING_CST
4480 && TREE_CODE (arg) != VAR_DECL)
4481 return;
4483 else
4484 return;
4486 /* The type of the object being referred to. It can be an array,
4487 string literal, or a non-array type when the MEM_REF represents
4488 a reference/subscript via a pointer to an object that is not
4489 an element of an array. References to members of structs and
4490 unions are excluded because MEM_REF doesn't make it possible
4491 to identify the member where the reference originated.
4492 Incomplete types are excluded as well because their size is
4493 not known. */
4494 tree reftype = TREE_TYPE (arg);
4495 if (POINTER_TYPE_P (reftype)
4496 || !COMPLETE_TYPE_P (reftype)
4497 || TREE_CODE (TYPE_SIZE_UNIT (reftype)) != INTEGER_CST
4498 || RECORD_OR_UNION_TYPE_P (reftype))
4499 return;
4501 offset_int eltsize;
4502 if (TREE_CODE (reftype) == ARRAY_TYPE)
4504 eltsize = wi::to_offset (TYPE_SIZE_UNIT (TREE_TYPE (reftype)));
4506 if (tree dom = TYPE_DOMAIN (reftype))
4508 tree bnds[] = { TYPE_MIN_VALUE (dom), TYPE_MAX_VALUE (dom) };
4509 if (array_at_struct_end_p (arg)
4510 || !bnds[0] || !bnds[1])
4512 arrbounds[0] = 0;
4513 arrbounds[1] = wi::lrshift (maxobjsize, wi::floor_log2 (eltsize));
4515 else
4517 arrbounds[0] = wi::to_offset (bnds[0]) * eltsize;
4518 arrbounds[1] = (wi::to_offset (bnds[1]) + 1) * eltsize;
4521 else
4523 arrbounds[0] = 0;
4524 arrbounds[1] = wi::lrshift (maxobjsize, wi::floor_log2 (eltsize));
4527 if (TREE_CODE (ref) == MEM_REF)
4529 /* For MEM_REF determine a tighter bound of the non-array
4530 element type. */
4531 tree eltype = TREE_TYPE (reftype);
4532 while (TREE_CODE (eltype) == ARRAY_TYPE)
4533 eltype = TREE_TYPE (eltype);
4534 eltsize = wi::to_offset (TYPE_SIZE_UNIT (eltype));
4537 else
4539 eltsize = 1;
4540 arrbounds[0] = 0;
4541 arrbounds[1] = wi::to_offset (TYPE_SIZE_UNIT (reftype));
4544 offrange[0] += ioff;
4545 offrange[1] += ioff;
4547 /* Compute the more permissive upper bound when IGNORE_OFF_BY_ONE
4548 is set (when taking the address of the one-past-last element
4549 of an array) but always use the stricter bound in diagnostics. */
4550 offset_int ubound = arrbounds[1];
4551 if (ignore_off_by_one)
4552 ubound += 1;
4554 if (offrange[0] >= ubound || offrange[1] < arrbounds[0])
4556 /* Treat a reference to a non-array object as one to an array
4557 of a single element. */
4558 if (TREE_CODE (reftype) != ARRAY_TYPE)
4559 reftype = build_array_type_nelts (reftype, 1);
4561 if (TREE_CODE (ref) == MEM_REF)
4563 /* Extract the element type out of MEM_REF and use its size
4564 to compute the index to print in the diagnostic; arrays
4565 in MEM_REF don't mean anything. */
4566 tree type = TREE_TYPE (ref);
4567 while (TREE_CODE (type) == ARRAY_TYPE)
4568 type = TREE_TYPE (type);
4569 tree size = TYPE_SIZE_UNIT (type);
4570 offrange[0] = offrange[0] / wi::to_offset (size);
4571 offrange[1] = offrange[1] / wi::to_offset (size);
4573 else
4575 /* For anything other than MEM_REF, compute the index to
4576 print in the diagnostic as the offset over element size. */
4577 offrange[0] = offrange[0] / eltsize;
4578 offrange[1] = offrange[1] / eltsize;
4581 bool warned;
4582 if (offrange[0] == offrange[1])
4583 warned = warning_at (location, OPT_Warray_bounds,
4584 "array subscript %wi is outside array bounds "
4585 "of %qT",
4586 offrange[0].to_shwi (), reftype);
4587 else
4588 warned = warning_at (location, OPT_Warray_bounds,
4589 "array subscript [%wi, %wi] is outside "
4590 "array bounds of %qT",
4591 offrange[0].to_shwi (),
4592 offrange[1].to_shwi (), reftype);
4593 if (warned && DECL_P (arg))
4594 inform (DECL_SOURCE_LOCATION (arg), "while referencing %qD", arg);
4596 TREE_NO_WARNING (ref) = 1;
4597 return;
4600 if (warn_array_bounds < 2)
4601 return;
4603 /* At level 2 check also intermediate offsets. */
4604 int i = 0;
4605 if (extrema[i] < -arrbounds[1] || extrema[i = 1] > ubound)
4607 HOST_WIDE_INT tmpidx = extrema[i].to_shwi () / eltsize.to_shwi ();
4609 warning_at (location, OPT_Warray_bounds,
4610 "intermediate array offset %wi is outside array bounds "
4611 "of %qT",
4612 tmpidx, reftype);
4613 TREE_NO_WARNING (ref) = 1;
4617 /* Searches if the expr T, located at LOCATION computes
4618 address of an ARRAY_REF, and call check_array_ref on it. */
4620 void
4621 vrp_prop::search_for_addr_array (tree t, location_t location)
4623 /* Check each ARRAY_REF and MEM_REF in the reference chain. */
4626 if (TREE_CODE (t) == ARRAY_REF)
4627 check_array_ref (location, t, true /*ignore_off_by_one*/);
4628 else if (TREE_CODE (t) == MEM_REF)
4629 check_mem_ref (location, t, true /*ignore_off_by_one*/);
4631 t = TREE_OPERAND (t, 0);
4633 while (handled_component_p (t) || TREE_CODE (t) == MEM_REF);
4635 if (TREE_CODE (t) != MEM_REF
4636 || TREE_CODE (TREE_OPERAND (t, 0)) != ADDR_EXPR
4637 || TREE_NO_WARNING (t))
4638 return;
4640 tree tem = TREE_OPERAND (TREE_OPERAND (t, 0), 0);
4641 tree low_bound, up_bound, el_sz;
4642 if (TREE_CODE (TREE_TYPE (tem)) != ARRAY_TYPE
4643 || TREE_CODE (TREE_TYPE (TREE_TYPE (tem))) == ARRAY_TYPE
4644 || !TYPE_DOMAIN (TREE_TYPE (tem)))
4645 return;
4647 low_bound = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
4648 up_bound = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
4649 el_sz = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (tem)));
4650 if (!low_bound
4651 || TREE_CODE (low_bound) != INTEGER_CST
4652 || !up_bound
4653 || TREE_CODE (up_bound) != INTEGER_CST
4654 || !el_sz
4655 || TREE_CODE (el_sz) != INTEGER_CST)
4656 return;
4658 offset_int idx;
4659 if (!mem_ref_offset (t).is_constant (&idx))
4660 return;
4662 bool warned = false;
4663 idx = wi::sdiv_trunc (idx, wi::to_offset (el_sz));
4664 if (idx < 0)
4666 if (dump_file && (dump_flags & TDF_DETAILS))
4668 fprintf (dump_file, "Array bound warning for ");
4669 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
4670 fprintf (dump_file, "\n");
4672 warned = warning_at (location, OPT_Warray_bounds,
4673 "array subscript %wi is below "
4674 "array bounds of %qT",
4675 idx.to_shwi (), TREE_TYPE (tem));
4677 else if (idx > (wi::to_offset (up_bound)
4678 - wi::to_offset (low_bound) + 1))
4680 if (dump_file && (dump_flags & TDF_DETAILS))
4682 fprintf (dump_file, "Array bound warning for ");
4683 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
4684 fprintf (dump_file, "\n");
4686 warned = warning_at (location, OPT_Warray_bounds,
4687 "array subscript %wu is above "
4688 "array bounds of %qT",
4689 idx.to_uhwi (), TREE_TYPE (tem));
4692 if (warned)
4694 if (DECL_P (t))
4695 inform (DECL_SOURCE_LOCATION (t), "while referencing %qD", t);
4697 TREE_NO_WARNING (t) = 1;
4701 /* walk_tree() callback that checks if *TP is
4702 an ARRAY_REF inside an ADDR_EXPR (in which an array
4703 subscript one outside the valid range is allowed). Call
4704 check_array_ref for each ARRAY_REF found. The location is
4705 passed in DATA. */
4707 static tree
4708 check_array_bounds (tree *tp, int *walk_subtree, void *data)
4710 tree t = *tp;
4711 struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
4712 location_t location;
4714 if (EXPR_HAS_LOCATION (t))
4715 location = EXPR_LOCATION (t);
4716 else
4717 location = gimple_location (wi->stmt);
4719 *walk_subtree = TRUE;
4721 vrp_prop *vrp_prop = (class vrp_prop *)wi->info;
4722 if (TREE_CODE (t) == ARRAY_REF)
4723 vrp_prop->check_array_ref (location, t, false /*ignore_off_by_one*/);
4724 else if (TREE_CODE (t) == MEM_REF)
4725 vrp_prop->check_mem_ref (location, t, false /*ignore_off_by_one*/);
4726 else if (TREE_CODE (t) == ADDR_EXPR)
4728 vrp_prop->search_for_addr_array (t, location);
4729 *walk_subtree = FALSE;
4732 return NULL_TREE;
4735 /* A dom_walker subclass for use by vrp_prop::check_all_array_refs,
4736 to walk over all statements of all reachable BBs and call
4737 check_array_bounds on them. */
4739 class check_array_bounds_dom_walker : public dom_walker
4741 public:
4742 check_array_bounds_dom_walker (vrp_prop *prop)
4743 : dom_walker (CDI_DOMINATORS,
4744 /* Discover non-executable edges, preserving EDGE_EXECUTABLE
4745 flags, so that we can merge in information on
4746 non-executable edges from vrp_folder . */
4747 REACHABLE_BLOCKS_PRESERVING_FLAGS),
4748 m_prop (prop) {}
4749 ~check_array_bounds_dom_walker () {}
4751 edge before_dom_children (basic_block) FINAL OVERRIDE;
4753 private:
4754 vrp_prop *m_prop;
4757 /* Implementation of dom_walker::before_dom_children.
4759 Walk over all statements of BB and call check_array_bounds on them,
4760 and determine if there's a unique successor edge. */
4762 edge
4763 check_array_bounds_dom_walker::before_dom_children (basic_block bb)
4765 gimple_stmt_iterator si;
4766 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
4768 gimple *stmt = gsi_stmt (si);
4769 struct walk_stmt_info wi;
4770 if (!gimple_has_location (stmt)
4771 || is_gimple_debug (stmt))
4772 continue;
4774 memset (&wi, 0, sizeof (wi));
4776 wi.info = m_prop;
4778 walk_gimple_op (stmt, check_array_bounds, &wi);
4781 /* Determine if there's a unique successor edge, and if so, return
4782 that back to dom_walker, ensuring that we don't visit blocks that
4783 became unreachable during the VRP propagation
4784 (PR tree-optimization/83312). */
4785 return find_taken_edge (bb, NULL_TREE);
4788 /* Walk over all statements of all reachable BBs and call check_array_bounds
4789 on them. */
4791 void
4792 vrp_prop::check_all_array_refs ()
4794 check_array_bounds_dom_walker w (this);
4795 w.walk (ENTRY_BLOCK_PTR_FOR_FN (cfun));
4798 /* Return true if all imm uses of VAR are either in STMT, or
4799 feed (optionally through a chain of single imm uses) GIMPLE_COND
4800 in basic block COND_BB. */
4802 static bool
4803 all_imm_uses_in_stmt_or_feed_cond (tree var, gimple *stmt, basic_block cond_bb)
4805 use_operand_p use_p, use2_p;
4806 imm_use_iterator iter;
4808 FOR_EACH_IMM_USE_FAST (use_p, iter, var)
4809 if (USE_STMT (use_p) != stmt)
4811 gimple *use_stmt = USE_STMT (use_p), *use_stmt2;
4812 if (is_gimple_debug (use_stmt))
4813 continue;
4814 while (is_gimple_assign (use_stmt)
4815 && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
4816 && single_imm_use (gimple_assign_lhs (use_stmt),
4817 &use2_p, &use_stmt2))
4818 use_stmt = use_stmt2;
4819 if (gimple_code (use_stmt) != GIMPLE_COND
4820 || gimple_bb (use_stmt) != cond_bb)
4821 return false;
4823 return true;
4826 /* Handle
4827 _4 = x_3 & 31;
4828 if (_4 != 0)
4829 goto <bb 6>;
4830 else
4831 goto <bb 7>;
4832 <bb 6>:
4833 __builtin_unreachable ();
4834 <bb 7>:
4835 x_5 = ASSERT_EXPR <x_3, ...>;
4836 If x_3 has no other immediate uses (checked by caller),
4837 var is the x_3 var from ASSERT_EXPR, we can clear low 5 bits
4838 from the non-zero bitmask. */
4840 void
4841 maybe_set_nonzero_bits (edge e, tree var)
4843 basic_block cond_bb = e->src;
4844 gimple *stmt = last_stmt (cond_bb);
4845 tree cst;
4847 if (stmt == NULL
4848 || gimple_code (stmt) != GIMPLE_COND
4849 || gimple_cond_code (stmt) != ((e->flags & EDGE_TRUE_VALUE)
4850 ? EQ_EXPR : NE_EXPR)
4851 || TREE_CODE (gimple_cond_lhs (stmt)) != SSA_NAME
4852 || !integer_zerop (gimple_cond_rhs (stmt)))
4853 return;
4855 stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt));
4856 if (!is_gimple_assign (stmt)
4857 || gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
4858 || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
4859 return;
4860 if (gimple_assign_rhs1 (stmt) != var)
4862 gimple *stmt2;
4864 if (TREE_CODE (gimple_assign_rhs1 (stmt)) != SSA_NAME)
4865 return;
4866 stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
4867 if (!gimple_assign_cast_p (stmt2)
4868 || gimple_assign_rhs1 (stmt2) != var
4869 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt2))
4870 || (TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (stmt)))
4871 != TYPE_PRECISION (TREE_TYPE (var))))
4872 return;
4874 cst = gimple_assign_rhs2 (stmt);
4875 set_nonzero_bits (var, wi::bit_and_not (get_nonzero_bits (var),
4876 wi::to_wide (cst)));
4879 /* Convert range assertion expressions into the implied copies and
4880 copy propagate away the copies. Doing the trivial copy propagation
4881 here avoids the need to run the full copy propagation pass after
4882 VRP.
4884 FIXME, this will eventually lead to copy propagation removing the
4885 names that had useful range information attached to them. For
4886 instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
4887 then N_i will have the range [3, +INF].
4889 However, by converting the assertion into the implied copy
4890 operation N_i = N_j, we will then copy-propagate N_j into the uses
4891 of N_i and lose the range information. We may want to hold on to
4892 ASSERT_EXPRs a little while longer as the ranges could be used in
4893 things like jump threading.
4895 The problem with keeping ASSERT_EXPRs around is that passes after
4896 VRP need to handle them appropriately.
4898 Another approach would be to make the range information a first
4899 class property of the SSA_NAME so that it can be queried from
4900 any pass. This is made somewhat more complex by the need for
4901 multiple ranges to be associated with one SSA_NAME. */
4903 static void
4904 remove_range_assertions (void)
4906 basic_block bb;
4907 gimple_stmt_iterator si;
4908 /* 1 if looking at ASSERT_EXPRs immediately at the beginning of
4909 a basic block preceeded by GIMPLE_COND branching to it and
4910 __builtin_trap, -1 if not yet checked, 0 otherwise. */
4911 int is_unreachable;
4913 /* Note that the BSI iterator bump happens at the bottom of the
4914 loop and no bump is necessary if we're removing the statement
4915 referenced by the current BSI. */
4916 FOR_EACH_BB_FN (bb, cfun)
4917 for (si = gsi_after_labels (bb), is_unreachable = -1; !gsi_end_p (si);)
4919 gimple *stmt = gsi_stmt (si);
4921 if (is_gimple_assign (stmt)
4922 && gimple_assign_rhs_code (stmt) == ASSERT_EXPR)
4924 tree lhs = gimple_assign_lhs (stmt);
4925 tree rhs = gimple_assign_rhs1 (stmt);
4926 tree var;
4928 var = ASSERT_EXPR_VAR (rhs);
4930 if (TREE_CODE (var) == SSA_NAME
4931 && !POINTER_TYPE_P (TREE_TYPE (lhs))
4932 && SSA_NAME_RANGE_INFO (lhs))
4934 if (is_unreachable == -1)
4936 is_unreachable = 0;
4937 if (single_pred_p (bb)
4938 && assert_unreachable_fallthru_edge_p
4939 (single_pred_edge (bb)))
4940 is_unreachable = 1;
4942 /* Handle
4943 if (x_7 >= 10 && x_7 < 20)
4944 __builtin_unreachable ();
4945 x_8 = ASSERT_EXPR <x_7, ...>;
4946 if the only uses of x_7 are in the ASSERT_EXPR and
4947 in the condition. In that case, we can copy the
4948 range info from x_8 computed in this pass also
4949 for x_7. */
4950 if (is_unreachable
4951 && all_imm_uses_in_stmt_or_feed_cond (var, stmt,
4952 single_pred (bb)))
4954 set_range_info (var, SSA_NAME_RANGE_TYPE (lhs),
4955 SSA_NAME_RANGE_INFO (lhs)->get_min (),
4956 SSA_NAME_RANGE_INFO (lhs)->get_max ());
4957 maybe_set_nonzero_bits (single_pred_edge (bb), var);
4961 /* Propagate the RHS into every use of the LHS. For SSA names
4962 also propagate abnormals as it merely restores the original
4963 IL in this case (an replace_uses_by would assert). */
4964 if (TREE_CODE (var) == SSA_NAME)
4966 imm_use_iterator iter;
4967 use_operand_p use_p;
4968 gimple *use_stmt;
4969 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
4970 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
4971 SET_USE (use_p, var);
4973 else
4974 replace_uses_by (lhs, var);
4976 /* And finally, remove the copy, it is not needed. */
4977 gsi_remove (&si, true);
4978 release_defs (stmt);
4980 else
4982 if (!is_gimple_debug (gsi_stmt (si)))
4983 is_unreachable = 0;
4984 gsi_next (&si);
4989 /* Return true if STMT is interesting for VRP. */
4991 bool
4992 stmt_interesting_for_vrp (gimple *stmt)
4994 if (gimple_code (stmt) == GIMPLE_PHI)
4996 tree res = gimple_phi_result (stmt);
4997 return (!virtual_operand_p (res)
4998 && (INTEGRAL_TYPE_P (TREE_TYPE (res))
4999 || POINTER_TYPE_P (TREE_TYPE (res))));
5001 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
5003 tree lhs = gimple_get_lhs (stmt);
5005 /* In general, assignments with virtual operands are not useful
5006 for deriving ranges, with the obvious exception of calls to
5007 builtin functions. */
5008 if (lhs && TREE_CODE (lhs) == SSA_NAME
5009 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
5010 || POINTER_TYPE_P (TREE_TYPE (lhs)))
5011 && (is_gimple_call (stmt)
5012 || !gimple_vuse (stmt)))
5013 return true;
5014 else if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
5015 switch (gimple_call_internal_fn (stmt))
5017 case IFN_ADD_OVERFLOW:
5018 case IFN_SUB_OVERFLOW:
5019 case IFN_MUL_OVERFLOW:
5020 case IFN_ATOMIC_COMPARE_EXCHANGE:
5021 /* These internal calls return _Complex integer type,
5022 but are interesting to VRP nevertheless. */
5023 if (lhs && TREE_CODE (lhs) == SSA_NAME)
5024 return true;
5025 break;
5026 default:
5027 break;
5030 else if (gimple_code (stmt) == GIMPLE_COND
5031 || gimple_code (stmt) == GIMPLE_SWITCH)
5032 return true;
5034 return false;
5037 /* Initialization required by ssa_propagate engine. */
5039 void
5040 vrp_prop::vrp_initialize ()
5042 basic_block bb;
5044 FOR_EACH_BB_FN (bb, cfun)
5046 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
5047 gsi_next (&si))
5049 gphi *phi = si.phi ();
5050 if (!stmt_interesting_for_vrp (phi))
5052 tree lhs = PHI_RESULT (phi);
5053 set_value_range_to_varying (get_value_range (lhs));
5054 prop_set_simulate_again (phi, false);
5056 else
5057 prop_set_simulate_again (phi, true);
5060 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
5061 gsi_next (&si))
5063 gimple *stmt = gsi_stmt (si);
5065 /* If the statement is a control insn, then we do not
5066 want to avoid simulating the statement once. Failure
5067 to do so means that those edges will never get added. */
5068 if (stmt_ends_bb_p (stmt))
5069 prop_set_simulate_again (stmt, true);
5070 else if (!stmt_interesting_for_vrp (stmt))
5072 set_defs_to_varying (stmt);
5073 prop_set_simulate_again (stmt, false);
5075 else
5076 prop_set_simulate_again (stmt, true);
5081 /* Searches the case label vector VEC for the index *IDX of the CASE_LABEL
5082 that includes the value VAL. The search is restricted to the range
5083 [START_IDX, n - 1] where n is the size of VEC.
5085 If there is a CASE_LABEL for VAL, its index is placed in IDX and true is
5086 returned.
5088 If there is no CASE_LABEL for VAL and there is one that is larger than VAL,
5089 it is placed in IDX and false is returned.
5091 If VAL is larger than any CASE_LABEL, n is placed on IDX and false is
5092 returned. */
5094 bool
5095 find_case_label_index (gswitch *stmt, size_t start_idx, tree val, size_t *idx)
5097 size_t n = gimple_switch_num_labels (stmt);
5098 size_t low, high;
5100 /* Find case label for minimum of the value range or the next one.
5101 At each iteration we are searching in [low, high - 1]. */
5103 for (low = start_idx, high = n; high != low; )
5105 tree t;
5106 int cmp;
5107 /* Note that i != high, so we never ask for n. */
5108 size_t i = (high + low) / 2;
5109 t = gimple_switch_label (stmt, i);
5111 /* Cache the result of comparing CASE_LOW and val. */
5112 cmp = tree_int_cst_compare (CASE_LOW (t), val);
5114 if (cmp == 0)
5116 /* Ranges cannot be empty. */
5117 *idx = i;
5118 return true;
5120 else if (cmp > 0)
5121 high = i;
5122 else
5124 low = i + 1;
5125 if (CASE_HIGH (t) != NULL
5126 && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
5128 *idx = i;
5129 return true;
5134 *idx = high;
5135 return false;
5138 /* Searches the case label vector VEC for the range of CASE_LABELs that is used
5139 for values between MIN and MAX. The first index is placed in MIN_IDX. The
5140 last index is placed in MAX_IDX. If the range of CASE_LABELs is empty
5141 then MAX_IDX < MIN_IDX.
5142 Returns true if the default label is not needed. */
5144 bool
5145 find_case_label_range (gswitch *stmt, tree min, tree max, size_t *min_idx,
5146 size_t *max_idx)
5148 size_t i, j;
5149 bool min_take_default = !find_case_label_index (stmt, 1, min, &i);
5150 bool max_take_default = !find_case_label_index (stmt, i, max, &j);
5152 if (i == j
5153 && min_take_default
5154 && max_take_default)
5156 /* Only the default case label reached.
5157 Return an empty range. */
5158 *min_idx = 1;
5159 *max_idx = 0;
5160 return false;
5162 else
5164 bool take_default = min_take_default || max_take_default;
5165 tree low, high;
5166 size_t k;
5168 if (max_take_default)
5169 j--;
5171 /* If the case label range is continuous, we do not need
5172 the default case label. Verify that. */
5173 high = CASE_LOW (gimple_switch_label (stmt, i));
5174 if (CASE_HIGH (gimple_switch_label (stmt, i)))
5175 high = CASE_HIGH (gimple_switch_label (stmt, i));
5176 for (k = i + 1; k <= j; ++k)
5178 low = CASE_LOW (gimple_switch_label (stmt, k));
5179 if (!integer_onep (int_const_binop (MINUS_EXPR, low, high)))
5181 take_default = true;
5182 break;
5184 high = low;
5185 if (CASE_HIGH (gimple_switch_label (stmt, k)))
5186 high = CASE_HIGH (gimple_switch_label (stmt, k));
5189 *min_idx = i;
5190 *max_idx = j;
5191 return !take_default;
5195 /* Evaluate statement STMT. If the statement produces a useful range,
5196 return SSA_PROP_INTERESTING and record the SSA name with the
5197 interesting range into *OUTPUT_P.
5199 If STMT is a conditional branch and we can determine its truth
5200 value, the taken edge is recorded in *TAKEN_EDGE_P.
5202 If STMT produces a varying value, return SSA_PROP_VARYING. */
5204 enum ssa_prop_result
5205 vrp_prop::visit_stmt (gimple *stmt, edge *taken_edge_p, tree *output_p)
5207 value_range vr = VR_INITIALIZER;
5208 tree lhs = gimple_get_lhs (stmt);
5209 extract_range_from_stmt (stmt, taken_edge_p, output_p, &vr);
5211 if (*output_p)
5213 if (update_value_range (*output_p, &vr))
5215 if (dump_file && (dump_flags & TDF_DETAILS))
5217 fprintf (dump_file, "Found new range for ");
5218 print_generic_expr (dump_file, *output_p);
5219 fprintf (dump_file, ": ");
5220 dump_value_range (dump_file, &vr);
5221 fprintf (dump_file, "\n");
5224 if (vr.type == VR_VARYING)
5225 return SSA_PROP_VARYING;
5227 return SSA_PROP_INTERESTING;
5229 return SSA_PROP_NOT_INTERESTING;
5232 if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
5233 switch (gimple_call_internal_fn (stmt))
5235 case IFN_ADD_OVERFLOW:
5236 case IFN_SUB_OVERFLOW:
5237 case IFN_MUL_OVERFLOW:
5238 case IFN_ATOMIC_COMPARE_EXCHANGE:
5239 /* These internal calls return _Complex integer type,
5240 which VRP does not track, but the immediate uses
5241 thereof might be interesting. */
5242 if (lhs && TREE_CODE (lhs) == SSA_NAME)
5244 imm_use_iterator iter;
5245 use_operand_p use_p;
5246 enum ssa_prop_result res = SSA_PROP_VARYING;
5248 set_value_range_to_varying (get_value_range (lhs));
5250 FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
5252 gimple *use_stmt = USE_STMT (use_p);
5253 if (!is_gimple_assign (use_stmt))
5254 continue;
5255 enum tree_code rhs_code = gimple_assign_rhs_code (use_stmt);
5256 if (rhs_code != REALPART_EXPR && rhs_code != IMAGPART_EXPR)
5257 continue;
5258 tree rhs1 = gimple_assign_rhs1 (use_stmt);
5259 tree use_lhs = gimple_assign_lhs (use_stmt);
5260 if (TREE_CODE (rhs1) != rhs_code
5261 || TREE_OPERAND (rhs1, 0) != lhs
5262 || TREE_CODE (use_lhs) != SSA_NAME
5263 || !stmt_interesting_for_vrp (use_stmt)
5264 || (!INTEGRAL_TYPE_P (TREE_TYPE (use_lhs))
5265 || !TYPE_MIN_VALUE (TREE_TYPE (use_lhs))
5266 || !TYPE_MAX_VALUE (TREE_TYPE (use_lhs))))
5267 continue;
5269 /* If there is a change in the value range for any of the
5270 REALPART_EXPR/IMAGPART_EXPR immediate uses, return
5271 SSA_PROP_INTERESTING. If there are any REALPART_EXPR
5272 or IMAGPART_EXPR immediate uses, but none of them have
5273 a change in their value ranges, return
5274 SSA_PROP_NOT_INTERESTING. If there are no
5275 {REAL,IMAG}PART_EXPR uses at all,
5276 return SSA_PROP_VARYING. */
5277 value_range new_vr = VR_INITIALIZER;
5278 extract_range_basic (&new_vr, use_stmt);
5279 value_range *old_vr = get_value_range (use_lhs);
5280 if (old_vr->type != new_vr.type
5281 || !vrp_operand_equal_p (old_vr->min, new_vr.min)
5282 || !vrp_operand_equal_p (old_vr->max, new_vr.max)
5283 || !vrp_bitmap_equal_p (old_vr->equiv, new_vr.equiv))
5284 res = SSA_PROP_INTERESTING;
5285 else
5286 res = SSA_PROP_NOT_INTERESTING;
5287 BITMAP_FREE (new_vr.equiv);
5288 if (res == SSA_PROP_INTERESTING)
5290 *output_p = lhs;
5291 return res;
5295 return res;
5297 break;
5298 default:
5299 break;
5302 /* All other statements produce nothing of interest for VRP, so mark
5303 their outputs varying and prevent further simulation. */
5304 set_defs_to_varying (stmt);
5306 return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
5309 /* Union the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
5310 { VR1TYPE, VR0MIN, VR0MAX } and store the result
5311 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
5312 possible such range. The resulting range is not canonicalized. */
5314 static void
5315 union_ranges (enum value_range_type *vr0type,
5316 tree *vr0min, tree *vr0max,
5317 enum value_range_type vr1type,
5318 tree vr1min, tree vr1max)
5320 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
5321 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
5323 /* [] is vr0, () is vr1 in the following classification comments. */
5324 if (mineq && maxeq)
5326 /* [( )] */
5327 if (*vr0type == vr1type)
5328 /* Nothing to do for equal ranges. */
5330 else if ((*vr0type == VR_RANGE
5331 && vr1type == VR_ANTI_RANGE)
5332 || (*vr0type == VR_ANTI_RANGE
5333 && vr1type == VR_RANGE))
5335 /* For anti-range with range union the result is varying. */
5336 goto give_up;
5338 else
5339 gcc_unreachable ();
5341 else if (operand_less_p (*vr0max, vr1min) == 1
5342 || operand_less_p (vr1max, *vr0min) == 1)
5344 /* [ ] ( ) or ( ) [ ]
5345 If the ranges have an empty intersection, result of the union
5346 operation is the anti-range or if both are anti-ranges
5347 it covers all. */
5348 if (*vr0type == VR_ANTI_RANGE
5349 && vr1type == VR_ANTI_RANGE)
5350 goto give_up;
5351 else if (*vr0type == VR_ANTI_RANGE
5352 && vr1type == VR_RANGE)
5354 else if (*vr0type == VR_RANGE
5355 && vr1type == VR_ANTI_RANGE)
5357 *vr0type = vr1type;
5358 *vr0min = vr1min;
5359 *vr0max = vr1max;
5361 else if (*vr0type == VR_RANGE
5362 && vr1type == VR_RANGE)
5364 /* The result is the convex hull of both ranges. */
5365 if (operand_less_p (*vr0max, vr1min) == 1)
5367 /* If the result can be an anti-range, create one. */
5368 if (TREE_CODE (*vr0max) == INTEGER_CST
5369 && TREE_CODE (vr1min) == INTEGER_CST
5370 && vrp_val_is_min (*vr0min)
5371 && vrp_val_is_max (vr1max))
5373 tree min = int_const_binop (PLUS_EXPR,
5374 *vr0max,
5375 build_int_cst (TREE_TYPE (*vr0max), 1));
5376 tree max = int_const_binop (MINUS_EXPR,
5377 vr1min,
5378 build_int_cst (TREE_TYPE (vr1min), 1));
5379 if (!operand_less_p (max, min))
5381 *vr0type = VR_ANTI_RANGE;
5382 *vr0min = min;
5383 *vr0max = max;
5385 else
5386 *vr0max = vr1max;
5388 else
5389 *vr0max = vr1max;
5391 else
5393 /* If the result can be an anti-range, create one. */
5394 if (TREE_CODE (vr1max) == INTEGER_CST
5395 && TREE_CODE (*vr0min) == INTEGER_CST
5396 && vrp_val_is_min (vr1min)
5397 && vrp_val_is_max (*vr0max))
5399 tree min = int_const_binop (PLUS_EXPR,
5400 vr1max,
5401 build_int_cst (TREE_TYPE (vr1max), 1));
5402 tree max = int_const_binop (MINUS_EXPR,
5403 *vr0min,
5404 build_int_cst (TREE_TYPE (*vr0min), 1));
5405 if (!operand_less_p (max, min))
5407 *vr0type = VR_ANTI_RANGE;
5408 *vr0min = min;
5409 *vr0max = max;
5411 else
5412 *vr0min = vr1min;
5414 else
5415 *vr0min = vr1min;
5418 else
5419 gcc_unreachable ();
5421 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
5422 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
5424 /* [ ( ) ] or [( ) ] or [ ( )] */
5425 if (*vr0type == VR_RANGE
5426 && vr1type == VR_RANGE)
5428 else if (*vr0type == VR_ANTI_RANGE
5429 && vr1type == VR_ANTI_RANGE)
5431 *vr0type = vr1type;
5432 *vr0min = vr1min;
5433 *vr0max = vr1max;
5435 else if (*vr0type == VR_ANTI_RANGE
5436 && vr1type == VR_RANGE)
5438 /* Arbitrarily choose the right or left gap. */
5439 if (!mineq && TREE_CODE (vr1min) == INTEGER_CST)
5440 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5441 build_int_cst (TREE_TYPE (vr1min), 1));
5442 else if (!maxeq && TREE_CODE (vr1max) == INTEGER_CST)
5443 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5444 build_int_cst (TREE_TYPE (vr1max), 1));
5445 else
5446 goto give_up;
5448 else if (*vr0type == VR_RANGE
5449 && vr1type == VR_ANTI_RANGE)
5450 /* The result covers everything. */
5451 goto give_up;
5452 else
5453 gcc_unreachable ();
5455 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
5456 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
5458 /* ( [ ] ) or ([ ] ) or ( [ ]) */
5459 if (*vr0type == VR_RANGE
5460 && vr1type == VR_RANGE)
5462 *vr0type = vr1type;
5463 *vr0min = vr1min;
5464 *vr0max = vr1max;
5466 else if (*vr0type == VR_ANTI_RANGE
5467 && vr1type == VR_ANTI_RANGE)
5469 else if (*vr0type == VR_RANGE
5470 && vr1type == VR_ANTI_RANGE)
5472 *vr0type = VR_ANTI_RANGE;
5473 if (!mineq && TREE_CODE (*vr0min) == INTEGER_CST)
5475 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5476 build_int_cst (TREE_TYPE (*vr0min), 1));
5477 *vr0min = vr1min;
5479 else if (!maxeq && TREE_CODE (*vr0max) == INTEGER_CST)
5481 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5482 build_int_cst (TREE_TYPE (*vr0max), 1));
5483 *vr0max = vr1max;
5485 else
5486 goto give_up;
5488 else if (*vr0type == VR_ANTI_RANGE
5489 && vr1type == VR_RANGE)
5490 /* The result covers everything. */
5491 goto give_up;
5492 else
5493 gcc_unreachable ();
5495 else if ((operand_less_p (vr1min, *vr0max) == 1
5496 || operand_equal_p (vr1min, *vr0max, 0))
5497 && operand_less_p (*vr0min, vr1min) == 1
5498 && operand_less_p (*vr0max, vr1max) == 1)
5500 /* [ ( ] ) or [ ]( ) */
5501 if (*vr0type == VR_RANGE
5502 && vr1type == VR_RANGE)
5503 *vr0max = vr1max;
5504 else if (*vr0type == VR_ANTI_RANGE
5505 && vr1type == VR_ANTI_RANGE)
5506 *vr0min = vr1min;
5507 else if (*vr0type == VR_ANTI_RANGE
5508 && vr1type == VR_RANGE)
5510 if (TREE_CODE (vr1min) == INTEGER_CST)
5511 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5512 build_int_cst (TREE_TYPE (vr1min), 1));
5513 else
5514 goto give_up;
5516 else if (*vr0type == VR_RANGE
5517 && vr1type == VR_ANTI_RANGE)
5519 if (TREE_CODE (*vr0max) == INTEGER_CST)
5521 *vr0type = vr1type;
5522 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5523 build_int_cst (TREE_TYPE (*vr0max), 1));
5524 *vr0max = vr1max;
5526 else
5527 goto give_up;
5529 else
5530 gcc_unreachable ();
5532 else if ((operand_less_p (*vr0min, vr1max) == 1
5533 || operand_equal_p (*vr0min, vr1max, 0))
5534 && operand_less_p (vr1min, *vr0min) == 1
5535 && operand_less_p (vr1max, *vr0max) == 1)
5537 /* ( [ ) ] or ( )[ ] */
5538 if (*vr0type == VR_RANGE
5539 && vr1type == VR_RANGE)
5540 *vr0min = vr1min;
5541 else if (*vr0type == VR_ANTI_RANGE
5542 && vr1type == VR_ANTI_RANGE)
5543 *vr0max = vr1max;
5544 else if (*vr0type == VR_ANTI_RANGE
5545 && vr1type == VR_RANGE)
5547 if (TREE_CODE (vr1max) == INTEGER_CST)
5548 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5549 build_int_cst (TREE_TYPE (vr1max), 1));
5550 else
5551 goto give_up;
5553 else if (*vr0type == VR_RANGE
5554 && vr1type == VR_ANTI_RANGE)
5556 if (TREE_CODE (*vr0min) == INTEGER_CST)
5558 *vr0type = vr1type;
5559 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5560 build_int_cst (TREE_TYPE (*vr0min), 1));
5561 *vr0min = vr1min;
5563 else
5564 goto give_up;
5566 else
5567 gcc_unreachable ();
5569 else
5570 goto give_up;
5572 return;
5574 give_up:
5575 *vr0type = VR_VARYING;
5576 *vr0min = NULL_TREE;
5577 *vr0max = NULL_TREE;
5580 /* Intersect the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
5581 { VR1TYPE, VR0MIN, VR0MAX } and store the result
5582 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
5583 possible such range. The resulting range is not canonicalized. */
5585 static void
5586 intersect_ranges (enum value_range_type *vr0type,
5587 tree *vr0min, tree *vr0max,
5588 enum value_range_type vr1type,
5589 tree vr1min, tree vr1max)
5591 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
5592 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
5594 /* [] is vr0, () is vr1 in the following classification comments. */
5595 if (mineq && maxeq)
5597 /* [( )] */
5598 if (*vr0type == vr1type)
5599 /* Nothing to do for equal ranges. */
5601 else if ((*vr0type == VR_RANGE
5602 && vr1type == VR_ANTI_RANGE)
5603 || (*vr0type == VR_ANTI_RANGE
5604 && vr1type == VR_RANGE))
5606 /* For anti-range with range intersection the result is empty. */
5607 *vr0type = VR_UNDEFINED;
5608 *vr0min = NULL_TREE;
5609 *vr0max = NULL_TREE;
5611 else
5612 gcc_unreachable ();
5614 else if (operand_less_p (*vr0max, vr1min) == 1
5615 || operand_less_p (vr1max, *vr0min) == 1)
5617 /* [ ] ( ) or ( ) [ ]
5618 If the ranges have an empty intersection, the result of the
5619 intersect operation is the range for intersecting an
5620 anti-range with a range or empty when intersecting two ranges. */
5621 if (*vr0type == VR_RANGE
5622 && vr1type == VR_ANTI_RANGE)
5624 else if (*vr0type == VR_ANTI_RANGE
5625 && vr1type == VR_RANGE)
5627 *vr0type = vr1type;
5628 *vr0min = vr1min;
5629 *vr0max = vr1max;
5631 else if (*vr0type == VR_RANGE
5632 && vr1type == VR_RANGE)
5634 *vr0type = VR_UNDEFINED;
5635 *vr0min = NULL_TREE;
5636 *vr0max = NULL_TREE;
5638 else if (*vr0type == VR_ANTI_RANGE
5639 && vr1type == VR_ANTI_RANGE)
5641 /* If the anti-ranges are adjacent to each other merge them. */
5642 if (TREE_CODE (*vr0max) == INTEGER_CST
5643 && TREE_CODE (vr1min) == INTEGER_CST
5644 && operand_less_p (*vr0max, vr1min) == 1
5645 && integer_onep (int_const_binop (MINUS_EXPR,
5646 vr1min, *vr0max)))
5647 *vr0max = vr1max;
5648 else if (TREE_CODE (vr1max) == INTEGER_CST
5649 && TREE_CODE (*vr0min) == INTEGER_CST
5650 && operand_less_p (vr1max, *vr0min) == 1
5651 && integer_onep (int_const_binop (MINUS_EXPR,
5652 *vr0min, vr1max)))
5653 *vr0min = vr1min;
5654 /* Else arbitrarily take VR0. */
5657 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
5658 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
5660 /* [ ( ) ] or [( ) ] or [ ( )] */
5661 if (*vr0type == VR_RANGE
5662 && vr1type == VR_RANGE)
5664 /* If both are ranges the result is the inner one. */
5665 *vr0type = vr1type;
5666 *vr0min = vr1min;
5667 *vr0max = vr1max;
5669 else if (*vr0type == VR_RANGE
5670 && vr1type == VR_ANTI_RANGE)
5672 /* Choose the right gap if the left one is empty. */
5673 if (mineq)
5675 if (TREE_CODE (vr1max) != INTEGER_CST)
5676 *vr0min = vr1max;
5677 else if (TYPE_PRECISION (TREE_TYPE (vr1max)) == 1
5678 && !TYPE_UNSIGNED (TREE_TYPE (vr1max)))
5679 *vr0min
5680 = int_const_binop (MINUS_EXPR, vr1max,
5681 build_int_cst (TREE_TYPE (vr1max), -1));
5682 else
5683 *vr0min
5684 = int_const_binop (PLUS_EXPR, vr1max,
5685 build_int_cst (TREE_TYPE (vr1max), 1));
5687 /* Choose the left gap if the right one is empty. */
5688 else if (maxeq)
5690 if (TREE_CODE (vr1min) != INTEGER_CST)
5691 *vr0max = vr1min;
5692 else if (TYPE_PRECISION (TREE_TYPE (vr1min)) == 1
5693 && !TYPE_UNSIGNED (TREE_TYPE (vr1min)))
5694 *vr0max
5695 = int_const_binop (PLUS_EXPR, vr1min,
5696 build_int_cst (TREE_TYPE (vr1min), -1));
5697 else
5698 *vr0max
5699 = int_const_binop (MINUS_EXPR, vr1min,
5700 build_int_cst (TREE_TYPE (vr1min), 1));
5702 /* Choose the anti-range if the range is effectively varying. */
5703 else if (vrp_val_is_min (*vr0min)
5704 && vrp_val_is_max (*vr0max))
5706 *vr0type = vr1type;
5707 *vr0min = vr1min;
5708 *vr0max = vr1max;
5710 /* Else choose the range. */
5712 else if (*vr0type == VR_ANTI_RANGE
5713 && vr1type == VR_ANTI_RANGE)
5714 /* If both are anti-ranges the result is the outer one. */
5716 else if (*vr0type == VR_ANTI_RANGE
5717 && vr1type == VR_RANGE)
5719 /* The intersection is empty. */
5720 *vr0type = VR_UNDEFINED;
5721 *vr0min = NULL_TREE;
5722 *vr0max = NULL_TREE;
5724 else
5725 gcc_unreachable ();
5727 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
5728 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
5730 /* ( [ ] ) or ([ ] ) or ( [ ]) */
5731 if (*vr0type == VR_RANGE
5732 && vr1type == VR_RANGE)
5733 /* Choose the inner range. */
5735 else if (*vr0type == VR_ANTI_RANGE
5736 && vr1type == VR_RANGE)
5738 /* Choose the right gap if the left is empty. */
5739 if (mineq)
5741 *vr0type = VR_RANGE;
5742 if (TREE_CODE (*vr0max) != INTEGER_CST)
5743 *vr0min = *vr0max;
5744 else if (TYPE_PRECISION (TREE_TYPE (*vr0max)) == 1
5745 && !TYPE_UNSIGNED (TREE_TYPE (*vr0max)))
5746 *vr0min
5747 = int_const_binop (MINUS_EXPR, *vr0max,
5748 build_int_cst (TREE_TYPE (*vr0max), -1));
5749 else
5750 *vr0min
5751 = int_const_binop (PLUS_EXPR, *vr0max,
5752 build_int_cst (TREE_TYPE (*vr0max), 1));
5753 *vr0max = vr1max;
5755 /* Choose the left gap if the right is empty. */
5756 else if (maxeq)
5758 *vr0type = VR_RANGE;
5759 if (TREE_CODE (*vr0min) != INTEGER_CST)
5760 *vr0max = *vr0min;
5761 else if (TYPE_PRECISION (TREE_TYPE (*vr0min)) == 1
5762 && !TYPE_UNSIGNED (TREE_TYPE (*vr0min)))
5763 *vr0max
5764 = int_const_binop (PLUS_EXPR, *vr0min,
5765 build_int_cst (TREE_TYPE (*vr0min), -1));
5766 else
5767 *vr0max
5768 = int_const_binop (MINUS_EXPR, *vr0min,
5769 build_int_cst (TREE_TYPE (*vr0min), 1));
5770 *vr0min = vr1min;
5772 /* Choose the anti-range if the range is effectively varying. */
5773 else if (vrp_val_is_min (vr1min)
5774 && vrp_val_is_max (vr1max))
5776 /* Choose the anti-range if it is ~[0,0], that range is special
5777 enough to special case when vr1's range is relatively wide.
5778 At least for types bigger than int - this covers pointers
5779 and arguments to functions like ctz. */
5780 else if (*vr0min == *vr0max
5781 && integer_zerop (*vr0min)
5782 && ((TYPE_PRECISION (TREE_TYPE (*vr0min))
5783 >= TYPE_PRECISION (integer_type_node))
5784 || POINTER_TYPE_P (TREE_TYPE (*vr0min)))
5785 && TREE_CODE (vr1max) == INTEGER_CST
5786 && TREE_CODE (vr1min) == INTEGER_CST
5787 && (wi::clz (wi::to_wide (vr1max) - wi::to_wide (vr1min))
5788 < TYPE_PRECISION (TREE_TYPE (*vr0min)) / 2))
5790 /* Else choose the range. */
5791 else
5793 *vr0type = vr1type;
5794 *vr0min = vr1min;
5795 *vr0max = vr1max;
5798 else if (*vr0type == VR_ANTI_RANGE
5799 && vr1type == VR_ANTI_RANGE)
5801 /* If both are anti-ranges the result is the outer one. */
5802 *vr0type = vr1type;
5803 *vr0min = vr1min;
5804 *vr0max = vr1max;
5806 else if (vr1type == VR_ANTI_RANGE
5807 && *vr0type == VR_RANGE)
5809 /* The intersection is empty. */
5810 *vr0type = VR_UNDEFINED;
5811 *vr0min = NULL_TREE;
5812 *vr0max = NULL_TREE;
5814 else
5815 gcc_unreachable ();
5817 else if ((operand_less_p (vr1min, *vr0max) == 1
5818 || operand_equal_p (vr1min, *vr0max, 0))
5819 && operand_less_p (*vr0min, vr1min) == 1)
5821 /* [ ( ] ) or [ ]( ) */
5822 if (*vr0type == VR_ANTI_RANGE
5823 && vr1type == VR_ANTI_RANGE)
5824 *vr0max = vr1max;
5825 else if (*vr0type == VR_RANGE
5826 && vr1type == VR_RANGE)
5827 *vr0min = vr1min;
5828 else if (*vr0type == VR_RANGE
5829 && vr1type == VR_ANTI_RANGE)
5831 if (TREE_CODE (vr1min) == INTEGER_CST)
5832 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5833 build_int_cst (TREE_TYPE (vr1min), 1));
5834 else
5835 *vr0max = vr1min;
5837 else if (*vr0type == VR_ANTI_RANGE
5838 && vr1type == VR_RANGE)
5840 *vr0type = VR_RANGE;
5841 if (TREE_CODE (*vr0max) == INTEGER_CST)
5842 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5843 build_int_cst (TREE_TYPE (*vr0max), 1));
5844 else
5845 *vr0min = *vr0max;
5846 *vr0max = vr1max;
5848 else
5849 gcc_unreachable ();
5851 else if ((operand_less_p (*vr0min, vr1max) == 1
5852 || operand_equal_p (*vr0min, vr1max, 0))
5853 && operand_less_p (vr1min, *vr0min) == 1)
5855 /* ( [ ) ] or ( )[ ] */
5856 if (*vr0type == VR_ANTI_RANGE
5857 && vr1type == VR_ANTI_RANGE)
5858 *vr0min = vr1min;
5859 else if (*vr0type == VR_RANGE
5860 && vr1type == VR_RANGE)
5861 *vr0max = vr1max;
5862 else if (*vr0type == VR_RANGE
5863 && vr1type == VR_ANTI_RANGE)
5865 if (TREE_CODE (vr1max) == INTEGER_CST)
5866 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5867 build_int_cst (TREE_TYPE (vr1max), 1));
5868 else
5869 *vr0min = vr1max;
5871 else if (*vr0type == VR_ANTI_RANGE
5872 && vr1type == VR_RANGE)
5874 *vr0type = VR_RANGE;
5875 if (TREE_CODE (*vr0min) == INTEGER_CST)
5876 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5877 build_int_cst (TREE_TYPE (*vr0min), 1));
5878 else
5879 *vr0max = *vr0min;
5880 *vr0min = vr1min;
5882 else
5883 gcc_unreachable ();
5886 /* As a fallback simply use { *VRTYPE, *VR0MIN, *VR0MAX } as
5887 result for the intersection. That's always a conservative
5888 correct estimate unless VR1 is a constant singleton range
5889 in which case we choose that. */
5890 if (vr1type == VR_RANGE
5891 && is_gimple_min_invariant (vr1min)
5892 && vrp_operand_equal_p (vr1min, vr1max))
5894 *vr0type = vr1type;
5895 *vr0min = vr1min;
5896 *vr0max = vr1max;
5899 return;
5903 /* Intersect the two value-ranges *VR0 and *VR1 and store the result
5904 in *VR0. This may not be the smallest possible such range. */
5906 static void
5907 vrp_intersect_ranges_1 (value_range *vr0, value_range *vr1)
5909 value_range saved;
5911 /* If either range is VR_VARYING the other one wins. */
5912 if (vr1->type == VR_VARYING)
5913 return;
5914 if (vr0->type == VR_VARYING)
5916 copy_value_range (vr0, vr1);
5917 return;
5920 /* When either range is VR_UNDEFINED the resulting range is
5921 VR_UNDEFINED, too. */
5922 if (vr0->type == VR_UNDEFINED)
5923 return;
5924 if (vr1->type == VR_UNDEFINED)
5926 set_value_range_to_undefined (vr0);
5927 return;
5930 /* Save the original vr0 so we can return it as conservative intersection
5931 result when our worker turns things to varying. */
5932 saved = *vr0;
5933 intersect_ranges (&vr0->type, &vr0->min, &vr0->max,
5934 vr1->type, vr1->min, vr1->max);
5935 /* Make sure to canonicalize the result though as the inversion of a
5936 VR_RANGE can still be a VR_RANGE. */
5937 set_and_canonicalize_value_range (vr0, vr0->type,
5938 vr0->min, vr0->max, vr0->equiv);
5939 /* If that failed, use the saved original VR0. */
5940 if (vr0->type == VR_VARYING)
5942 *vr0 = saved;
5943 return;
5945 /* If the result is VR_UNDEFINED there is no need to mess with
5946 the equivalencies. */
5947 if (vr0->type == VR_UNDEFINED)
5948 return;
5950 /* The resulting set of equivalences for range intersection is the union of
5951 the two sets. */
5952 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
5953 bitmap_ior_into (vr0->equiv, vr1->equiv);
5954 else if (vr1->equiv && !vr0->equiv)
5956 /* All equivalence bitmaps are allocated from the same obstack. So
5957 we can use the obstack associated with VR to allocate vr0->equiv. */
5958 vr0->equiv = BITMAP_ALLOC (vr1->equiv->obstack);
5959 bitmap_copy (vr0->equiv, vr1->equiv);
5963 void
5964 vrp_intersect_ranges (value_range *vr0, value_range *vr1)
5966 if (dump_file && (dump_flags & TDF_DETAILS))
5968 fprintf (dump_file, "Intersecting\n ");
5969 dump_value_range (dump_file, vr0);
5970 fprintf (dump_file, "\nand\n ");
5971 dump_value_range (dump_file, vr1);
5972 fprintf (dump_file, "\n");
5974 vrp_intersect_ranges_1 (vr0, vr1);
5975 if (dump_file && (dump_flags & TDF_DETAILS))
5977 fprintf (dump_file, "to\n ");
5978 dump_value_range (dump_file, vr0);
5979 fprintf (dump_file, "\n");
5983 /* Meet operation for value ranges. Given two value ranges VR0 and
5984 VR1, store in VR0 a range that contains both VR0 and VR1. This
5985 may not be the smallest possible such range. */
5987 static void
5988 vrp_meet_1 (value_range *vr0, const value_range *vr1)
5990 value_range saved;
5992 if (vr0->type == VR_UNDEFINED)
5994 set_value_range (vr0, vr1->type, vr1->min, vr1->max, vr1->equiv);
5995 return;
5998 if (vr1->type == VR_UNDEFINED)
6000 /* VR0 already has the resulting range. */
6001 return;
6004 if (vr0->type == VR_VARYING)
6006 /* Nothing to do. VR0 already has the resulting range. */
6007 return;
6010 if (vr1->type == VR_VARYING)
6012 set_value_range_to_varying (vr0);
6013 return;
6016 saved = *vr0;
6017 union_ranges (&vr0->type, &vr0->min, &vr0->max,
6018 vr1->type, vr1->min, vr1->max);
6019 if (vr0->type == VR_VARYING)
6021 /* Failed to find an efficient meet. Before giving up and setting
6022 the result to VARYING, see if we can at least derive a useful
6023 anti-range. FIXME, all this nonsense about distinguishing
6024 anti-ranges from ranges is necessary because of the odd
6025 semantics of range_includes_zero_p and friends. */
6026 if (((saved.type == VR_RANGE
6027 && range_includes_zero_p (saved.min, saved.max) == 0)
6028 || (saved.type == VR_ANTI_RANGE
6029 && range_includes_zero_p (saved.min, saved.max) == 1))
6030 && ((vr1->type == VR_RANGE
6031 && range_includes_zero_p (vr1->min, vr1->max) == 0)
6032 || (vr1->type == VR_ANTI_RANGE
6033 && range_includes_zero_p (vr1->min, vr1->max) == 1)))
6035 set_value_range_to_nonnull (vr0, TREE_TYPE (saved.min));
6037 /* Since this meet operation did not result from the meeting of
6038 two equivalent names, VR0 cannot have any equivalences. */
6039 if (vr0->equiv)
6040 bitmap_clear (vr0->equiv);
6041 return;
6044 set_value_range_to_varying (vr0);
6045 return;
6047 set_and_canonicalize_value_range (vr0, vr0->type, vr0->min, vr0->max,
6048 vr0->equiv);
6049 if (vr0->type == VR_VARYING)
6050 return;
6052 /* The resulting set of equivalences is always the intersection of
6053 the two sets. */
6054 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
6055 bitmap_and_into (vr0->equiv, vr1->equiv);
6056 else if (vr0->equiv && !vr1->equiv)
6057 bitmap_clear (vr0->equiv);
6060 void
6061 vrp_meet (value_range *vr0, const value_range *vr1)
6063 if (dump_file && (dump_flags & TDF_DETAILS))
6065 fprintf (dump_file, "Meeting\n ");
6066 dump_value_range (dump_file, vr0);
6067 fprintf (dump_file, "\nand\n ");
6068 dump_value_range (dump_file, vr1);
6069 fprintf (dump_file, "\n");
6071 vrp_meet_1 (vr0, vr1);
6072 if (dump_file && (dump_flags & TDF_DETAILS))
6074 fprintf (dump_file, "to\n ");
6075 dump_value_range (dump_file, vr0);
6076 fprintf (dump_file, "\n");
6081 /* Visit all arguments for PHI node PHI that flow through executable
6082 edges. If a valid value range can be derived from all the incoming
6083 value ranges, set a new range for the LHS of PHI. */
6085 enum ssa_prop_result
6086 vrp_prop::visit_phi (gphi *phi)
6088 tree lhs = PHI_RESULT (phi);
6089 value_range vr_result = VR_INITIALIZER;
6090 extract_range_from_phi_node (phi, &vr_result);
6091 if (update_value_range (lhs, &vr_result))
6093 if (dump_file && (dump_flags & TDF_DETAILS))
6095 fprintf (dump_file, "Found new range for ");
6096 print_generic_expr (dump_file, lhs);
6097 fprintf (dump_file, ": ");
6098 dump_value_range (dump_file, &vr_result);
6099 fprintf (dump_file, "\n");
6102 if (vr_result.type == VR_VARYING)
6103 return SSA_PROP_VARYING;
6105 return SSA_PROP_INTERESTING;
6108 /* Nothing changed, don't add outgoing edges. */
6109 return SSA_PROP_NOT_INTERESTING;
6112 class vrp_folder : public substitute_and_fold_engine
6114 public:
6115 tree get_value (tree) FINAL OVERRIDE;
6116 bool fold_stmt (gimple_stmt_iterator *) FINAL OVERRIDE;
6117 bool fold_predicate_in (gimple_stmt_iterator *);
6119 class vr_values *vr_values;
6121 /* Delegators. */
6122 tree vrp_evaluate_conditional (tree_code code, tree op0,
6123 tree op1, gimple *stmt)
6124 { return vr_values->vrp_evaluate_conditional (code, op0, op1, stmt); }
6125 bool simplify_stmt_using_ranges (gimple_stmt_iterator *gsi)
6126 { return vr_values->simplify_stmt_using_ranges (gsi); }
6127 tree op_with_constant_singleton_value_range (tree op)
6128 { return vr_values->op_with_constant_singleton_value_range (op); }
6131 /* If the statement pointed by SI has a predicate whose value can be
6132 computed using the value range information computed by VRP, compute
6133 its value and return true. Otherwise, return false. */
6135 bool
6136 vrp_folder::fold_predicate_in (gimple_stmt_iterator *si)
6138 bool assignment_p = false;
6139 tree val;
6140 gimple *stmt = gsi_stmt (*si);
6142 if (is_gimple_assign (stmt)
6143 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
6145 assignment_p = true;
6146 val = vrp_evaluate_conditional (gimple_assign_rhs_code (stmt),
6147 gimple_assign_rhs1 (stmt),
6148 gimple_assign_rhs2 (stmt),
6149 stmt);
6151 else if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
6152 val = vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
6153 gimple_cond_lhs (cond_stmt),
6154 gimple_cond_rhs (cond_stmt),
6155 stmt);
6156 else
6157 return false;
6159 if (val)
6161 if (assignment_p)
6162 val = fold_convert (gimple_expr_type (stmt), val);
6164 if (dump_file)
6166 fprintf (dump_file, "Folding predicate ");
6167 print_gimple_expr (dump_file, stmt, 0);
6168 fprintf (dump_file, " to ");
6169 print_generic_expr (dump_file, val);
6170 fprintf (dump_file, "\n");
6173 if (is_gimple_assign (stmt))
6174 gimple_assign_set_rhs_from_tree (si, val);
6175 else
6177 gcc_assert (gimple_code (stmt) == GIMPLE_COND);
6178 gcond *cond_stmt = as_a <gcond *> (stmt);
6179 if (integer_zerop (val))
6180 gimple_cond_make_false (cond_stmt);
6181 else if (integer_onep (val))
6182 gimple_cond_make_true (cond_stmt);
6183 else
6184 gcc_unreachable ();
6187 return true;
6190 return false;
6193 /* Callback for substitute_and_fold folding the stmt at *SI. */
6195 bool
6196 vrp_folder::fold_stmt (gimple_stmt_iterator *si)
6198 if (fold_predicate_in (si))
6199 return true;
6201 return simplify_stmt_using_ranges (si);
6204 /* If OP has a value range with a single constant value return that,
6205 otherwise return NULL_TREE. This returns OP itself if OP is a
6206 constant.
6208 Implemented as a pure wrapper right now, but this will change. */
6210 tree
6211 vrp_folder::get_value (tree op)
6213 return op_with_constant_singleton_value_range (op);
6216 /* Return the LHS of any ASSERT_EXPR where OP appears as the first
6217 argument to the ASSERT_EXPR and in which the ASSERT_EXPR dominates
6218 BB. If no such ASSERT_EXPR is found, return OP. */
6220 static tree
6221 lhs_of_dominating_assert (tree op, basic_block bb, gimple *stmt)
6223 imm_use_iterator imm_iter;
6224 gimple *use_stmt;
6225 use_operand_p use_p;
6227 if (TREE_CODE (op) == SSA_NAME)
6229 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, op)
6231 use_stmt = USE_STMT (use_p);
6232 if (use_stmt != stmt
6233 && gimple_assign_single_p (use_stmt)
6234 && TREE_CODE (gimple_assign_rhs1 (use_stmt)) == ASSERT_EXPR
6235 && TREE_OPERAND (gimple_assign_rhs1 (use_stmt), 0) == op
6236 && dominated_by_p (CDI_DOMINATORS, bb, gimple_bb (use_stmt)))
6237 return gimple_assign_lhs (use_stmt);
6240 return op;
6243 /* A hack. */
6244 static class vr_values *x_vr_values;
6246 /* A trivial wrapper so that we can present the generic jump threading
6247 code with a simple API for simplifying statements. STMT is the
6248 statement we want to simplify, WITHIN_STMT provides the location
6249 for any overflow warnings. */
6251 static tree
6252 simplify_stmt_for_jump_threading (gimple *stmt, gimple *within_stmt,
6253 class avail_exprs_stack *avail_exprs_stack ATTRIBUTE_UNUSED,
6254 basic_block bb)
6256 /* First see if the conditional is in the hash table. */
6257 tree cached_lhs = avail_exprs_stack->lookup_avail_expr (stmt, false, true);
6258 if (cached_lhs && is_gimple_min_invariant (cached_lhs))
6259 return cached_lhs;
6261 vr_values *vr_values = x_vr_values;
6262 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
6264 tree op0 = gimple_cond_lhs (cond_stmt);
6265 op0 = lhs_of_dominating_assert (op0, bb, stmt);
6267 tree op1 = gimple_cond_rhs (cond_stmt);
6268 op1 = lhs_of_dominating_assert (op1, bb, stmt);
6270 return vr_values->vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
6271 op0, op1, within_stmt);
6274 /* We simplify a switch statement by trying to determine which case label
6275 will be taken. If we are successful then we return the corresponding
6276 CASE_LABEL_EXPR. */
6277 if (gswitch *switch_stmt = dyn_cast <gswitch *> (stmt))
6279 tree op = gimple_switch_index (switch_stmt);
6280 if (TREE_CODE (op) != SSA_NAME)
6281 return NULL_TREE;
6283 op = lhs_of_dominating_assert (op, bb, stmt);
6285 value_range *vr = vr_values->get_value_range (op);
6286 if ((vr->type != VR_RANGE && vr->type != VR_ANTI_RANGE)
6287 || symbolic_range_p (vr))
6288 return NULL_TREE;
6290 if (vr->type == VR_RANGE)
6292 size_t i, j;
6293 /* Get the range of labels that contain a part of the operand's
6294 value range. */
6295 find_case_label_range (switch_stmt, vr->min, vr->max, &i, &j);
6297 /* Is there only one such label? */
6298 if (i == j)
6300 tree label = gimple_switch_label (switch_stmt, i);
6302 /* The i'th label will be taken only if the value range of the
6303 operand is entirely within the bounds of this label. */
6304 if (CASE_HIGH (label) != NULL_TREE
6305 ? (tree_int_cst_compare (CASE_LOW (label), vr->min) <= 0
6306 && tree_int_cst_compare (CASE_HIGH (label), vr->max) >= 0)
6307 : (tree_int_cst_equal (CASE_LOW (label), vr->min)
6308 && tree_int_cst_equal (vr->min, vr->max)))
6309 return label;
6312 /* If there are no such labels then the default label will be
6313 taken. */
6314 if (i > j)
6315 return gimple_switch_label (switch_stmt, 0);
6318 if (vr->type == VR_ANTI_RANGE)
6320 unsigned n = gimple_switch_num_labels (switch_stmt);
6321 tree min_label = gimple_switch_label (switch_stmt, 1);
6322 tree max_label = gimple_switch_label (switch_stmt, n - 1);
6324 /* The default label will be taken only if the anti-range of the
6325 operand is entirely outside the bounds of all the (non-default)
6326 case labels. */
6327 if (tree_int_cst_compare (vr->min, CASE_LOW (min_label)) <= 0
6328 && (CASE_HIGH (max_label) != NULL_TREE
6329 ? tree_int_cst_compare (vr->max, CASE_HIGH (max_label)) >= 0
6330 : tree_int_cst_compare (vr->max, CASE_LOW (max_label)) >= 0))
6331 return gimple_switch_label (switch_stmt, 0);
6334 return NULL_TREE;
6337 if (gassign *assign_stmt = dyn_cast <gassign *> (stmt))
6339 tree lhs = gimple_assign_lhs (assign_stmt);
6340 if (TREE_CODE (lhs) == SSA_NAME
6341 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
6342 || POINTER_TYPE_P (TREE_TYPE (lhs)))
6343 && stmt_interesting_for_vrp (stmt))
6345 edge dummy_e;
6346 tree dummy_tree;
6347 value_range new_vr = VR_INITIALIZER;
6348 vr_values->extract_range_from_stmt (stmt, &dummy_e,
6349 &dummy_tree, &new_vr);
6350 if (range_int_cst_singleton_p (&new_vr))
6351 return new_vr.min;
6355 return NULL_TREE;
6358 class vrp_dom_walker : public dom_walker
6360 public:
6361 vrp_dom_walker (cdi_direction direction,
6362 class const_and_copies *const_and_copies,
6363 class avail_exprs_stack *avail_exprs_stack)
6364 : dom_walker (direction, REACHABLE_BLOCKS),
6365 m_const_and_copies (const_and_copies),
6366 m_avail_exprs_stack (avail_exprs_stack),
6367 m_dummy_cond (NULL) {}
6369 virtual edge before_dom_children (basic_block);
6370 virtual void after_dom_children (basic_block);
6372 class vr_values *vr_values;
6374 private:
6375 class const_and_copies *m_const_and_copies;
6376 class avail_exprs_stack *m_avail_exprs_stack;
6378 gcond *m_dummy_cond;
6382 /* Called before processing dominator children of BB. We want to look
6383 at ASSERT_EXPRs and record information from them in the appropriate
6384 tables.
6386 We could look at other statements here. It's not seen as likely
6387 to significantly increase the jump threads we discover. */
6389 edge
6390 vrp_dom_walker::before_dom_children (basic_block bb)
6392 gimple_stmt_iterator gsi;
6394 m_avail_exprs_stack->push_marker ();
6395 m_const_and_copies->push_marker ();
6396 for (gsi = gsi_start_nondebug_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
6398 gimple *stmt = gsi_stmt (gsi);
6399 if (gimple_assign_single_p (stmt)
6400 && TREE_CODE (gimple_assign_rhs1 (stmt)) == ASSERT_EXPR)
6402 tree rhs1 = gimple_assign_rhs1 (stmt);
6403 tree cond = TREE_OPERAND (rhs1, 1);
6404 tree inverted = invert_truthvalue (cond);
6405 vec<cond_equivalence> p;
6406 p.create (3);
6407 record_conditions (&p, cond, inverted);
6408 for (unsigned int i = 0; i < p.length (); i++)
6409 m_avail_exprs_stack->record_cond (&p[i]);
6411 tree lhs = gimple_assign_lhs (stmt);
6412 m_const_and_copies->record_const_or_copy (lhs,
6413 TREE_OPERAND (rhs1, 0));
6414 p.release ();
6415 continue;
6417 break;
6419 return NULL;
6422 /* Called after processing dominator children of BB. This is where we
6423 actually call into the threader. */
6424 void
6425 vrp_dom_walker::after_dom_children (basic_block bb)
6427 if (!m_dummy_cond)
6428 m_dummy_cond = gimple_build_cond (NE_EXPR,
6429 integer_zero_node, integer_zero_node,
6430 NULL, NULL);
6432 x_vr_values = vr_values;
6433 thread_outgoing_edges (bb, m_dummy_cond, m_const_and_copies,
6434 m_avail_exprs_stack, NULL,
6435 simplify_stmt_for_jump_threading);
6436 x_vr_values = NULL;
6438 m_avail_exprs_stack->pop_to_marker ();
6439 m_const_and_copies->pop_to_marker ();
6442 /* Blocks which have more than one predecessor and more than
6443 one successor present jump threading opportunities, i.e.,
6444 when the block is reached from a specific predecessor, we
6445 may be able to determine which of the outgoing edges will
6446 be traversed. When this optimization applies, we are able
6447 to avoid conditionals at runtime and we may expose secondary
6448 optimization opportunities.
6450 This routine is effectively a driver for the generic jump
6451 threading code. It basically just presents the generic code
6452 with edges that may be suitable for jump threading.
6454 Unlike DOM, we do not iterate VRP if jump threading was successful.
6455 While iterating may expose new opportunities for VRP, it is expected
6456 those opportunities would be very limited and the compile time cost
6457 to expose those opportunities would be significant.
6459 As jump threading opportunities are discovered, they are registered
6460 for later realization. */
6462 static void
6463 identify_jump_threads (class vr_values *vr_values)
6465 int i;
6466 edge e;
6468 /* Ugh. When substituting values earlier in this pass we can
6469 wipe the dominance information. So rebuild the dominator
6470 information as we need it within the jump threading code. */
6471 calculate_dominance_info (CDI_DOMINATORS);
6473 /* We do not allow VRP information to be used for jump threading
6474 across a back edge in the CFG. Otherwise it becomes too
6475 difficult to avoid eliminating loop exit tests. Of course
6476 EDGE_DFS_BACK is not accurate at this time so we have to
6477 recompute it. */
6478 mark_dfs_back_edges ();
6480 /* Do not thread across edges we are about to remove. Just marking
6481 them as EDGE_IGNORE will do. */
6482 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
6483 e->flags |= EDGE_IGNORE;
6485 /* Allocate our unwinder stack to unwind any temporary equivalences
6486 that might be recorded. */
6487 const_and_copies *equiv_stack = new const_and_copies ();
6489 hash_table<expr_elt_hasher> *avail_exprs
6490 = new hash_table<expr_elt_hasher> (1024);
6491 avail_exprs_stack *avail_exprs_stack
6492 = new class avail_exprs_stack (avail_exprs);
6494 vrp_dom_walker walker (CDI_DOMINATORS, equiv_stack, avail_exprs_stack);
6495 walker.vr_values = vr_values;
6496 walker.walk (cfun->cfg->x_entry_block_ptr);
6498 /* Clear EDGE_IGNORE. */
6499 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
6500 e->flags &= ~EDGE_IGNORE;
6502 /* We do not actually update the CFG or SSA graphs at this point as
6503 ASSERT_EXPRs are still in the IL and cfg cleanup code does not yet
6504 handle ASSERT_EXPRs gracefully. */
6505 delete equiv_stack;
6506 delete avail_exprs;
6507 delete avail_exprs_stack;
6510 /* Traverse all the blocks folding conditionals with known ranges. */
6512 void
6513 vrp_prop::vrp_finalize (bool warn_array_bounds_p)
6515 size_t i;
6517 /* We have completed propagating through the lattice. */
6518 vr_values.set_lattice_propagation_complete ();
6520 if (dump_file)
6522 fprintf (dump_file, "\nValue ranges after VRP:\n\n");
6523 vr_values.dump_all_value_ranges (dump_file);
6524 fprintf (dump_file, "\n");
6527 /* Set value range to non pointer SSA_NAMEs. */
6528 for (i = 0; i < num_ssa_names; i++)
6530 tree name = ssa_name (i);
6531 if (!name)
6532 continue;
6534 value_range *vr = get_value_range (name);
6535 if (!name
6536 || (vr->type == VR_VARYING)
6537 || (vr->type == VR_UNDEFINED)
6538 || (TREE_CODE (vr->min) != INTEGER_CST)
6539 || (TREE_CODE (vr->max) != INTEGER_CST))
6540 continue;
6542 if (POINTER_TYPE_P (TREE_TYPE (name))
6543 && ((vr->type == VR_RANGE
6544 && range_includes_zero_p (vr->min, vr->max) == 0)
6545 || (vr->type == VR_ANTI_RANGE
6546 && range_includes_zero_p (vr->min, vr->max) == 1)))
6547 set_ptr_nonnull (name);
6548 else if (!POINTER_TYPE_P (TREE_TYPE (name)))
6549 set_range_info (name, vr->type,
6550 wi::to_wide (vr->min),
6551 wi::to_wide (vr->max));
6554 /* If we're checking array refs, we want to merge information on
6555 the executability of each edge between vrp_folder and the
6556 check_array_bounds_dom_walker: each can clear the
6557 EDGE_EXECUTABLE flag on edges, in different ways.
6559 Hence, if we're going to call check_all_array_refs, set
6560 the flag on every edge now, rather than in
6561 check_array_bounds_dom_walker's ctor; vrp_folder may clear
6562 it from some edges. */
6563 if (warn_array_bounds && warn_array_bounds_p)
6564 set_all_edges_as_executable (cfun);
6566 class vrp_folder vrp_folder;
6567 vrp_folder.vr_values = &vr_values;
6568 vrp_folder.substitute_and_fold ();
6570 if (warn_array_bounds && warn_array_bounds_p)
6571 check_all_array_refs ();
6574 /* Main entry point to VRP (Value Range Propagation). This pass is
6575 loosely based on J. R. C. Patterson, ``Accurate Static Branch
6576 Prediction by Value Range Propagation,'' in SIGPLAN Conference on
6577 Programming Language Design and Implementation, pp. 67-78, 1995.
6578 Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
6580 This is essentially an SSA-CCP pass modified to deal with ranges
6581 instead of constants.
6583 While propagating ranges, we may find that two or more SSA name
6584 have equivalent, though distinct ranges. For instance,
6586 1 x_9 = p_3->a;
6587 2 p_4 = ASSERT_EXPR <p_3, p_3 != 0>
6588 3 if (p_4 == q_2)
6589 4 p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
6590 5 endif
6591 6 if (q_2)
6593 In the code above, pointer p_5 has range [q_2, q_2], but from the
6594 code we can also determine that p_5 cannot be NULL and, if q_2 had
6595 a non-varying range, p_5's range should also be compatible with it.
6597 These equivalences are created by two expressions: ASSERT_EXPR and
6598 copy operations. Since p_5 is an assertion on p_4, and p_4 was the
6599 result of another assertion, then we can use the fact that p_5 and
6600 p_4 are equivalent when evaluating p_5's range.
6602 Together with value ranges, we also propagate these equivalences
6603 between names so that we can take advantage of information from
6604 multiple ranges when doing final replacement. Note that this
6605 equivalency relation is transitive but not symmetric.
6607 In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
6608 cannot assert that q_2 is equivalent to p_5 because q_2 may be used
6609 in contexts where that assertion does not hold (e.g., in line 6).
6611 TODO, the main difference between this pass and Patterson's is that
6612 we do not propagate edge probabilities. We only compute whether
6613 edges can be taken or not. That is, instead of having a spectrum
6614 of jump probabilities between 0 and 1, we only deal with 0, 1 and
6615 DON'T KNOW. In the future, it may be worthwhile to propagate
6616 probabilities to aid branch prediction. */
6618 static unsigned int
6619 execute_vrp (bool warn_array_bounds_p)
6621 int i;
6622 edge e;
6623 switch_update *su;
6625 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
6626 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
6627 scev_initialize ();
6629 /* ??? This ends up using stale EDGE_DFS_BACK for liveness computation.
6630 Inserting assertions may split edges which will invalidate
6631 EDGE_DFS_BACK. */
6632 insert_range_assertions ();
6634 to_remove_edges.create (10);
6635 to_update_switch_stmts.create (5);
6636 threadedge_initialize_values ();
6638 /* For visiting PHI nodes we need EDGE_DFS_BACK computed. */
6639 mark_dfs_back_edges ();
6641 class vrp_prop vrp_prop;
6642 vrp_prop.vrp_initialize ();
6643 vrp_prop.ssa_propagate ();
6644 vrp_prop.vrp_finalize (warn_array_bounds_p);
6646 /* We must identify jump threading opportunities before we release
6647 the datastructures built by VRP. */
6648 identify_jump_threads (&vrp_prop.vr_values);
6650 /* A comparison of an SSA_NAME against a constant where the SSA_NAME
6651 was set by a type conversion can often be rewritten to use the
6652 RHS of the type conversion.
6654 However, doing so inhibits jump threading through the comparison.
6655 So that transformation is not performed until after jump threading
6656 is complete. */
6657 basic_block bb;
6658 FOR_EACH_BB_FN (bb, cfun)
6660 gimple *last = last_stmt (bb);
6661 if (last && gimple_code (last) == GIMPLE_COND)
6662 vrp_prop.vr_values.simplify_cond_using_ranges_2 (as_a <gcond *> (last));
6665 free_numbers_of_iterations_estimates (cfun);
6667 /* ASSERT_EXPRs must be removed before finalizing jump threads
6668 as finalizing jump threads calls the CFG cleanup code which
6669 does not properly handle ASSERT_EXPRs. */
6670 remove_range_assertions ();
6672 /* If we exposed any new variables, go ahead and put them into
6673 SSA form now, before we handle jump threading. This simplifies
6674 interactions between rewriting of _DECL nodes into SSA form
6675 and rewriting SSA_NAME nodes into SSA form after block
6676 duplication and CFG manipulation. */
6677 update_ssa (TODO_update_ssa);
6679 /* We identified all the jump threading opportunities earlier, but could
6680 not transform the CFG at that time. This routine transforms the
6681 CFG and arranges for the dominator tree to be rebuilt if necessary.
6683 Note the SSA graph update will occur during the normal TODO
6684 processing by the pass manager. */
6685 thread_through_all_blocks (false);
6687 /* Remove dead edges from SWITCH_EXPR optimization. This leaves the
6688 CFG in a broken state and requires a cfg_cleanup run. */
6689 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
6690 remove_edge (e);
6691 /* Update SWITCH_EXPR case label vector. */
6692 FOR_EACH_VEC_ELT (to_update_switch_stmts, i, su)
6694 size_t j;
6695 size_t n = TREE_VEC_LENGTH (su->vec);
6696 tree label;
6697 gimple_switch_set_num_labels (su->stmt, n);
6698 for (j = 0; j < n; j++)
6699 gimple_switch_set_label (su->stmt, j, TREE_VEC_ELT (su->vec, j));
6700 /* As we may have replaced the default label with a regular one
6701 make sure to make it a real default label again. This ensures
6702 optimal expansion. */
6703 label = gimple_switch_label (su->stmt, 0);
6704 CASE_LOW (label) = NULL_TREE;
6705 CASE_HIGH (label) = NULL_TREE;
6708 if (to_remove_edges.length () > 0)
6710 free_dominance_info (CDI_DOMINATORS);
6711 loops_state_set (LOOPS_NEED_FIXUP);
6714 to_remove_edges.release ();
6715 to_update_switch_stmts.release ();
6716 threadedge_finalize_values ();
6718 scev_finalize ();
6719 loop_optimizer_finalize ();
6720 return 0;
6723 namespace {
6725 const pass_data pass_data_vrp =
6727 GIMPLE_PASS, /* type */
6728 "vrp", /* name */
6729 OPTGROUP_NONE, /* optinfo_flags */
6730 TV_TREE_VRP, /* tv_id */
6731 PROP_ssa, /* properties_required */
6732 0, /* properties_provided */
6733 0, /* properties_destroyed */
6734 0, /* todo_flags_start */
6735 ( TODO_cleanup_cfg | TODO_update_ssa ), /* todo_flags_finish */
6738 class pass_vrp : public gimple_opt_pass
6740 public:
6741 pass_vrp (gcc::context *ctxt)
6742 : gimple_opt_pass (pass_data_vrp, ctxt), warn_array_bounds_p (false)
6745 /* opt_pass methods: */
6746 opt_pass * clone () { return new pass_vrp (m_ctxt); }
6747 void set_pass_param (unsigned int n, bool param)
6749 gcc_assert (n == 0);
6750 warn_array_bounds_p = param;
6752 virtual bool gate (function *) { return flag_tree_vrp != 0; }
6753 virtual unsigned int execute (function *)
6754 { return execute_vrp (warn_array_bounds_p); }
6756 private:
6757 bool warn_array_bounds_p;
6758 }; // class pass_vrp
6760 } // anon namespace
6762 gimple_opt_pass *
6763 make_pass_vrp (gcc::context *ctxt)
6765 return new pass_vrp (ctxt);
6769 /* Worker for determine_value_range. */
6771 static void
6772 determine_value_range_1 (value_range *vr, tree expr)
6774 if (BINARY_CLASS_P (expr))
6776 value_range vr0 = VR_INITIALIZER, vr1 = VR_INITIALIZER;
6777 determine_value_range_1 (&vr0, TREE_OPERAND (expr, 0));
6778 determine_value_range_1 (&vr1, TREE_OPERAND (expr, 1));
6779 extract_range_from_binary_expr_1 (vr, TREE_CODE (expr), TREE_TYPE (expr),
6780 &vr0, &vr1);
6782 else if (UNARY_CLASS_P (expr))
6784 value_range vr0 = VR_INITIALIZER;
6785 determine_value_range_1 (&vr0, TREE_OPERAND (expr, 0));
6786 extract_range_from_unary_expr (vr, TREE_CODE (expr), TREE_TYPE (expr),
6787 &vr0, TREE_TYPE (TREE_OPERAND (expr, 0)));
6789 else if (TREE_CODE (expr) == INTEGER_CST)
6790 set_value_range_to_value (vr, expr, NULL);
6791 else
6793 value_range_type kind;
6794 wide_int min, max;
6795 /* For SSA names try to extract range info computed by VRP. Otherwise
6796 fall back to varying. */
6797 if (TREE_CODE (expr) == SSA_NAME
6798 && INTEGRAL_TYPE_P (TREE_TYPE (expr))
6799 && (kind = get_range_info (expr, &min, &max)) != VR_VARYING)
6800 set_value_range (vr, kind, wide_int_to_tree (TREE_TYPE (expr), min),
6801 wide_int_to_tree (TREE_TYPE (expr), max), NULL);
6802 else
6803 set_value_range_to_varying (vr);
6807 /* Compute a value-range for EXPR and set it in *MIN and *MAX. Return
6808 the determined range type. */
6810 value_range_type
6811 determine_value_range (tree expr, wide_int *min, wide_int *max)
6813 value_range vr = VR_INITIALIZER;
6814 determine_value_range_1 (&vr, expr);
6815 if ((vr.type == VR_RANGE
6816 || vr.type == VR_ANTI_RANGE)
6817 && !symbolic_range_p (&vr))
6819 *min = wi::to_wide (vr.min);
6820 *max = wi::to_wide (vr.max);
6821 return vr.type;
6824 return VR_VARYING;