* builtins.h (c_srlen): Add argument.
[official-gcc.git] / gcc / tree-vrp.c
blobd26011a9e66394456cd45ae88f5ff54d6a0c46d1
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, const 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 static inline bool
508 range_is_null (const value_range *vr)
510 return vr->type == VR_RANGE
511 && integer_zerop (vr->min)
512 && integer_zerop (vr->max);
515 /* Return true if max and min of VR are INTEGER_CST. It's not necessary
516 a singleton. */
518 bool
519 range_int_cst_p (const value_range *vr)
521 return (vr->type == VR_RANGE
522 && TREE_CODE (vr->max) == INTEGER_CST
523 && TREE_CODE (vr->min) == INTEGER_CST);
526 /* Return true if VR is a INTEGER_CST singleton. */
528 bool
529 range_int_cst_singleton_p (const value_range *vr)
531 return (range_int_cst_p (vr)
532 && tree_int_cst_equal (vr->min, vr->max));
535 /* Return true if value range VR involves at least one symbol. */
537 bool
538 symbolic_range_p (const value_range *vr)
540 return (!is_gimple_min_invariant (vr->min)
541 || !is_gimple_min_invariant (vr->max));
544 /* Return the single symbol (an SSA_NAME) contained in T if any, or NULL_TREE
545 otherwise. We only handle additive operations and set NEG to true if the
546 symbol is negated and INV to the invariant part, if any. */
548 tree
549 get_single_symbol (tree t, bool *neg, tree *inv)
551 bool neg_;
552 tree inv_;
554 *inv = NULL_TREE;
555 *neg = false;
557 if (TREE_CODE (t) == PLUS_EXPR
558 || TREE_CODE (t) == POINTER_PLUS_EXPR
559 || TREE_CODE (t) == MINUS_EXPR)
561 if (is_gimple_min_invariant (TREE_OPERAND (t, 0)))
563 neg_ = (TREE_CODE (t) == MINUS_EXPR);
564 inv_ = TREE_OPERAND (t, 0);
565 t = TREE_OPERAND (t, 1);
567 else if (is_gimple_min_invariant (TREE_OPERAND (t, 1)))
569 neg_ = false;
570 inv_ = TREE_OPERAND (t, 1);
571 t = TREE_OPERAND (t, 0);
573 else
574 return NULL_TREE;
576 else
578 neg_ = false;
579 inv_ = NULL_TREE;
582 if (TREE_CODE (t) == NEGATE_EXPR)
584 t = TREE_OPERAND (t, 0);
585 neg_ = !neg_;
588 if (TREE_CODE (t) != SSA_NAME)
589 return NULL_TREE;
591 if (inv_ && TREE_OVERFLOW_P (inv_))
592 inv_ = drop_tree_overflow (inv_);
594 *neg = neg_;
595 *inv = inv_;
596 return t;
599 /* The reverse operation: build a symbolic expression with TYPE
600 from symbol SYM, negated according to NEG, and invariant INV. */
602 static tree
603 build_symbolic_expr (tree type, tree sym, bool neg, tree inv)
605 const bool pointer_p = POINTER_TYPE_P (type);
606 tree t = sym;
608 if (neg)
609 t = build1 (NEGATE_EXPR, type, t);
611 if (integer_zerop (inv))
612 return t;
614 return build2 (pointer_p ? POINTER_PLUS_EXPR : PLUS_EXPR, type, t, inv);
617 /* Return
618 1 if VAL < VAL2
619 0 if !(VAL < VAL2)
620 -2 if those are incomparable. */
622 operand_less_p (tree val, tree val2)
624 /* LT is folded faster than GE and others. Inline the common case. */
625 if (TREE_CODE (val) == INTEGER_CST && TREE_CODE (val2) == INTEGER_CST)
626 return tree_int_cst_lt (val, val2);
627 else
629 tree tcmp;
631 fold_defer_overflow_warnings ();
633 tcmp = fold_binary_to_constant (LT_EXPR, boolean_type_node, val, val2);
635 fold_undefer_and_ignore_overflow_warnings ();
637 if (!tcmp
638 || TREE_CODE (tcmp) != INTEGER_CST)
639 return -2;
641 if (!integer_zerop (tcmp))
642 return 1;
645 return 0;
648 /* Compare two values VAL1 and VAL2. Return
650 -2 if VAL1 and VAL2 cannot be compared at compile-time,
651 -1 if VAL1 < VAL2,
652 0 if VAL1 == VAL2,
653 +1 if VAL1 > VAL2, and
654 +2 if VAL1 != VAL2
656 This is similar to tree_int_cst_compare but supports pointer values
657 and values that cannot be compared at compile time.
659 If STRICT_OVERFLOW_P is not NULL, then set *STRICT_OVERFLOW_P to
660 true if the return value is only valid if we assume that signed
661 overflow is undefined. */
664 compare_values_warnv (tree val1, tree val2, bool *strict_overflow_p)
666 if (val1 == val2)
667 return 0;
669 /* Below we rely on the fact that VAL1 and VAL2 are both pointers or
670 both integers. */
671 gcc_assert (POINTER_TYPE_P (TREE_TYPE (val1))
672 == POINTER_TYPE_P (TREE_TYPE (val2)));
674 /* Convert the two values into the same type. This is needed because
675 sizetype causes sign extension even for unsigned types. */
676 val2 = fold_convert (TREE_TYPE (val1), val2);
677 STRIP_USELESS_TYPE_CONVERSION (val2);
679 const bool overflow_undefined
680 = INTEGRAL_TYPE_P (TREE_TYPE (val1))
681 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1));
682 tree inv1, inv2;
683 bool neg1, neg2;
684 tree sym1 = get_single_symbol (val1, &neg1, &inv1);
685 tree sym2 = get_single_symbol (val2, &neg2, &inv2);
687 /* If VAL1 and VAL2 are of the form '[-]NAME [+ CST]', return -1 or +1
688 accordingly. If VAL1 and VAL2 don't use the same name, return -2. */
689 if (sym1 && sym2)
691 /* Both values must use the same name with the same sign. */
692 if (sym1 != sym2 || neg1 != neg2)
693 return -2;
695 /* [-]NAME + CST == [-]NAME + CST. */
696 if (inv1 == inv2)
697 return 0;
699 /* If overflow is defined we cannot simplify more. */
700 if (!overflow_undefined)
701 return -2;
703 if (strict_overflow_p != NULL
704 /* Symbolic range building sets TREE_NO_WARNING to declare
705 that overflow doesn't happen. */
706 && (!inv1 || !TREE_NO_WARNING (val1))
707 && (!inv2 || !TREE_NO_WARNING (val2)))
708 *strict_overflow_p = true;
710 if (!inv1)
711 inv1 = build_int_cst (TREE_TYPE (val1), 0);
712 if (!inv2)
713 inv2 = build_int_cst (TREE_TYPE (val2), 0);
715 return wi::cmp (wi::to_wide (inv1), wi::to_wide (inv2),
716 TYPE_SIGN (TREE_TYPE (val1)));
719 const bool cst1 = is_gimple_min_invariant (val1);
720 const bool cst2 = is_gimple_min_invariant (val2);
722 /* If one is of the form '[-]NAME + CST' and the other is constant, then
723 it might be possible to say something depending on the constants. */
724 if ((sym1 && inv1 && cst2) || (sym2 && inv2 && cst1))
726 if (!overflow_undefined)
727 return -2;
729 if (strict_overflow_p != NULL
730 /* Symbolic range building sets TREE_NO_WARNING to declare
731 that overflow doesn't happen. */
732 && (!sym1 || !TREE_NO_WARNING (val1))
733 && (!sym2 || !TREE_NO_WARNING (val2)))
734 *strict_overflow_p = true;
736 const signop sgn = TYPE_SIGN (TREE_TYPE (val1));
737 tree cst = cst1 ? val1 : val2;
738 tree inv = cst1 ? inv2 : inv1;
740 /* Compute the difference between the constants. If it overflows or
741 underflows, this means that we can trivially compare the NAME with
742 it and, consequently, the two values with each other. */
743 wide_int diff = wi::to_wide (cst) - wi::to_wide (inv);
744 if (wi::cmp (0, wi::to_wide (inv), sgn)
745 != wi::cmp (diff, wi::to_wide (cst), sgn))
747 const int res = wi::cmp (wi::to_wide (cst), wi::to_wide (inv), sgn);
748 return cst1 ? res : -res;
751 return -2;
754 /* We cannot say anything more for non-constants. */
755 if (!cst1 || !cst2)
756 return -2;
758 if (!POINTER_TYPE_P (TREE_TYPE (val1)))
760 /* We cannot compare overflowed values. */
761 if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
762 return -2;
764 if (TREE_CODE (val1) == INTEGER_CST
765 && TREE_CODE (val2) == INTEGER_CST)
766 return tree_int_cst_compare (val1, val2);
768 if (poly_int_tree_p (val1) && poly_int_tree_p (val2))
770 if (known_eq (wi::to_poly_widest (val1),
771 wi::to_poly_widest (val2)))
772 return 0;
773 if (known_lt (wi::to_poly_widest (val1),
774 wi::to_poly_widest (val2)))
775 return -1;
776 if (known_gt (wi::to_poly_widest (val1),
777 wi::to_poly_widest (val2)))
778 return 1;
781 return -2;
783 else
785 tree t;
787 /* First see if VAL1 and VAL2 are not the same. */
788 if (val1 == val2 || operand_equal_p (val1, val2, 0))
789 return 0;
791 /* If VAL1 is a lower address than VAL2, return -1. */
792 if (operand_less_p (val1, val2) == 1)
793 return -1;
795 /* If VAL1 is a higher address than VAL2, return +1. */
796 if (operand_less_p (val2, val1) == 1)
797 return 1;
799 /* If VAL1 is different than VAL2, return +2.
800 For integer constants we either have already returned -1 or 1
801 or they are equivalent. We still might succeed in proving
802 something about non-trivial operands. */
803 if (TREE_CODE (val1) != INTEGER_CST
804 || TREE_CODE (val2) != INTEGER_CST)
806 t = fold_binary_to_constant (NE_EXPR, boolean_type_node, val1, val2);
807 if (t && integer_onep (t))
808 return 2;
811 return -2;
815 /* Compare values like compare_values_warnv. */
818 compare_values (tree val1, tree val2)
820 bool sop;
821 return compare_values_warnv (val1, val2, &sop);
825 /* Return 1 if VAL is inside value range MIN <= VAL <= MAX,
826 0 if VAL is not inside [MIN, MAX],
827 -2 if we cannot tell either way.
829 Benchmark compile/20001226-1.c compilation time after changing this
830 function. */
833 value_inside_range (tree val, tree min, tree max)
835 int cmp1, cmp2;
837 cmp1 = operand_less_p (val, min);
838 if (cmp1 == -2)
839 return -2;
840 if (cmp1 == 1)
841 return 0;
843 cmp2 = operand_less_p (max, val);
844 if (cmp2 == -2)
845 return -2;
847 return !cmp2;
851 /* Return true if value ranges VR0 and VR1 have a non-empty
852 intersection.
854 Benchmark compile/20001226-1.c compilation time after changing this
855 function.
858 static inline bool
859 value_ranges_intersect_p (const value_range *vr0, const value_range *vr1)
861 /* The value ranges do not intersect if the maximum of the first range is
862 less than the minimum of the second range or vice versa.
863 When those relations are unknown, we can't do any better. */
864 if (operand_less_p (vr0->max, vr1->min) != 0)
865 return false;
866 if (operand_less_p (vr1->max, vr0->min) != 0)
867 return false;
868 return true;
872 /* Return TRUE if *VR includes the value zero. */
874 bool
875 range_includes_zero_p (const value_range *vr)
877 if (vr->type == VR_VARYING)
878 return true;
880 /* Ughh, we don't know. We choose not to optimize. */
881 if (vr->type == VR_UNDEFINED)
882 return true;
884 tree zero = build_int_cst (TREE_TYPE (vr->min), 0);
885 if (vr->type == VR_ANTI_RANGE)
887 int res = value_inside_range (zero, vr->min, vr->max);
888 return res == 0 || res == -2;
890 return value_inside_range (zero, vr->min, vr->max) != 0;
893 /* Return true if *VR is know to only contain nonnegative values. */
895 static inline bool
896 value_range_nonnegative_p (const 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 (const 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 const 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 (const 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 (const value_range *vr,
1003 signop sign, unsigned prec,
1004 wide_int &wmin, wide_int &wmax)
1006 if ((vr->type == VR_RANGE
1007 || vr->type == VR_ANTI_RANGE)
1008 && TREE_CODE (vr->min) == INTEGER_CST
1009 && TREE_CODE (vr->max) == INTEGER_CST)
1011 wmin = wi::to_wide (vr->min);
1012 wmax = wi::to_wide (vr->max);
1014 else
1016 wmin = wi::min_value (prec, sign);
1017 wmax = wi::max_value (prec, sign);
1021 /* Value range wrapper for wide_int_range_multiplicative_op:
1023 *VR = *VR0 .CODE. *VR1. */
1025 static void
1026 extract_range_from_multiplicative_op (value_range *vr,
1027 enum tree_code code,
1028 const value_range *vr0,
1029 const value_range *vr1)
1031 gcc_assert (code == MULT_EXPR
1032 || code == TRUNC_DIV_EXPR
1033 || code == FLOOR_DIV_EXPR
1034 || code == CEIL_DIV_EXPR
1035 || code == EXACT_DIV_EXPR
1036 || code == ROUND_DIV_EXPR
1037 || code == RSHIFT_EXPR
1038 || code == LSHIFT_EXPR);
1039 gcc_assert (vr0->type == VR_RANGE && vr0->type == vr1->type);
1041 tree type = TREE_TYPE (vr0->min);
1042 wide_int res_lb, res_ub;
1043 wide_int vr0_lb = wi::to_wide (vr0->min);
1044 wide_int vr0_ub = wi::to_wide (vr0->max);
1045 wide_int vr1_lb = wi::to_wide (vr1->min);
1046 wide_int vr1_ub = wi::to_wide (vr1->max);
1047 bool overflow_undefined = TYPE_OVERFLOW_UNDEFINED (type);
1048 bool overflow_wraps = TYPE_OVERFLOW_WRAPS (type);
1049 unsigned prec = TYPE_PRECISION (type);
1051 if (wide_int_range_multiplicative_op (res_lb, res_ub,
1052 code, TYPE_SIGN (type), prec,
1053 vr0_lb, vr0_ub, vr1_lb, vr1_ub,
1054 overflow_undefined, overflow_wraps))
1055 set_and_canonicalize_value_range (vr, VR_RANGE,
1056 wide_int_to_tree (type, res_lb),
1057 wide_int_to_tree (type, res_ub), NULL);
1058 else
1059 set_value_range_to_varying (vr);
1062 /* If BOUND will include a symbolic bound, adjust it accordingly,
1063 otherwise leave it as is.
1065 CODE is the original operation that combined the bounds (PLUS_EXPR
1066 or MINUS_EXPR).
1068 TYPE is the type of the original operation.
1070 SYM_OPn is the symbolic for OPn if it has a symbolic.
1072 NEG_OPn is TRUE if the OPn was negated. */
1074 static void
1075 adjust_symbolic_bound (tree &bound, enum tree_code code, tree type,
1076 tree sym_op0, tree sym_op1,
1077 bool neg_op0, bool neg_op1)
1079 bool minus_p = (code == MINUS_EXPR);
1080 /* If the result bound is constant, we're done; otherwise, build the
1081 symbolic lower bound. */
1082 if (sym_op0 == sym_op1)
1084 else if (sym_op0)
1085 bound = build_symbolic_expr (type, sym_op0,
1086 neg_op0, bound);
1087 else if (sym_op1)
1089 /* We may not negate if that might introduce
1090 undefined overflow. */
1091 if (!minus_p
1092 || neg_op1
1093 || TYPE_OVERFLOW_WRAPS (type))
1094 bound = build_symbolic_expr (type, sym_op1,
1095 neg_op1 ^ minus_p, bound);
1096 else
1097 bound = NULL_TREE;
1101 /* Combine OP1 and OP1, which are two parts of a bound, into one wide
1102 int bound according to CODE. CODE is the operation combining the
1103 bound (either a PLUS_EXPR or a MINUS_EXPR).
1105 TYPE is the type of the combine operation.
1107 WI is the wide int to store the result.
1109 OVF is -1 if an underflow occurred, +1 if an overflow occurred or 0
1110 if over/underflow occurred. */
1112 static void
1113 combine_bound (enum tree_code code, wide_int &wi, wi::overflow_type &ovf,
1114 tree type, tree op0, tree op1)
1116 bool minus_p = (code == MINUS_EXPR);
1117 const signop sgn = TYPE_SIGN (type);
1118 const unsigned int prec = TYPE_PRECISION (type);
1120 /* Combine the bounds, if any. */
1121 if (op0 && op1)
1123 if (minus_p)
1124 wi = wi::sub (wi::to_wide (op0), wi::to_wide (op1), sgn, &ovf);
1125 else
1126 wi = wi::add (wi::to_wide (op0), wi::to_wide (op1), sgn, &ovf);
1128 else if (op0)
1129 wi = wi::to_wide (op0);
1130 else if (op1)
1132 if (minus_p)
1133 wi = wi::neg (wi::to_wide (op1), &ovf);
1134 else
1135 wi = wi::to_wide (op1);
1137 else
1138 wi = wi::shwi (0, prec);
1141 /* Given a range in [WMIN, WMAX], adjust it for possible overflow and
1142 put the result in VR.
1144 TYPE is the type of the range.
1146 MIN_OVF and MAX_OVF indicate what type of overflow, if any,
1147 occurred while originally calculating WMIN or WMAX. -1 indicates
1148 underflow. +1 indicates overflow. 0 indicates neither. */
1150 static void
1151 set_value_range_with_overflow (value_range &vr,
1152 tree type,
1153 const wide_int &wmin, const wide_int &wmax,
1154 wi::overflow_type min_ovf,
1155 wi::overflow_type max_ovf)
1157 const signop sgn = TYPE_SIGN (type);
1158 const unsigned int prec = TYPE_PRECISION (type);
1159 vr.type = VR_RANGE;
1160 vr.equiv = NULL;
1161 if (TYPE_OVERFLOW_WRAPS (type))
1163 /* If overflow wraps, truncate the values and adjust the
1164 range kind and bounds appropriately. */
1165 wide_int tmin = wide_int::from (wmin, prec, sgn);
1166 wide_int tmax = wide_int::from (wmax, prec, sgn);
1167 if ((min_ovf != wi::OVF_NONE) == (max_ovf != wi::OVF_NONE))
1169 /* No overflow or both overflow or underflow. The
1170 range kind stays VR_RANGE. */
1171 vr.min = wide_int_to_tree (type, tmin);
1172 vr.max = wide_int_to_tree (type, tmax);
1174 else if ((min_ovf == wi::OVF_UNDERFLOW && max_ovf == wi::OVF_NONE)
1175 || (max_ovf == wi::OVF_OVERFLOW && min_ovf == wi::OVF_NONE))
1177 /* Min underflow or max overflow. The range kind
1178 changes to VR_ANTI_RANGE. */
1179 bool covers = false;
1180 wide_int tem = tmin;
1181 vr.type = VR_ANTI_RANGE;
1182 tmin = tmax + 1;
1183 if (wi::cmp (tmin, tmax, sgn) < 0)
1184 covers = true;
1185 tmax = tem - 1;
1186 if (wi::cmp (tmax, tem, sgn) > 0)
1187 covers = true;
1188 /* If the anti-range would cover nothing, drop to varying.
1189 Likewise if the anti-range bounds are outside of the
1190 types values. */
1191 if (covers || wi::cmp (tmin, tmax, sgn) > 0)
1193 set_value_range_to_varying (&vr);
1194 return;
1196 vr.min = wide_int_to_tree (type, tmin);
1197 vr.max = wide_int_to_tree (type, tmax);
1199 else
1201 /* Other underflow and/or overflow, drop to VR_VARYING. */
1202 set_value_range_to_varying (&vr);
1203 return;
1206 else
1208 /* If overflow does not wrap, saturate to the types min/max
1209 value. */
1210 wide_int type_min = wi::min_value (prec, sgn);
1211 wide_int type_max = wi::max_value (prec, sgn);
1212 if (min_ovf == wi::OVF_UNDERFLOW)
1213 vr.min = wide_int_to_tree (type, type_min);
1214 else if (min_ovf == wi::OVF_OVERFLOW)
1215 vr.min = wide_int_to_tree (type, type_max);
1216 else
1217 vr.min = wide_int_to_tree (type, wmin);
1219 if (max_ovf == wi::OVF_UNDERFLOW)
1220 vr.max = wide_int_to_tree (type, type_min);
1221 else if (max_ovf == wi::OVF_OVERFLOW)
1222 vr.max = wide_int_to_tree (type, type_max);
1223 else
1224 vr.max = wide_int_to_tree (type, wmax);
1228 /* Extract range information from a binary operation CODE based on
1229 the ranges of each of its operands *VR0 and *VR1 with resulting
1230 type EXPR_TYPE. The resulting range is stored in *VR. */
1232 void
1233 extract_range_from_binary_expr_1 (value_range *vr,
1234 enum tree_code code, tree expr_type,
1235 const value_range *vr0_,
1236 const value_range *vr1_)
1238 signop sign = TYPE_SIGN (expr_type);
1239 unsigned int prec = TYPE_PRECISION (expr_type);
1240 value_range vr0 = *vr0_, vr1 = *vr1_;
1241 value_range vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
1242 enum value_range_type type;
1243 tree min = NULL_TREE, max = NULL_TREE;
1244 int cmp;
1246 if (!INTEGRAL_TYPE_P (expr_type)
1247 && !POINTER_TYPE_P (expr_type))
1249 set_value_range_to_varying (vr);
1250 return;
1253 /* Not all binary expressions can be applied to ranges in a
1254 meaningful way. Handle only arithmetic operations. */
1255 if (code != PLUS_EXPR
1256 && code != MINUS_EXPR
1257 && code != POINTER_PLUS_EXPR
1258 && code != MULT_EXPR
1259 && code != TRUNC_DIV_EXPR
1260 && code != FLOOR_DIV_EXPR
1261 && code != CEIL_DIV_EXPR
1262 && code != EXACT_DIV_EXPR
1263 && code != ROUND_DIV_EXPR
1264 && code != TRUNC_MOD_EXPR
1265 && code != RSHIFT_EXPR
1266 && code != LSHIFT_EXPR
1267 && code != MIN_EXPR
1268 && code != MAX_EXPR
1269 && code != BIT_AND_EXPR
1270 && code != BIT_IOR_EXPR
1271 && code != BIT_XOR_EXPR)
1273 set_value_range_to_varying (vr);
1274 return;
1277 /* If both ranges are UNDEFINED, so is the result. */
1278 if (vr0.type == VR_UNDEFINED && vr1.type == VR_UNDEFINED)
1280 set_value_range_to_undefined (vr);
1281 return;
1283 /* If one of the ranges is UNDEFINED drop it to VARYING for the following
1284 code. At some point we may want to special-case operations that
1285 have UNDEFINED result for all or some value-ranges of the not UNDEFINED
1286 operand. */
1287 else if (vr0.type == VR_UNDEFINED)
1288 set_value_range_to_varying (&vr0);
1289 else if (vr1.type == VR_UNDEFINED)
1290 set_value_range_to_varying (&vr1);
1292 /* We get imprecise results from ranges_from_anti_range when
1293 code is EXACT_DIV_EXPR. We could mask out bits in the resulting
1294 range, but then we also need to hack up vrp_meet. It's just
1295 easier to special case when vr0 is ~[0,0] for EXACT_DIV_EXPR. */
1296 if (code == EXACT_DIV_EXPR
1297 && vr0.type == VR_ANTI_RANGE
1298 && vr0.min == vr0.max
1299 && integer_zerop (vr0.min))
1301 set_value_range_to_nonnull (vr, expr_type);
1302 return;
1305 /* Now canonicalize anti-ranges to ranges when they are not symbolic
1306 and express ~[] op X as ([]' op X) U ([]'' op X). */
1307 if (vr0.type == VR_ANTI_RANGE
1308 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
1310 extract_range_from_binary_expr_1 (vr, code, expr_type, &vrtem0, vr1_);
1311 if (vrtem1.type != VR_UNDEFINED)
1313 value_range vrres = VR_INITIALIZER;
1314 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
1315 &vrtem1, vr1_);
1316 vrp_meet (vr, &vrres);
1318 return;
1320 /* Likewise for X op ~[]. */
1321 if (vr1.type == VR_ANTI_RANGE
1322 && ranges_from_anti_range (&vr1, &vrtem0, &vrtem1))
1324 extract_range_from_binary_expr_1 (vr, code, expr_type, vr0_, &vrtem0);
1325 if (vrtem1.type != VR_UNDEFINED)
1327 value_range vrres = VR_INITIALIZER;
1328 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
1329 vr0_, &vrtem1);
1330 vrp_meet (vr, &vrres);
1332 return;
1335 /* The type of the resulting value range defaults to VR0.TYPE. */
1336 type = vr0.type;
1338 /* Refuse to operate on VARYING ranges, ranges of different kinds
1339 and symbolic ranges. As an exception, we allow BIT_{AND,IOR}
1340 because we may be able to derive a useful range even if one of
1341 the operands is VR_VARYING or symbolic range. Similarly for
1342 divisions, MIN/MAX and PLUS/MINUS.
1344 TODO, we may be able to derive anti-ranges in some cases. */
1345 if (code != BIT_AND_EXPR
1346 && code != BIT_IOR_EXPR
1347 && code != TRUNC_DIV_EXPR
1348 && code != FLOOR_DIV_EXPR
1349 && code != CEIL_DIV_EXPR
1350 && code != EXACT_DIV_EXPR
1351 && code != ROUND_DIV_EXPR
1352 && code != TRUNC_MOD_EXPR
1353 && code != MIN_EXPR
1354 && code != MAX_EXPR
1355 && code != PLUS_EXPR
1356 && code != MINUS_EXPR
1357 && code != RSHIFT_EXPR
1358 && code != POINTER_PLUS_EXPR
1359 && (vr0.type == VR_VARYING
1360 || vr1.type == VR_VARYING
1361 || vr0.type != vr1.type
1362 || symbolic_range_p (&vr0)
1363 || symbolic_range_p (&vr1)))
1365 set_value_range_to_varying (vr);
1366 return;
1369 /* Now evaluate the expression to determine the new range. */
1370 if (POINTER_TYPE_P (expr_type))
1372 if (code == MIN_EXPR || code == MAX_EXPR)
1374 /* For MIN/MAX expressions with pointers, we only care about
1375 nullness, if both are non null, then the result is nonnull.
1376 If both are null, then the result is null. Otherwise they
1377 are varying. */
1378 if (!range_includes_zero_p (&vr0) && !range_includes_zero_p (&vr1))
1379 set_value_range_to_nonnull (vr, expr_type);
1380 else if (range_is_null (&vr0) && range_is_null (&vr1))
1381 set_value_range_to_null (vr, expr_type);
1382 else
1383 set_value_range_to_varying (vr);
1385 else if (code == POINTER_PLUS_EXPR)
1387 /* For pointer types, we are really only interested in asserting
1388 whether the expression evaluates to non-NULL. */
1389 if (!range_includes_zero_p (&vr0)
1390 || !range_includes_zero_p (&vr1))
1391 set_value_range_to_nonnull (vr, expr_type);
1392 else if (range_is_null (&vr0) && range_is_null (&vr1))
1393 set_value_range_to_null (vr, expr_type);
1394 else
1395 set_value_range_to_varying (vr);
1397 else if (code == BIT_AND_EXPR)
1399 /* For pointer types, we are really only interested in asserting
1400 whether the expression evaluates to non-NULL. */
1401 if (!range_includes_zero_p (&vr0) && !range_includes_zero_p (&vr1))
1402 set_value_range_to_nonnull (vr, expr_type);
1403 else if (range_is_null (&vr0) || range_is_null (&vr1))
1404 set_value_range_to_null (vr, expr_type);
1405 else
1406 set_value_range_to_varying (vr);
1408 else
1409 set_value_range_to_varying (vr);
1411 return;
1414 /* For integer ranges, apply the operation to each end of the
1415 range and see what we end up with. */
1416 if (code == PLUS_EXPR || code == MINUS_EXPR)
1418 const bool minus_p = (code == MINUS_EXPR);
1419 tree min_op0 = vr0.min;
1420 tree min_op1 = minus_p ? vr1.max : vr1.min;
1421 tree max_op0 = vr0.max;
1422 tree max_op1 = minus_p ? vr1.min : vr1.max;
1423 tree sym_min_op0 = NULL_TREE;
1424 tree sym_min_op1 = NULL_TREE;
1425 tree sym_max_op0 = NULL_TREE;
1426 tree sym_max_op1 = NULL_TREE;
1427 bool neg_min_op0, neg_min_op1, neg_max_op0, neg_max_op1;
1429 neg_min_op0 = neg_min_op1 = neg_max_op0 = neg_max_op1 = false;
1431 /* If we have a PLUS or MINUS with two VR_RANGEs, either constant or
1432 single-symbolic ranges, try to compute the precise resulting range,
1433 but only if we know that this resulting range will also be constant
1434 or single-symbolic. */
1435 if (vr0.type == VR_RANGE && vr1.type == VR_RANGE
1436 && (TREE_CODE (min_op0) == INTEGER_CST
1437 || (sym_min_op0
1438 = get_single_symbol (min_op0, &neg_min_op0, &min_op0)))
1439 && (TREE_CODE (min_op1) == INTEGER_CST
1440 || (sym_min_op1
1441 = get_single_symbol (min_op1, &neg_min_op1, &min_op1)))
1442 && (!(sym_min_op0 && sym_min_op1)
1443 || (sym_min_op0 == sym_min_op1
1444 && neg_min_op0 == (minus_p ? neg_min_op1 : !neg_min_op1)))
1445 && (TREE_CODE (max_op0) == INTEGER_CST
1446 || (sym_max_op0
1447 = get_single_symbol (max_op0, &neg_max_op0, &max_op0)))
1448 && (TREE_CODE (max_op1) == INTEGER_CST
1449 || (sym_max_op1
1450 = get_single_symbol (max_op1, &neg_max_op1, &max_op1)))
1451 && (!(sym_max_op0 && sym_max_op1)
1452 || (sym_max_op0 == sym_max_op1
1453 && neg_max_op0 == (minus_p ? neg_max_op1 : !neg_max_op1))))
1455 wide_int wmin, wmax;
1456 wi::overflow_type min_ovf = wi::OVF_NONE;
1457 wi::overflow_type max_ovf = wi::OVF_NONE;
1459 /* Build the bounds. */
1460 combine_bound (code, wmin, min_ovf, expr_type, min_op0, min_op1);
1461 combine_bound (code, wmax, max_ovf, expr_type, max_op0, max_op1);
1463 /* If we have overflow for the constant part and the resulting
1464 range will be symbolic, drop to VR_VARYING. */
1465 if (((bool)min_ovf && sym_min_op0 != sym_min_op1)
1466 || ((bool)max_ovf && sym_max_op0 != sym_max_op1))
1468 set_value_range_to_varying (vr);
1469 return;
1472 /* Adjust the range for possible overflow. */
1473 set_value_range_with_overflow (*vr, expr_type,
1474 wmin, wmax, min_ovf, max_ovf);
1475 if (vr->type == VR_VARYING)
1476 return;
1478 /* Build the symbolic bounds if needed. */
1479 adjust_symbolic_bound (vr->min, code, expr_type,
1480 sym_min_op0, sym_min_op1,
1481 neg_min_op0, neg_min_op1);
1482 adjust_symbolic_bound (vr->max, code, expr_type,
1483 sym_max_op0, sym_max_op1,
1484 neg_max_op0, neg_max_op1);
1485 /* ?? It would probably be cleaner to eliminate min/max/type
1486 entirely and hold these values in VR directly. */
1487 min = vr->min;
1488 max = vr->max;
1489 type = vr->type;
1491 else
1493 /* For other cases, for example if we have a PLUS_EXPR with two
1494 VR_ANTI_RANGEs, drop to VR_VARYING. It would take more effort
1495 to compute a precise range for such a case.
1496 ??? General even mixed range kind operations can be expressed
1497 by for example transforming ~[3, 5] + [1, 2] to range-only
1498 operations and a union primitive:
1499 [-INF, 2] + [1, 2] U [5, +INF] + [1, 2]
1500 [-INF+1, 4] U [6, +INF(OVF)]
1501 though usually the union is not exactly representable with
1502 a single range or anti-range as the above is
1503 [-INF+1, +INF(OVF)] intersected with ~[5, 5]
1504 but one could use a scheme similar to equivalences for this. */
1505 set_value_range_to_varying (vr);
1506 return;
1509 else if (code == MIN_EXPR
1510 || code == MAX_EXPR)
1512 wide_int wmin, wmax;
1513 wide_int vr0_min, vr0_max;
1514 wide_int vr1_min, vr1_max;
1515 extract_range_into_wide_ints (&vr0, sign, prec, vr0_min, vr0_max);
1516 extract_range_into_wide_ints (&vr1, sign, prec, vr1_min, vr1_max);
1517 if (wide_int_range_min_max (wmin, wmax, code, sign, prec,
1518 vr0_min, vr0_max, vr1_min, vr1_max))
1519 set_value_range (vr, VR_RANGE,
1520 wide_int_to_tree (expr_type, wmin),
1521 wide_int_to_tree (expr_type, wmax), NULL);
1522 else
1523 set_value_range_to_varying (vr);
1524 return;
1526 else if (code == MULT_EXPR)
1528 if (!range_int_cst_p (&vr0)
1529 || !range_int_cst_p (&vr1))
1531 set_value_range_to_varying (vr);
1532 return;
1534 extract_range_from_multiplicative_op (vr, code, &vr0, &vr1);
1535 return;
1537 else if (code == RSHIFT_EXPR
1538 || code == LSHIFT_EXPR)
1540 if (range_int_cst_p (&vr1)
1541 && !wide_int_range_shift_undefined_p (prec,
1542 wi::to_wide (vr1.min),
1543 wi::to_wide (vr1.max)))
1545 if (code == RSHIFT_EXPR)
1547 /* Even if vr0 is VARYING or otherwise not usable, we can derive
1548 useful ranges just from the shift count. E.g.
1549 x >> 63 for signed 64-bit x is always [-1, 0]. */
1550 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
1552 vr0.type = type = VR_RANGE;
1553 vr0.min = vrp_val_min (expr_type);
1554 vr0.max = vrp_val_max (expr_type);
1556 extract_range_from_multiplicative_op (vr, code, &vr0, &vr1);
1557 return;
1559 else if (code == LSHIFT_EXPR
1560 && range_int_cst_p (&vr0))
1562 wide_int res_lb, res_ub;
1563 if (wide_int_range_lshift (res_lb, res_ub, sign, prec,
1564 wi::to_wide (vr0.min),
1565 wi::to_wide (vr0.max),
1566 wi::to_wide (vr1.min),
1567 wi::to_wide (vr1.max),
1568 TYPE_OVERFLOW_UNDEFINED (expr_type),
1569 TYPE_OVERFLOW_WRAPS (expr_type)))
1571 min = wide_int_to_tree (expr_type, res_lb);
1572 max = wide_int_to_tree (expr_type, res_ub);
1573 set_and_canonicalize_value_range (vr, VR_RANGE,
1574 min, max, NULL);
1575 return;
1579 set_value_range_to_varying (vr);
1580 return;
1582 else if (code == TRUNC_DIV_EXPR
1583 || code == FLOOR_DIV_EXPR
1584 || code == CEIL_DIV_EXPR
1585 || code == EXACT_DIV_EXPR
1586 || code == ROUND_DIV_EXPR)
1588 wide_int dividend_min, dividend_max, divisor_min, divisor_max;
1589 wide_int wmin, wmax, extra_min, extra_max;
1590 bool extra_range_p;
1592 /* Special case explicit division by zero as undefined. */
1593 if (range_is_null (&vr1))
1595 set_value_range_to_undefined (vr);
1596 return;
1599 /* First, normalize ranges into constants we can handle. Note
1600 that VR_ANTI_RANGE's of constants were already normalized
1601 before arriving here.
1603 NOTE: As a future improvement, we may be able to do better
1604 with mixed symbolic (anti-)ranges like [0, A]. See note in
1605 ranges_from_anti_range. */
1606 extract_range_into_wide_ints (&vr0, sign, prec,
1607 dividend_min, dividend_max);
1608 extract_range_into_wide_ints (&vr1, sign, prec,
1609 divisor_min, divisor_max);
1610 if (!wide_int_range_div (wmin, wmax, code, sign, prec,
1611 dividend_min, dividend_max,
1612 divisor_min, divisor_max,
1613 TYPE_OVERFLOW_UNDEFINED (expr_type),
1614 TYPE_OVERFLOW_WRAPS (expr_type),
1615 extra_range_p, extra_min, extra_max))
1617 set_value_range_to_varying (vr);
1618 return;
1620 set_value_range (vr, VR_RANGE,
1621 wide_int_to_tree (expr_type, wmin),
1622 wide_int_to_tree (expr_type, wmax), NULL);
1623 if (extra_range_p)
1625 value_range extra_range = VR_INITIALIZER;
1626 set_value_range (&extra_range, VR_RANGE,
1627 wide_int_to_tree (expr_type, extra_min),
1628 wide_int_to_tree (expr_type, extra_max), NULL);
1629 vrp_meet (vr, &extra_range);
1631 return;
1633 else if (code == TRUNC_MOD_EXPR)
1635 if (range_is_null (&vr1))
1637 set_value_range_to_undefined (vr);
1638 return;
1640 wide_int wmin, wmax, tmp;
1641 wide_int vr0_min, vr0_max, vr1_min, vr1_max;
1642 extract_range_into_wide_ints (&vr0, sign, prec, vr0_min, vr0_max);
1643 extract_range_into_wide_ints (&vr1, sign, prec, vr1_min, vr1_max);
1644 wide_int_range_trunc_mod (wmin, wmax, sign, prec,
1645 vr0_min, vr0_max, vr1_min, vr1_max);
1646 min = wide_int_to_tree (expr_type, wmin);
1647 max = wide_int_to_tree (expr_type, wmax);
1648 set_value_range (vr, VR_RANGE, min, max, NULL);
1649 return;
1651 else if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR || code == BIT_XOR_EXPR)
1653 wide_int may_be_nonzero0, may_be_nonzero1;
1654 wide_int must_be_nonzero0, must_be_nonzero1;
1655 wide_int wmin, wmax;
1656 wide_int vr0_min, vr0_max, vr1_min, vr1_max;
1657 vrp_set_zero_nonzero_bits (expr_type, &vr0,
1658 &may_be_nonzero0, &must_be_nonzero0);
1659 vrp_set_zero_nonzero_bits (expr_type, &vr1,
1660 &may_be_nonzero1, &must_be_nonzero1);
1661 extract_range_into_wide_ints (&vr0, sign, prec, vr0_min, vr0_max);
1662 extract_range_into_wide_ints (&vr1, sign, prec, vr1_min, vr1_max);
1663 if (code == BIT_AND_EXPR)
1665 if (wide_int_range_bit_and (wmin, wmax, sign, prec,
1666 vr0_min, vr0_max,
1667 vr1_min, vr1_max,
1668 must_be_nonzero0,
1669 may_be_nonzero0,
1670 must_be_nonzero1,
1671 may_be_nonzero1))
1673 min = wide_int_to_tree (expr_type, wmin);
1674 max = wide_int_to_tree (expr_type, wmax);
1675 set_value_range (vr, VR_RANGE, min, max, NULL);
1677 else
1678 set_value_range_to_varying (vr);
1679 return;
1681 else if (code == BIT_IOR_EXPR)
1683 if (wide_int_range_bit_ior (wmin, wmax, sign,
1684 vr0_min, vr0_max,
1685 vr1_min, vr1_max,
1686 must_be_nonzero0,
1687 may_be_nonzero0,
1688 must_be_nonzero1,
1689 may_be_nonzero1))
1691 min = wide_int_to_tree (expr_type, wmin);
1692 max = wide_int_to_tree (expr_type, wmax);
1693 set_value_range (vr, VR_RANGE, min, max, NULL);
1695 else
1696 set_value_range_to_varying (vr);
1697 return;
1699 else if (code == BIT_XOR_EXPR)
1701 if (wide_int_range_bit_xor (wmin, wmax, sign, prec,
1702 must_be_nonzero0,
1703 may_be_nonzero0,
1704 must_be_nonzero1,
1705 may_be_nonzero1))
1707 min = wide_int_to_tree (expr_type, wmin);
1708 max = wide_int_to_tree (expr_type, wmax);
1709 set_value_range (vr, VR_RANGE, min, max, NULL);
1711 else
1712 set_value_range_to_varying (vr);
1713 return;
1716 else
1717 gcc_unreachable ();
1719 /* If either MIN or MAX overflowed, then set the resulting range to
1720 VARYING. */
1721 if (min == NULL_TREE
1722 || TREE_OVERFLOW_P (min)
1723 || max == NULL_TREE
1724 || TREE_OVERFLOW_P (max))
1726 set_value_range_to_varying (vr);
1727 return;
1730 /* We punt for [-INF, +INF].
1731 We learn nothing when we have INF on both sides.
1732 Note that we do accept [-INF, -INF] and [+INF, +INF]. */
1733 if (vrp_val_is_min (min) && vrp_val_is_max (max))
1735 set_value_range_to_varying (vr);
1736 return;
1739 cmp = compare_values (min, max);
1740 if (cmp == -2 || cmp == 1)
1742 /* If the new range has its limits swapped around (MIN > MAX),
1743 then the operation caused one of them to wrap around, mark
1744 the new range VARYING. */
1745 set_value_range_to_varying (vr);
1747 else
1748 set_value_range (vr, type, min, max, NULL);
1751 /* Extract range information from a unary operation CODE based on
1752 the range of its operand *VR0 with type OP0_TYPE with resulting type TYPE.
1753 The resulting range is stored in *VR. */
1755 void
1756 extract_range_from_unary_expr (value_range *vr,
1757 enum tree_code code, tree type,
1758 const value_range *vr0_, tree op0_type)
1760 signop sign = TYPE_SIGN (type);
1761 unsigned int prec = TYPE_PRECISION (type);
1762 value_range vr0 = *vr0_, vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
1764 /* VRP only operates on integral and pointer types. */
1765 if (!(INTEGRAL_TYPE_P (op0_type)
1766 || POINTER_TYPE_P (op0_type))
1767 || !(INTEGRAL_TYPE_P (type)
1768 || POINTER_TYPE_P (type)))
1770 set_value_range_to_varying (vr);
1771 return;
1774 /* If VR0 is UNDEFINED, so is the result. */
1775 if (vr0.type == VR_UNDEFINED)
1777 set_value_range_to_undefined (vr);
1778 return;
1781 /* Handle operations that we express in terms of others. */
1782 if (code == PAREN_EXPR || code == OBJ_TYPE_REF)
1784 /* PAREN_EXPR and OBJ_TYPE_REF are simple copies. */
1785 copy_value_range (vr, &vr0);
1786 return;
1788 else if (code == NEGATE_EXPR)
1790 /* -X is simply 0 - X, so re-use existing code that also handles
1791 anti-ranges fine. */
1792 value_range zero = VR_INITIALIZER;
1793 set_value_range_to_value (&zero, build_int_cst (type, 0), NULL);
1794 extract_range_from_binary_expr_1 (vr, MINUS_EXPR, type, &zero, &vr0);
1795 return;
1797 else if (code == BIT_NOT_EXPR)
1799 /* ~X is simply -1 - X, so re-use existing code that also handles
1800 anti-ranges fine. */
1801 value_range minusone = VR_INITIALIZER;
1802 set_value_range_to_value (&minusone, build_int_cst (type, -1), NULL);
1803 extract_range_from_binary_expr_1 (vr, MINUS_EXPR,
1804 type, &minusone, &vr0);
1805 return;
1808 /* Now canonicalize anti-ranges to ranges when they are not symbolic
1809 and express op ~[] as (op []') U (op []''). */
1810 if (vr0.type == VR_ANTI_RANGE
1811 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
1813 extract_range_from_unary_expr (vr, code, type, &vrtem0, op0_type);
1814 if (vrtem1.type != VR_UNDEFINED)
1816 value_range vrres = VR_INITIALIZER;
1817 extract_range_from_unary_expr (&vrres, code, type,
1818 &vrtem1, op0_type);
1819 vrp_meet (vr, &vrres);
1821 return;
1824 if (CONVERT_EXPR_CODE_P (code))
1826 tree inner_type = op0_type;
1827 tree outer_type = type;
1829 /* If the expression evaluates to a pointer, we are only interested in
1830 determining if it evaluates to NULL [0, 0] or non-NULL (~[0, 0]). */
1831 if (POINTER_TYPE_P (type))
1833 if (!range_includes_zero_p (&vr0))
1834 set_value_range_to_nonnull (vr, type);
1835 else if (range_is_null (&vr0))
1836 set_value_range_to_null (vr, type);
1837 else
1838 set_value_range_to_varying (vr);
1839 return;
1842 /* We normalize everything to a VR_RANGE, but for constant
1843 anti-ranges we must handle them by leaving the final result
1844 as an anti range. This allows us to convert things like
1845 ~[0,5] seamlessly. */
1846 value_range_type vr_type = VR_RANGE;
1847 if (vr0.type == VR_ANTI_RANGE
1848 && TREE_CODE (vr0.min) == INTEGER_CST
1849 && TREE_CODE (vr0.max) == INTEGER_CST)
1850 vr_type = VR_ANTI_RANGE;
1852 /* NOTES: Previously we were returning VARYING for all symbolics, but
1853 we can do better by treating them as [-MIN, +MAX]. For
1854 example, converting [SYM, SYM] from INT to LONG UNSIGNED,
1855 we can return: ~[0x8000000, 0xffffffff7fffffff].
1857 We were also failing to convert ~[0,0] from char* to unsigned,
1858 instead choosing to return VR_VARYING. Now we return ~[0,0]. */
1859 wide_int vr0_min, vr0_max, wmin, wmax;
1860 signop inner_sign = TYPE_SIGN (inner_type);
1861 signop outer_sign = TYPE_SIGN (outer_type);
1862 unsigned inner_prec = TYPE_PRECISION (inner_type);
1863 unsigned outer_prec = TYPE_PRECISION (outer_type);
1864 extract_range_into_wide_ints (&vr0, inner_sign, inner_prec,
1865 vr0_min, vr0_max);
1866 if (wide_int_range_convert (wmin, wmax,
1867 inner_sign, inner_prec,
1868 outer_sign, outer_prec,
1869 vr0_min, vr0_max))
1871 tree min = wide_int_to_tree (outer_type, wmin);
1872 tree max = wide_int_to_tree (outer_type, wmax);
1873 set_and_canonicalize_value_range (vr, vr_type, min, max, NULL);
1875 else
1876 set_value_range_to_varying (vr);
1877 return;
1879 else if (code == ABS_EXPR)
1881 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
1883 set_value_range_to_varying (vr);
1884 return;
1886 wide_int wmin, wmax;
1887 wide_int vr0_min, vr0_max;
1888 extract_range_into_wide_ints (&vr0, sign, prec, vr0_min, vr0_max);
1889 if (wide_int_range_abs (wmin, wmax, sign, prec, vr0_min, vr0_max,
1890 TYPE_OVERFLOW_UNDEFINED (type)))
1891 set_value_range (vr, VR_RANGE,
1892 wide_int_to_tree (type, wmin),
1893 wide_int_to_tree (type, wmax), NULL);
1894 else
1895 set_value_range_to_varying (vr);
1896 return;
1899 /* For unhandled operations fall back to varying. */
1900 set_value_range_to_varying (vr);
1901 return;
1904 /* Debugging dumps. */
1906 void dump_value_range (FILE *, const value_range *);
1907 void debug_value_range (const value_range *);
1908 void dump_all_value_ranges (FILE *);
1909 void dump_vr_equiv (FILE *, bitmap);
1910 void debug_vr_equiv (bitmap);
1913 /* Dump value range VR to FILE. */
1915 void
1916 dump_value_range (FILE *file, const value_range *vr)
1918 if (vr == NULL)
1919 fprintf (file, "[]");
1920 else if (vr->type == VR_UNDEFINED)
1921 fprintf (file, "UNDEFINED");
1922 else if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
1924 tree type = TREE_TYPE (vr->min);
1926 fprintf (file, "%s[", (vr->type == VR_ANTI_RANGE) ? "~" : "");
1928 if (INTEGRAL_TYPE_P (type)
1929 && !TYPE_UNSIGNED (type)
1930 && vrp_val_is_min (vr->min))
1931 fprintf (file, "-INF");
1932 else
1933 print_generic_expr (file, vr->min);
1935 fprintf (file, ", ");
1937 if (INTEGRAL_TYPE_P (type)
1938 && vrp_val_is_max (vr->max))
1939 fprintf (file, "+INF");
1940 else
1941 print_generic_expr (file, vr->max);
1943 fprintf (file, "]");
1945 if (vr->equiv)
1947 bitmap_iterator bi;
1948 unsigned i, c = 0;
1950 fprintf (file, " EQUIVALENCES: { ");
1952 EXECUTE_IF_SET_IN_BITMAP (vr->equiv, 0, i, bi)
1954 print_generic_expr (file, ssa_name (i));
1955 fprintf (file, " ");
1956 c++;
1959 fprintf (file, "} (%u elements)", c);
1962 else if (vr->type == VR_VARYING)
1963 fprintf (file, "VARYING");
1964 else
1965 fprintf (file, "INVALID RANGE");
1969 /* Dump value range VR to stderr. */
1971 DEBUG_FUNCTION void
1972 debug_value_range (const value_range *vr)
1974 dump_value_range (stderr, vr);
1975 fprintf (stderr, "\n");
1978 void
1979 value_range::dump () const
1981 debug_value_range (this);
1985 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
1986 create a new SSA name N and return the assertion assignment
1987 'N = ASSERT_EXPR <V, V OP W>'. */
1989 static gimple *
1990 build_assert_expr_for (tree cond, tree v)
1992 tree a;
1993 gassign *assertion;
1995 gcc_assert (TREE_CODE (v) == SSA_NAME
1996 && COMPARISON_CLASS_P (cond));
1998 a = build2 (ASSERT_EXPR, TREE_TYPE (v), v, cond);
1999 assertion = gimple_build_assign (NULL_TREE, a);
2001 /* The new ASSERT_EXPR, creates a new SSA name that replaces the
2002 operand of the ASSERT_EXPR. Create it so the new name and the old one
2003 are registered in the replacement table so that we can fix the SSA web
2004 after adding all the ASSERT_EXPRs. */
2005 tree new_def = create_new_def_for (v, assertion, NULL);
2006 /* Make sure we preserve abnormalness throughout an ASSERT_EXPR chain
2007 given we have to be able to fully propagate those out to re-create
2008 valid SSA when removing the asserts. */
2009 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (v))
2010 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_def) = 1;
2012 return assertion;
2016 /* Return false if EXPR is a predicate expression involving floating
2017 point values. */
2019 static inline bool
2020 fp_predicate (gimple *stmt)
2022 GIMPLE_CHECK (stmt, GIMPLE_COND);
2024 return FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)));
2027 /* If the range of values taken by OP can be inferred after STMT executes,
2028 return the comparison code (COMP_CODE_P) and value (VAL_P) that
2029 describes the inferred range. Return true if a range could be
2030 inferred. */
2032 bool
2033 infer_value_range (gimple *stmt, tree op, tree_code *comp_code_p, tree *val_p)
2035 *val_p = NULL_TREE;
2036 *comp_code_p = ERROR_MARK;
2038 /* Do not attempt to infer anything in names that flow through
2039 abnormal edges. */
2040 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
2041 return false;
2043 /* If STMT is the last statement of a basic block with no normal
2044 successors, there is no point inferring anything about any of its
2045 operands. We would not be able to find a proper insertion point
2046 for the assertion, anyway. */
2047 if (stmt_ends_bb_p (stmt))
2049 edge_iterator ei;
2050 edge e;
2052 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
2053 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
2054 break;
2055 if (e == NULL)
2056 return false;
2059 if (infer_nonnull_range (stmt, op))
2061 *val_p = build_int_cst (TREE_TYPE (op), 0);
2062 *comp_code_p = NE_EXPR;
2063 return true;
2066 return false;
2070 void dump_asserts_for (FILE *, tree);
2071 void debug_asserts_for (tree);
2072 void dump_all_asserts (FILE *);
2073 void debug_all_asserts (void);
2075 /* Dump all the registered assertions for NAME to FILE. */
2077 void
2078 dump_asserts_for (FILE *file, tree name)
2080 assert_locus *loc;
2082 fprintf (file, "Assertions to be inserted for ");
2083 print_generic_expr (file, name);
2084 fprintf (file, "\n");
2086 loc = asserts_for[SSA_NAME_VERSION (name)];
2087 while (loc)
2089 fprintf (file, "\t");
2090 print_gimple_stmt (file, gsi_stmt (loc->si), 0);
2091 fprintf (file, "\n\tBB #%d", loc->bb->index);
2092 if (loc->e)
2094 fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
2095 loc->e->dest->index);
2096 dump_edge_info (file, loc->e, dump_flags, 0);
2098 fprintf (file, "\n\tPREDICATE: ");
2099 print_generic_expr (file, loc->expr);
2100 fprintf (file, " %s ", get_tree_code_name (loc->comp_code));
2101 print_generic_expr (file, loc->val);
2102 fprintf (file, "\n\n");
2103 loc = loc->next;
2106 fprintf (file, "\n");
2110 /* Dump all the registered assertions for NAME to stderr. */
2112 DEBUG_FUNCTION void
2113 debug_asserts_for (tree name)
2115 dump_asserts_for (stderr, name);
2119 /* Dump all the registered assertions for all the names to FILE. */
2121 void
2122 dump_all_asserts (FILE *file)
2124 unsigned i;
2125 bitmap_iterator bi;
2127 fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
2128 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
2129 dump_asserts_for (file, ssa_name (i));
2130 fprintf (file, "\n");
2134 /* Dump all the registered assertions for all the names to stderr. */
2136 DEBUG_FUNCTION void
2137 debug_all_asserts (void)
2139 dump_all_asserts (stderr);
2142 /* Push the assert info for NAME, EXPR, COMP_CODE and VAL to ASSERTS. */
2144 static void
2145 add_assert_info (vec<assert_info> &asserts,
2146 tree name, tree expr, enum tree_code comp_code, tree val)
2148 assert_info info;
2149 info.comp_code = comp_code;
2150 info.name = name;
2151 if (TREE_OVERFLOW_P (val))
2152 val = drop_tree_overflow (val);
2153 info.val = val;
2154 info.expr = expr;
2155 asserts.safe_push (info);
2158 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
2159 'EXPR COMP_CODE VAL' at a location that dominates block BB or
2160 E->DEST, then register this location as a possible insertion point
2161 for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
2163 BB, E and SI provide the exact insertion point for the new
2164 ASSERT_EXPR. If BB is NULL, then the ASSERT_EXPR is to be inserted
2165 on edge E. Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
2166 BB. If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
2167 must not be NULL. */
2169 static void
2170 register_new_assert_for (tree name, tree expr,
2171 enum tree_code comp_code,
2172 tree val,
2173 basic_block bb,
2174 edge e,
2175 gimple_stmt_iterator si)
2177 assert_locus *n, *loc, *last_loc;
2178 basic_block dest_bb;
2180 gcc_checking_assert (bb == NULL || e == NULL);
2182 if (e == NULL)
2183 gcc_checking_assert (gimple_code (gsi_stmt (si)) != GIMPLE_COND
2184 && gimple_code (gsi_stmt (si)) != GIMPLE_SWITCH);
2186 /* Never build an assert comparing against an integer constant with
2187 TREE_OVERFLOW set. This confuses our undefined overflow warning
2188 machinery. */
2189 if (TREE_OVERFLOW_P (val))
2190 val = drop_tree_overflow (val);
2192 /* The new assertion A will be inserted at BB or E. We need to
2193 determine if the new location is dominated by a previously
2194 registered location for A. If we are doing an edge insertion,
2195 assume that A will be inserted at E->DEST. Note that this is not
2196 necessarily true.
2198 If E is a critical edge, it will be split. But even if E is
2199 split, the new block will dominate the same set of blocks that
2200 E->DEST dominates.
2202 The reverse, however, is not true, blocks dominated by E->DEST
2203 will not be dominated by the new block created to split E. So,
2204 if the insertion location is on a critical edge, we will not use
2205 the new location to move another assertion previously registered
2206 at a block dominated by E->DEST. */
2207 dest_bb = (bb) ? bb : e->dest;
2209 /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
2210 VAL at a block dominating DEST_BB, then we don't need to insert a new
2211 one. Similarly, if the same assertion already exists at a block
2212 dominated by DEST_BB and the new location is not on a critical
2213 edge, then update the existing location for the assertion (i.e.,
2214 move the assertion up in the dominance tree).
2216 Note, this is implemented as a simple linked list because there
2217 should not be more than a handful of assertions registered per
2218 name. If this becomes a performance problem, a table hashed by
2219 COMP_CODE and VAL could be implemented. */
2220 loc = asserts_for[SSA_NAME_VERSION (name)];
2221 last_loc = loc;
2222 while (loc)
2224 if (loc->comp_code == comp_code
2225 && (loc->val == val
2226 || operand_equal_p (loc->val, val, 0))
2227 && (loc->expr == expr
2228 || operand_equal_p (loc->expr, expr, 0)))
2230 /* If E is not a critical edge and DEST_BB
2231 dominates the existing location for the assertion, move
2232 the assertion up in the dominance tree by updating its
2233 location information. */
2234 if ((e == NULL || !EDGE_CRITICAL_P (e))
2235 && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
2237 loc->bb = dest_bb;
2238 loc->e = e;
2239 loc->si = si;
2240 return;
2244 /* Update the last node of the list and move to the next one. */
2245 last_loc = loc;
2246 loc = loc->next;
2249 /* If we didn't find an assertion already registered for
2250 NAME COMP_CODE VAL, add a new one at the end of the list of
2251 assertions associated with NAME. */
2252 n = XNEW (struct assert_locus);
2253 n->bb = dest_bb;
2254 n->e = e;
2255 n->si = si;
2256 n->comp_code = comp_code;
2257 n->val = val;
2258 n->expr = expr;
2259 n->next = NULL;
2261 if (last_loc)
2262 last_loc->next = n;
2263 else
2264 asserts_for[SSA_NAME_VERSION (name)] = n;
2266 bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
2269 /* (COND_OP0 COND_CODE COND_OP1) is a predicate which uses NAME.
2270 Extract a suitable test code and value and store them into *CODE_P and
2271 *VAL_P so the predicate is normalized to NAME *CODE_P *VAL_P.
2273 If no extraction was possible, return FALSE, otherwise return TRUE.
2275 If INVERT is true, then we invert the result stored into *CODE_P. */
2277 static bool
2278 extract_code_and_val_from_cond_with_ops (tree name, enum tree_code cond_code,
2279 tree cond_op0, tree cond_op1,
2280 bool invert, enum tree_code *code_p,
2281 tree *val_p)
2283 enum tree_code comp_code;
2284 tree val;
2286 /* Otherwise, we have a comparison of the form NAME COMP VAL
2287 or VAL COMP NAME. */
2288 if (name == cond_op1)
2290 /* If the predicate is of the form VAL COMP NAME, flip
2291 COMP around because we need to register NAME as the
2292 first operand in the predicate. */
2293 comp_code = swap_tree_comparison (cond_code);
2294 val = cond_op0;
2296 else if (name == cond_op0)
2298 /* The comparison is of the form NAME COMP VAL, so the
2299 comparison code remains unchanged. */
2300 comp_code = cond_code;
2301 val = cond_op1;
2303 else
2304 gcc_unreachable ();
2306 /* Invert the comparison code as necessary. */
2307 if (invert)
2308 comp_code = invert_tree_comparison (comp_code, 0);
2310 /* VRP only handles integral and pointer types. */
2311 if (! INTEGRAL_TYPE_P (TREE_TYPE (val))
2312 && ! POINTER_TYPE_P (TREE_TYPE (val)))
2313 return false;
2315 /* Do not register always-false predicates.
2316 FIXME: this works around a limitation in fold() when dealing with
2317 enumerations. Given 'enum { N1, N2 } x;', fold will not
2318 fold 'if (x > N2)' to 'if (0)'. */
2319 if ((comp_code == GT_EXPR || comp_code == LT_EXPR)
2320 && INTEGRAL_TYPE_P (TREE_TYPE (val)))
2322 tree min = TYPE_MIN_VALUE (TREE_TYPE (val));
2323 tree max = TYPE_MAX_VALUE (TREE_TYPE (val));
2325 if (comp_code == GT_EXPR
2326 && (!max
2327 || compare_values (val, max) == 0))
2328 return false;
2330 if (comp_code == LT_EXPR
2331 && (!min
2332 || compare_values (val, min) == 0))
2333 return false;
2335 *code_p = comp_code;
2336 *val_p = val;
2337 return true;
2340 /* Find out smallest RES where RES > VAL && (RES & MASK) == RES, if any
2341 (otherwise return VAL). VAL and MASK must be zero-extended for
2342 precision PREC. If SGNBIT is non-zero, first xor VAL with SGNBIT
2343 (to transform signed values into unsigned) and at the end xor
2344 SGNBIT back. */
2346 static wide_int
2347 masked_increment (const wide_int &val_in, const wide_int &mask,
2348 const wide_int &sgnbit, unsigned int prec)
2350 wide_int bit = wi::one (prec), res;
2351 unsigned int i;
2353 wide_int val = val_in ^ sgnbit;
2354 for (i = 0; i < prec; i++, bit += bit)
2356 res = mask;
2357 if ((res & bit) == 0)
2358 continue;
2359 res = bit - 1;
2360 res = wi::bit_and_not (val + bit, res);
2361 res &= mask;
2362 if (wi::gtu_p (res, val))
2363 return res ^ sgnbit;
2365 return val ^ sgnbit;
2368 /* Helper for overflow_comparison_p
2370 OP0 CODE OP1 is a comparison. Examine the comparison and potentially
2371 OP1's defining statement to see if it ultimately has the form
2372 OP0 CODE (OP0 PLUS INTEGER_CST)
2374 If so, return TRUE indicating this is an overflow test and store into
2375 *NEW_CST an updated constant that can be used in a narrowed range test.
2377 REVERSED indicates if the comparison was originally:
2379 OP1 CODE' OP0.
2381 This affects how we build the updated constant. */
2383 static bool
2384 overflow_comparison_p_1 (enum tree_code code, tree op0, tree op1,
2385 bool follow_assert_exprs, bool reversed, tree *new_cst)
2387 /* See if this is a relational operation between two SSA_NAMES with
2388 unsigned, overflow wrapping values. If so, check it more deeply. */
2389 if ((code == LT_EXPR || code == LE_EXPR
2390 || code == GE_EXPR || code == GT_EXPR)
2391 && TREE_CODE (op0) == SSA_NAME
2392 && TREE_CODE (op1) == SSA_NAME
2393 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
2394 && TYPE_UNSIGNED (TREE_TYPE (op0))
2395 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0)))
2397 gimple *op1_def = SSA_NAME_DEF_STMT (op1);
2399 /* If requested, follow any ASSERT_EXPRs backwards for OP1. */
2400 if (follow_assert_exprs)
2402 while (gimple_assign_single_p (op1_def)
2403 && TREE_CODE (gimple_assign_rhs1 (op1_def)) == ASSERT_EXPR)
2405 op1 = TREE_OPERAND (gimple_assign_rhs1 (op1_def), 0);
2406 if (TREE_CODE (op1) != SSA_NAME)
2407 break;
2408 op1_def = SSA_NAME_DEF_STMT (op1);
2412 /* Now look at the defining statement of OP1 to see if it adds
2413 or subtracts a nonzero constant from another operand. */
2414 if (op1_def
2415 && is_gimple_assign (op1_def)
2416 && gimple_assign_rhs_code (op1_def) == PLUS_EXPR
2417 && TREE_CODE (gimple_assign_rhs2 (op1_def)) == INTEGER_CST
2418 && !integer_zerop (gimple_assign_rhs2 (op1_def)))
2420 tree target = gimple_assign_rhs1 (op1_def);
2422 /* If requested, follow ASSERT_EXPRs backwards for op0 looking
2423 for one where TARGET appears on the RHS. */
2424 if (follow_assert_exprs)
2426 /* Now see if that "other operand" is op0, following the chain
2427 of ASSERT_EXPRs if necessary. */
2428 gimple *op0_def = SSA_NAME_DEF_STMT (op0);
2429 while (op0 != target
2430 && gimple_assign_single_p (op0_def)
2431 && TREE_CODE (gimple_assign_rhs1 (op0_def)) == ASSERT_EXPR)
2433 op0 = TREE_OPERAND (gimple_assign_rhs1 (op0_def), 0);
2434 if (TREE_CODE (op0) != SSA_NAME)
2435 break;
2436 op0_def = SSA_NAME_DEF_STMT (op0);
2440 /* If we did not find our target SSA_NAME, then this is not
2441 an overflow test. */
2442 if (op0 != target)
2443 return false;
2445 tree type = TREE_TYPE (op0);
2446 wide_int max = wi::max_value (TYPE_PRECISION (type), UNSIGNED);
2447 tree inc = gimple_assign_rhs2 (op1_def);
2448 if (reversed)
2449 *new_cst = wide_int_to_tree (type, max + wi::to_wide (inc));
2450 else
2451 *new_cst = wide_int_to_tree (type, max - wi::to_wide (inc));
2452 return true;
2455 return false;
2458 /* OP0 CODE OP1 is a comparison. Examine the comparison and potentially
2459 OP1's defining statement to see if it ultimately has the form
2460 OP0 CODE (OP0 PLUS INTEGER_CST)
2462 If so, return TRUE indicating this is an overflow test and store into
2463 *NEW_CST an updated constant that can be used in a narrowed range test.
2465 These statements are left as-is in the IL to facilitate discovery of
2466 {ADD,SUB}_OVERFLOW sequences later in the optimizer pipeline. But
2467 the alternate range representation is often useful within VRP. */
2469 bool
2470 overflow_comparison_p (tree_code code, tree name, tree val,
2471 bool use_equiv_p, tree *new_cst)
2473 if (overflow_comparison_p_1 (code, name, val, use_equiv_p, false, new_cst))
2474 return true;
2475 return overflow_comparison_p_1 (swap_tree_comparison (code), val, name,
2476 use_equiv_p, true, new_cst);
2480 /* Try to register an edge assertion for SSA name NAME on edge E for
2481 the condition COND contributing to the conditional jump pointed to by BSI.
2482 Invert the condition COND if INVERT is true. */
2484 static void
2485 register_edge_assert_for_2 (tree name, edge e,
2486 enum tree_code cond_code,
2487 tree cond_op0, tree cond_op1, bool invert,
2488 vec<assert_info> &asserts)
2490 tree val;
2491 enum tree_code comp_code;
2493 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
2494 cond_op0,
2495 cond_op1,
2496 invert, &comp_code, &val))
2497 return;
2499 /* Queue the assert. */
2500 tree x;
2501 if (overflow_comparison_p (comp_code, name, val, false, &x))
2503 enum tree_code new_code = ((comp_code == GT_EXPR || comp_code == GE_EXPR)
2504 ? GT_EXPR : LE_EXPR);
2505 add_assert_info (asserts, name, name, new_code, x);
2507 add_assert_info (asserts, name, name, comp_code, val);
2509 /* In the case of NAME <= CST and NAME being defined as
2510 NAME = (unsigned) NAME2 + CST2 we can assert NAME2 >= -CST2
2511 and NAME2 <= CST - CST2. We can do the same for NAME > CST.
2512 This catches range and anti-range tests. */
2513 if ((comp_code == LE_EXPR
2514 || comp_code == GT_EXPR)
2515 && TREE_CODE (val) == INTEGER_CST
2516 && TYPE_UNSIGNED (TREE_TYPE (val)))
2518 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
2519 tree cst2 = NULL_TREE, name2 = NULL_TREE, name3 = NULL_TREE;
2521 /* Extract CST2 from the (optional) addition. */
2522 if (is_gimple_assign (def_stmt)
2523 && gimple_assign_rhs_code (def_stmt) == PLUS_EXPR)
2525 name2 = gimple_assign_rhs1 (def_stmt);
2526 cst2 = gimple_assign_rhs2 (def_stmt);
2527 if (TREE_CODE (name2) == SSA_NAME
2528 && TREE_CODE (cst2) == INTEGER_CST)
2529 def_stmt = SSA_NAME_DEF_STMT (name2);
2532 /* Extract NAME2 from the (optional) sign-changing cast. */
2533 if (gimple_assign_cast_p (def_stmt))
2535 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt))
2536 && ! TYPE_UNSIGNED (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
2537 && (TYPE_PRECISION (gimple_expr_type (def_stmt))
2538 == TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))))
2539 name3 = gimple_assign_rhs1 (def_stmt);
2542 /* If name3 is used later, create an ASSERT_EXPR for it. */
2543 if (name3 != NULL_TREE
2544 && TREE_CODE (name3) == SSA_NAME
2545 && (cst2 == NULL_TREE
2546 || TREE_CODE (cst2) == INTEGER_CST)
2547 && INTEGRAL_TYPE_P (TREE_TYPE (name3)))
2549 tree tmp;
2551 /* Build an expression for the range test. */
2552 tmp = build1 (NOP_EXPR, TREE_TYPE (name), name3);
2553 if (cst2 != NULL_TREE)
2554 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
2556 if (dump_file)
2558 fprintf (dump_file, "Adding assert for ");
2559 print_generic_expr (dump_file, name3);
2560 fprintf (dump_file, " from ");
2561 print_generic_expr (dump_file, tmp);
2562 fprintf (dump_file, "\n");
2565 add_assert_info (asserts, name3, tmp, comp_code, val);
2568 /* If name2 is used later, create an ASSERT_EXPR for it. */
2569 if (name2 != NULL_TREE
2570 && TREE_CODE (name2) == SSA_NAME
2571 && TREE_CODE (cst2) == INTEGER_CST
2572 && INTEGRAL_TYPE_P (TREE_TYPE (name2)))
2574 tree tmp;
2576 /* Build an expression for the range test. */
2577 tmp = name2;
2578 if (TREE_TYPE (name) != TREE_TYPE (name2))
2579 tmp = build1 (NOP_EXPR, TREE_TYPE (name), tmp);
2580 if (cst2 != NULL_TREE)
2581 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
2583 if (dump_file)
2585 fprintf (dump_file, "Adding assert for ");
2586 print_generic_expr (dump_file, name2);
2587 fprintf (dump_file, " from ");
2588 print_generic_expr (dump_file, tmp);
2589 fprintf (dump_file, "\n");
2592 add_assert_info (asserts, name2, tmp, comp_code, val);
2596 /* In the case of post-in/decrement tests like if (i++) ... and uses
2597 of the in/decremented value on the edge the extra name we want to
2598 assert for is not on the def chain of the name compared. Instead
2599 it is in the set of use stmts.
2600 Similar cases happen for conversions that were simplified through
2601 fold_{sign_changed,widened}_comparison. */
2602 if ((comp_code == NE_EXPR
2603 || comp_code == EQ_EXPR)
2604 && TREE_CODE (val) == INTEGER_CST)
2606 imm_use_iterator ui;
2607 gimple *use_stmt;
2608 FOR_EACH_IMM_USE_STMT (use_stmt, ui, name)
2610 if (!is_gimple_assign (use_stmt))
2611 continue;
2613 /* Cut off to use-stmts that are dominating the predecessor. */
2614 if (!dominated_by_p (CDI_DOMINATORS, e->src, gimple_bb (use_stmt)))
2615 continue;
2617 tree name2 = gimple_assign_lhs (use_stmt);
2618 if (TREE_CODE (name2) != SSA_NAME)
2619 continue;
2621 enum tree_code code = gimple_assign_rhs_code (use_stmt);
2622 tree cst;
2623 if (code == PLUS_EXPR
2624 || code == MINUS_EXPR)
2626 cst = gimple_assign_rhs2 (use_stmt);
2627 if (TREE_CODE (cst) != INTEGER_CST)
2628 continue;
2629 cst = int_const_binop (code, val, cst);
2631 else if (CONVERT_EXPR_CODE_P (code))
2633 /* For truncating conversions we cannot record
2634 an inequality. */
2635 if (comp_code == NE_EXPR
2636 && (TYPE_PRECISION (TREE_TYPE (name2))
2637 < TYPE_PRECISION (TREE_TYPE (name))))
2638 continue;
2639 cst = fold_convert (TREE_TYPE (name2), val);
2641 else
2642 continue;
2644 if (TREE_OVERFLOW_P (cst))
2645 cst = drop_tree_overflow (cst);
2646 add_assert_info (asserts, name2, name2, comp_code, cst);
2650 if (TREE_CODE_CLASS (comp_code) == tcc_comparison
2651 && TREE_CODE (val) == INTEGER_CST)
2653 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
2654 tree name2 = NULL_TREE, names[2], cst2 = NULL_TREE;
2655 tree val2 = NULL_TREE;
2656 unsigned int prec = TYPE_PRECISION (TREE_TYPE (val));
2657 wide_int mask = wi::zero (prec);
2658 unsigned int nprec = prec;
2659 enum tree_code rhs_code = ERROR_MARK;
2661 if (is_gimple_assign (def_stmt))
2662 rhs_code = gimple_assign_rhs_code (def_stmt);
2664 /* In the case of NAME != CST1 where NAME = A +- CST2 we can
2665 assert that A != CST1 -+ CST2. */
2666 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
2667 && (rhs_code == PLUS_EXPR || rhs_code == MINUS_EXPR))
2669 tree op0 = gimple_assign_rhs1 (def_stmt);
2670 tree op1 = gimple_assign_rhs2 (def_stmt);
2671 if (TREE_CODE (op0) == SSA_NAME
2672 && TREE_CODE (op1) == INTEGER_CST)
2674 enum tree_code reverse_op = (rhs_code == PLUS_EXPR
2675 ? MINUS_EXPR : PLUS_EXPR);
2676 op1 = int_const_binop (reverse_op, val, op1);
2677 if (TREE_OVERFLOW (op1))
2678 op1 = drop_tree_overflow (op1);
2679 add_assert_info (asserts, op0, op0, comp_code, op1);
2683 /* Add asserts for NAME cmp CST and NAME being defined
2684 as NAME = (int) NAME2. */
2685 if (!TYPE_UNSIGNED (TREE_TYPE (val))
2686 && (comp_code == LE_EXPR || comp_code == LT_EXPR
2687 || comp_code == GT_EXPR || comp_code == GE_EXPR)
2688 && gimple_assign_cast_p (def_stmt))
2690 name2 = gimple_assign_rhs1 (def_stmt);
2691 if (CONVERT_EXPR_CODE_P (rhs_code)
2692 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
2693 && TYPE_UNSIGNED (TREE_TYPE (name2))
2694 && prec == TYPE_PRECISION (TREE_TYPE (name2))
2695 && (comp_code == LE_EXPR || comp_code == GT_EXPR
2696 || !tree_int_cst_equal (val,
2697 TYPE_MIN_VALUE (TREE_TYPE (val)))))
2699 tree tmp, cst;
2700 enum tree_code new_comp_code = comp_code;
2702 cst = fold_convert (TREE_TYPE (name2),
2703 TYPE_MIN_VALUE (TREE_TYPE (val)));
2704 /* Build an expression for the range test. */
2705 tmp = build2 (PLUS_EXPR, TREE_TYPE (name2), name2, cst);
2706 cst = fold_build2 (PLUS_EXPR, TREE_TYPE (name2), cst,
2707 fold_convert (TREE_TYPE (name2), val));
2708 if (comp_code == LT_EXPR || comp_code == GE_EXPR)
2710 new_comp_code = comp_code == LT_EXPR ? LE_EXPR : GT_EXPR;
2711 cst = fold_build2 (MINUS_EXPR, TREE_TYPE (name2), cst,
2712 build_int_cst (TREE_TYPE (name2), 1));
2715 if (dump_file)
2717 fprintf (dump_file, "Adding assert for ");
2718 print_generic_expr (dump_file, name2);
2719 fprintf (dump_file, " from ");
2720 print_generic_expr (dump_file, tmp);
2721 fprintf (dump_file, "\n");
2724 add_assert_info (asserts, name2, tmp, new_comp_code, cst);
2728 /* Add asserts for NAME cmp CST and NAME being defined as
2729 NAME = NAME2 >> CST2.
2731 Extract CST2 from the right shift. */
2732 if (rhs_code == RSHIFT_EXPR)
2734 name2 = gimple_assign_rhs1 (def_stmt);
2735 cst2 = gimple_assign_rhs2 (def_stmt);
2736 if (TREE_CODE (name2) == SSA_NAME
2737 && tree_fits_uhwi_p (cst2)
2738 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
2739 && IN_RANGE (tree_to_uhwi (cst2), 1, prec - 1)
2740 && type_has_mode_precision_p (TREE_TYPE (val)))
2742 mask = wi::mask (tree_to_uhwi (cst2), false, prec);
2743 val2 = fold_binary (LSHIFT_EXPR, TREE_TYPE (val), val, cst2);
2746 if (val2 != NULL_TREE
2747 && TREE_CODE (val2) == INTEGER_CST
2748 && simple_cst_equal (fold_build2 (RSHIFT_EXPR,
2749 TREE_TYPE (val),
2750 val2, cst2), val))
2752 enum tree_code new_comp_code = comp_code;
2753 tree tmp, new_val;
2755 tmp = name2;
2756 if (comp_code == EQ_EXPR || comp_code == NE_EXPR)
2758 if (!TYPE_UNSIGNED (TREE_TYPE (val)))
2760 tree type = build_nonstandard_integer_type (prec, 1);
2761 tmp = build1 (NOP_EXPR, type, name2);
2762 val2 = fold_convert (type, val2);
2764 tmp = fold_build2 (MINUS_EXPR, TREE_TYPE (tmp), tmp, val2);
2765 new_val = wide_int_to_tree (TREE_TYPE (tmp), mask);
2766 new_comp_code = comp_code == EQ_EXPR ? LE_EXPR : GT_EXPR;
2768 else if (comp_code == LT_EXPR || comp_code == GE_EXPR)
2770 wide_int minval
2771 = wi::min_value (prec, TYPE_SIGN (TREE_TYPE (val)));
2772 new_val = val2;
2773 if (minval == wi::to_wide (new_val))
2774 new_val = NULL_TREE;
2776 else
2778 wide_int maxval
2779 = wi::max_value (prec, TYPE_SIGN (TREE_TYPE (val)));
2780 mask |= wi::to_wide (val2);
2781 if (wi::eq_p (mask, maxval))
2782 new_val = NULL_TREE;
2783 else
2784 new_val = wide_int_to_tree (TREE_TYPE (val2), mask);
2787 if (new_val)
2789 if (dump_file)
2791 fprintf (dump_file, "Adding assert for ");
2792 print_generic_expr (dump_file, name2);
2793 fprintf (dump_file, " from ");
2794 print_generic_expr (dump_file, tmp);
2795 fprintf (dump_file, "\n");
2798 add_assert_info (asserts, name2, tmp, new_comp_code, new_val);
2802 /* Add asserts for NAME cmp CST and NAME being defined as
2803 NAME = NAME2 & CST2.
2805 Extract CST2 from the and.
2807 Also handle
2808 NAME = (unsigned) NAME2;
2809 casts where NAME's type is unsigned and has smaller precision
2810 than NAME2's type as if it was NAME = NAME2 & MASK. */
2811 names[0] = NULL_TREE;
2812 names[1] = NULL_TREE;
2813 cst2 = NULL_TREE;
2814 if (rhs_code == BIT_AND_EXPR
2815 || (CONVERT_EXPR_CODE_P (rhs_code)
2816 && INTEGRAL_TYPE_P (TREE_TYPE (val))
2817 && TYPE_UNSIGNED (TREE_TYPE (val))
2818 && TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
2819 > prec))
2821 name2 = gimple_assign_rhs1 (def_stmt);
2822 if (rhs_code == BIT_AND_EXPR)
2823 cst2 = gimple_assign_rhs2 (def_stmt);
2824 else
2826 cst2 = TYPE_MAX_VALUE (TREE_TYPE (val));
2827 nprec = TYPE_PRECISION (TREE_TYPE (name2));
2829 if (TREE_CODE (name2) == SSA_NAME
2830 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
2831 && TREE_CODE (cst2) == INTEGER_CST
2832 && !integer_zerop (cst2)
2833 && (nprec > 1
2834 || TYPE_UNSIGNED (TREE_TYPE (val))))
2836 gimple *def_stmt2 = SSA_NAME_DEF_STMT (name2);
2837 if (gimple_assign_cast_p (def_stmt2))
2839 names[1] = gimple_assign_rhs1 (def_stmt2);
2840 if (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt2))
2841 || !INTEGRAL_TYPE_P (TREE_TYPE (names[1]))
2842 || (TYPE_PRECISION (TREE_TYPE (name2))
2843 != TYPE_PRECISION (TREE_TYPE (names[1]))))
2844 names[1] = NULL_TREE;
2846 names[0] = name2;
2849 if (names[0] || names[1])
2851 wide_int minv, maxv, valv, cst2v;
2852 wide_int tem, sgnbit;
2853 bool valid_p = false, valn, cst2n;
2854 enum tree_code ccode = comp_code;
2856 valv = wide_int::from (wi::to_wide (val), nprec, UNSIGNED);
2857 cst2v = wide_int::from (wi::to_wide (cst2), nprec, UNSIGNED);
2858 valn = wi::neg_p (valv, TYPE_SIGN (TREE_TYPE (val)));
2859 cst2n = wi::neg_p (cst2v, TYPE_SIGN (TREE_TYPE (val)));
2860 /* If CST2 doesn't have most significant bit set,
2861 but VAL is negative, we have comparison like
2862 if ((x & 0x123) > -4) (always true). Just give up. */
2863 if (!cst2n && valn)
2864 ccode = ERROR_MARK;
2865 if (cst2n)
2866 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
2867 else
2868 sgnbit = wi::zero (nprec);
2869 minv = valv & cst2v;
2870 switch (ccode)
2872 case EQ_EXPR:
2873 /* Minimum unsigned value for equality is VAL & CST2
2874 (should be equal to VAL, otherwise we probably should
2875 have folded the comparison into false) and
2876 maximum unsigned value is VAL | ~CST2. */
2877 maxv = valv | ~cst2v;
2878 valid_p = true;
2879 break;
2881 case NE_EXPR:
2882 tem = valv | ~cst2v;
2883 /* If VAL is 0, handle (X & CST2) != 0 as (X & CST2) > 0U. */
2884 if (valv == 0)
2886 cst2n = false;
2887 sgnbit = wi::zero (nprec);
2888 goto gt_expr;
2890 /* If (VAL | ~CST2) is all ones, handle it as
2891 (X & CST2) < VAL. */
2892 if (tem == -1)
2894 cst2n = false;
2895 valn = false;
2896 sgnbit = wi::zero (nprec);
2897 goto lt_expr;
2899 if (!cst2n && wi::neg_p (cst2v))
2900 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
2901 if (sgnbit != 0)
2903 if (valv == sgnbit)
2905 cst2n = true;
2906 valn = true;
2907 goto gt_expr;
2909 if (tem == wi::mask (nprec - 1, false, nprec))
2911 cst2n = true;
2912 goto lt_expr;
2914 if (!cst2n)
2915 sgnbit = wi::zero (nprec);
2917 break;
2919 case GE_EXPR:
2920 /* Minimum unsigned value for >= if (VAL & CST2) == VAL
2921 is VAL and maximum unsigned value is ~0. For signed
2922 comparison, if CST2 doesn't have most significant bit
2923 set, handle it similarly. If CST2 has MSB set,
2924 the minimum is the same, and maximum is ~0U/2. */
2925 if (minv != valv)
2927 /* If (VAL & CST2) != VAL, X & CST2 can't be equal to
2928 VAL. */
2929 minv = masked_increment (valv, cst2v, sgnbit, nprec);
2930 if (minv == valv)
2931 break;
2933 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
2934 valid_p = true;
2935 break;
2937 case GT_EXPR:
2938 gt_expr:
2939 /* Find out smallest MINV where MINV > VAL
2940 && (MINV & CST2) == MINV, if any. If VAL is signed and
2941 CST2 has MSB set, compute it biased by 1 << (nprec - 1). */
2942 minv = masked_increment (valv, cst2v, sgnbit, nprec);
2943 if (minv == valv)
2944 break;
2945 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
2946 valid_p = true;
2947 break;
2949 case LE_EXPR:
2950 /* Minimum unsigned value for <= is 0 and maximum
2951 unsigned value is VAL | ~CST2 if (VAL & CST2) == VAL.
2952 Otherwise, find smallest VAL2 where VAL2 > VAL
2953 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
2954 as maximum.
2955 For signed comparison, if CST2 doesn't have most
2956 significant bit set, handle it similarly. If CST2 has
2957 MSB set, the maximum is the same and minimum is INT_MIN. */
2958 if (minv == valv)
2959 maxv = valv;
2960 else
2962 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
2963 if (maxv == valv)
2964 break;
2965 maxv -= 1;
2967 maxv |= ~cst2v;
2968 minv = sgnbit;
2969 valid_p = true;
2970 break;
2972 case LT_EXPR:
2973 lt_expr:
2974 /* Minimum unsigned value for < is 0 and maximum
2975 unsigned value is (VAL-1) | ~CST2 if (VAL & CST2) == VAL.
2976 Otherwise, find smallest VAL2 where VAL2 > VAL
2977 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
2978 as maximum.
2979 For signed comparison, if CST2 doesn't have most
2980 significant bit set, handle it similarly. If CST2 has
2981 MSB set, the maximum is the same and minimum is INT_MIN. */
2982 if (minv == valv)
2984 if (valv == sgnbit)
2985 break;
2986 maxv = valv;
2988 else
2990 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
2991 if (maxv == valv)
2992 break;
2994 maxv -= 1;
2995 maxv |= ~cst2v;
2996 minv = sgnbit;
2997 valid_p = true;
2998 break;
3000 default:
3001 break;
3003 if (valid_p
3004 && (maxv - minv) != -1)
3006 tree tmp, new_val, type;
3007 int i;
3009 for (i = 0; i < 2; i++)
3010 if (names[i])
3012 wide_int maxv2 = maxv;
3013 tmp = names[i];
3014 type = TREE_TYPE (names[i]);
3015 if (!TYPE_UNSIGNED (type))
3017 type = build_nonstandard_integer_type (nprec, 1);
3018 tmp = build1 (NOP_EXPR, type, names[i]);
3020 if (minv != 0)
3022 tmp = build2 (PLUS_EXPR, type, tmp,
3023 wide_int_to_tree (type, -minv));
3024 maxv2 = maxv - minv;
3026 new_val = wide_int_to_tree (type, maxv2);
3028 if (dump_file)
3030 fprintf (dump_file, "Adding assert for ");
3031 print_generic_expr (dump_file, names[i]);
3032 fprintf (dump_file, " from ");
3033 print_generic_expr (dump_file, tmp);
3034 fprintf (dump_file, "\n");
3037 add_assert_info (asserts, names[i], tmp, LE_EXPR, new_val);
3044 /* OP is an operand of a truth value expression which is known to have
3045 a particular value. Register any asserts for OP and for any
3046 operands in OP's defining statement.
3048 If CODE is EQ_EXPR, then we want to register OP is zero (false),
3049 if CODE is NE_EXPR, then we want to register OP is nonzero (true). */
3051 static void
3052 register_edge_assert_for_1 (tree op, enum tree_code code,
3053 edge e, vec<assert_info> &asserts)
3055 gimple *op_def;
3056 tree val;
3057 enum tree_code rhs_code;
3059 /* We only care about SSA_NAMEs. */
3060 if (TREE_CODE (op) != SSA_NAME)
3061 return;
3063 /* We know that OP will have a zero or nonzero value. */
3064 val = build_int_cst (TREE_TYPE (op), 0);
3065 add_assert_info (asserts, op, op, code, val);
3067 /* Now look at how OP is set. If it's set from a comparison,
3068 a truth operation or some bit operations, then we may be able
3069 to register information about the operands of that assignment. */
3070 op_def = SSA_NAME_DEF_STMT (op);
3071 if (gimple_code (op_def) != GIMPLE_ASSIGN)
3072 return;
3074 rhs_code = gimple_assign_rhs_code (op_def);
3076 if (TREE_CODE_CLASS (rhs_code) == tcc_comparison)
3078 bool invert = (code == EQ_EXPR ? true : false);
3079 tree op0 = gimple_assign_rhs1 (op_def);
3080 tree op1 = gimple_assign_rhs2 (op_def);
3082 if (TREE_CODE (op0) == SSA_NAME)
3083 register_edge_assert_for_2 (op0, e, rhs_code, op0, op1, invert, asserts);
3084 if (TREE_CODE (op1) == SSA_NAME)
3085 register_edge_assert_for_2 (op1, e, rhs_code, op0, op1, invert, asserts);
3087 else if ((code == NE_EXPR
3088 && gimple_assign_rhs_code (op_def) == BIT_AND_EXPR)
3089 || (code == EQ_EXPR
3090 && gimple_assign_rhs_code (op_def) == BIT_IOR_EXPR))
3092 /* Recurse on each operand. */
3093 tree op0 = gimple_assign_rhs1 (op_def);
3094 tree op1 = gimple_assign_rhs2 (op_def);
3095 if (TREE_CODE (op0) == SSA_NAME
3096 && has_single_use (op0))
3097 register_edge_assert_for_1 (op0, code, e, asserts);
3098 if (TREE_CODE (op1) == SSA_NAME
3099 && has_single_use (op1))
3100 register_edge_assert_for_1 (op1, code, e, asserts);
3102 else if (gimple_assign_rhs_code (op_def) == BIT_NOT_EXPR
3103 && TYPE_PRECISION (TREE_TYPE (gimple_assign_lhs (op_def))) == 1)
3105 /* Recurse, flipping CODE. */
3106 code = invert_tree_comparison (code, false);
3107 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
3109 else if (gimple_assign_rhs_code (op_def) == SSA_NAME)
3111 /* Recurse through the copy. */
3112 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
3114 else if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (op_def)))
3116 /* Recurse through the type conversion, unless it is a narrowing
3117 conversion or conversion from non-integral type. */
3118 tree rhs = gimple_assign_rhs1 (op_def);
3119 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs))
3120 && (TYPE_PRECISION (TREE_TYPE (rhs))
3121 <= TYPE_PRECISION (TREE_TYPE (op))))
3122 register_edge_assert_for_1 (rhs, code, e, asserts);
3126 /* Check if comparison
3127 NAME COND_OP INTEGER_CST
3128 has a form of
3129 (X & 11...100..0) COND_OP XX...X00...0
3130 Such comparison can yield assertions like
3131 X >= XX...X00...0
3132 X <= XX...X11...1
3133 in case of COND_OP being EQ_EXPR or
3134 X < XX...X00...0
3135 X > XX...X11...1
3136 in case of NE_EXPR. */
3138 static bool
3139 is_masked_range_test (tree name, tree valt, enum tree_code cond_code,
3140 tree *new_name, tree *low, enum tree_code *low_code,
3141 tree *high, enum tree_code *high_code)
3143 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3145 if (!is_gimple_assign (def_stmt)
3146 || gimple_assign_rhs_code (def_stmt) != BIT_AND_EXPR)
3147 return false;
3149 tree t = gimple_assign_rhs1 (def_stmt);
3150 tree maskt = gimple_assign_rhs2 (def_stmt);
3151 if (TREE_CODE (t) != SSA_NAME || TREE_CODE (maskt) != INTEGER_CST)
3152 return false;
3154 wi::tree_to_wide_ref mask = wi::to_wide (maskt);
3155 wide_int inv_mask = ~mask;
3156 /* Must have been removed by now so don't bother optimizing. */
3157 if (mask == 0 || inv_mask == 0)
3158 return false;
3160 /* Assume VALT is INTEGER_CST. */
3161 wi::tree_to_wide_ref val = wi::to_wide (valt);
3163 if ((inv_mask & (inv_mask + 1)) != 0
3164 || (val & mask) != val)
3165 return false;
3167 bool is_range = cond_code == EQ_EXPR;
3169 tree type = TREE_TYPE (t);
3170 wide_int min = wi::min_value (type),
3171 max = wi::max_value (type);
3173 if (is_range)
3175 *low_code = val == min ? ERROR_MARK : GE_EXPR;
3176 *high_code = val == max ? ERROR_MARK : LE_EXPR;
3178 else
3180 /* We can still generate assertion if one of alternatives
3181 is known to always be false. */
3182 if (val == min)
3184 *low_code = (enum tree_code) 0;
3185 *high_code = GT_EXPR;
3187 else if ((val | inv_mask) == max)
3189 *low_code = LT_EXPR;
3190 *high_code = (enum tree_code) 0;
3192 else
3193 return false;
3196 *new_name = t;
3197 *low = wide_int_to_tree (type, val);
3198 *high = wide_int_to_tree (type, val | inv_mask);
3200 return true;
3203 /* Try to register an edge assertion for SSA name NAME on edge E for
3204 the condition COND contributing to the conditional jump pointed to by
3205 SI. */
3207 void
3208 register_edge_assert_for (tree name, edge e,
3209 enum tree_code cond_code, tree cond_op0,
3210 tree cond_op1, vec<assert_info> &asserts)
3212 tree val;
3213 enum tree_code comp_code;
3214 bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
3216 /* Do not attempt to infer anything in names that flow through
3217 abnormal edges. */
3218 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
3219 return;
3221 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
3222 cond_op0, cond_op1,
3223 is_else_edge,
3224 &comp_code, &val))
3225 return;
3227 /* Register ASSERT_EXPRs for name. */
3228 register_edge_assert_for_2 (name, e, cond_code, cond_op0,
3229 cond_op1, is_else_edge, asserts);
3232 /* If COND is effectively an equality test of an SSA_NAME against
3233 the value zero or one, then we may be able to assert values
3234 for SSA_NAMEs which flow into COND. */
3236 /* In the case of NAME == 1 or NAME != 0, for BIT_AND_EXPR defining
3237 statement of NAME we can assert both operands of the BIT_AND_EXPR
3238 have nonzero value. */
3239 if (((comp_code == EQ_EXPR && integer_onep (val))
3240 || (comp_code == NE_EXPR && integer_zerop (val))))
3242 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3244 if (is_gimple_assign (def_stmt)
3245 && gimple_assign_rhs_code (def_stmt) == BIT_AND_EXPR)
3247 tree op0 = gimple_assign_rhs1 (def_stmt);
3248 tree op1 = gimple_assign_rhs2 (def_stmt);
3249 register_edge_assert_for_1 (op0, NE_EXPR, e, asserts);
3250 register_edge_assert_for_1 (op1, NE_EXPR, e, asserts);
3254 /* In the case of NAME == 0 or NAME != 1, for BIT_IOR_EXPR defining
3255 statement of NAME we can assert both operands of the BIT_IOR_EXPR
3256 have zero value. */
3257 if (((comp_code == EQ_EXPR && integer_zerop (val))
3258 || (comp_code == NE_EXPR && integer_onep (val))))
3260 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3262 /* For BIT_IOR_EXPR only if NAME == 0 both operands have
3263 necessarily zero value, or if type-precision is one. */
3264 if (is_gimple_assign (def_stmt)
3265 && (gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR
3266 && (TYPE_PRECISION (TREE_TYPE (name)) == 1
3267 || comp_code == EQ_EXPR)))
3269 tree op0 = gimple_assign_rhs1 (def_stmt);
3270 tree op1 = gimple_assign_rhs2 (def_stmt);
3271 register_edge_assert_for_1 (op0, EQ_EXPR, e, asserts);
3272 register_edge_assert_for_1 (op1, EQ_EXPR, e, asserts);
3276 /* Sometimes we can infer ranges from (NAME & MASK) == VALUE. */
3277 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
3278 && TREE_CODE (val) == INTEGER_CST)
3280 enum tree_code low_code, high_code;
3281 tree low, high;
3282 if (is_masked_range_test (name, val, comp_code, &name, &low,
3283 &low_code, &high, &high_code))
3285 if (low_code != ERROR_MARK)
3286 register_edge_assert_for_2 (name, e, low_code, name,
3287 low, /*invert*/false, asserts);
3288 if (high_code != ERROR_MARK)
3289 register_edge_assert_for_2 (name, e, high_code, name,
3290 high, /*invert*/false, asserts);
3295 /* Finish found ASSERTS for E and register them at GSI. */
3297 static void
3298 finish_register_edge_assert_for (edge e, gimple_stmt_iterator gsi,
3299 vec<assert_info> &asserts)
3301 for (unsigned i = 0; i < asserts.length (); ++i)
3302 /* Only register an ASSERT_EXPR if NAME was found in the sub-graph
3303 reachable from E. */
3304 if (live_on_edge (e, asserts[i].name))
3305 register_new_assert_for (asserts[i].name, asserts[i].expr,
3306 asserts[i].comp_code, asserts[i].val,
3307 NULL, e, gsi);
3312 /* Determine whether the outgoing edges of BB should receive an
3313 ASSERT_EXPR for each of the operands of BB's LAST statement.
3314 The last statement of BB must be a COND_EXPR.
3316 If any of the sub-graphs rooted at BB have an interesting use of
3317 the predicate operands, an assert location node is added to the
3318 list of assertions for the corresponding operands. */
3320 static void
3321 find_conditional_asserts (basic_block bb, gcond *last)
3323 gimple_stmt_iterator bsi;
3324 tree op;
3325 edge_iterator ei;
3326 edge e;
3327 ssa_op_iter iter;
3329 bsi = gsi_for_stmt (last);
3331 /* Look for uses of the operands in each of the sub-graphs
3332 rooted at BB. We need to check each of the outgoing edges
3333 separately, so that we know what kind of ASSERT_EXPR to
3334 insert. */
3335 FOR_EACH_EDGE (e, ei, bb->succs)
3337 if (e->dest == bb)
3338 continue;
3340 /* Register the necessary assertions for each operand in the
3341 conditional predicate. */
3342 auto_vec<assert_info, 8> asserts;
3343 FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
3344 register_edge_assert_for (op, e,
3345 gimple_cond_code (last),
3346 gimple_cond_lhs (last),
3347 gimple_cond_rhs (last), asserts);
3348 finish_register_edge_assert_for (e, bsi, asserts);
3352 struct case_info
3354 tree expr;
3355 basic_block bb;
3358 /* Compare two case labels sorting first by the destination bb index
3359 and then by the case value. */
3361 static int
3362 compare_case_labels (const void *p1, const void *p2)
3364 const struct case_info *ci1 = (const struct case_info *) p1;
3365 const struct case_info *ci2 = (const struct case_info *) p2;
3366 int idx1 = ci1->bb->index;
3367 int idx2 = ci2->bb->index;
3369 if (idx1 < idx2)
3370 return -1;
3371 else if (idx1 == idx2)
3373 /* Make sure the default label is first in a group. */
3374 if (!CASE_LOW (ci1->expr))
3375 return -1;
3376 else if (!CASE_LOW (ci2->expr))
3377 return 1;
3378 else
3379 return tree_int_cst_compare (CASE_LOW (ci1->expr),
3380 CASE_LOW (ci2->expr));
3382 else
3383 return 1;
3386 /* Determine whether the outgoing edges of BB should receive an
3387 ASSERT_EXPR for each of the operands of BB's LAST statement.
3388 The last statement of BB must be a SWITCH_EXPR.
3390 If any of the sub-graphs rooted at BB have an interesting use of
3391 the predicate operands, an assert location node is added to the
3392 list of assertions for the corresponding operands. */
3394 static void
3395 find_switch_asserts (basic_block bb, gswitch *last)
3397 gimple_stmt_iterator bsi;
3398 tree op;
3399 edge e;
3400 struct case_info *ci;
3401 size_t n = gimple_switch_num_labels (last);
3402 #if GCC_VERSION >= 4000
3403 unsigned int idx;
3404 #else
3405 /* Work around GCC 3.4 bug (PR 37086). */
3406 volatile unsigned int idx;
3407 #endif
3409 bsi = gsi_for_stmt (last);
3410 op = gimple_switch_index (last);
3411 if (TREE_CODE (op) != SSA_NAME)
3412 return;
3414 /* Build a vector of case labels sorted by destination label. */
3415 ci = XNEWVEC (struct case_info, n);
3416 for (idx = 0; idx < n; ++idx)
3418 ci[idx].expr = gimple_switch_label (last, idx);
3419 ci[idx].bb = label_to_block (cfun, CASE_LABEL (ci[idx].expr));
3421 edge default_edge = find_edge (bb, ci[0].bb);
3422 qsort (ci, n, sizeof (struct case_info), compare_case_labels);
3424 for (idx = 0; idx < n; ++idx)
3426 tree min, max;
3427 tree cl = ci[idx].expr;
3428 basic_block cbb = ci[idx].bb;
3430 min = CASE_LOW (cl);
3431 max = CASE_HIGH (cl);
3433 /* If there are multiple case labels with the same destination
3434 we need to combine them to a single value range for the edge. */
3435 if (idx + 1 < n && cbb == ci[idx + 1].bb)
3437 /* Skip labels until the last of the group. */
3438 do {
3439 ++idx;
3440 } while (idx < n && cbb == ci[idx].bb);
3441 --idx;
3443 /* Pick up the maximum of the case label range. */
3444 if (CASE_HIGH (ci[idx].expr))
3445 max = CASE_HIGH (ci[idx].expr);
3446 else
3447 max = CASE_LOW (ci[idx].expr);
3450 /* Can't extract a useful assertion out of a range that includes the
3451 default label. */
3452 if (min == NULL_TREE)
3453 continue;
3455 /* Find the edge to register the assert expr on. */
3456 e = find_edge (bb, cbb);
3458 /* Register the necessary assertions for the operand in the
3459 SWITCH_EXPR. */
3460 auto_vec<assert_info, 8> asserts;
3461 register_edge_assert_for (op, e,
3462 max ? GE_EXPR : EQ_EXPR,
3463 op, fold_convert (TREE_TYPE (op), min),
3464 asserts);
3465 if (max)
3466 register_edge_assert_for (op, e, LE_EXPR, op,
3467 fold_convert (TREE_TYPE (op), max),
3468 asserts);
3469 finish_register_edge_assert_for (e, bsi, asserts);
3472 XDELETEVEC (ci);
3474 if (!live_on_edge (default_edge, op))
3475 return;
3477 /* Now register along the default label assertions that correspond to the
3478 anti-range of each label. */
3479 int insertion_limit = PARAM_VALUE (PARAM_MAX_VRP_SWITCH_ASSERTIONS);
3480 if (insertion_limit == 0)
3481 return;
3483 /* We can't do this if the default case shares a label with another case. */
3484 tree default_cl = gimple_switch_default_label (last);
3485 for (idx = 1; idx < n; idx++)
3487 tree min, max;
3488 tree cl = gimple_switch_label (last, idx);
3489 if (CASE_LABEL (cl) == CASE_LABEL (default_cl))
3490 continue;
3492 min = CASE_LOW (cl);
3493 max = CASE_HIGH (cl);
3495 /* Combine contiguous case ranges to reduce the number of assertions
3496 to insert. */
3497 for (idx = idx + 1; idx < n; idx++)
3499 tree next_min, next_max;
3500 tree next_cl = gimple_switch_label (last, idx);
3501 if (CASE_LABEL (next_cl) == CASE_LABEL (default_cl))
3502 break;
3504 next_min = CASE_LOW (next_cl);
3505 next_max = CASE_HIGH (next_cl);
3507 wide_int difference = (wi::to_wide (next_min)
3508 - wi::to_wide (max ? max : min));
3509 if (wi::eq_p (difference, 1))
3510 max = next_max ? next_max : next_min;
3511 else
3512 break;
3514 idx--;
3516 if (max == NULL_TREE)
3518 /* Register the assertion OP != MIN. */
3519 auto_vec<assert_info, 8> asserts;
3520 min = fold_convert (TREE_TYPE (op), min);
3521 register_edge_assert_for (op, default_edge, NE_EXPR, op, min,
3522 asserts);
3523 finish_register_edge_assert_for (default_edge, bsi, asserts);
3525 else
3527 /* Register the assertion (unsigned)OP - MIN > (MAX - MIN),
3528 which will give OP the anti-range ~[MIN,MAX]. */
3529 tree uop = fold_convert (unsigned_type_for (TREE_TYPE (op)), op);
3530 min = fold_convert (TREE_TYPE (uop), min);
3531 max = fold_convert (TREE_TYPE (uop), max);
3533 tree lhs = fold_build2 (MINUS_EXPR, TREE_TYPE (uop), uop, min);
3534 tree rhs = int_const_binop (MINUS_EXPR, max, min);
3535 register_new_assert_for (op, lhs, GT_EXPR, rhs,
3536 NULL, default_edge, bsi);
3539 if (--insertion_limit == 0)
3540 break;
3545 /* Traverse all the statements in block BB looking for statements that
3546 may generate useful assertions for the SSA names in their operand.
3547 If a statement produces a useful assertion A for name N_i, then the
3548 list of assertions already generated for N_i is scanned to
3549 determine if A is actually needed.
3551 If N_i already had the assertion A at a location dominating the
3552 current location, then nothing needs to be done. Otherwise, the
3553 new location for A is recorded instead.
3555 1- For every statement S in BB, all the variables used by S are
3556 added to bitmap FOUND_IN_SUBGRAPH.
3558 2- If statement S uses an operand N in a way that exposes a known
3559 value range for N, then if N was not already generated by an
3560 ASSERT_EXPR, create a new assert location for N. For instance,
3561 if N is a pointer and the statement dereferences it, we can
3562 assume that N is not NULL.
3564 3- COND_EXPRs are a special case of #2. We can derive range
3565 information from the predicate but need to insert different
3566 ASSERT_EXPRs for each of the sub-graphs rooted at the
3567 conditional block. If the last statement of BB is a conditional
3568 expression of the form 'X op Y', then
3570 a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
3572 b) If the conditional is the only entry point to the sub-graph
3573 corresponding to the THEN_CLAUSE, recurse into it. On
3574 return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
3575 an ASSERT_EXPR is added for the corresponding variable.
3577 c) Repeat step (b) on the ELSE_CLAUSE.
3579 d) Mark X and Y in FOUND_IN_SUBGRAPH.
3581 For instance,
3583 if (a == 9)
3584 b = a;
3585 else
3586 b = c + 1;
3588 In this case, an assertion on the THEN clause is useful to
3589 determine that 'a' is always 9 on that edge. However, an assertion
3590 on the ELSE clause would be unnecessary.
3592 4- If BB does not end in a conditional expression, then we recurse
3593 into BB's dominator children.
3595 At the end of the recursive traversal, every SSA name will have a
3596 list of locations where ASSERT_EXPRs should be added. When a new
3597 location for name N is found, it is registered by calling
3598 register_new_assert_for. That function keeps track of all the
3599 registered assertions to prevent adding unnecessary assertions.
3600 For instance, if a pointer P_4 is dereferenced more than once in a
3601 dominator tree, only the location dominating all the dereference of
3602 P_4 will receive an ASSERT_EXPR. */
3604 static void
3605 find_assert_locations_1 (basic_block bb, sbitmap live)
3607 gimple *last;
3609 last = last_stmt (bb);
3611 /* If BB's last statement is a conditional statement involving integer
3612 operands, determine if we need to add ASSERT_EXPRs. */
3613 if (last
3614 && gimple_code (last) == GIMPLE_COND
3615 && !fp_predicate (last)
3616 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
3617 find_conditional_asserts (bb, as_a <gcond *> (last));
3619 /* If BB's last statement is a switch statement involving integer
3620 operands, determine if we need to add ASSERT_EXPRs. */
3621 if (last
3622 && gimple_code (last) == GIMPLE_SWITCH
3623 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
3624 find_switch_asserts (bb, as_a <gswitch *> (last));
3626 /* Traverse all the statements in BB marking used names and looking
3627 for statements that may infer assertions for their used operands. */
3628 for (gimple_stmt_iterator si = gsi_last_bb (bb); !gsi_end_p (si);
3629 gsi_prev (&si))
3631 gimple *stmt;
3632 tree op;
3633 ssa_op_iter i;
3635 stmt = gsi_stmt (si);
3637 if (is_gimple_debug (stmt))
3638 continue;
3640 /* See if we can derive an assertion for any of STMT's operands. */
3641 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
3643 tree value;
3644 enum tree_code comp_code;
3646 /* If op is not live beyond this stmt, do not bother to insert
3647 asserts for it. */
3648 if (!bitmap_bit_p (live, SSA_NAME_VERSION (op)))
3649 continue;
3651 /* If OP is used in such a way that we can infer a value
3652 range for it, and we don't find a previous assertion for
3653 it, create a new assertion location node for OP. */
3654 if (infer_value_range (stmt, op, &comp_code, &value))
3656 /* If we are able to infer a nonzero value range for OP,
3657 then walk backwards through the use-def chain to see if OP
3658 was set via a typecast.
3660 If so, then we can also infer a nonzero value range
3661 for the operand of the NOP_EXPR. */
3662 if (comp_code == NE_EXPR && integer_zerop (value))
3664 tree t = op;
3665 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
3667 while (is_gimple_assign (def_stmt)
3668 && CONVERT_EXPR_CODE_P
3669 (gimple_assign_rhs_code (def_stmt))
3670 && TREE_CODE
3671 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
3672 && POINTER_TYPE_P
3673 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
3675 t = gimple_assign_rhs1 (def_stmt);
3676 def_stmt = SSA_NAME_DEF_STMT (t);
3678 /* Note we want to register the assert for the
3679 operand of the NOP_EXPR after SI, not after the
3680 conversion. */
3681 if (bitmap_bit_p (live, SSA_NAME_VERSION (t)))
3682 register_new_assert_for (t, t, comp_code, value,
3683 bb, NULL, si);
3687 register_new_assert_for (op, op, comp_code, value, bb, NULL, si);
3691 /* Update live. */
3692 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
3693 bitmap_set_bit (live, SSA_NAME_VERSION (op));
3694 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_DEF)
3695 bitmap_clear_bit (live, SSA_NAME_VERSION (op));
3698 /* Traverse all PHI nodes in BB, updating live. */
3699 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
3700 gsi_next (&si))
3702 use_operand_p arg_p;
3703 ssa_op_iter i;
3704 gphi *phi = si.phi ();
3705 tree res = gimple_phi_result (phi);
3707 if (virtual_operand_p (res))
3708 continue;
3710 FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
3712 tree arg = USE_FROM_PTR (arg_p);
3713 if (TREE_CODE (arg) == SSA_NAME)
3714 bitmap_set_bit (live, SSA_NAME_VERSION (arg));
3717 bitmap_clear_bit (live, SSA_NAME_VERSION (res));
3721 /* Do an RPO walk over the function computing SSA name liveness
3722 on-the-fly and deciding on assert expressions to insert. */
3724 static void
3725 find_assert_locations (void)
3727 int *rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
3728 int *bb_rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
3729 int *last_rpo = XCNEWVEC (int, last_basic_block_for_fn (cfun));
3730 int rpo_cnt, i;
3732 live = XCNEWVEC (sbitmap, last_basic_block_for_fn (cfun));
3733 rpo_cnt = pre_and_rev_post_order_compute (NULL, rpo, false);
3734 for (i = 0; i < rpo_cnt; ++i)
3735 bb_rpo[rpo[i]] = i;
3737 /* Pre-seed loop latch liveness from loop header PHI nodes. Due to
3738 the order we compute liveness and insert asserts we otherwise
3739 fail to insert asserts into the loop latch. */
3740 loop_p loop;
3741 FOR_EACH_LOOP (loop, 0)
3743 i = loop->latch->index;
3744 unsigned int j = single_succ_edge (loop->latch)->dest_idx;
3745 for (gphi_iterator gsi = gsi_start_phis (loop->header);
3746 !gsi_end_p (gsi); gsi_next (&gsi))
3748 gphi *phi = gsi.phi ();
3749 if (virtual_operand_p (gimple_phi_result (phi)))
3750 continue;
3751 tree arg = gimple_phi_arg_def (phi, j);
3752 if (TREE_CODE (arg) == SSA_NAME)
3754 if (live[i] == NULL)
3756 live[i] = sbitmap_alloc (num_ssa_names);
3757 bitmap_clear (live[i]);
3759 bitmap_set_bit (live[i], SSA_NAME_VERSION (arg));
3764 for (i = rpo_cnt - 1; i >= 0; --i)
3766 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, rpo[i]);
3767 edge e;
3768 edge_iterator ei;
3770 if (!live[rpo[i]])
3772 live[rpo[i]] = sbitmap_alloc (num_ssa_names);
3773 bitmap_clear (live[rpo[i]]);
3776 /* Process BB and update the live information with uses in
3777 this block. */
3778 find_assert_locations_1 (bb, live[rpo[i]]);
3780 /* Merge liveness into the predecessor blocks and free it. */
3781 if (!bitmap_empty_p (live[rpo[i]]))
3783 int pred_rpo = i;
3784 FOR_EACH_EDGE (e, ei, bb->preds)
3786 int pred = e->src->index;
3787 if ((e->flags & EDGE_DFS_BACK) || pred == ENTRY_BLOCK)
3788 continue;
3790 if (!live[pred])
3792 live[pred] = sbitmap_alloc (num_ssa_names);
3793 bitmap_clear (live[pred]);
3795 bitmap_ior (live[pred], live[pred], live[rpo[i]]);
3797 if (bb_rpo[pred] < pred_rpo)
3798 pred_rpo = bb_rpo[pred];
3801 /* Record the RPO number of the last visited block that needs
3802 live information from this block. */
3803 last_rpo[rpo[i]] = pred_rpo;
3805 else
3807 sbitmap_free (live[rpo[i]]);
3808 live[rpo[i]] = NULL;
3811 /* We can free all successors live bitmaps if all their
3812 predecessors have been visited already. */
3813 FOR_EACH_EDGE (e, ei, bb->succs)
3814 if (last_rpo[e->dest->index] == i
3815 && live[e->dest->index])
3817 sbitmap_free (live[e->dest->index]);
3818 live[e->dest->index] = NULL;
3822 XDELETEVEC (rpo);
3823 XDELETEVEC (bb_rpo);
3824 XDELETEVEC (last_rpo);
3825 for (i = 0; i < last_basic_block_for_fn (cfun); ++i)
3826 if (live[i])
3827 sbitmap_free (live[i]);
3828 XDELETEVEC (live);
3831 /* Create an ASSERT_EXPR for NAME and insert it in the location
3832 indicated by LOC. Return true if we made any edge insertions. */
3834 static bool
3835 process_assert_insertions_for (tree name, assert_locus *loc)
3837 /* Build the comparison expression NAME_i COMP_CODE VAL. */
3838 gimple *stmt;
3839 tree cond;
3840 gimple *assert_stmt;
3841 edge_iterator ei;
3842 edge e;
3844 /* If we have X <=> X do not insert an assert expr for that. */
3845 if (loc->expr == loc->val)
3846 return false;
3848 cond = build2 (loc->comp_code, boolean_type_node, loc->expr, loc->val);
3849 assert_stmt = build_assert_expr_for (cond, name);
3850 if (loc->e)
3852 /* We have been asked to insert the assertion on an edge. This
3853 is used only by COND_EXPR and SWITCH_EXPR assertions. */
3854 gcc_checking_assert (gimple_code (gsi_stmt (loc->si)) == GIMPLE_COND
3855 || (gimple_code (gsi_stmt (loc->si))
3856 == GIMPLE_SWITCH));
3858 gsi_insert_on_edge (loc->e, assert_stmt);
3859 return true;
3862 /* If the stmt iterator points at the end then this is an insertion
3863 at the beginning of a block. */
3864 if (gsi_end_p (loc->si))
3866 gimple_stmt_iterator si = gsi_after_labels (loc->bb);
3867 gsi_insert_before (&si, assert_stmt, GSI_SAME_STMT);
3868 return false;
3871 /* Otherwise, we can insert right after LOC->SI iff the
3872 statement must not be the last statement in the block. */
3873 stmt = gsi_stmt (loc->si);
3874 if (!stmt_ends_bb_p (stmt))
3876 gsi_insert_after (&loc->si, assert_stmt, GSI_SAME_STMT);
3877 return false;
3880 /* If STMT must be the last statement in BB, we can only insert new
3881 assertions on the non-abnormal edge out of BB. Note that since
3882 STMT is not control flow, there may only be one non-abnormal/eh edge
3883 out of BB. */
3884 FOR_EACH_EDGE (e, ei, loc->bb->succs)
3885 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
3887 gsi_insert_on_edge (e, assert_stmt);
3888 return true;
3891 gcc_unreachable ();
3894 /* Qsort helper for sorting assert locations. If stable is true, don't
3895 use iterative_hash_expr because it can be unstable for -fcompare-debug,
3896 on the other side some pointers might be NULL. */
3898 template <bool stable>
3899 static int
3900 compare_assert_loc (const void *pa, const void *pb)
3902 assert_locus * const a = *(assert_locus * const *)pa;
3903 assert_locus * const b = *(assert_locus * const *)pb;
3905 /* If stable, some asserts might be optimized away already, sort
3906 them last. */
3907 if (stable)
3909 if (a == NULL)
3910 return b != NULL;
3911 else if (b == NULL)
3912 return -1;
3915 if (a->e == NULL && b->e != NULL)
3916 return 1;
3917 else if (a->e != NULL && b->e == NULL)
3918 return -1;
3920 /* After the above checks, we know that (a->e == NULL) == (b->e == NULL),
3921 no need to test both a->e and b->e. */
3923 /* Sort after destination index. */
3924 if (a->e == NULL)
3926 else if (a->e->dest->index > b->e->dest->index)
3927 return 1;
3928 else if (a->e->dest->index < b->e->dest->index)
3929 return -1;
3931 /* Sort after comp_code. */
3932 if (a->comp_code > b->comp_code)
3933 return 1;
3934 else if (a->comp_code < b->comp_code)
3935 return -1;
3937 hashval_t ha, hb;
3939 /* E.g. if a->val is ADDR_EXPR of a VAR_DECL, iterative_hash_expr
3940 uses DECL_UID of the VAR_DECL, so sorting might differ between
3941 -g and -g0. When doing the removal of redundant assert exprs
3942 and commonization to successors, this does not matter, but for
3943 the final sort needs to be stable. */
3944 if (stable)
3946 ha = 0;
3947 hb = 0;
3949 else
3951 ha = iterative_hash_expr (a->expr, iterative_hash_expr (a->val, 0));
3952 hb = iterative_hash_expr (b->expr, iterative_hash_expr (b->val, 0));
3955 /* Break the tie using hashing and source/bb index. */
3956 if (ha == hb)
3957 return (a->e != NULL
3958 ? a->e->src->index - b->e->src->index
3959 : a->bb->index - b->bb->index);
3960 return ha > hb ? 1 : -1;
3963 /* Process all the insertions registered for every name N_i registered
3964 in NEED_ASSERT_FOR. The list of assertions to be inserted are
3965 found in ASSERTS_FOR[i]. */
3967 static void
3968 process_assert_insertions (void)
3970 unsigned i;
3971 bitmap_iterator bi;
3972 bool update_edges_p = false;
3973 int num_asserts = 0;
3975 if (dump_file && (dump_flags & TDF_DETAILS))
3976 dump_all_asserts (dump_file);
3978 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
3980 assert_locus *loc = asserts_for[i];
3981 gcc_assert (loc);
3983 auto_vec<assert_locus *, 16> asserts;
3984 for (; loc; loc = loc->next)
3985 asserts.safe_push (loc);
3986 asserts.qsort (compare_assert_loc<false>);
3988 /* Push down common asserts to successors and remove redundant ones. */
3989 unsigned ecnt = 0;
3990 assert_locus *common = NULL;
3991 unsigned commonj = 0;
3992 for (unsigned j = 0; j < asserts.length (); ++j)
3994 loc = asserts[j];
3995 if (! loc->e)
3996 common = NULL;
3997 else if (! common
3998 || loc->e->dest != common->e->dest
3999 || loc->comp_code != common->comp_code
4000 || ! operand_equal_p (loc->val, common->val, 0)
4001 || ! operand_equal_p (loc->expr, common->expr, 0))
4003 commonj = j;
4004 common = loc;
4005 ecnt = 1;
4007 else if (loc->e == asserts[j-1]->e)
4009 /* Remove duplicate asserts. */
4010 if (commonj == j - 1)
4012 commonj = j;
4013 common = loc;
4015 free (asserts[j-1]);
4016 asserts[j-1] = NULL;
4018 else
4020 ecnt++;
4021 if (EDGE_COUNT (common->e->dest->preds) == ecnt)
4023 /* We have the same assertion on all incoming edges of a BB.
4024 Insert it at the beginning of that block. */
4025 loc->bb = loc->e->dest;
4026 loc->e = NULL;
4027 loc->si = gsi_none ();
4028 common = NULL;
4029 /* Clear asserts commoned. */
4030 for (; commonj != j; ++commonj)
4031 if (asserts[commonj])
4033 free (asserts[commonj]);
4034 asserts[commonj] = NULL;
4040 /* The asserts vector sorting above might be unstable for
4041 -fcompare-debug, sort again to ensure a stable sort. */
4042 asserts.qsort (compare_assert_loc<true>);
4043 for (unsigned j = 0; j < asserts.length (); ++j)
4045 loc = asserts[j];
4046 if (! loc)
4047 break;
4048 update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
4049 num_asserts++;
4050 free (loc);
4054 if (update_edges_p)
4055 gsi_commit_edge_inserts ();
4057 statistics_counter_event (cfun, "Number of ASSERT_EXPR expressions inserted",
4058 num_asserts);
4062 /* Traverse the flowgraph looking for conditional jumps to insert range
4063 expressions. These range expressions are meant to provide information
4064 to optimizations that need to reason in terms of value ranges. They
4065 will not be expanded into RTL. For instance, given:
4067 x = ...
4068 y = ...
4069 if (x < y)
4070 y = x - 2;
4071 else
4072 x = y + 3;
4074 this pass will transform the code into:
4076 x = ...
4077 y = ...
4078 if (x < y)
4080 x = ASSERT_EXPR <x, x < y>
4081 y = x - 2
4083 else
4085 y = ASSERT_EXPR <y, x >= y>
4086 x = y + 3
4089 The idea is that once copy and constant propagation have run, other
4090 optimizations will be able to determine what ranges of values can 'x'
4091 take in different paths of the code, simply by checking the reaching
4092 definition of 'x'. */
4094 static void
4095 insert_range_assertions (void)
4097 need_assert_for = BITMAP_ALLOC (NULL);
4098 asserts_for = XCNEWVEC (assert_locus *, num_ssa_names);
4100 calculate_dominance_info (CDI_DOMINATORS);
4102 find_assert_locations ();
4103 if (!bitmap_empty_p (need_assert_for))
4105 process_assert_insertions ();
4106 update_ssa (TODO_update_ssa_no_phi);
4109 if (dump_file && (dump_flags & TDF_DETAILS))
4111 fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
4112 dump_function_to_file (current_function_decl, dump_file, dump_flags);
4115 free (asserts_for);
4116 BITMAP_FREE (need_assert_for);
4119 class vrp_prop : public ssa_propagation_engine
4121 public:
4122 enum ssa_prop_result visit_stmt (gimple *, edge *, tree *) FINAL OVERRIDE;
4123 enum ssa_prop_result visit_phi (gphi *) FINAL OVERRIDE;
4125 void vrp_initialize (void);
4126 void vrp_finalize (bool);
4127 void check_all_array_refs (void);
4128 void check_array_ref (location_t, tree, bool);
4129 void check_mem_ref (location_t, tree, bool);
4130 void search_for_addr_array (tree, location_t);
4132 class vr_values vr_values;
4133 /* Temporary delegator to minimize code churn. */
4134 value_range *get_value_range (const_tree op)
4135 { return vr_values.get_value_range (op); }
4136 void set_defs_to_varying (gimple *stmt)
4137 { return vr_values.set_defs_to_varying (stmt); }
4138 void extract_range_from_stmt (gimple *stmt, edge *taken_edge_p,
4139 tree *output_p, value_range *vr)
4140 { vr_values.extract_range_from_stmt (stmt, taken_edge_p, output_p, vr); }
4141 bool update_value_range (const_tree op, value_range *vr)
4142 { return vr_values.update_value_range (op, vr); }
4143 void extract_range_basic (value_range *vr, gimple *stmt)
4144 { vr_values.extract_range_basic (vr, stmt); }
4145 void extract_range_from_phi_node (gphi *phi, value_range *vr)
4146 { vr_values.extract_range_from_phi_node (phi, vr); }
4148 /* Checks one ARRAY_REF in REF, located at LOCUS. Ignores flexible arrays
4149 and "struct" hacks. If VRP can determine that the
4150 array subscript is a constant, check if it is outside valid
4151 range. If the array subscript is a RANGE, warn if it is
4152 non-overlapping with valid range.
4153 IGNORE_OFF_BY_ONE is true if the ARRAY_REF is inside a ADDR_EXPR. */
4155 void
4156 vrp_prop::check_array_ref (location_t location, tree ref,
4157 bool ignore_off_by_one)
4159 const value_range *vr = NULL;
4160 tree low_sub, up_sub;
4161 tree low_bound, up_bound, up_bound_p1;
4163 if (TREE_NO_WARNING (ref))
4164 return;
4166 low_sub = up_sub = TREE_OPERAND (ref, 1);
4167 up_bound = array_ref_up_bound (ref);
4169 if (!up_bound
4170 || TREE_CODE (up_bound) != INTEGER_CST
4171 || (warn_array_bounds < 2
4172 && array_at_struct_end_p (ref)))
4174 /* Accesses to trailing arrays via pointers may access storage
4175 beyond the types array bounds. For such arrays, or for flexible
4176 array members, as well as for other arrays of an unknown size,
4177 replace the upper bound with a more permissive one that assumes
4178 the size of the largest object is PTRDIFF_MAX. */
4179 tree eltsize = array_ref_element_size (ref);
4181 if (TREE_CODE (eltsize) != INTEGER_CST
4182 || integer_zerop (eltsize))
4184 up_bound = NULL_TREE;
4185 up_bound_p1 = NULL_TREE;
4187 else
4189 tree maxbound = TYPE_MAX_VALUE (ptrdiff_type_node);
4190 tree arg = TREE_OPERAND (ref, 0);
4191 poly_int64 off;
4193 if (get_addr_base_and_unit_offset (arg, &off) && known_gt (off, 0))
4194 maxbound = wide_int_to_tree (sizetype,
4195 wi::sub (wi::to_wide (maxbound),
4196 off));
4197 else
4198 maxbound = fold_convert (sizetype, maxbound);
4200 up_bound_p1 = int_const_binop (TRUNC_DIV_EXPR, maxbound, eltsize);
4202 up_bound = int_const_binop (MINUS_EXPR, up_bound_p1,
4203 build_int_cst (ptrdiff_type_node, 1));
4206 else
4207 up_bound_p1 = int_const_binop (PLUS_EXPR, up_bound,
4208 build_int_cst (TREE_TYPE (up_bound), 1));
4210 low_bound = array_ref_low_bound (ref);
4212 tree artype = TREE_TYPE (TREE_OPERAND (ref, 0));
4214 bool warned = false;
4216 /* Empty array. */
4217 if (up_bound && tree_int_cst_equal (low_bound, up_bound_p1))
4218 warned = warning_at (location, OPT_Warray_bounds,
4219 "array subscript %E is above array bounds of %qT",
4220 low_bound, artype);
4222 if (TREE_CODE (low_sub) == SSA_NAME)
4224 vr = get_value_range (low_sub);
4225 if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
4227 low_sub = vr->type == VR_RANGE ? vr->max : vr->min;
4228 up_sub = vr->type == VR_RANGE ? vr->min : vr->max;
4232 if (vr && vr->type == VR_ANTI_RANGE)
4234 if (up_bound
4235 && TREE_CODE (up_sub) == INTEGER_CST
4236 && (ignore_off_by_one
4237 ? tree_int_cst_lt (up_bound, up_sub)
4238 : tree_int_cst_le (up_bound, up_sub))
4239 && TREE_CODE (low_sub) == INTEGER_CST
4240 && tree_int_cst_le (low_sub, low_bound))
4241 warned = warning_at (location, OPT_Warray_bounds,
4242 "array subscript [%E, %E] is outside "
4243 "array bounds of %qT",
4244 low_sub, up_sub, artype);
4246 else if (up_bound
4247 && TREE_CODE (up_sub) == INTEGER_CST
4248 && (ignore_off_by_one
4249 ? !tree_int_cst_le (up_sub, up_bound_p1)
4250 : !tree_int_cst_le (up_sub, up_bound)))
4252 if (dump_file && (dump_flags & TDF_DETAILS))
4254 fprintf (dump_file, "Array bound warning for ");
4255 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
4256 fprintf (dump_file, "\n");
4258 warned = warning_at (location, OPT_Warray_bounds,
4259 "array subscript %E is above array bounds of %qT",
4260 up_sub, artype);
4262 else if (TREE_CODE (low_sub) == INTEGER_CST
4263 && tree_int_cst_lt (low_sub, low_bound))
4265 if (dump_file && (dump_flags & TDF_DETAILS))
4267 fprintf (dump_file, "Array bound warning for ");
4268 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
4269 fprintf (dump_file, "\n");
4271 warned = warning_at (location, OPT_Warray_bounds,
4272 "array subscript %E is below array bounds of %qT",
4273 low_sub, artype);
4276 if (warned)
4278 ref = TREE_OPERAND (ref, 0);
4280 if (DECL_P (ref))
4281 inform (DECL_SOURCE_LOCATION (ref), "while referencing %qD", ref);
4283 TREE_NO_WARNING (ref) = 1;
4287 /* Checks one MEM_REF in REF, located at LOCATION, for out-of-bounds
4288 references to string constants. If VRP can determine that the array
4289 subscript is a constant, check if it is outside valid range.
4290 If the array subscript is a RANGE, warn if it is non-overlapping
4291 with valid range.
4292 IGNORE_OFF_BY_ONE is true if the MEM_REF is inside an ADDR_EXPR
4293 (used to allow one-past-the-end indices for code that takes
4294 the address of the just-past-the-end element of an array). */
4296 void
4297 vrp_prop::check_mem_ref (location_t location, tree ref,
4298 bool ignore_off_by_one)
4300 if (TREE_NO_WARNING (ref))
4301 return;
4303 tree arg = TREE_OPERAND (ref, 0);
4304 /* The constant and variable offset of the reference. */
4305 tree cstoff = TREE_OPERAND (ref, 1);
4306 tree varoff = NULL_TREE;
4308 const offset_int maxobjsize = tree_to_shwi (max_object_size ());
4310 /* The array or string constant bounds in bytes. Initially set
4311 to [-MAXOBJSIZE - 1, MAXOBJSIZE] until a tighter bound is
4312 determined. */
4313 offset_int arrbounds[2] = { -maxobjsize - 1, maxobjsize };
4315 /* The minimum and maximum intermediate offset. For a reference
4316 to be valid, not only does the final offset/subscript must be
4317 in bounds but all intermediate offsets should be as well.
4318 GCC may be able to deal gracefully with such out-of-bounds
4319 offsets so the checking is only enbaled at -Warray-bounds=2
4320 where it may help detect bugs in uses of the intermediate
4321 offsets that could otherwise not be detectable. */
4322 offset_int ioff = wi::to_offset (fold_convert (ptrdiff_type_node, cstoff));
4323 offset_int extrema[2] = { 0, wi::abs (ioff) };
4325 /* The range of the byte offset into the reference. */
4326 offset_int offrange[2] = { 0, 0 };
4328 const value_range *vr = NULL;
4330 /* Determine the offsets and increment OFFRANGE for the bounds of each.
4331 The loop computes the the range of the final offset for expressions
4332 such as (A + i0 + ... + iN)[CSTOFF] where i0 through iN are SSA_NAMEs
4333 in some range. */
4334 while (TREE_CODE (arg) == SSA_NAME)
4336 gimple *def = SSA_NAME_DEF_STMT (arg);
4337 if (!is_gimple_assign (def))
4338 break;
4340 tree_code code = gimple_assign_rhs_code (def);
4341 if (code == POINTER_PLUS_EXPR)
4343 arg = gimple_assign_rhs1 (def);
4344 varoff = gimple_assign_rhs2 (def);
4346 else if (code == ASSERT_EXPR)
4348 arg = TREE_OPERAND (gimple_assign_rhs1 (def), 0);
4349 continue;
4351 else
4352 return;
4354 /* VAROFF should always be a SSA_NAME here (and not even
4355 INTEGER_CST) but there's no point in taking chances. */
4356 if (TREE_CODE (varoff) != SSA_NAME)
4357 break;
4359 vr = get_value_range (varoff);
4360 if (!vr || vr->type == VR_UNDEFINED || !vr->min || !vr->max)
4361 break;
4363 if (TREE_CODE (vr->min) != INTEGER_CST
4364 || TREE_CODE (vr->max) != INTEGER_CST)
4365 break;
4367 if (vr->type == VR_RANGE)
4369 if (tree_int_cst_lt (vr->min, vr->max))
4371 offset_int min
4372 = wi::to_offset (fold_convert (ptrdiff_type_node, vr->min));
4373 offset_int max
4374 = wi::to_offset (fold_convert (ptrdiff_type_node, vr->max));
4375 if (min < max)
4377 offrange[0] += min;
4378 offrange[1] += max;
4380 else
4382 offrange[0] += max;
4383 offrange[1] += min;
4386 else
4388 /* Conservatively add [-MAXOBJSIZE -1, MAXOBJSIZE]
4389 to OFFRANGE. */
4390 offrange[0] += arrbounds[0];
4391 offrange[1] += arrbounds[1];
4394 else
4396 /* For an anti-range, analogously to the above, conservatively
4397 add [-MAXOBJSIZE -1, MAXOBJSIZE] to OFFRANGE. */
4398 offrange[0] += arrbounds[0];
4399 offrange[1] += arrbounds[1];
4402 /* Keep track of the minimum and maximum offset. */
4403 if (offrange[1] < 0 && offrange[1] < extrema[0])
4404 extrema[0] = offrange[1];
4405 if (offrange[0] > 0 && offrange[0] > extrema[1])
4406 extrema[1] = offrange[0];
4408 if (offrange[0] < arrbounds[0])
4409 offrange[0] = arrbounds[0];
4411 if (offrange[1] > arrbounds[1])
4412 offrange[1] = arrbounds[1];
4415 if (TREE_CODE (arg) == ADDR_EXPR)
4417 arg = TREE_OPERAND (arg, 0);
4418 if (TREE_CODE (arg) != STRING_CST
4419 && TREE_CODE (arg) != VAR_DECL)
4420 return;
4422 else
4423 return;
4425 /* The type of the object being referred to. It can be an array,
4426 string literal, or a non-array type when the MEM_REF represents
4427 a reference/subscript via a pointer to an object that is not
4428 an element of an array. References to members of structs and
4429 unions are excluded because MEM_REF doesn't make it possible
4430 to identify the member where the reference originated.
4431 Incomplete types are excluded as well because their size is
4432 not known. */
4433 tree reftype = TREE_TYPE (arg);
4434 if (POINTER_TYPE_P (reftype)
4435 || !COMPLETE_TYPE_P (reftype)
4436 || TREE_CODE (TYPE_SIZE_UNIT (reftype)) != INTEGER_CST
4437 || RECORD_OR_UNION_TYPE_P (reftype))
4438 return;
4440 offset_int eltsize;
4441 if (TREE_CODE (reftype) == ARRAY_TYPE)
4443 eltsize = wi::to_offset (TYPE_SIZE_UNIT (TREE_TYPE (reftype)));
4445 if (tree dom = TYPE_DOMAIN (reftype))
4447 tree bnds[] = { TYPE_MIN_VALUE (dom), TYPE_MAX_VALUE (dom) };
4448 if (array_at_struct_end_p (arg)
4449 || !bnds[0] || !bnds[1])
4451 arrbounds[0] = 0;
4452 arrbounds[1] = wi::lrshift (maxobjsize, wi::floor_log2 (eltsize));
4454 else
4456 arrbounds[0] = wi::to_offset (bnds[0]) * eltsize;
4457 arrbounds[1] = (wi::to_offset (bnds[1]) + 1) * eltsize;
4460 else
4462 arrbounds[0] = 0;
4463 arrbounds[1] = wi::lrshift (maxobjsize, wi::floor_log2 (eltsize));
4466 if (TREE_CODE (ref) == MEM_REF)
4468 /* For MEM_REF determine a tighter bound of the non-array
4469 element type. */
4470 tree eltype = TREE_TYPE (reftype);
4471 while (TREE_CODE (eltype) == ARRAY_TYPE)
4472 eltype = TREE_TYPE (eltype);
4473 eltsize = wi::to_offset (TYPE_SIZE_UNIT (eltype));
4476 else
4478 eltsize = 1;
4479 arrbounds[0] = 0;
4480 arrbounds[1] = wi::to_offset (TYPE_SIZE_UNIT (reftype));
4483 offrange[0] += ioff;
4484 offrange[1] += ioff;
4486 /* Compute the more permissive upper bound when IGNORE_OFF_BY_ONE
4487 is set (when taking the address of the one-past-last element
4488 of an array) but always use the stricter bound in diagnostics. */
4489 offset_int ubound = arrbounds[1];
4490 if (ignore_off_by_one)
4491 ubound += 1;
4493 if (offrange[0] >= ubound || offrange[1] < arrbounds[0])
4495 /* Treat a reference to a non-array object as one to an array
4496 of a single element. */
4497 if (TREE_CODE (reftype) != ARRAY_TYPE)
4498 reftype = build_array_type_nelts (reftype, 1);
4500 if (TREE_CODE (ref) == MEM_REF)
4502 /* Extract the element type out of MEM_REF and use its size
4503 to compute the index to print in the diagnostic; arrays
4504 in MEM_REF don't mean anything. */
4505 tree type = TREE_TYPE (ref);
4506 while (TREE_CODE (type) == ARRAY_TYPE)
4507 type = TREE_TYPE (type);
4508 tree size = TYPE_SIZE_UNIT (type);
4509 offrange[0] = offrange[0] / wi::to_offset (size);
4510 offrange[1] = offrange[1] / wi::to_offset (size);
4512 else
4514 /* For anything other than MEM_REF, compute the index to
4515 print in the diagnostic as the offset over element size. */
4516 offrange[0] = offrange[0] / eltsize;
4517 offrange[1] = offrange[1] / eltsize;
4520 bool warned;
4521 if (offrange[0] == offrange[1])
4522 warned = warning_at (location, OPT_Warray_bounds,
4523 "array subscript %wi is outside array bounds "
4524 "of %qT",
4525 offrange[0].to_shwi (), reftype);
4526 else
4527 warned = warning_at (location, OPT_Warray_bounds,
4528 "array subscript [%wi, %wi] is outside "
4529 "array bounds of %qT",
4530 offrange[0].to_shwi (),
4531 offrange[1].to_shwi (), reftype);
4532 if (warned && DECL_P (arg))
4533 inform (DECL_SOURCE_LOCATION (arg), "while referencing %qD", arg);
4535 TREE_NO_WARNING (ref) = 1;
4536 return;
4539 if (warn_array_bounds < 2)
4540 return;
4542 /* At level 2 check also intermediate offsets. */
4543 int i = 0;
4544 if (extrema[i] < -arrbounds[1] || extrema[i = 1] > ubound)
4546 HOST_WIDE_INT tmpidx = extrema[i].to_shwi () / eltsize.to_shwi ();
4548 warning_at (location, OPT_Warray_bounds,
4549 "intermediate array offset %wi is outside array bounds "
4550 "of %qT",
4551 tmpidx, reftype);
4552 TREE_NO_WARNING (ref) = 1;
4556 /* Searches if the expr T, located at LOCATION computes
4557 address of an ARRAY_REF, and call check_array_ref on it. */
4559 void
4560 vrp_prop::search_for_addr_array (tree t, location_t location)
4562 /* Check each ARRAY_REF and MEM_REF in the reference chain. */
4565 if (TREE_CODE (t) == ARRAY_REF)
4566 check_array_ref (location, t, true /*ignore_off_by_one*/);
4567 else if (TREE_CODE (t) == MEM_REF)
4568 check_mem_ref (location, t, true /*ignore_off_by_one*/);
4570 t = TREE_OPERAND (t, 0);
4572 while (handled_component_p (t) || TREE_CODE (t) == MEM_REF);
4574 if (TREE_CODE (t) != MEM_REF
4575 || TREE_CODE (TREE_OPERAND (t, 0)) != ADDR_EXPR
4576 || TREE_NO_WARNING (t))
4577 return;
4579 tree tem = TREE_OPERAND (TREE_OPERAND (t, 0), 0);
4580 tree low_bound, up_bound, el_sz;
4581 if (TREE_CODE (TREE_TYPE (tem)) != ARRAY_TYPE
4582 || TREE_CODE (TREE_TYPE (TREE_TYPE (tem))) == ARRAY_TYPE
4583 || !TYPE_DOMAIN (TREE_TYPE (tem)))
4584 return;
4586 low_bound = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
4587 up_bound = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
4588 el_sz = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (tem)));
4589 if (!low_bound
4590 || TREE_CODE (low_bound) != INTEGER_CST
4591 || !up_bound
4592 || TREE_CODE (up_bound) != INTEGER_CST
4593 || !el_sz
4594 || TREE_CODE (el_sz) != INTEGER_CST)
4595 return;
4597 offset_int idx;
4598 if (!mem_ref_offset (t).is_constant (&idx))
4599 return;
4601 bool warned = false;
4602 idx = wi::sdiv_trunc (idx, wi::to_offset (el_sz));
4603 if (idx < 0)
4605 if (dump_file && (dump_flags & TDF_DETAILS))
4607 fprintf (dump_file, "Array bound warning for ");
4608 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
4609 fprintf (dump_file, "\n");
4611 warned = warning_at (location, OPT_Warray_bounds,
4612 "array subscript %wi is below "
4613 "array bounds of %qT",
4614 idx.to_shwi (), TREE_TYPE (tem));
4616 else if (idx > (wi::to_offset (up_bound)
4617 - wi::to_offset (low_bound) + 1))
4619 if (dump_file && (dump_flags & TDF_DETAILS))
4621 fprintf (dump_file, "Array bound warning for ");
4622 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
4623 fprintf (dump_file, "\n");
4625 warned = warning_at (location, OPT_Warray_bounds,
4626 "array subscript %wu is above "
4627 "array bounds of %qT",
4628 idx.to_uhwi (), TREE_TYPE (tem));
4631 if (warned)
4633 if (DECL_P (t))
4634 inform (DECL_SOURCE_LOCATION (t), "while referencing %qD", t);
4636 TREE_NO_WARNING (t) = 1;
4640 /* walk_tree() callback that checks if *TP is
4641 an ARRAY_REF inside an ADDR_EXPR (in which an array
4642 subscript one outside the valid range is allowed). Call
4643 check_array_ref for each ARRAY_REF found. The location is
4644 passed in DATA. */
4646 static tree
4647 check_array_bounds (tree *tp, int *walk_subtree, void *data)
4649 tree t = *tp;
4650 struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
4651 location_t location;
4653 if (EXPR_HAS_LOCATION (t))
4654 location = EXPR_LOCATION (t);
4655 else
4656 location = gimple_location (wi->stmt);
4658 *walk_subtree = TRUE;
4660 vrp_prop *vrp_prop = (class vrp_prop *)wi->info;
4661 if (TREE_CODE (t) == ARRAY_REF)
4662 vrp_prop->check_array_ref (location, t, false /*ignore_off_by_one*/);
4663 else if (TREE_CODE (t) == MEM_REF)
4664 vrp_prop->check_mem_ref (location, t, false /*ignore_off_by_one*/);
4665 else if (TREE_CODE (t) == ADDR_EXPR)
4667 vrp_prop->search_for_addr_array (t, location);
4668 *walk_subtree = FALSE;
4671 return NULL_TREE;
4674 /* A dom_walker subclass for use by vrp_prop::check_all_array_refs,
4675 to walk over all statements of all reachable BBs and call
4676 check_array_bounds on them. */
4678 class check_array_bounds_dom_walker : public dom_walker
4680 public:
4681 check_array_bounds_dom_walker (vrp_prop *prop)
4682 : dom_walker (CDI_DOMINATORS,
4683 /* Discover non-executable edges, preserving EDGE_EXECUTABLE
4684 flags, so that we can merge in information on
4685 non-executable edges from vrp_folder . */
4686 REACHABLE_BLOCKS_PRESERVING_FLAGS),
4687 m_prop (prop) {}
4688 ~check_array_bounds_dom_walker () {}
4690 edge before_dom_children (basic_block) FINAL OVERRIDE;
4692 private:
4693 vrp_prop *m_prop;
4696 /* Implementation of dom_walker::before_dom_children.
4698 Walk over all statements of BB and call check_array_bounds on them,
4699 and determine if there's a unique successor edge. */
4701 edge
4702 check_array_bounds_dom_walker::before_dom_children (basic_block bb)
4704 gimple_stmt_iterator si;
4705 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
4707 gimple *stmt = gsi_stmt (si);
4708 struct walk_stmt_info wi;
4709 if (!gimple_has_location (stmt)
4710 || is_gimple_debug (stmt))
4711 continue;
4713 memset (&wi, 0, sizeof (wi));
4715 wi.info = m_prop;
4717 walk_gimple_op (stmt, check_array_bounds, &wi);
4720 /* Determine if there's a unique successor edge, and if so, return
4721 that back to dom_walker, ensuring that we don't visit blocks that
4722 became unreachable during the VRP propagation
4723 (PR tree-optimization/83312). */
4724 return find_taken_edge (bb, NULL_TREE);
4727 /* Walk over all statements of all reachable BBs and call check_array_bounds
4728 on them. */
4730 void
4731 vrp_prop::check_all_array_refs ()
4733 check_array_bounds_dom_walker w (this);
4734 w.walk (ENTRY_BLOCK_PTR_FOR_FN (cfun));
4737 /* Return true if all imm uses of VAR are either in STMT, or
4738 feed (optionally through a chain of single imm uses) GIMPLE_COND
4739 in basic block COND_BB. */
4741 static bool
4742 all_imm_uses_in_stmt_or_feed_cond (tree var, gimple *stmt, basic_block cond_bb)
4744 use_operand_p use_p, use2_p;
4745 imm_use_iterator iter;
4747 FOR_EACH_IMM_USE_FAST (use_p, iter, var)
4748 if (USE_STMT (use_p) != stmt)
4750 gimple *use_stmt = USE_STMT (use_p), *use_stmt2;
4751 if (is_gimple_debug (use_stmt))
4752 continue;
4753 while (is_gimple_assign (use_stmt)
4754 && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
4755 && single_imm_use (gimple_assign_lhs (use_stmt),
4756 &use2_p, &use_stmt2))
4757 use_stmt = use_stmt2;
4758 if (gimple_code (use_stmt) != GIMPLE_COND
4759 || gimple_bb (use_stmt) != cond_bb)
4760 return false;
4762 return true;
4765 /* Handle
4766 _4 = x_3 & 31;
4767 if (_4 != 0)
4768 goto <bb 6>;
4769 else
4770 goto <bb 7>;
4771 <bb 6>:
4772 __builtin_unreachable ();
4773 <bb 7>:
4774 x_5 = ASSERT_EXPR <x_3, ...>;
4775 If x_3 has no other immediate uses (checked by caller),
4776 var is the x_3 var from ASSERT_EXPR, we can clear low 5 bits
4777 from the non-zero bitmask. */
4779 void
4780 maybe_set_nonzero_bits (edge e, tree var)
4782 basic_block cond_bb = e->src;
4783 gimple *stmt = last_stmt (cond_bb);
4784 tree cst;
4786 if (stmt == NULL
4787 || gimple_code (stmt) != GIMPLE_COND
4788 || gimple_cond_code (stmt) != ((e->flags & EDGE_TRUE_VALUE)
4789 ? EQ_EXPR : NE_EXPR)
4790 || TREE_CODE (gimple_cond_lhs (stmt)) != SSA_NAME
4791 || !integer_zerop (gimple_cond_rhs (stmt)))
4792 return;
4794 stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt));
4795 if (!is_gimple_assign (stmt)
4796 || gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
4797 || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
4798 return;
4799 if (gimple_assign_rhs1 (stmt) != var)
4801 gimple *stmt2;
4803 if (TREE_CODE (gimple_assign_rhs1 (stmt)) != SSA_NAME)
4804 return;
4805 stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
4806 if (!gimple_assign_cast_p (stmt2)
4807 || gimple_assign_rhs1 (stmt2) != var
4808 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt2))
4809 || (TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (stmt)))
4810 != TYPE_PRECISION (TREE_TYPE (var))))
4811 return;
4813 cst = gimple_assign_rhs2 (stmt);
4814 set_nonzero_bits (var, wi::bit_and_not (get_nonzero_bits (var),
4815 wi::to_wide (cst)));
4818 /* Convert range assertion expressions into the implied copies and
4819 copy propagate away the copies. Doing the trivial copy propagation
4820 here avoids the need to run the full copy propagation pass after
4821 VRP.
4823 FIXME, this will eventually lead to copy propagation removing the
4824 names that had useful range information attached to them. For
4825 instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
4826 then N_i will have the range [3, +INF].
4828 However, by converting the assertion into the implied copy
4829 operation N_i = N_j, we will then copy-propagate N_j into the uses
4830 of N_i and lose the range information. We may want to hold on to
4831 ASSERT_EXPRs a little while longer as the ranges could be used in
4832 things like jump threading.
4834 The problem with keeping ASSERT_EXPRs around is that passes after
4835 VRP need to handle them appropriately.
4837 Another approach would be to make the range information a first
4838 class property of the SSA_NAME so that it can be queried from
4839 any pass. This is made somewhat more complex by the need for
4840 multiple ranges to be associated with one SSA_NAME. */
4842 static void
4843 remove_range_assertions (void)
4845 basic_block bb;
4846 gimple_stmt_iterator si;
4847 /* 1 if looking at ASSERT_EXPRs immediately at the beginning of
4848 a basic block preceeded by GIMPLE_COND branching to it and
4849 __builtin_trap, -1 if not yet checked, 0 otherwise. */
4850 int is_unreachable;
4852 /* Note that the BSI iterator bump happens at the bottom of the
4853 loop and no bump is necessary if we're removing the statement
4854 referenced by the current BSI. */
4855 FOR_EACH_BB_FN (bb, cfun)
4856 for (si = gsi_after_labels (bb), is_unreachable = -1; !gsi_end_p (si);)
4858 gimple *stmt = gsi_stmt (si);
4860 if (is_gimple_assign (stmt)
4861 && gimple_assign_rhs_code (stmt) == ASSERT_EXPR)
4863 tree lhs = gimple_assign_lhs (stmt);
4864 tree rhs = gimple_assign_rhs1 (stmt);
4865 tree var;
4867 var = ASSERT_EXPR_VAR (rhs);
4869 if (TREE_CODE (var) == SSA_NAME
4870 && !POINTER_TYPE_P (TREE_TYPE (lhs))
4871 && SSA_NAME_RANGE_INFO (lhs))
4873 if (is_unreachable == -1)
4875 is_unreachable = 0;
4876 if (single_pred_p (bb)
4877 && assert_unreachable_fallthru_edge_p
4878 (single_pred_edge (bb)))
4879 is_unreachable = 1;
4881 /* Handle
4882 if (x_7 >= 10 && x_7 < 20)
4883 __builtin_unreachable ();
4884 x_8 = ASSERT_EXPR <x_7, ...>;
4885 if the only uses of x_7 are in the ASSERT_EXPR and
4886 in the condition. In that case, we can copy the
4887 range info from x_8 computed in this pass also
4888 for x_7. */
4889 if (is_unreachable
4890 && all_imm_uses_in_stmt_or_feed_cond (var, stmt,
4891 single_pred (bb)))
4893 set_range_info (var, SSA_NAME_RANGE_TYPE (lhs),
4894 SSA_NAME_RANGE_INFO (lhs)->get_min (),
4895 SSA_NAME_RANGE_INFO (lhs)->get_max ());
4896 maybe_set_nonzero_bits (single_pred_edge (bb), var);
4900 /* Propagate the RHS into every use of the LHS. For SSA names
4901 also propagate abnormals as it merely restores the original
4902 IL in this case (an replace_uses_by would assert). */
4903 if (TREE_CODE (var) == SSA_NAME)
4905 imm_use_iterator iter;
4906 use_operand_p use_p;
4907 gimple *use_stmt;
4908 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
4909 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
4910 SET_USE (use_p, var);
4912 else
4913 replace_uses_by (lhs, var);
4915 /* And finally, remove the copy, it is not needed. */
4916 gsi_remove (&si, true);
4917 release_defs (stmt);
4919 else
4921 if (!is_gimple_debug (gsi_stmt (si)))
4922 is_unreachable = 0;
4923 gsi_next (&si);
4928 /* Return true if STMT is interesting for VRP. */
4930 bool
4931 stmt_interesting_for_vrp (gimple *stmt)
4933 if (gimple_code (stmt) == GIMPLE_PHI)
4935 tree res = gimple_phi_result (stmt);
4936 return (!virtual_operand_p (res)
4937 && (INTEGRAL_TYPE_P (TREE_TYPE (res))
4938 || POINTER_TYPE_P (TREE_TYPE (res))));
4940 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
4942 tree lhs = gimple_get_lhs (stmt);
4944 /* In general, assignments with virtual operands are not useful
4945 for deriving ranges, with the obvious exception of calls to
4946 builtin functions. */
4947 if (lhs && TREE_CODE (lhs) == SSA_NAME
4948 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
4949 || POINTER_TYPE_P (TREE_TYPE (lhs)))
4950 && (is_gimple_call (stmt)
4951 || !gimple_vuse (stmt)))
4952 return true;
4953 else if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
4954 switch (gimple_call_internal_fn (stmt))
4956 case IFN_ADD_OVERFLOW:
4957 case IFN_SUB_OVERFLOW:
4958 case IFN_MUL_OVERFLOW:
4959 case IFN_ATOMIC_COMPARE_EXCHANGE:
4960 /* These internal calls return _Complex integer type,
4961 but are interesting to VRP nevertheless. */
4962 if (lhs && TREE_CODE (lhs) == SSA_NAME)
4963 return true;
4964 break;
4965 default:
4966 break;
4969 else if (gimple_code (stmt) == GIMPLE_COND
4970 || gimple_code (stmt) == GIMPLE_SWITCH)
4971 return true;
4973 return false;
4976 /* Initialization required by ssa_propagate engine. */
4978 void
4979 vrp_prop::vrp_initialize ()
4981 basic_block bb;
4983 FOR_EACH_BB_FN (bb, cfun)
4985 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
4986 gsi_next (&si))
4988 gphi *phi = si.phi ();
4989 if (!stmt_interesting_for_vrp (phi))
4991 tree lhs = PHI_RESULT (phi);
4992 set_value_range_to_varying (get_value_range (lhs));
4993 prop_set_simulate_again (phi, false);
4995 else
4996 prop_set_simulate_again (phi, true);
4999 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
5000 gsi_next (&si))
5002 gimple *stmt = gsi_stmt (si);
5004 /* If the statement is a control insn, then we do not
5005 want to avoid simulating the statement once. Failure
5006 to do so means that those edges will never get added. */
5007 if (stmt_ends_bb_p (stmt))
5008 prop_set_simulate_again (stmt, true);
5009 else if (!stmt_interesting_for_vrp (stmt))
5011 set_defs_to_varying (stmt);
5012 prop_set_simulate_again (stmt, false);
5014 else
5015 prop_set_simulate_again (stmt, true);
5020 /* Searches the case label vector VEC for the index *IDX of the CASE_LABEL
5021 that includes the value VAL. The search is restricted to the range
5022 [START_IDX, n - 1] where n is the size of VEC.
5024 If there is a CASE_LABEL for VAL, its index is placed in IDX and true is
5025 returned.
5027 If there is no CASE_LABEL for VAL and there is one that is larger than VAL,
5028 it is placed in IDX and false is returned.
5030 If VAL is larger than any CASE_LABEL, n is placed on IDX and false is
5031 returned. */
5033 bool
5034 find_case_label_index (gswitch *stmt, size_t start_idx, tree val, size_t *idx)
5036 size_t n = gimple_switch_num_labels (stmt);
5037 size_t low, high;
5039 /* Find case label for minimum of the value range or the next one.
5040 At each iteration we are searching in [low, high - 1]. */
5042 for (low = start_idx, high = n; high != low; )
5044 tree t;
5045 int cmp;
5046 /* Note that i != high, so we never ask for n. */
5047 size_t i = (high + low) / 2;
5048 t = gimple_switch_label (stmt, i);
5050 /* Cache the result of comparing CASE_LOW and val. */
5051 cmp = tree_int_cst_compare (CASE_LOW (t), val);
5053 if (cmp == 0)
5055 /* Ranges cannot be empty. */
5056 *idx = i;
5057 return true;
5059 else if (cmp > 0)
5060 high = i;
5061 else
5063 low = i + 1;
5064 if (CASE_HIGH (t) != NULL
5065 && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
5067 *idx = i;
5068 return true;
5073 *idx = high;
5074 return false;
5077 /* Searches the case label vector VEC for the range of CASE_LABELs that is used
5078 for values between MIN and MAX. The first index is placed in MIN_IDX. The
5079 last index is placed in MAX_IDX. If the range of CASE_LABELs is empty
5080 then MAX_IDX < MIN_IDX.
5081 Returns true if the default label is not needed. */
5083 bool
5084 find_case_label_range (gswitch *stmt, tree min, tree max, size_t *min_idx,
5085 size_t *max_idx)
5087 size_t i, j;
5088 bool min_take_default = !find_case_label_index (stmt, 1, min, &i);
5089 bool max_take_default = !find_case_label_index (stmt, i, max, &j);
5091 if (i == j
5092 && min_take_default
5093 && max_take_default)
5095 /* Only the default case label reached.
5096 Return an empty range. */
5097 *min_idx = 1;
5098 *max_idx = 0;
5099 return false;
5101 else
5103 bool take_default = min_take_default || max_take_default;
5104 tree low, high;
5105 size_t k;
5107 if (max_take_default)
5108 j--;
5110 /* If the case label range is continuous, we do not need
5111 the default case label. Verify that. */
5112 high = CASE_LOW (gimple_switch_label (stmt, i));
5113 if (CASE_HIGH (gimple_switch_label (stmt, i)))
5114 high = CASE_HIGH (gimple_switch_label (stmt, i));
5115 for (k = i + 1; k <= j; ++k)
5117 low = CASE_LOW (gimple_switch_label (stmt, k));
5118 if (!integer_onep (int_const_binop (MINUS_EXPR, low, high)))
5120 take_default = true;
5121 break;
5123 high = low;
5124 if (CASE_HIGH (gimple_switch_label (stmt, k)))
5125 high = CASE_HIGH (gimple_switch_label (stmt, k));
5128 *min_idx = i;
5129 *max_idx = j;
5130 return !take_default;
5134 /* Evaluate statement STMT. If the statement produces a useful range,
5135 return SSA_PROP_INTERESTING and record the SSA name with the
5136 interesting range into *OUTPUT_P.
5138 If STMT is a conditional branch and we can determine its truth
5139 value, the taken edge is recorded in *TAKEN_EDGE_P.
5141 If STMT produces a varying value, return SSA_PROP_VARYING. */
5143 enum ssa_prop_result
5144 vrp_prop::visit_stmt (gimple *stmt, edge *taken_edge_p, tree *output_p)
5146 value_range vr = VR_INITIALIZER;
5147 tree lhs = gimple_get_lhs (stmt);
5148 extract_range_from_stmt (stmt, taken_edge_p, output_p, &vr);
5150 if (*output_p)
5152 if (update_value_range (*output_p, &vr))
5154 if (dump_file && (dump_flags & TDF_DETAILS))
5156 fprintf (dump_file, "Found new range for ");
5157 print_generic_expr (dump_file, *output_p);
5158 fprintf (dump_file, ": ");
5159 dump_value_range (dump_file, &vr);
5160 fprintf (dump_file, "\n");
5163 if (vr.type == VR_VARYING)
5164 return SSA_PROP_VARYING;
5166 return SSA_PROP_INTERESTING;
5168 return SSA_PROP_NOT_INTERESTING;
5171 if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
5172 switch (gimple_call_internal_fn (stmt))
5174 case IFN_ADD_OVERFLOW:
5175 case IFN_SUB_OVERFLOW:
5176 case IFN_MUL_OVERFLOW:
5177 case IFN_ATOMIC_COMPARE_EXCHANGE:
5178 /* These internal calls return _Complex integer type,
5179 which VRP does not track, but the immediate uses
5180 thereof might be interesting. */
5181 if (lhs && TREE_CODE (lhs) == SSA_NAME)
5183 imm_use_iterator iter;
5184 use_operand_p use_p;
5185 enum ssa_prop_result res = SSA_PROP_VARYING;
5187 set_value_range_to_varying (get_value_range (lhs));
5189 FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
5191 gimple *use_stmt = USE_STMT (use_p);
5192 if (!is_gimple_assign (use_stmt))
5193 continue;
5194 enum tree_code rhs_code = gimple_assign_rhs_code (use_stmt);
5195 if (rhs_code != REALPART_EXPR && rhs_code != IMAGPART_EXPR)
5196 continue;
5197 tree rhs1 = gimple_assign_rhs1 (use_stmt);
5198 tree use_lhs = gimple_assign_lhs (use_stmt);
5199 if (TREE_CODE (rhs1) != rhs_code
5200 || TREE_OPERAND (rhs1, 0) != lhs
5201 || TREE_CODE (use_lhs) != SSA_NAME
5202 || !stmt_interesting_for_vrp (use_stmt)
5203 || (!INTEGRAL_TYPE_P (TREE_TYPE (use_lhs))
5204 || !TYPE_MIN_VALUE (TREE_TYPE (use_lhs))
5205 || !TYPE_MAX_VALUE (TREE_TYPE (use_lhs))))
5206 continue;
5208 /* If there is a change in the value range for any of the
5209 REALPART_EXPR/IMAGPART_EXPR immediate uses, return
5210 SSA_PROP_INTERESTING. If there are any REALPART_EXPR
5211 or IMAGPART_EXPR immediate uses, but none of them have
5212 a change in their value ranges, return
5213 SSA_PROP_NOT_INTERESTING. If there are no
5214 {REAL,IMAG}PART_EXPR uses at all,
5215 return SSA_PROP_VARYING. */
5216 value_range new_vr = VR_INITIALIZER;
5217 extract_range_basic (&new_vr, use_stmt);
5218 const value_range *old_vr = get_value_range (use_lhs);
5219 if (old_vr->type != new_vr.type
5220 || !vrp_operand_equal_p (old_vr->min, new_vr.min)
5221 || !vrp_operand_equal_p (old_vr->max, new_vr.max)
5222 || !vrp_bitmap_equal_p (old_vr->equiv, new_vr.equiv))
5223 res = SSA_PROP_INTERESTING;
5224 else
5225 res = SSA_PROP_NOT_INTERESTING;
5226 BITMAP_FREE (new_vr.equiv);
5227 if (res == SSA_PROP_INTERESTING)
5229 *output_p = lhs;
5230 return res;
5234 return res;
5236 break;
5237 default:
5238 break;
5241 /* All other statements produce nothing of interest for VRP, so mark
5242 their outputs varying and prevent further simulation. */
5243 set_defs_to_varying (stmt);
5245 return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
5248 /* Union the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
5249 { VR1TYPE, VR0MIN, VR0MAX } and store the result
5250 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
5251 possible such range. The resulting range is not canonicalized. */
5253 static void
5254 union_ranges (enum value_range_type *vr0type,
5255 tree *vr0min, tree *vr0max,
5256 enum value_range_type vr1type,
5257 tree vr1min, tree vr1max)
5259 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
5260 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
5262 /* [] is vr0, () is vr1 in the following classification comments. */
5263 if (mineq && maxeq)
5265 /* [( )] */
5266 if (*vr0type == vr1type)
5267 /* Nothing to do for equal ranges. */
5269 else if ((*vr0type == VR_RANGE
5270 && vr1type == VR_ANTI_RANGE)
5271 || (*vr0type == VR_ANTI_RANGE
5272 && vr1type == VR_RANGE))
5274 /* For anti-range with range union the result is varying. */
5275 goto give_up;
5277 else
5278 gcc_unreachable ();
5280 else if (operand_less_p (*vr0max, vr1min) == 1
5281 || operand_less_p (vr1max, *vr0min) == 1)
5283 /* [ ] ( ) or ( ) [ ]
5284 If the ranges have an empty intersection, result of the union
5285 operation is the anti-range or if both are anti-ranges
5286 it covers all. */
5287 if (*vr0type == VR_ANTI_RANGE
5288 && vr1type == VR_ANTI_RANGE)
5289 goto give_up;
5290 else if (*vr0type == VR_ANTI_RANGE
5291 && vr1type == VR_RANGE)
5293 else if (*vr0type == VR_RANGE
5294 && vr1type == VR_ANTI_RANGE)
5296 *vr0type = vr1type;
5297 *vr0min = vr1min;
5298 *vr0max = vr1max;
5300 else if (*vr0type == VR_RANGE
5301 && vr1type == VR_RANGE)
5303 /* The result is the convex hull of both ranges. */
5304 if (operand_less_p (*vr0max, vr1min) == 1)
5306 /* If the result can be an anti-range, create one. */
5307 if (TREE_CODE (*vr0max) == INTEGER_CST
5308 && TREE_CODE (vr1min) == INTEGER_CST
5309 && vrp_val_is_min (*vr0min)
5310 && vrp_val_is_max (vr1max))
5312 tree min = int_const_binop (PLUS_EXPR,
5313 *vr0max,
5314 build_int_cst (TREE_TYPE (*vr0max), 1));
5315 tree max = int_const_binop (MINUS_EXPR,
5316 vr1min,
5317 build_int_cst (TREE_TYPE (vr1min), 1));
5318 if (!operand_less_p (max, min))
5320 *vr0type = VR_ANTI_RANGE;
5321 *vr0min = min;
5322 *vr0max = max;
5324 else
5325 *vr0max = vr1max;
5327 else
5328 *vr0max = vr1max;
5330 else
5332 /* If the result can be an anti-range, create one. */
5333 if (TREE_CODE (vr1max) == INTEGER_CST
5334 && TREE_CODE (*vr0min) == INTEGER_CST
5335 && vrp_val_is_min (vr1min)
5336 && vrp_val_is_max (*vr0max))
5338 tree min = int_const_binop (PLUS_EXPR,
5339 vr1max,
5340 build_int_cst (TREE_TYPE (vr1max), 1));
5341 tree max = int_const_binop (MINUS_EXPR,
5342 *vr0min,
5343 build_int_cst (TREE_TYPE (*vr0min), 1));
5344 if (!operand_less_p (max, min))
5346 *vr0type = VR_ANTI_RANGE;
5347 *vr0min = min;
5348 *vr0max = max;
5350 else
5351 *vr0min = vr1min;
5353 else
5354 *vr0min = vr1min;
5357 else
5358 gcc_unreachable ();
5360 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
5361 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
5363 /* [ ( ) ] or [( ) ] or [ ( )] */
5364 if (*vr0type == VR_RANGE
5365 && vr1type == VR_RANGE)
5367 else if (*vr0type == VR_ANTI_RANGE
5368 && vr1type == VR_ANTI_RANGE)
5370 *vr0type = vr1type;
5371 *vr0min = vr1min;
5372 *vr0max = vr1max;
5374 else if (*vr0type == VR_ANTI_RANGE
5375 && vr1type == VR_RANGE)
5377 /* Arbitrarily choose the right or left gap. */
5378 if (!mineq && TREE_CODE (vr1min) == INTEGER_CST)
5379 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5380 build_int_cst (TREE_TYPE (vr1min), 1));
5381 else if (!maxeq && TREE_CODE (vr1max) == INTEGER_CST)
5382 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5383 build_int_cst (TREE_TYPE (vr1max), 1));
5384 else
5385 goto give_up;
5387 else if (*vr0type == VR_RANGE
5388 && vr1type == VR_ANTI_RANGE)
5389 /* The result covers everything. */
5390 goto give_up;
5391 else
5392 gcc_unreachable ();
5394 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
5395 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
5397 /* ( [ ] ) or ([ ] ) or ( [ ]) */
5398 if (*vr0type == VR_RANGE
5399 && vr1type == VR_RANGE)
5401 *vr0type = vr1type;
5402 *vr0min = vr1min;
5403 *vr0max = vr1max;
5405 else if (*vr0type == VR_ANTI_RANGE
5406 && vr1type == VR_ANTI_RANGE)
5408 else if (*vr0type == VR_RANGE
5409 && vr1type == VR_ANTI_RANGE)
5411 *vr0type = VR_ANTI_RANGE;
5412 if (!mineq && TREE_CODE (*vr0min) == INTEGER_CST)
5414 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5415 build_int_cst (TREE_TYPE (*vr0min), 1));
5416 *vr0min = vr1min;
5418 else if (!maxeq && TREE_CODE (*vr0max) == INTEGER_CST)
5420 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5421 build_int_cst (TREE_TYPE (*vr0max), 1));
5422 *vr0max = vr1max;
5424 else
5425 goto give_up;
5427 else if (*vr0type == VR_ANTI_RANGE
5428 && vr1type == VR_RANGE)
5429 /* The result covers everything. */
5430 goto give_up;
5431 else
5432 gcc_unreachable ();
5434 else if ((operand_less_p (vr1min, *vr0max) == 1
5435 || operand_equal_p (vr1min, *vr0max, 0))
5436 && operand_less_p (*vr0min, vr1min) == 1
5437 && operand_less_p (*vr0max, vr1max) == 1)
5439 /* [ ( ] ) or [ ]( ) */
5440 if (*vr0type == VR_RANGE
5441 && vr1type == VR_RANGE)
5442 *vr0max = vr1max;
5443 else if (*vr0type == VR_ANTI_RANGE
5444 && vr1type == VR_ANTI_RANGE)
5445 *vr0min = vr1min;
5446 else if (*vr0type == VR_ANTI_RANGE
5447 && vr1type == VR_RANGE)
5449 if (TREE_CODE (vr1min) == INTEGER_CST)
5450 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5451 build_int_cst (TREE_TYPE (vr1min), 1));
5452 else
5453 goto give_up;
5455 else if (*vr0type == VR_RANGE
5456 && vr1type == VR_ANTI_RANGE)
5458 if (TREE_CODE (*vr0max) == INTEGER_CST)
5460 *vr0type = vr1type;
5461 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5462 build_int_cst (TREE_TYPE (*vr0max), 1));
5463 *vr0max = vr1max;
5465 else
5466 goto give_up;
5468 else
5469 gcc_unreachable ();
5471 else if ((operand_less_p (*vr0min, vr1max) == 1
5472 || operand_equal_p (*vr0min, vr1max, 0))
5473 && operand_less_p (vr1min, *vr0min) == 1
5474 && operand_less_p (vr1max, *vr0max) == 1)
5476 /* ( [ ) ] or ( )[ ] */
5477 if (*vr0type == VR_RANGE
5478 && vr1type == VR_RANGE)
5479 *vr0min = vr1min;
5480 else if (*vr0type == VR_ANTI_RANGE
5481 && vr1type == VR_ANTI_RANGE)
5482 *vr0max = vr1max;
5483 else if (*vr0type == VR_ANTI_RANGE
5484 && vr1type == VR_RANGE)
5486 if (TREE_CODE (vr1max) == INTEGER_CST)
5487 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5488 build_int_cst (TREE_TYPE (vr1max), 1));
5489 else
5490 goto give_up;
5492 else if (*vr0type == VR_RANGE
5493 && vr1type == VR_ANTI_RANGE)
5495 if (TREE_CODE (*vr0min) == INTEGER_CST)
5497 *vr0type = vr1type;
5498 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5499 build_int_cst (TREE_TYPE (*vr0min), 1));
5500 *vr0min = vr1min;
5502 else
5503 goto give_up;
5505 else
5506 gcc_unreachable ();
5508 else
5509 goto give_up;
5511 return;
5513 give_up:
5514 *vr0type = VR_VARYING;
5515 *vr0min = NULL_TREE;
5516 *vr0max = NULL_TREE;
5519 /* Intersect the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
5520 { VR1TYPE, VR0MIN, VR0MAX } and store the result
5521 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
5522 possible such range. The resulting range is not canonicalized. */
5524 static void
5525 intersect_ranges (enum value_range_type *vr0type,
5526 tree *vr0min, tree *vr0max,
5527 enum value_range_type vr1type,
5528 tree vr1min, tree vr1max)
5530 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
5531 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
5533 /* [] is vr0, () is vr1 in the following classification comments. */
5534 if (mineq && maxeq)
5536 /* [( )] */
5537 if (*vr0type == vr1type)
5538 /* Nothing to do for equal ranges. */
5540 else if ((*vr0type == VR_RANGE
5541 && vr1type == VR_ANTI_RANGE)
5542 || (*vr0type == VR_ANTI_RANGE
5543 && vr1type == VR_RANGE))
5545 /* For anti-range with range intersection the result is empty. */
5546 *vr0type = VR_UNDEFINED;
5547 *vr0min = NULL_TREE;
5548 *vr0max = NULL_TREE;
5550 else
5551 gcc_unreachable ();
5553 else if (operand_less_p (*vr0max, vr1min) == 1
5554 || operand_less_p (vr1max, *vr0min) == 1)
5556 /* [ ] ( ) or ( ) [ ]
5557 If the ranges have an empty intersection, the result of the
5558 intersect operation is the range for intersecting an
5559 anti-range with a range or empty when intersecting two ranges. */
5560 if (*vr0type == VR_RANGE
5561 && vr1type == VR_ANTI_RANGE)
5563 else if (*vr0type == VR_ANTI_RANGE
5564 && vr1type == VR_RANGE)
5566 *vr0type = vr1type;
5567 *vr0min = vr1min;
5568 *vr0max = vr1max;
5570 else if (*vr0type == VR_RANGE
5571 && vr1type == VR_RANGE)
5573 *vr0type = VR_UNDEFINED;
5574 *vr0min = NULL_TREE;
5575 *vr0max = NULL_TREE;
5577 else if (*vr0type == VR_ANTI_RANGE
5578 && vr1type == VR_ANTI_RANGE)
5580 /* If the anti-ranges are adjacent to each other merge them. */
5581 if (TREE_CODE (*vr0max) == INTEGER_CST
5582 && TREE_CODE (vr1min) == INTEGER_CST
5583 && operand_less_p (*vr0max, vr1min) == 1
5584 && integer_onep (int_const_binop (MINUS_EXPR,
5585 vr1min, *vr0max)))
5586 *vr0max = vr1max;
5587 else if (TREE_CODE (vr1max) == INTEGER_CST
5588 && TREE_CODE (*vr0min) == INTEGER_CST
5589 && operand_less_p (vr1max, *vr0min) == 1
5590 && integer_onep (int_const_binop (MINUS_EXPR,
5591 *vr0min, vr1max)))
5592 *vr0min = vr1min;
5593 /* Else arbitrarily take VR0. */
5596 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
5597 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
5599 /* [ ( ) ] or [( ) ] or [ ( )] */
5600 if (*vr0type == VR_RANGE
5601 && vr1type == VR_RANGE)
5603 /* If both are ranges the result is the inner one. */
5604 *vr0type = vr1type;
5605 *vr0min = vr1min;
5606 *vr0max = vr1max;
5608 else if (*vr0type == VR_RANGE
5609 && vr1type == VR_ANTI_RANGE)
5611 /* Choose the right gap if the left one is empty. */
5612 if (mineq)
5614 if (TREE_CODE (vr1max) != INTEGER_CST)
5615 *vr0min = vr1max;
5616 else if (TYPE_PRECISION (TREE_TYPE (vr1max)) == 1
5617 && !TYPE_UNSIGNED (TREE_TYPE (vr1max)))
5618 *vr0min
5619 = int_const_binop (MINUS_EXPR, vr1max,
5620 build_int_cst (TREE_TYPE (vr1max), -1));
5621 else
5622 *vr0min
5623 = int_const_binop (PLUS_EXPR, vr1max,
5624 build_int_cst (TREE_TYPE (vr1max), 1));
5626 /* Choose the left gap if the right one is empty. */
5627 else if (maxeq)
5629 if (TREE_CODE (vr1min) != INTEGER_CST)
5630 *vr0max = vr1min;
5631 else if (TYPE_PRECISION (TREE_TYPE (vr1min)) == 1
5632 && !TYPE_UNSIGNED (TREE_TYPE (vr1min)))
5633 *vr0max
5634 = int_const_binop (PLUS_EXPR, vr1min,
5635 build_int_cst (TREE_TYPE (vr1min), -1));
5636 else
5637 *vr0max
5638 = int_const_binop (MINUS_EXPR, vr1min,
5639 build_int_cst (TREE_TYPE (vr1min), 1));
5641 /* Choose the anti-range if the range is effectively varying. */
5642 else if (vrp_val_is_min (*vr0min)
5643 && vrp_val_is_max (*vr0max))
5645 *vr0type = vr1type;
5646 *vr0min = vr1min;
5647 *vr0max = vr1max;
5649 /* Else choose the range. */
5651 else if (*vr0type == VR_ANTI_RANGE
5652 && vr1type == VR_ANTI_RANGE)
5653 /* If both are anti-ranges the result is the outer one. */
5655 else if (*vr0type == VR_ANTI_RANGE
5656 && vr1type == VR_RANGE)
5658 /* The intersection is empty. */
5659 *vr0type = VR_UNDEFINED;
5660 *vr0min = NULL_TREE;
5661 *vr0max = NULL_TREE;
5663 else
5664 gcc_unreachable ();
5666 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
5667 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
5669 /* ( [ ] ) or ([ ] ) or ( [ ]) */
5670 if (*vr0type == VR_RANGE
5671 && vr1type == VR_RANGE)
5672 /* Choose the inner range. */
5674 else if (*vr0type == VR_ANTI_RANGE
5675 && vr1type == VR_RANGE)
5677 /* Choose the right gap if the left is empty. */
5678 if (mineq)
5680 *vr0type = VR_RANGE;
5681 if (TREE_CODE (*vr0max) != INTEGER_CST)
5682 *vr0min = *vr0max;
5683 else if (TYPE_PRECISION (TREE_TYPE (*vr0max)) == 1
5684 && !TYPE_UNSIGNED (TREE_TYPE (*vr0max)))
5685 *vr0min
5686 = int_const_binop (MINUS_EXPR, *vr0max,
5687 build_int_cst (TREE_TYPE (*vr0max), -1));
5688 else
5689 *vr0min
5690 = int_const_binop (PLUS_EXPR, *vr0max,
5691 build_int_cst (TREE_TYPE (*vr0max), 1));
5692 *vr0max = vr1max;
5694 /* Choose the left gap if the right is empty. */
5695 else if (maxeq)
5697 *vr0type = VR_RANGE;
5698 if (TREE_CODE (*vr0min) != INTEGER_CST)
5699 *vr0max = *vr0min;
5700 else if (TYPE_PRECISION (TREE_TYPE (*vr0min)) == 1
5701 && !TYPE_UNSIGNED (TREE_TYPE (*vr0min)))
5702 *vr0max
5703 = int_const_binop (PLUS_EXPR, *vr0min,
5704 build_int_cst (TREE_TYPE (*vr0min), -1));
5705 else
5706 *vr0max
5707 = int_const_binop (MINUS_EXPR, *vr0min,
5708 build_int_cst (TREE_TYPE (*vr0min), 1));
5709 *vr0min = vr1min;
5711 /* Choose the anti-range if the range is effectively varying. */
5712 else if (vrp_val_is_min (vr1min)
5713 && vrp_val_is_max (vr1max))
5715 /* Choose the anti-range if it is ~[0,0], that range is special
5716 enough to special case when vr1's range is relatively wide.
5717 At least for types bigger than int - this covers pointers
5718 and arguments to functions like ctz. */
5719 else if (*vr0min == *vr0max
5720 && integer_zerop (*vr0min)
5721 && ((TYPE_PRECISION (TREE_TYPE (*vr0min))
5722 >= TYPE_PRECISION (integer_type_node))
5723 || POINTER_TYPE_P (TREE_TYPE (*vr0min)))
5724 && TREE_CODE (vr1max) == INTEGER_CST
5725 && TREE_CODE (vr1min) == INTEGER_CST
5726 && (wi::clz (wi::to_wide (vr1max) - wi::to_wide (vr1min))
5727 < TYPE_PRECISION (TREE_TYPE (*vr0min)) / 2))
5729 /* Else choose the range. */
5730 else
5732 *vr0type = vr1type;
5733 *vr0min = vr1min;
5734 *vr0max = vr1max;
5737 else if (*vr0type == VR_ANTI_RANGE
5738 && vr1type == VR_ANTI_RANGE)
5740 /* If both are anti-ranges the result is the outer one. */
5741 *vr0type = vr1type;
5742 *vr0min = vr1min;
5743 *vr0max = vr1max;
5745 else if (vr1type == VR_ANTI_RANGE
5746 && *vr0type == VR_RANGE)
5748 /* The intersection is empty. */
5749 *vr0type = VR_UNDEFINED;
5750 *vr0min = NULL_TREE;
5751 *vr0max = NULL_TREE;
5753 else
5754 gcc_unreachable ();
5756 else if ((operand_less_p (vr1min, *vr0max) == 1
5757 || operand_equal_p (vr1min, *vr0max, 0))
5758 && operand_less_p (*vr0min, vr1min) == 1)
5760 /* [ ( ] ) or [ ]( ) */
5761 if (*vr0type == VR_ANTI_RANGE
5762 && vr1type == VR_ANTI_RANGE)
5763 *vr0max = vr1max;
5764 else if (*vr0type == VR_RANGE
5765 && vr1type == VR_RANGE)
5766 *vr0min = vr1min;
5767 else if (*vr0type == VR_RANGE
5768 && vr1type == VR_ANTI_RANGE)
5770 if (TREE_CODE (vr1min) == INTEGER_CST)
5771 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5772 build_int_cst (TREE_TYPE (vr1min), 1));
5773 else
5774 *vr0max = vr1min;
5776 else if (*vr0type == VR_ANTI_RANGE
5777 && vr1type == VR_RANGE)
5779 *vr0type = VR_RANGE;
5780 if (TREE_CODE (*vr0max) == INTEGER_CST)
5781 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5782 build_int_cst (TREE_TYPE (*vr0max), 1));
5783 else
5784 *vr0min = *vr0max;
5785 *vr0max = vr1max;
5787 else
5788 gcc_unreachable ();
5790 else if ((operand_less_p (*vr0min, vr1max) == 1
5791 || operand_equal_p (*vr0min, vr1max, 0))
5792 && operand_less_p (vr1min, *vr0min) == 1)
5794 /* ( [ ) ] or ( )[ ] */
5795 if (*vr0type == VR_ANTI_RANGE
5796 && vr1type == VR_ANTI_RANGE)
5797 *vr0min = vr1min;
5798 else if (*vr0type == VR_RANGE
5799 && vr1type == VR_RANGE)
5800 *vr0max = vr1max;
5801 else if (*vr0type == VR_RANGE
5802 && vr1type == VR_ANTI_RANGE)
5804 if (TREE_CODE (vr1max) == INTEGER_CST)
5805 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5806 build_int_cst (TREE_TYPE (vr1max), 1));
5807 else
5808 *vr0min = vr1max;
5810 else if (*vr0type == VR_ANTI_RANGE
5811 && vr1type == VR_RANGE)
5813 *vr0type = VR_RANGE;
5814 if (TREE_CODE (*vr0min) == INTEGER_CST)
5815 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5816 build_int_cst (TREE_TYPE (*vr0min), 1));
5817 else
5818 *vr0max = *vr0min;
5819 *vr0min = vr1min;
5821 else
5822 gcc_unreachable ();
5825 /* As a fallback simply use { *VRTYPE, *VR0MIN, *VR0MAX } as
5826 result for the intersection. That's always a conservative
5827 correct estimate unless VR1 is a constant singleton range
5828 in which case we choose that. */
5829 if (vr1type == VR_RANGE
5830 && is_gimple_min_invariant (vr1min)
5831 && vrp_operand_equal_p (vr1min, vr1max))
5833 *vr0type = vr1type;
5834 *vr0min = vr1min;
5835 *vr0max = vr1max;
5838 return;
5842 /* Intersect the two value-ranges *VR0 and *VR1 and store the result
5843 in *VR0. This may not be the smallest possible such range. */
5845 static void
5846 vrp_intersect_ranges_1 (value_range *vr0, const value_range *vr1)
5848 value_range saved;
5850 /* If either range is VR_VARYING the other one wins. */
5851 if (vr1->type == VR_VARYING)
5852 return;
5853 if (vr0->type == VR_VARYING)
5855 copy_value_range (vr0, vr1);
5856 return;
5859 /* When either range is VR_UNDEFINED the resulting range is
5860 VR_UNDEFINED, too. */
5861 if (vr0->type == VR_UNDEFINED)
5862 return;
5863 if (vr1->type == VR_UNDEFINED)
5865 set_value_range_to_undefined (vr0);
5866 return;
5869 /* Save the original vr0 so we can return it as conservative intersection
5870 result when our worker turns things to varying. */
5871 saved = *vr0;
5872 intersect_ranges (&vr0->type, &vr0->min, &vr0->max,
5873 vr1->type, vr1->min, vr1->max);
5874 /* Make sure to canonicalize the result though as the inversion of a
5875 VR_RANGE can still be a VR_RANGE. */
5876 set_and_canonicalize_value_range (vr0, vr0->type,
5877 vr0->min, vr0->max, vr0->equiv);
5878 /* If that failed, use the saved original VR0. */
5879 if (vr0->type == VR_VARYING)
5881 *vr0 = saved;
5882 return;
5884 /* If the result is VR_UNDEFINED there is no need to mess with
5885 the equivalencies. */
5886 if (vr0->type == VR_UNDEFINED)
5887 return;
5889 /* The resulting set of equivalences for range intersection is the union of
5890 the two sets. */
5891 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
5892 bitmap_ior_into (vr0->equiv, vr1->equiv);
5893 else if (vr1->equiv && !vr0->equiv)
5895 /* All equivalence bitmaps are allocated from the same obstack. So
5896 we can use the obstack associated with VR to allocate vr0->equiv. */
5897 vr0->equiv = BITMAP_ALLOC (vr1->equiv->obstack);
5898 bitmap_copy (vr0->equiv, vr1->equiv);
5902 void
5903 vrp_intersect_ranges (value_range *vr0, const value_range *vr1)
5905 if (dump_file && (dump_flags & TDF_DETAILS))
5907 fprintf (dump_file, "Intersecting\n ");
5908 dump_value_range (dump_file, vr0);
5909 fprintf (dump_file, "\nand\n ");
5910 dump_value_range (dump_file, vr1);
5911 fprintf (dump_file, "\n");
5913 vrp_intersect_ranges_1 (vr0, vr1);
5914 if (dump_file && (dump_flags & TDF_DETAILS))
5916 fprintf (dump_file, "to\n ");
5917 dump_value_range (dump_file, vr0);
5918 fprintf (dump_file, "\n");
5922 /* Meet operation for value ranges. Given two value ranges VR0 and
5923 VR1, store in VR0 a range that contains both VR0 and VR1. This
5924 may not be the smallest possible such range. */
5926 static void
5927 vrp_meet_1 (value_range *vr0, const value_range *vr1)
5929 value_range saved;
5931 if (vr0->type == VR_UNDEFINED)
5933 set_value_range (vr0, vr1->type, vr1->min, vr1->max, vr1->equiv);
5934 return;
5937 if (vr1->type == VR_UNDEFINED)
5939 /* VR0 already has the resulting range. */
5940 return;
5943 if (vr0->type == VR_VARYING)
5945 /* Nothing to do. VR0 already has the resulting range. */
5946 return;
5949 if (vr1->type == VR_VARYING)
5951 set_value_range_to_varying (vr0);
5952 return;
5955 saved = *vr0;
5956 union_ranges (&vr0->type, &vr0->min, &vr0->max,
5957 vr1->type, vr1->min, vr1->max);
5958 if (vr0->type == VR_VARYING)
5960 /* Failed to find an efficient meet. Before giving up and setting
5961 the result to VARYING, see if we can at least derive a useful
5962 anti-range. */
5963 if (range_includes_zero_p (&saved) == 0
5964 && range_includes_zero_p (vr1) == 0)
5966 set_value_range_to_nonnull (vr0, TREE_TYPE (saved.min));
5968 /* Since this meet operation did not result from the meeting of
5969 two equivalent names, VR0 cannot have any equivalences. */
5970 if (vr0->equiv)
5971 bitmap_clear (vr0->equiv);
5972 return;
5975 set_value_range_to_varying (vr0);
5976 return;
5978 set_and_canonicalize_value_range (vr0, vr0->type, vr0->min, vr0->max,
5979 vr0->equiv);
5980 if (vr0->type == VR_VARYING)
5981 return;
5983 /* The resulting set of equivalences is always the intersection of
5984 the two sets. */
5985 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
5986 bitmap_and_into (vr0->equiv, vr1->equiv);
5987 else if (vr0->equiv && !vr1->equiv)
5988 bitmap_clear (vr0->equiv);
5991 void
5992 vrp_meet (value_range *vr0, const value_range *vr1)
5994 if (dump_file && (dump_flags & TDF_DETAILS))
5996 fprintf (dump_file, "Meeting\n ");
5997 dump_value_range (dump_file, vr0);
5998 fprintf (dump_file, "\nand\n ");
5999 dump_value_range (dump_file, vr1);
6000 fprintf (dump_file, "\n");
6002 vrp_meet_1 (vr0, vr1);
6003 if (dump_file && (dump_flags & TDF_DETAILS))
6005 fprintf (dump_file, "to\n ");
6006 dump_value_range (dump_file, vr0);
6007 fprintf (dump_file, "\n");
6012 /* Visit all arguments for PHI node PHI that flow through executable
6013 edges. If a valid value range can be derived from all the incoming
6014 value ranges, set a new range for the LHS of PHI. */
6016 enum ssa_prop_result
6017 vrp_prop::visit_phi (gphi *phi)
6019 tree lhs = PHI_RESULT (phi);
6020 value_range vr_result = VR_INITIALIZER;
6021 extract_range_from_phi_node (phi, &vr_result);
6022 if (update_value_range (lhs, &vr_result))
6024 if (dump_file && (dump_flags & TDF_DETAILS))
6026 fprintf (dump_file, "Found new range for ");
6027 print_generic_expr (dump_file, lhs);
6028 fprintf (dump_file, ": ");
6029 dump_value_range (dump_file, &vr_result);
6030 fprintf (dump_file, "\n");
6033 if (vr_result.type == VR_VARYING)
6034 return SSA_PROP_VARYING;
6036 return SSA_PROP_INTERESTING;
6039 /* Nothing changed, don't add outgoing edges. */
6040 return SSA_PROP_NOT_INTERESTING;
6043 class vrp_folder : public substitute_and_fold_engine
6045 public:
6046 tree get_value (tree) FINAL OVERRIDE;
6047 bool fold_stmt (gimple_stmt_iterator *) FINAL OVERRIDE;
6048 bool fold_predicate_in (gimple_stmt_iterator *);
6050 class vr_values *vr_values;
6052 /* Delegators. */
6053 tree vrp_evaluate_conditional (tree_code code, tree op0,
6054 tree op1, gimple *stmt)
6055 { return vr_values->vrp_evaluate_conditional (code, op0, op1, stmt); }
6056 bool simplify_stmt_using_ranges (gimple_stmt_iterator *gsi)
6057 { return vr_values->simplify_stmt_using_ranges (gsi); }
6058 tree op_with_constant_singleton_value_range (tree op)
6059 { return vr_values->op_with_constant_singleton_value_range (op); }
6062 /* If the statement pointed by SI has a predicate whose value can be
6063 computed using the value range information computed by VRP, compute
6064 its value and return true. Otherwise, return false. */
6066 bool
6067 vrp_folder::fold_predicate_in (gimple_stmt_iterator *si)
6069 bool assignment_p = false;
6070 tree val;
6071 gimple *stmt = gsi_stmt (*si);
6073 if (is_gimple_assign (stmt)
6074 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
6076 assignment_p = true;
6077 val = vrp_evaluate_conditional (gimple_assign_rhs_code (stmt),
6078 gimple_assign_rhs1 (stmt),
6079 gimple_assign_rhs2 (stmt),
6080 stmt);
6082 else if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
6083 val = vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
6084 gimple_cond_lhs (cond_stmt),
6085 gimple_cond_rhs (cond_stmt),
6086 stmt);
6087 else
6088 return false;
6090 if (val)
6092 if (assignment_p)
6093 val = fold_convert (gimple_expr_type (stmt), val);
6095 if (dump_file)
6097 fprintf (dump_file, "Folding predicate ");
6098 print_gimple_expr (dump_file, stmt, 0);
6099 fprintf (dump_file, " to ");
6100 print_generic_expr (dump_file, val);
6101 fprintf (dump_file, "\n");
6104 if (is_gimple_assign (stmt))
6105 gimple_assign_set_rhs_from_tree (si, val);
6106 else
6108 gcc_assert (gimple_code (stmt) == GIMPLE_COND);
6109 gcond *cond_stmt = as_a <gcond *> (stmt);
6110 if (integer_zerop (val))
6111 gimple_cond_make_false (cond_stmt);
6112 else if (integer_onep (val))
6113 gimple_cond_make_true (cond_stmt);
6114 else
6115 gcc_unreachable ();
6118 return true;
6121 return false;
6124 /* Callback for substitute_and_fold folding the stmt at *SI. */
6126 bool
6127 vrp_folder::fold_stmt (gimple_stmt_iterator *si)
6129 if (fold_predicate_in (si))
6130 return true;
6132 return simplify_stmt_using_ranges (si);
6135 /* If OP has a value range with a single constant value return that,
6136 otherwise return NULL_TREE. This returns OP itself if OP is a
6137 constant.
6139 Implemented as a pure wrapper right now, but this will change. */
6141 tree
6142 vrp_folder::get_value (tree op)
6144 return op_with_constant_singleton_value_range (op);
6147 /* Return the LHS of any ASSERT_EXPR where OP appears as the first
6148 argument to the ASSERT_EXPR and in which the ASSERT_EXPR dominates
6149 BB. If no such ASSERT_EXPR is found, return OP. */
6151 static tree
6152 lhs_of_dominating_assert (tree op, basic_block bb, gimple *stmt)
6154 imm_use_iterator imm_iter;
6155 gimple *use_stmt;
6156 use_operand_p use_p;
6158 if (TREE_CODE (op) == SSA_NAME)
6160 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, op)
6162 use_stmt = USE_STMT (use_p);
6163 if (use_stmt != stmt
6164 && gimple_assign_single_p (use_stmt)
6165 && TREE_CODE (gimple_assign_rhs1 (use_stmt)) == ASSERT_EXPR
6166 && TREE_OPERAND (gimple_assign_rhs1 (use_stmt), 0) == op
6167 && dominated_by_p (CDI_DOMINATORS, bb, gimple_bb (use_stmt)))
6168 return gimple_assign_lhs (use_stmt);
6171 return op;
6174 /* A hack. */
6175 static class vr_values *x_vr_values;
6177 /* A trivial wrapper so that we can present the generic jump threading
6178 code with a simple API for simplifying statements. STMT is the
6179 statement we want to simplify, WITHIN_STMT provides the location
6180 for any overflow warnings. */
6182 static tree
6183 simplify_stmt_for_jump_threading (gimple *stmt, gimple *within_stmt,
6184 class avail_exprs_stack *avail_exprs_stack ATTRIBUTE_UNUSED,
6185 basic_block bb)
6187 /* First see if the conditional is in the hash table. */
6188 tree cached_lhs = avail_exprs_stack->lookup_avail_expr (stmt, false, true);
6189 if (cached_lhs && is_gimple_min_invariant (cached_lhs))
6190 return cached_lhs;
6192 vr_values *vr_values = x_vr_values;
6193 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
6195 tree op0 = gimple_cond_lhs (cond_stmt);
6196 op0 = lhs_of_dominating_assert (op0, bb, stmt);
6198 tree op1 = gimple_cond_rhs (cond_stmt);
6199 op1 = lhs_of_dominating_assert (op1, bb, stmt);
6201 return vr_values->vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
6202 op0, op1, within_stmt);
6205 /* We simplify a switch statement by trying to determine which case label
6206 will be taken. If we are successful then we return the corresponding
6207 CASE_LABEL_EXPR. */
6208 if (gswitch *switch_stmt = dyn_cast <gswitch *> (stmt))
6210 tree op = gimple_switch_index (switch_stmt);
6211 if (TREE_CODE (op) != SSA_NAME)
6212 return NULL_TREE;
6214 op = lhs_of_dominating_assert (op, bb, stmt);
6216 const value_range *vr = vr_values->get_value_range (op);
6217 if ((vr->type != VR_RANGE && vr->type != VR_ANTI_RANGE)
6218 || symbolic_range_p (vr))
6219 return NULL_TREE;
6221 if (vr->type == VR_RANGE)
6223 size_t i, j;
6224 /* Get the range of labels that contain a part of the operand's
6225 value range. */
6226 find_case_label_range (switch_stmt, vr->min, vr->max, &i, &j);
6228 /* Is there only one such label? */
6229 if (i == j)
6231 tree label = gimple_switch_label (switch_stmt, i);
6233 /* The i'th label will be taken only if the value range of the
6234 operand is entirely within the bounds of this label. */
6235 if (CASE_HIGH (label) != NULL_TREE
6236 ? (tree_int_cst_compare (CASE_LOW (label), vr->min) <= 0
6237 && tree_int_cst_compare (CASE_HIGH (label), vr->max) >= 0)
6238 : (tree_int_cst_equal (CASE_LOW (label), vr->min)
6239 && tree_int_cst_equal (vr->min, vr->max)))
6240 return label;
6243 /* If there are no such labels then the default label will be
6244 taken. */
6245 if (i > j)
6246 return gimple_switch_label (switch_stmt, 0);
6249 if (vr->type == VR_ANTI_RANGE)
6251 unsigned n = gimple_switch_num_labels (switch_stmt);
6252 tree min_label = gimple_switch_label (switch_stmt, 1);
6253 tree max_label = gimple_switch_label (switch_stmt, n - 1);
6255 /* The default label will be taken only if the anti-range of the
6256 operand is entirely outside the bounds of all the (non-default)
6257 case labels. */
6258 if (tree_int_cst_compare (vr->min, CASE_LOW (min_label)) <= 0
6259 && (CASE_HIGH (max_label) != NULL_TREE
6260 ? tree_int_cst_compare (vr->max, CASE_HIGH (max_label)) >= 0
6261 : tree_int_cst_compare (vr->max, CASE_LOW (max_label)) >= 0))
6262 return gimple_switch_label (switch_stmt, 0);
6265 return NULL_TREE;
6268 if (gassign *assign_stmt = dyn_cast <gassign *> (stmt))
6270 tree lhs = gimple_assign_lhs (assign_stmt);
6271 if (TREE_CODE (lhs) == SSA_NAME
6272 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
6273 || POINTER_TYPE_P (TREE_TYPE (lhs)))
6274 && stmt_interesting_for_vrp (stmt))
6276 edge dummy_e;
6277 tree dummy_tree;
6278 value_range new_vr = VR_INITIALIZER;
6279 vr_values->extract_range_from_stmt (stmt, &dummy_e,
6280 &dummy_tree, &new_vr);
6281 if (range_int_cst_singleton_p (&new_vr))
6282 return new_vr.min;
6286 return NULL_TREE;
6289 class vrp_dom_walker : public dom_walker
6291 public:
6292 vrp_dom_walker (cdi_direction direction,
6293 class const_and_copies *const_and_copies,
6294 class avail_exprs_stack *avail_exprs_stack)
6295 : dom_walker (direction, REACHABLE_BLOCKS),
6296 m_const_and_copies (const_and_copies),
6297 m_avail_exprs_stack (avail_exprs_stack),
6298 m_dummy_cond (NULL) {}
6300 virtual edge before_dom_children (basic_block);
6301 virtual void after_dom_children (basic_block);
6303 class vr_values *vr_values;
6305 private:
6306 class const_and_copies *m_const_and_copies;
6307 class avail_exprs_stack *m_avail_exprs_stack;
6309 gcond *m_dummy_cond;
6313 /* Called before processing dominator children of BB. We want to look
6314 at ASSERT_EXPRs and record information from them in the appropriate
6315 tables.
6317 We could look at other statements here. It's not seen as likely
6318 to significantly increase the jump threads we discover. */
6320 edge
6321 vrp_dom_walker::before_dom_children (basic_block bb)
6323 gimple_stmt_iterator gsi;
6325 m_avail_exprs_stack->push_marker ();
6326 m_const_and_copies->push_marker ();
6327 for (gsi = gsi_start_nondebug_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
6329 gimple *stmt = gsi_stmt (gsi);
6330 if (gimple_assign_single_p (stmt)
6331 && TREE_CODE (gimple_assign_rhs1 (stmt)) == ASSERT_EXPR)
6333 tree rhs1 = gimple_assign_rhs1 (stmt);
6334 tree cond = TREE_OPERAND (rhs1, 1);
6335 tree inverted = invert_truthvalue (cond);
6336 vec<cond_equivalence> p;
6337 p.create (3);
6338 record_conditions (&p, cond, inverted);
6339 for (unsigned int i = 0; i < p.length (); i++)
6340 m_avail_exprs_stack->record_cond (&p[i]);
6342 tree lhs = gimple_assign_lhs (stmt);
6343 m_const_and_copies->record_const_or_copy (lhs,
6344 TREE_OPERAND (rhs1, 0));
6345 p.release ();
6346 continue;
6348 break;
6350 return NULL;
6353 /* Called after processing dominator children of BB. This is where we
6354 actually call into the threader. */
6355 void
6356 vrp_dom_walker::after_dom_children (basic_block bb)
6358 if (!m_dummy_cond)
6359 m_dummy_cond = gimple_build_cond (NE_EXPR,
6360 integer_zero_node, integer_zero_node,
6361 NULL, NULL);
6363 x_vr_values = vr_values;
6364 thread_outgoing_edges (bb, m_dummy_cond, m_const_and_copies,
6365 m_avail_exprs_stack, NULL,
6366 simplify_stmt_for_jump_threading);
6367 x_vr_values = NULL;
6369 m_avail_exprs_stack->pop_to_marker ();
6370 m_const_and_copies->pop_to_marker ();
6373 /* Blocks which have more than one predecessor and more than
6374 one successor present jump threading opportunities, i.e.,
6375 when the block is reached from a specific predecessor, we
6376 may be able to determine which of the outgoing edges will
6377 be traversed. When this optimization applies, we are able
6378 to avoid conditionals at runtime and we may expose secondary
6379 optimization opportunities.
6381 This routine is effectively a driver for the generic jump
6382 threading code. It basically just presents the generic code
6383 with edges that may be suitable for jump threading.
6385 Unlike DOM, we do not iterate VRP if jump threading was successful.
6386 While iterating may expose new opportunities for VRP, it is expected
6387 those opportunities would be very limited and the compile time cost
6388 to expose those opportunities would be significant.
6390 As jump threading opportunities are discovered, they are registered
6391 for later realization. */
6393 static void
6394 identify_jump_threads (class vr_values *vr_values)
6396 int i;
6397 edge e;
6399 /* Ugh. When substituting values earlier in this pass we can
6400 wipe the dominance information. So rebuild the dominator
6401 information as we need it within the jump threading code. */
6402 calculate_dominance_info (CDI_DOMINATORS);
6404 /* We do not allow VRP information to be used for jump threading
6405 across a back edge in the CFG. Otherwise it becomes too
6406 difficult to avoid eliminating loop exit tests. Of course
6407 EDGE_DFS_BACK is not accurate at this time so we have to
6408 recompute it. */
6409 mark_dfs_back_edges ();
6411 /* Do not thread across edges we are about to remove. Just marking
6412 them as EDGE_IGNORE will do. */
6413 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
6414 e->flags |= EDGE_IGNORE;
6416 /* Allocate our unwinder stack to unwind any temporary equivalences
6417 that might be recorded. */
6418 const_and_copies *equiv_stack = new const_and_copies ();
6420 hash_table<expr_elt_hasher> *avail_exprs
6421 = new hash_table<expr_elt_hasher> (1024);
6422 avail_exprs_stack *avail_exprs_stack
6423 = new class avail_exprs_stack (avail_exprs);
6425 vrp_dom_walker walker (CDI_DOMINATORS, equiv_stack, avail_exprs_stack);
6426 walker.vr_values = vr_values;
6427 walker.walk (cfun->cfg->x_entry_block_ptr);
6429 /* Clear EDGE_IGNORE. */
6430 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
6431 e->flags &= ~EDGE_IGNORE;
6433 /* We do not actually update the CFG or SSA graphs at this point as
6434 ASSERT_EXPRs are still in the IL and cfg cleanup code does not yet
6435 handle ASSERT_EXPRs gracefully. */
6436 delete equiv_stack;
6437 delete avail_exprs;
6438 delete avail_exprs_stack;
6441 /* Traverse all the blocks folding conditionals with known ranges. */
6443 void
6444 vrp_prop::vrp_finalize (bool warn_array_bounds_p)
6446 size_t i;
6448 /* We have completed propagating through the lattice. */
6449 vr_values.set_lattice_propagation_complete ();
6451 if (dump_file)
6453 fprintf (dump_file, "\nValue ranges after VRP:\n\n");
6454 vr_values.dump_all_value_ranges (dump_file);
6455 fprintf (dump_file, "\n");
6458 /* Set value range to non pointer SSA_NAMEs. */
6459 for (i = 0; i < num_ssa_names; i++)
6461 tree name = ssa_name (i);
6462 if (!name)
6463 continue;
6465 const value_range *vr = get_value_range (name);
6466 if (!name
6467 || (vr->type == VR_VARYING)
6468 || (vr->type == VR_UNDEFINED)
6469 || (TREE_CODE (vr->min) != INTEGER_CST)
6470 || (TREE_CODE (vr->max) != INTEGER_CST))
6471 continue;
6473 if (POINTER_TYPE_P (TREE_TYPE (name))
6474 && range_includes_zero_p (vr) == 0)
6475 set_ptr_nonnull (name);
6476 else if (!POINTER_TYPE_P (TREE_TYPE (name)))
6477 set_range_info (name, vr->type,
6478 wi::to_wide (vr->min),
6479 wi::to_wide (vr->max));
6482 /* If we're checking array refs, we want to merge information on
6483 the executability of each edge between vrp_folder and the
6484 check_array_bounds_dom_walker: each can clear the
6485 EDGE_EXECUTABLE flag on edges, in different ways.
6487 Hence, if we're going to call check_all_array_refs, set
6488 the flag on every edge now, rather than in
6489 check_array_bounds_dom_walker's ctor; vrp_folder may clear
6490 it from some edges. */
6491 if (warn_array_bounds && warn_array_bounds_p)
6492 set_all_edges_as_executable (cfun);
6494 class vrp_folder vrp_folder;
6495 vrp_folder.vr_values = &vr_values;
6496 vrp_folder.substitute_and_fold ();
6498 if (warn_array_bounds && warn_array_bounds_p)
6499 check_all_array_refs ();
6502 /* Main entry point to VRP (Value Range Propagation). This pass is
6503 loosely based on J. R. C. Patterson, ``Accurate Static Branch
6504 Prediction by Value Range Propagation,'' in SIGPLAN Conference on
6505 Programming Language Design and Implementation, pp. 67-78, 1995.
6506 Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
6508 This is essentially an SSA-CCP pass modified to deal with ranges
6509 instead of constants.
6511 While propagating ranges, we may find that two or more SSA name
6512 have equivalent, though distinct ranges. For instance,
6514 1 x_9 = p_3->a;
6515 2 p_4 = ASSERT_EXPR <p_3, p_3 != 0>
6516 3 if (p_4 == q_2)
6517 4 p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
6518 5 endif
6519 6 if (q_2)
6521 In the code above, pointer p_5 has range [q_2, q_2], but from the
6522 code we can also determine that p_5 cannot be NULL and, if q_2 had
6523 a non-varying range, p_5's range should also be compatible with it.
6525 These equivalences are created by two expressions: ASSERT_EXPR and
6526 copy operations. Since p_5 is an assertion on p_4, and p_4 was the
6527 result of another assertion, then we can use the fact that p_5 and
6528 p_4 are equivalent when evaluating p_5's range.
6530 Together with value ranges, we also propagate these equivalences
6531 between names so that we can take advantage of information from
6532 multiple ranges when doing final replacement. Note that this
6533 equivalency relation is transitive but not symmetric.
6535 In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
6536 cannot assert that q_2 is equivalent to p_5 because q_2 may be used
6537 in contexts where that assertion does not hold (e.g., in line 6).
6539 TODO, the main difference between this pass and Patterson's is that
6540 we do not propagate edge probabilities. We only compute whether
6541 edges can be taken or not. That is, instead of having a spectrum
6542 of jump probabilities between 0 and 1, we only deal with 0, 1 and
6543 DON'T KNOW. In the future, it may be worthwhile to propagate
6544 probabilities to aid branch prediction. */
6546 static unsigned int
6547 execute_vrp (bool warn_array_bounds_p)
6549 int i;
6550 edge e;
6551 switch_update *su;
6553 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
6554 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
6555 scev_initialize ();
6557 /* ??? This ends up using stale EDGE_DFS_BACK for liveness computation.
6558 Inserting assertions may split edges which will invalidate
6559 EDGE_DFS_BACK. */
6560 insert_range_assertions ();
6562 to_remove_edges.create (10);
6563 to_update_switch_stmts.create (5);
6564 threadedge_initialize_values ();
6566 /* For visiting PHI nodes we need EDGE_DFS_BACK computed. */
6567 mark_dfs_back_edges ();
6569 class vrp_prop vrp_prop;
6570 vrp_prop.vrp_initialize ();
6571 vrp_prop.ssa_propagate ();
6572 vrp_prop.vrp_finalize (warn_array_bounds_p);
6574 /* We must identify jump threading opportunities before we release
6575 the datastructures built by VRP. */
6576 identify_jump_threads (&vrp_prop.vr_values);
6578 /* A comparison of an SSA_NAME against a constant where the SSA_NAME
6579 was set by a type conversion can often be rewritten to use the
6580 RHS of the type conversion.
6582 However, doing so inhibits jump threading through the comparison.
6583 So that transformation is not performed until after jump threading
6584 is complete. */
6585 basic_block bb;
6586 FOR_EACH_BB_FN (bb, cfun)
6588 gimple *last = last_stmt (bb);
6589 if (last && gimple_code (last) == GIMPLE_COND)
6590 vrp_prop.vr_values.simplify_cond_using_ranges_2 (as_a <gcond *> (last));
6593 free_numbers_of_iterations_estimates (cfun);
6595 /* ASSERT_EXPRs must be removed before finalizing jump threads
6596 as finalizing jump threads calls the CFG cleanup code which
6597 does not properly handle ASSERT_EXPRs. */
6598 remove_range_assertions ();
6600 /* If we exposed any new variables, go ahead and put them into
6601 SSA form now, before we handle jump threading. This simplifies
6602 interactions between rewriting of _DECL nodes into SSA form
6603 and rewriting SSA_NAME nodes into SSA form after block
6604 duplication and CFG manipulation. */
6605 update_ssa (TODO_update_ssa);
6607 /* We identified all the jump threading opportunities earlier, but could
6608 not transform the CFG at that time. This routine transforms the
6609 CFG and arranges for the dominator tree to be rebuilt if necessary.
6611 Note the SSA graph update will occur during the normal TODO
6612 processing by the pass manager. */
6613 thread_through_all_blocks (false);
6615 /* Remove dead edges from SWITCH_EXPR optimization. This leaves the
6616 CFG in a broken state and requires a cfg_cleanup run. */
6617 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
6618 remove_edge (e);
6619 /* Update SWITCH_EXPR case label vector. */
6620 FOR_EACH_VEC_ELT (to_update_switch_stmts, i, su)
6622 size_t j;
6623 size_t n = TREE_VEC_LENGTH (su->vec);
6624 tree label;
6625 gimple_switch_set_num_labels (su->stmt, n);
6626 for (j = 0; j < n; j++)
6627 gimple_switch_set_label (su->stmt, j, TREE_VEC_ELT (su->vec, j));
6628 /* As we may have replaced the default label with a regular one
6629 make sure to make it a real default label again. This ensures
6630 optimal expansion. */
6631 label = gimple_switch_label (su->stmt, 0);
6632 CASE_LOW (label) = NULL_TREE;
6633 CASE_HIGH (label) = NULL_TREE;
6636 if (to_remove_edges.length () > 0)
6638 free_dominance_info (CDI_DOMINATORS);
6639 loops_state_set (LOOPS_NEED_FIXUP);
6642 to_remove_edges.release ();
6643 to_update_switch_stmts.release ();
6644 threadedge_finalize_values ();
6646 scev_finalize ();
6647 loop_optimizer_finalize ();
6648 return 0;
6651 namespace {
6653 const pass_data pass_data_vrp =
6655 GIMPLE_PASS, /* type */
6656 "vrp", /* name */
6657 OPTGROUP_NONE, /* optinfo_flags */
6658 TV_TREE_VRP, /* tv_id */
6659 PROP_ssa, /* properties_required */
6660 0, /* properties_provided */
6661 0, /* properties_destroyed */
6662 0, /* todo_flags_start */
6663 ( TODO_cleanup_cfg | TODO_update_ssa ), /* todo_flags_finish */
6666 class pass_vrp : public gimple_opt_pass
6668 public:
6669 pass_vrp (gcc::context *ctxt)
6670 : gimple_opt_pass (pass_data_vrp, ctxt), warn_array_bounds_p (false)
6673 /* opt_pass methods: */
6674 opt_pass * clone () { return new pass_vrp (m_ctxt); }
6675 void set_pass_param (unsigned int n, bool param)
6677 gcc_assert (n == 0);
6678 warn_array_bounds_p = param;
6680 virtual bool gate (function *) { return flag_tree_vrp != 0; }
6681 virtual unsigned int execute (function *)
6682 { return execute_vrp (warn_array_bounds_p); }
6684 private:
6685 bool warn_array_bounds_p;
6686 }; // class pass_vrp
6688 } // anon namespace
6690 gimple_opt_pass *
6691 make_pass_vrp (gcc::context *ctxt)
6693 return new pass_vrp (ctxt);
6697 /* Worker for determine_value_range. */
6699 static void
6700 determine_value_range_1 (value_range *vr, tree expr)
6702 if (BINARY_CLASS_P (expr))
6704 value_range vr0 = VR_INITIALIZER, vr1 = VR_INITIALIZER;
6705 determine_value_range_1 (&vr0, TREE_OPERAND (expr, 0));
6706 determine_value_range_1 (&vr1, TREE_OPERAND (expr, 1));
6707 extract_range_from_binary_expr_1 (vr, TREE_CODE (expr), TREE_TYPE (expr),
6708 &vr0, &vr1);
6710 else if (UNARY_CLASS_P (expr))
6712 value_range vr0 = VR_INITIALIZER;
6713 determine_value_range_1 (&vr0, TREE_OPERAND (expr, 0));
6714 extract_range_from_unary_expr (vr, TREE_CODE (expr), TREE_TYPE (expr),
6715 &vr0, TREE_TYPE (TREE_OPERAND (expr, 0)));
6717 else if (TREE_CODE (expr) == INTEGER_CST)
6718 set_value_range_to_value (vr, expr, NULL);
6719 else
6721 value_range_type kind;
6722 wide_int min, max;
6723 /* For SSA names try to extract range info computed by VRP. Otherwise
6724 fall back to varying. */
6725 if (TREE_CODE (expr) == SSA_NAME
6726 && INTEGRAL_TYPE_P (TREE_TYPE (expr))
6727 && (kind = get_range_info (expr, &min, &max)) != VR_VARYING)
6728 set_value_range (vr, kind, wide_int_to_tree (TREE_TYPE (expr), min),
6729 wide_int_to_tree (TREE_TYPE (expr), max), NULL);
6730 else
6731 set_value_range_to_varying (vr);
6735 /* Compute a value-range for EXPR and set it in *MIN and *MAX. Return
6736 the determined range type. */
6738 value_range_type
6739 determine_value_range (tree expr, wide_int *min, wide_int *max)
6741 value_range vr = VR_INITIALIZER;
6742 determine_value_range_1 (&vr, expr);
6743 if ((vr.type == VR_RANGE
6744 || vr.type == VR_ANTI_RANGE)
6745 && !symbolic_range_p (&vr))
6747 *min = wi::to_wide (vr.min);
6748 *max = wi::to_wide (vr.max);
6749 return vr.type;
6752 return VR_VARYING;