C++: -Wwrite-strings: use location of string constant
[official-gcc.git] / gcc / tree-vrp.c
blobd553a254878a1b2b40d47cc8a79a8f171155b197
1 /* Support routines for Value Range Propagation (VRP).
2 Copyright (C) 2005-2018 Free Software Foundation, Inc.
3 Contributed by Diego Novillo <dnovillo@redhat.com>.
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "backend.h"
25 #include "insn-codes.h"
26 #include "rtl.h"
27 #include "tree.h"
28 #include "gimple.h"
29 #include "cfghooks.h"
30 #include "tree-pass.h"
31 #include "ssa.h"
32 #include "optabs-tree.h"
33 #include "gimple-pretty-print.h"
34 #include "diagnostic-core.h"
35 #include "flags.h"
36 #include "fold-const.h"
37 #include "stor-layout.h"
38 #include "calls.h"
39 #include "cfganal.h"
40 #include "gimple-fold.h"
41 #include "tree-eh.h"
42 #include "gimple-iterator.h"
43 #include "gimple-walk.h"
44 #include "tree-cfg.h"
45 #include "tree-dfa.h"
46 #include "tree-ssa-loop-manip.h"
47 #include "tree-ssa-loop-niter.h"
48 #include "tree-ssa-loop.h"
49 #include "tree-into-ssa.h"
50 #include "tree-ssa.h"
51 #include "intl.h"
52 #include "cfgloop.h"
53 #include "tree-scalar-evolution.h"
54 #include "tree-ssa-propagate.h"
55 #include "tree-chrec.h"
56 #include "tree-ssa-threadupdate.h"
57 #include "tree-ssa-scopedtables.h"
58 #include "tree-ssa-threadedge.h"
59 #include "omp-general.h"
60 #include "target.h"
61 #include "case-cfn-macros.h"
62 #include "params.h"
63 #include "alloc-pool.h"
64 #include "domwalk.h"
65 #include "tree-cfgcleanup.h"
66 #include "stringpool.h"
67 #include "attribs.h"
68 #include "vr-values.h"
69 #include "builtins.h"
70 #include "wide-int-range.h"
72 /* Set of SSA names found live during the RPO traversal of the function
73 for still active basic-blocks. */
74 static sbitmap *live;
76 /* Return true if the SSA name NAME is live on the edge E. */
78 static bool
79 live_on_edge (edge e, tree name)
81 return (live[e->dest->index]
82 && bitmap_bit_p (live[e->dest->index], SSA_NAME_VERSION (name)));
85 /* Location information for ASSERT_EXPRs. Each instance of this
86 structure describes an ASSERT_EXPR for an SSA name. Since a single
87 SSA name may have more than one assertion associated with it, these
88 locations are kept in a linked list attached to the corresponding
89 SSA name. */
90 struct assert_locus
92 /* Basic block where the assertion would be inserted. */
93 basic_block bb;
95 /* Some assertions need to be inserted on an edge (e.g., assertions
96 generated by COND_EXPRs). In those cases, BB will be NULL. */
97 edge e;
99 /* Pointer to the statement that generated this assertion. */
100 gimple_stmt_iterator si;
102 /* Predicate code for the ASSERT_EXPR. Must be COMPARISON_CLASS_P. */
103 enum tree_code comp_code;
105 /* Value being compared against. */
106 tree val;
108 /* Expression to compare. */
109 tree expr;
111 /* Next node in the linked list. */
112 assert_locus *next;
115 /* If bit I is present, it means that SSA name N_i has a list of
116 assertions that should be inserted in the IL. */
117 static bitmap need_assert_for;
119 /* Array of locations lists where to insert assertions. ASSERTS_FOR[I]
120 holds a list of ASSERT_LOCUS_T nodes that describe where
121 ASSERT_EXPRs for SSA name N_I should be inserted. */
122 static assert_locus **asserts_for;
124 vec<edge> to_remove_edges;
125 vec<switch_update> to_update_switch_stmts;
128 /* Return the maximum value for TYPE. */
130 tree
131 vrp_val_max (const_tree type)
133 if (!INTEGRAL_TYPE_P (type))
134 return NULL_TREE;
136 return TYPE_MAX_VALUE (type);
139 /* Return the minimum value for TYPE. */
141 tree
142 vrp_val_min (const_tree type)
144 if (!INTEGRAL_TYPE_P (type))
145 return NULL_TREE;
147 return TYPE_MIN_VALUE (type);
150 /* Return whether VAL is equal to the maximum value of its type.
151 We can't do a simple equality comparison with TYPE_MAX_VALUE because
152 C typedefs and Ada subtypes can produce types whose TYPE_MAX_VALUE
153 is not == to the integer constant with the same value in the type. */
155 bool
156 vrp_val_is_max (const_tree val)
158 tree type_max = vrp_val_max (TREE_TYPE (val));
159 return (val == type_max
160 || (type_max != NULL_TREE
161 && operand_equal_p (val, type_max, 0)));
164 /* Return whether VAL is equal to the minimum value of its type. */
166 bool
167 vrp_val_is_min (const_tree val)
169 tree type_min = vrp_val_min (TREE_TYPE (val));
170 return (val == type_min
171 || (type_min != NULL_TREE
172 && operand_equal_p (val, type_min, 0)));
175 /* VR_TYPE describes a range with mininum value *MIN and maximum
176 value *MAX. Restrict the range to the set of values that have
177 no bits set outside NONZERO_BITS. Update *MIN and *MAX and
178 return the new range type.
180 SGN gives the sign of the values described by the range. */
182 enum value_range_type
183 intersect_range_with_nonzero_bits (enum value_range_type vr_type,
184 wide_int *min, wide_int *max,
185 const wide_int &nonzero_bits,
186 signop sgn)
188 if (vr_type == VR_ANTI_RANGE)
190 /* The VR_ANTI_RANGE is equivalent to the union of the ranges
191 A: [-INF, *MIN) and B: (*MAX, +INF]. First use NONZERO_BITS
192 to create an inclusive upper bound for A and an inclusive lower
193 bound for B. */
194 wide_int a_max = wi::round_down_for_mask (*min - 1, nonzero_bits);
195 wide_int b_min = wi::round_up_for_mask (*max + 1, nonzero_bits);
197 /* If the calculation of A_MAX wrapped, A is effectively empty
198 and A_MAX is the highest value that satisfies NONZERO_BITS.
199 Likewise if the calculation of B_MIN wrapped, B is effectively
200 empty and B_MIN is the lowest value that satisfies NONZERO_BITS. */
201 bool a_empty = wi::ge_p (a_max, *min, sgn);
202 bool b_empty = wi::le_p (b_min, *max, sgn);
204 /* If both A and B are empty, there are no valid values. */
205 if (a_empty && b_empty)
206 return VR_UNDEFINED;
208 /* If exactly one of A or B is empty, return a VR_RANGE for the
209 other one. */
210 if (a_empty || b_empty)
212 *min = b_min;
213 *max = a_max;
214 gcc_checking_assert (wi::le_p (*min, *max, sgn));
215 return VR_RANGE;
218 /* Update the VR_ANTI_RANGE bounds. */
219 *min = a_max + 1;
220 *max = b_min - 1;
221 gcc_checking_assert (wi::le_p (*min, *max, sgn));
223 /* Now check whether the excluded range includes any values that
224 satisfy NONZERO_BITS. If not, switch to a full VR_RANGE. */
225 if (wi::round_up_for_mask (*min, nonzero_bits) == b_min)
227 unsigned int precision = min->get_precision ();
228 *min = wi::min_value (precision, sgn);
229 *max = wi::max_value (precision, sgn);
230 vr_type = VR_RANGE;
233 if (vr_type == VR_RANGE)
235 *max = wi::round_down_for_mask (*max, nonzero_bits);
237 /* Check that the range contains at least one valid value. */
238 if (wi::gt_p (*min, *max, sgn))
239 return VR_UNDEFINED;
241 *min = wi::round_up_for_mask (*min, nonzero_bits);
242 gcc_checking_assert (wi::le_p (*min, *max, sgn));
244 return vr_type;
247 /* Set value range VR to VR_UNDEFINED. */
249 static inline void
250 set_value_range_to_undefined (value_range *vr)
252 vr->type = VR_UNDEFINED;
253 vr->min = vr->max = NULL_TREE;
254 if (vr->equiv)
255 bitmap_clear (vr->equiv);
258 /* Set value range VR to VR_VARYING. */
260 void
261 set_value_range_to_varying (value_range *vr)
263 vr->type = VR_VARYING;
264 vr->min = vr->max = NULL_TREE;
265 if (vr->equiv)
266 bitmap_clear (vr->equiv);
269 /* Set value range VR to {T, MIN, MAX, EQUIV}. */
271 void
272 set_value_range (value_range *vr, enum value_range_type t, tree min,
273 tree max, bitmap equiv)
275 /* Check the validity of the range. */
276 if (flag_checking
277 && (t == VR_RANGE || t == VR_ANTI_RANGE))
279 int cmp;
281 gcc_assert (min && max);
283 gcc_assert (!TREE_OVERFLOW_P (min) && !TREE_OVERFLOW_P (max));
285 if (INTEGRAL_TYPE_P (TREE_TYPE (min)) && t == VR_ANTI_RANGE)
286 gcc_assert (!vrp_val_is_min (min) || !vrp_val_is_max (max));
288 cmp = compare_values (min, max);
289 gcc_assert (cmp == 0 || cmp == -1 || cmp == -2);
292 if (flag_checking
293 && (t == VR_UNDEFINED || t == VR_VARYING))
295 gcc_assert (min == NULL_TREE && max == NULL_TREE);
296 gcc_assert (equiv == NULL || bitmap_empty_p (equiv));
299 vr->type = t;
300 vr->min = min;
301 vr->max = max;
303 /* Since updating the equivalence set involves deep copying the
304 bitmaps, only do it if absolutely necessary.
306 All equivalence bitmaps are allocated from the same obstack. So
307 we can use the obstack associated with EQUIV to allocate vr->equiv. */
308 if (vr->equiv == NULL
309 && equiv != NULL)
310 vr->equiv = BITMAP_ALLOC (equiv->obstack);
312 if (equiv != vr->equiv)
314 if (equiv && !bitmap_empty_p (equiv))
315 bitmap_copy (vr->equiv, equiv);
316 else
317 bitmap_clear (vr->equiv);
322 /* Set value range VR to the canonical form of {T, MIN, MAX, EQUIV}.
323 This means adjusting T, MIN and MAX representing the case of a
324 wrapping range with MAX < MIN covering [MIN, type_max] U [type_min, MAX]
325 as anti-rage ~[MAX+1, MIN-1]. Likewise for wrapping anti-ranges.
326 In corner cases where MAX+1 or MIN-1 wraps this will fall back
327 to varying.
328 This routine exists to ease canonicalization in the case where we
329 extract ranges from var + CST op limit. */
331 void
332 set_and_canonicalize_value_range (value_range *vr, enum value_range_type t,
333 tree min, tree max, bitmap equiv)
335 /* Use the canonical setters for VR_UNDEFINED and VR_VARYING. */
336 if (t == VR_UNDEFINED)
338 set_value_range_to_undefined (vr);
339 return;
341 else if (t == VR_VARYING)
343 set_value_range_to_varying (vr);
344 return;
347 /* Nothing to canonicalize for symbolic ranges. */
348 if (TREE_CODE (min) != INTEGER_CST
349 || TREE_CODE (max) != INTEGER_CST)
351 set_value_range (vr, t, min, max, equiv);
352 return;
355 /* Wrong order for min and max, to swap them and the VR type we need
356 to adjust them. */
357 if (tree_int_cst_lt (max, min))
359 tree one, tmp;
361 /* For one bit precision if max < min, then the swapped
362 range covers all values, so for VR_RANGE it is varying and
363 for VR_ANTI_RANGE empty range, so drop to varying as well. */
364 if (TYPE_PRECISION (TREE_TYPE (min)) == 1)
366 set_value_range_to_varying (vr);
367 return;
370 one = build_int_cst (TREE_TYPE (min), 1);
371 tmp = int_const_binop (PLUS_EXPR, max, one);
372 max = int_const_binop (MINUS_EXPR, min, one);
373 min = tmp;
375 /* There's one corner case, if we had [C+1, C] before we now have
376 that again. But this represents an empty value range, so drop
377 to varying in this case. */
378 if (tree_int_cst_lt (max, min))
380 set_value_range_to_varying (vr);
381 return;
384 t = t == VR_RANGE ? VR_ANTI_RANGE : VR_RANGE;
387 /* Anti-ranges that can be represented as ranges should be so. */
388 if (t == VR_ANTI_RANGE)
390 /* For -fstrict-enums we may receive out-of-range ranges so consider
391 values < -INF and values > INF as -INF/INF as well. */
392 tree type = TREE_TYPE (min);
393 bool is_min = (INTEGRAL_TYPE_P (type)
394 && tree_int_cst_compare (min, TYPE_MIN_VALUE (type)) <= 0);
395 bool is_max = (INTEGRAL_TYPE_P (type)
396 && tree_int_cst_compare (max, TYPE_MAX_VALUE (type)) >= 0);
398 if (is_min && is_max)
400 /* We cannot deal with empty ranges, drop to varying.
401 ??? This could be VR_UNDEFINED instead. */
402 set_value_range_to_varying (vr);
403 return;
405 else if (TYPE_PRECISION (TREE_TYPE (min)) == 1
406 && (is_min || is_max))
408 /* Non-empty boolean ranges can always be represented
409 as a singleton range. */
410 if (is_min)
411 min = max = vrp_val_max (TREE_TYPE (min));
412 else
413 min = max = vrp_val_min (TREE_TYPE (min));
414 t = VR_RANGE;
416 else if (is_min
417 /* As a special exception preserve non-null ranges. */
418 && !(TYPE_UNSIGNED (TREE_TYPE (min))
419 && integer_zerop (max)))
421 tree one = build_int_cst (TREE_TYPE (max), 1);
422 min = int_const_binop (PLUS_EXPR, max, one);
423 max = vrp_val_max (TREE_TYPE (max));
424 t = VR_RANGE;
426 else if (is_max)
428 tree one = build_int_cst (TREE_TYPE (min), 1);
429 max = int_const_binop (MINUS_EXPR, min, one);
430 min = vrp_val_min (TREE_TYPE (min));
431 t = VR_RANGE;
435 /* Do not drop [-INF(OVF), +INF(OVF)] to varying. (OVF) has to be sticky
436 to make sure VRP iteration terminates, otherwise we can get into
437 oscillations. */
439 set_value_range (vr, t, min, max, equiv);
442 /* Copy value range FROM into value range TO. */
444 void
445 copy_value_range (value_range *to, value_range *from)
447 set_value_range (to, from->type, from->min, from->max, from->equiv);
450 /* Set value range VR to a single value. This function is only called
451 with values we get from statements, and exists to clear the
452 TREE_OVERFLOW flag. */
454 void
455 set_value_range_to_value (value_range *vr, tree val, bitmap equiv)
457 gcc_assert (is_gimple_min_invariant (val));
458 if (TREE_OVERFLOW_P (val))
459 val = drop_tree_overflow (val);
460 set_value_range (vr, VR_RANGE, val, val, equiv);
463 /* Set value range VR to a non-NULL range of type TYPE. */
465 void
466 set_value_range_to_nonnull (value_range *vr, tree type)
468 tree zero = build_int_cst (type, 0);
469 set_value_range (vr, VR_ANTI_RANGE, zero, zero, vr->equiv);
473 /* Set value range VR to a NULL range of type TYPE. */
475 void
476 set_value_range_to_null (value_range *vr, tree type)
478 set_value_range_to_value (vr, build_int_cst (type, 0), vr->equiv);
482 /* If abs (min) < abs (max), set VR to [-max, max], if
483 abs (min) >= abs (max), set VR to [-min, min]. */
485 static void
486 abs_extent_range (value_range *vr, tree min, tree max)
488 int cmp;
490 gcc_assert (TREE_CODE (min) == INTEGER_CST);
491 gcc_assert (TREE_CODE (max) == INTEGER_CST);
492 gcc_assert (INTEGRAL_TYPE_P (TREE_TYPE (min)));
493 gcc_assert (!TYPE_UNSIGNED (TREE_TYPE (min)));
494 min = fold_unary (ABS_EXPR, TREE_TYPE (min), min);
495 max = fold_unary (ABS_EXPR, TREE_TYPE (max), max);
496 if (TREE_OVERFLOW (min) || TREE_OVERFLOW (max))
498 set_value_range_to_varying (vr);
499 return;
501 cmp = compare_values (min, max);
502 if (cmp == -1)
503 min = fold_unary (NEGATE_EXPR, TREE_TYPE (min), max);
504 else if (cmp == 0 || cmp == 1)
506 max = min;
507 min = fold_unary (NEGATE_EXPR, TREE_TYPE (min), min);
509 else
511 set_value_range_to_varying (vr);
512 return;
514 set_and_canonicalize_value_range (vr, VR_RANGE, min, max, NULL);
517 /* Return true, if VAL1 and VAL2 are equal values for VRP purposes. */
519 bool
520 vrp_operand_equal_p (const_tree val1, const_tree val2)
522 if (val1 == val2)
523 return true;
524 if (!val1 || !val2 || !operand_equal_p (val1, val2, 0))
525 return false;
526 return true;
529 /* Return true, if the bitmaps B1 and B2 are equal. */
531 bool
532 vrp_bitmap_equal_p (const_bitmap b1, const_bitmap b2)
534 return (b1 == b2
535 || ((!b1 || bitmap_empty_p (b1))
536 && (!b2 || bitmap_empty_p (b2)))
537 || (b1 && b2
538 && bitmap_equal_p (b1, b2)));
541 /* Return true if VR is ~[0, 0]. */
543 bool
544 range_is_nonnull (value_range *vr)
546 return vr->type == VR_ANTI_RANGE
547 && integer_zerop (vr->min)
548 && integer_zerop (vr->max);
552 /* Return true if VR is [0, 0]. */
554 static inline bool
555 range_is_null (value_range *vr)
557 return vr->type == VR_RANGE
558 && integer_zerop (vr->min)
559 && integer_zerop (vr->max);
562 /* Return true if max and min of VR are INTEGER_CST. It's not necessary
563 a singleton. */
565 bool
566 range_int_cst_p (value_range *vr)
568 return (vr->type == VR_RANGE
569 && TREE_CODE (vr->max) == INTEGER_CST
570 && TREE_CODE (vr->min) == INTEGER_CST);
573 /* Return true if VR is a INTEGER_CST singleton. */
575 bool
576 range_int_cst_singleton_p (value_range *vr)
578 return (range_int_cst_p (vr)
579 && tree_int_cst_equal (vr->min, vr->max));
582 /* Return true if value range VR involves at least one symbol. */
584 bool
585 symbolic_range_p (value_range *vr)
587 return (!is_gimple_min_invariant (vr->min)
588 || !is_gimple_min_invariant (vr->max));
591 /* Return the single symbol (an SSA_NAME) contained in T if any, or NULL_TREE
592 otherwise. We only handle additive operations and set NEG to true if the
593 symbol is negated and INV to the invariant part, if any. */
595 tree
596 get_single_symbol (tree t, bool *neg, tree *inv)
598 bool neg_;
599 tree inv_;
601 *inv = NULL_TREE;
602 *neg = false;
604 if (TREE_CODE (t) == PLUS_EXPR
605 || TREE_CODE (t) == POINTER_PLUS_EXPR
606 || TREE_CODE (t) == MINUS_EXPR)
608 if (is_gimple_min_invariant (TREE_OPERAND (t, 0)))
610 neg_ = (TREE_CODE (t) == MINUS_EXPR);
611 inv_ = TREE_OPERAND (t, 0);
612 t = TREE_OPERAND (t, 1);
614 else if (is_gimple_min_invariant (TREE_OPERAND (t, 1)))
616 neg_ = false;
617 inv_ = TREE_OPERAND (t, 1);
618 t = TREE_OPERAND (t, 0);
620 else
621 return NULL_TREE;
623 else
625 neg_ = false;
626 inv_ = NULL_TREE;
629 if (TREE_CODE (t) == NEGATE_EXPR)
631 t = TREE_OPERAND (t, 0);
632 neg_ = !neg_;
635 if (TREE_CODE (t) != SSA_NAME)
636 return NULL_TREE;
638 if (inv_ && TREE_OVERFLOW_P (inv_))
639 inv_ = drop_tree_overflow (inv_);
641 *neg = neg_;
642 *inv = inv_;
643 return t;
646 /* The reverse operation: build a symbolic expression with TYPE
647 from symbol SYM, negated according to NEG, and invariant INV. */
649 static tree
650 build_symbolic_expr (tree type, tree sym, bool neg, tree inv)
652 const bool pointer_p = POINTER_TYPE_P (type);
653 tree t = sym;
655 if (neg)
656 t = build1 (NEGATE_EXPR, type, t);
658 if (integer_zerop (inv))
659 return t;
661 return build2 (pointer_p ? POINTER_PLUS_EXPR : PLUS_EXPR, type, t, inv);
664 /* Return
665 1 if VAL < VAL2
666 0 if !(VAL < VAL2)
667 -2 if those are incomparable. */
669 operand_less_p (tree val, tree val2)
671 /* LT is folded faster than GE and others. Inline the common case. */
672 if (TREE_CODE (val) == INTEGER_CST && TREE_CODE (val2) == INTEGER_CST)
673 return tree_int_cst_lt (val, val2);
674 else
676 tree tcmp;
678 fold_defer_overflow_warnings ();
680 tcmp = fold_binary_to_constant (LT_EXPR, boolean_type_node, val, val2);
682 fold_undefer_and_ignore_overflow_warnings ();
684 if (!tcmp
685 || TREE_CODE (tcmp) != INTEGER_CST)
686 return -2;
688 if (!integer_zerop (tcmp))
689 return 1;
692 return 0;
695 /* Compare two values VAL1 and VAL2. Return
697 -2 if VAL1 and VAL2 cannot be compared at compile-time,
698 -1 if VAL1 < VAL2,
699 0 if VAL1 == VAL2,
700 +1 if VAL1 > VAL2, and
701 +2 if VAL1 != VAL2
703 This is similar to tree_int_cst_compare but supports pointer values
704 and values that cannot be compared at compile time.
706 If STRICT_OVERFLOW_P is not NULL, then set *STRICT_OVERFLOW_P to
707 true if the return value is only valid if we assume that signed
708 overflow is undefined. */
711 compare_values_warnv (tree val1, tree val2, bool *strict_overflow_p)
713 if (val1 == val2)
714 return 0;
716 /* Below we rely on the fact that VAL1 and VAL2 are both pointers or
717 both integers. */
718 gcc_assert (POINTER_TYPE_P (TREE_TYPE (val1))
719 == POINTER_TYPE_P (TREE_TYPE (val2)));
721 /* Convert the two values into the same type. This is needed because
722 sizetype causes sign extension even for unsigned types. */
723 val2 = fold_convert (TREE_TYPE (val1), val2);
724 STRIP_USELESS_TYPE_CONVERSION (val2);
726 const bool overflow_undefined
727 = INTEGRAL_TYPE_P (TREE_TYPE (val1))
728 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1));
729 tree inv1, inv2;
730 bool neg1, neg2;
731 tree sym1 = get_single_symbol (val1, &neg1, &inv1);
732 tree sym2 = get_single_symbol (val2, &neg2, &inv2);
734 /* If VAL1 and VAL2 are of the form '[-]NAME [+ CST]', return -1 or +1
735 accordingly. If VAL1 and VAL2 don't use the same name, return -2. */
736 if (sym1 && sym2)
738 /* Both values must use the same name with the same sign. */
739 if (sym1 != sym2 || neg1 != neg2)
740 return -2;
742 /* [-]NAME + CST == [-]NAME + CST. */
743 if (inv1 == inv2)
744 return 0;
746 /* If overflow is defined we cannot simplify more. */
747 if (!overflow_undefined)
748 return -2;
750 if (strict_overflow_p != NULL
751 /* Symbolic range building sets TREE_NO_WARNING to declare
752 that overflow doesn't happen. */
753 && (!inv1 || !TREE_NO_WARNING (val1))
754 && (!inv2 || !TREE_NO_WARNING (val2)))
755 *strict_overflow_p = true;
757 if (!inv1)
758 inv1 = build_int_cst (TREE_TYPE (val1), 0);
759 if (!inv2)
760 inv2 = build_int_cst (TREE_TYPE (val2), 0);
762 return wi::cmp (wi::to_wide (inv1), wi::to_wide (inv2),
763 TYPE_SIGN (TREE_TYPE (val1)));
766 const bool cst1 = is_gimple_min_invariant (val1);
767 const bool cst2 = is_gimple_min_invariant (val2);
769 /* If one is of the form '[-]NAME + CST' and the other is constant, then
770 it might be possible to say something depending on the constants. */
771 if ((sym1 && inv1 && cst2) || (sym2 && inv2 && cst1))
773 if (!overflow_undefined)
774 return -2;
776 if (strict_overflow_p != NULL
777 /* Symbolic range building sets TREE_NO_WARNING to declare
778 that overflow doesn't happen. */
779 && (!sym1 || !TREE_NO_WARNING (val1))
780 && (!sym2 || !TREE_NO_WARNING (val2)))
781 *strict_overflow_p = true;
783 const signop sgn = TYPE_SIGN (TREE_TYPE (val1));
784 tree cst = cst1 ? val1 : val2;
785 tree inv = cst1 ? inv2 : inv1;
787 /* Compute the difference between the constants. If it overflows or
788 underflows, this means that we can trivially compare the NAME with
789 it and, consequently, the two values with each other. */
790 wide_int diff = wi::to_wide (cst) - wi::to_wide (inv);
791 if (wi::cmp (0, wi::to_wide (inv), sgn)
792 != wi::cmp (diff, wi::to_wide (cst), sgn))
794 const int res = wi::cmp (wi::to_wide (cst), wi::to_wide (inv), sgn);
795 return cst1 ? res : -res;
798 return -2;
801 /* We cannot say anything more for non-constants. */
802 if (!cst1 || !cst2)
803 return -2;
805 if (!POINTER_TYPE_P (TREE_TYPE (val1)))
807 /* We cannot compare overflowed values. */
808 if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
809 return -2;
811 if (TREE_CODE (val1) == INTEGER_CST
812 && TREE_CODE (val2) == INTEGER_CST)
813 return tree_int_cst_compare (val1, val2);
815 if (poly_int_tree_p (val1) && poly_int_tree_p (val2))
817 if (known_eq (wi::to_poly_widest (val1),
818 wi::to_poly_widest (val2)))
819 return 0;
820 if (known_lt (wi::to_poly_widest (val1),
821 wi::to_poly_widest (val2)))
822 return -1;
823 if (known_gt (wi::to_poly_widest (val1),
824 wi::to_poly_widest (val2)))
825 return 1;
828 return -2;
830 else
832 tree t;
834 /* First see if VAL1 and VAL2 are not the same. */
835 if (val1 == val2 || operand_equal_p (val1, val2, 0))
836 return 0;
838 /* If VAL1 is a lower address than VAL2, return -1. */
839 if (operand_less_p (val1, val2) == 1)
840 return -1;
842 /* If VAL1 is a higher address than VAL2, return +1. */
843 if (operand_less_p (val2, val1) == 1)
844 return 1;
846 /* If VAL1 is different than VAL2, return +2.
847 For integer constants we either have already returned -1 or 1
848 or they are equivalent. We still might succeed in proving
849 something about non-trivial operands. */
850 if (TREE_CODE (val1) != INTEGER_CST
851 || TREE_CODE (val2) != INTEGER_CST)
853 t = fold_binary_to_constant (NE_EXPR, boolean_type_node, val1, val2);
854 if (t && integer_onep (t))
855 return 2;
858 return -2;
862 /* Compare values like compare_values_warnv. */
865 compare_values (tree val1, tree val2)
867 bool sop;
868 return compare_values_warnv (val1, val2, &sop);
872 /* Return 1 if VAL is inside value range MIN <= VAL <= MAX,
873 0 if VAL is not inside [MIN, MAX],
874 -2 if we cannot tell either way.
876 Benchmark compile/20001226-1.c compilation time after changing this
877 function. */
880 value_inside_range (tree val, tree min, tree max)
882 int cmp1, cmp2;
884 cmp1 = operand_less_p (val, min);
885 if (cmp1 == -2)
886 return -2;
887 if (cmp1 == 1)
888 return 0;
890 cmp2 = operand_less_p (max, val);
891 if (cmp2 == -2)
892 return -2;
894 return !cmp2;
898 /* Return true if value ranges VR0 and VR1 have a non-empty
899 intersection.
901 Benchmark compile/20001226-1.c compilation time after changing this
902 function.
905 static inline bool
906 value_ranges_intersect_p (value_range *vr0, value_range *vr1)
908 /* The value ranges do not intersect if the maximum of the first range is
909 less than the minimum of the second range or vice versa.
910 When those relations are unknown, we can't do any better. */
911 if (operand_less_p (vr0->max, vr1->min) != 0)
912 return false;
913 if (operand_less_p (vr1->max, vr0->min) != 0)
914 return false;
915 return true;
919 /* Return 1 if [MIN, MAX] includes the value zero, 0 if it does not
920 include the value zero, -2 if we cannot tell. */
923 range_includes_zero_p (tree min, tree max)
925 tree zero = build_int_cst (TREE_TYPE (min), 0);
926 return value_inside_range (zero, min, max);
929 /* Return true if *VR is know to only contain nonnegative values. */
931 static inline bool
932 value_range_nonnegative_p (value_range *vr)
934 /* Testing for VR_ANTI_RANGE is not useful here as any anti-range
935 which would return a useful value should be encoded as a
936 VR_RANGE. */
937 if (vr->type == VR_RANGE)
939 int result = compare_values (vr->min, integer_zero_node);
940 return (result == 0 || result == 1);
943 return false;
946 /* If *VR has a value rante that is a single constant value return that,
947 otherwise return NULL_TREE. */
949 tree
950 value_range_constant_singleton (value_range *vr)
952 if (vr->type == VR_RANGE
953 && vrp_operand_equal_p (vr->min, vr->max)
954 && is_gimple_min_invariant (vr->min))
955 return vr->min;
957 return NULL_TREE;
960 /* Value range wrapper for wide_int_range_set_zero_nonzero_bits.
962 Compute MAY_BE_NONZERO and MUST_BE_NONZERO bit masks for range in VR.
964 Return TRUE if VR was a constant range and we were able to compute
965 the bit masks. */
967 bool
968 vrp_set_zero_nonzero_bits (const tree expr_type,
969 value_range *vr,
970 wide_int *may_be_nonzero,
971 wide_int *must_be_nonzero)
973 if (!range_int_cst_p (vr))
975 *may_be_nonzero = wi::minus_one (TYPE_PRECISION (expr_type));
976 *must_be_nonzero = wi::zero (TYPE_PRECISION (expr_type));
977 return false;
979 wide_int_range_set_zero_nonzero_bits (TYPE_SIGN (expr_type),
980 wi::to_wide (vr->min),
981 wi::to_wide (vr->max),
982 *may_be_nonzero, *must_be_nonzero);
983 return true;
986 /* Create two value-ranges in *VR0 and *VR1 from the anti-range *AR
987 so that *VR0 U *VR1 == *AR. Returns true if that is possible,
988 false otherwise. If *AR can be represented with a single range
989 *VR1 will be VR_UNDEFINED. */
991 static bool
992 ranges_from_anti_range (value_range *ar,
993 value_range *vr0, value_range *vr1)
995 tree type = TREE_TYPE (ar->min);
997 vr0->type = VR_UNDEFINED;
998 vr1->type = VR_UNDEFINED;
1000 if (ar->type != VR_ANTI_RANGE
1001 || TREE_CODE (ar->min) != INTEGER_CST
1002 || TREE_CODE (ar->max) != INTEGER_CST
1003 || !vrp_val_min (type)
1004 || !vrp_val_max (type))
1005 return false;
1007 if (!vrp_val_is_min (ar->min))
1009 vr0->type = VR_RANGE;
1010 vr0->min = vrp_val_min (type);
1011 vr0->max = wide_int_to_tree (type, wi::to_wide (ar->min) - 1);
1013 if (!vrp_val_is_max (ar->max))
1015 vr1->type = VR_RANGE;
1016 vr1->min = wide_int_to_tree (type, wi::to_wide (ar->max) + 1);
1017 vr1->max = vrp_val_max (type);
1019 if (vr0->type == VR_UNDEFINED)
1021 *vr0 = *vr1;
1022 vr1->type = VR_UNDEFINED;
1025 return vr0->type != VR_UNDEFINED;
1028 /* Extract the components of a value range into a pair of wide ints in
1029 [WMIN, WMAX].
1031 If the value range is anything but a VR_RANGE of constants, the
1032 resulting wide ints are set to [-MIN, +MAX] for the type. */
1034 static void inline
1035 extract_range_into_wide_ints (value_range *vr,
1036 signop sign, unsigned prec,
1037 wide_int *wmin, wide_int *wmax)
1039 if (range_int_cst_p (vr))
1041 *wmin = wi::to_wide (vr->min);
1042 *wmax = wi::to_wide (vr->max);
1044 else
1046 *wmin = wi::min_value (prec, sign);
1047 *wmax = wi::max_value (prec, sign);
1051 /* Value range wrapper for wide_int_range_shift_undefined_p. */
1053 static inline bool
1054 vrp_shift_undefined_p (const value_range &shifter, unsigned prec)
1056 tree type = TREE_TYPE (shifter.min);
1057 return wide_int_range_shift_undefined_p (TYPE_SIGN (type), prec,
1058 wi::to_wide (shifter.min),
1059 wi::to_wide (shifter.max));
1062 /* Value range wrapper for wide_int_range_multiplicative_op:
1064 *VR = *VR0 .CODE. *VR1. */
1066 static void
1067 extract_range_from_multiplicative_op (value_range *vr,
1068 enum tree_code code,
1069 value_range *vr0, value_range *vr1)
1071 gcc_assert (code == MULT_EXPR
1072 || code == TRUNC_DIV_EXPR
1073 || code == FLOOR_DIV_EXPR
1074 || code == CEIL_DIV_EXPR
1075 || code == EXACT_DIV_EXPR
1076 || code == ROUND_DIV_EXPR
1077 || code == RSHIFT_EXPR
1078 || code == LSHIFT_EXPR);
1079 gcc_assert (vr0->type == VR_RANGE && vr0->type == vr1->type);
1081 tree type = TREE_TYPE (vr0->min);
1082 wide_int res_lb, res_ub;
1083 wide_int vr0_lb = wi::to_wide (vr0->min);
1084 wide_int vr0_ub = wi::to_wide (vr0->max);
1085 wide_int vr1_lb = wi::to_wide (vr1->min);
1086 wide_int vr1_ub = wi::to_wide (vr1->max);
1087 bool overflow_undefined = TYPE_OVERFLOW_UNDEFINED (type);
1088 bool overflow_wraps = TYPE_OVERFLOW_WRAPS (type);
1089 unsigned prec = TYPE_PRECISION (type);
1091 if (wide_int_range_multiplicative_op (res_lb, res_ub,
1092 code, TYPE_SIGN (type), prec,
1093 vr0_lb, vr0_ub, vr1_lb, vr1_ub,
1094 overflow_undefined, overflow_wraps))
1095 set_and_canonicalize_value_range (vr, VR_RANGE,
1096 wide_int_to_tree (type, res_lb),
1097 wide_int_to_tree (type, res_ub), NULL);
1098 else
1099 set_value_range_to_varying (vr);
1102 /* Value range wrapper for wide_int_range_can_optimize_bit_op.
1104 If a bit operation on two ranges can be easily optimized in terms
1105 of a mask, store the optimized new range in VR and return TRUE. */
1107 static bool
1108 vrp_can_optimize_bit_op (value_range *vr, enum tree_code code,
1109 value_range *vr0, value_range *vr1)
1111 tree lower_bound, upper_bound, mask;
1112 if (code != BIT_AND_EXPR && code != BIT_IOR_EXPR)
1113 return false;
1114 if (range_int_cst_singleton_p (vr1))
1116 if (!range_int_cst_p (vr0))
1117 return false;
1118 mask = vr1->min;
1119 lower_bound = vr0->min;
1120 upper_bound = vr0->max;
1122 else if (range_int_cst_singleton_p (vr0))
1124 if (!range_int_cst_p (vr1))
1125 return false;
1126 mask = vr0->min;
1127 lower_bound = vr1->min;
1128 upper_bound = vr1->max;
1130 else
1131 return false;
1132 if (wide_int_range_can_optimize_bit_op (code,
1133 wi::to_wide (lower_bound),
1134 wi::to_wide (upper_bound),
1135 wi::to_wide (mask)))
1137 tree min = int_const_binop (code, lower_bound, mask);
1138 tree max = int_const_binop (code, upper_bound, mask);
1139 set_value_range (vr, VR_RANGE, min, max, NULL);
1140 return true;
1142 return false;
1145 /* If BOUND will include a symbolic bound, adjust it accordingly,
1146 otherwise leave it as is.
1148 CODE is the original operation that combined the bounds (PLUS_EXPR
1149 or MINUS_EXPR).
1151 TYPE is the type of the original operation.
1153 SYM_OPn is the symbolic for OPn if it has a symbolic.
1155 NEG_OPn is TRUE if the OPn was negated. */
1157 static void
1158 adjust_symbolic_bound (tree &bound, enum tree_code code, tree type,
1159 tree sym_op0, tree sym_op1,
1160 bool neg_op0, bool neg_op1)
1162 bool minus_p = (code == MINUS_EXPR);
1163 /* If the result bound is constant, we're done; otherwise, build the
1164 symbolic lower bound. */
1165 if (sym_op0 == sym_op1)
1167 else if (sym_op0)
1168 bound = build_symbolic_expr (type, sym_op0,
1169 neg_op0, bound);
1170 else if (sym_op1)
1172 /* We may not negate if that might introduce
1173 undefined overflow. */
1174 if (!minus_p
1175 || neg_op1
1176 || TYPE_OVERFLOW_WRAPS (type))
1177 bound = build_symbolic_expr (type, sym_op1,
1178 neg_op1 ^ minus_p, bound);
1179 else
1180 bound = NULL_TREE;
1184 /* Combine OP1 and OP1, which are two parts of a bound, into one wide
1185 int bound according to CODE. CODE is the operation combining the
1186 bound (either a PLUS_EXPR or a MINUS_EXPR).
1188 TYPE is the type of the combine operation.
1190 WI is the wide int to store the result.
1192 OVF is -1 if an underflow occurred, +1 if an overflow occurred or 0
1193 if over/underflow occurred. */
1195 static void
1196 combine_bound (enum tree_code code, wide_int &wi, wi::overflow_type &ovf,
1197 tree type, tree op0, tree op1)
1199 bool minus_p = (code == MINUS_EXPR);
1200 const signop sgn = TYPE_SIGN (type);
1201 const unsigned int prec = TYPE_PRECISION (type);
1203 /* Combine the bounds, if any. */
1204 if (op0 && op1)
1206 if (minus_p)
1207 wi = wi::sub (wi::to_wide (op0), wi::to_wide (op1), sgn, &ovf);
1208 else
1209 wi = wi::add (wi::to_wide (op0), wi::to_wide (op1), sgn, &ovf);
1211 else if (op0)
1212 wi = wi::to_wide (op0);
1213 else if (op1)
1215 if (minus_p)
1216 wi = wi::neg (wi::to_wide (op1), &ovf);
1217 else
1218 wi = wi::to_wide (op1);
1220 else
1221 wi = wi::shwi (0, prec);
1224 /* Given a range in [WMIN, WMAX], adjust it for possible overflow and
1225 put the result in VR.
1227 TYPE is the type of the range.
1229 MIN_OVF and MAX_OVF indicate what type of overflow, if any,
1230 occurred while originally calculating WMIN or WMAX. -1 indicates
1231 underflow. +1 indicates overflow. 0 indicates neither. */
1233 static void
1234 set_value_range_with_overflow (value_range &vr,
1235 tree type,
1236 const wide_int &wmin, const wide_int &wmax,
1237 wi::overflow_type min_ovf,
1238 wi::overflow_type max_ovf)
1240 const signop sgn = TYPE_SIGN (type);
1241 const unsigned int prec = TYPE_PRECISION (type);
1242 vr.type = VR_RANGE;
1243 vr.equiv = NULL;
1244 if (TYPE_OVERFLOW_WRAPS (type))
1246 /* If overflow wraps, truncate the values and adjust the
1247 range kind and bounds appropriately. */
1248 wide_int tmin = wide_int::from (wmin, prec, sgn);
1249 wide_int tmax = wide_int::from (wmax, prec, sgn);
1250 if ((min_ovf != wi::OVF_NONE) == (max_ovf != wi::OVF_NONE))
1252 /* No overflow or both overflow or underflow. The
1253 range kind stays VR_RANGE. */
1254 vr.min = wide_int_to_tree (type, tmin);
1255 vr.max = wide_int_to_tree (type, tmax);
1257 else if ((min_ovf == wi::OVF_UNDERFLOW && max_ovf == wi::OVF_NONE)
1258 || (max_ovf == wi::OVF_OVERFLOW && min_ovf == wi::OVF_NONE))
1260 /* Min underflow or max overflow. The range kind
1261 changes to VR_ANTI_RANGE. */
1262 bool covers = false;
1263 wide_int tem = tmin;
1264 vr.type = VR_ANTI_RANGE;
1265 tmin = tmax + 1;
1266 if (wi::cmp (tmin, tmax, sgn) < 0)
1267 covers = true;
1268 tmax = tem - 1;
1269 if (wi::cmp (tmax, tem, sgn) > 0)
1270 covers = true;
1271 /* If the anti-range would cover nothing, drop to varying.
1272 Likewise if the anti-range bounds are outside of the
1273 types values. */
1274 if (covers || wi::cmp (tmin, tmax, sgn) > 0)
1276 set_value_range_to_varying (&vr);
1277 return;
1279 vr.min = wide_int_to_tree (type, tmin);
1280 vr.max = wide_int_to_tree (type, tmax);
1282 else
1284 /* Other underflow and/or overflow, drop to VR_VARYING. */
1285 set_value_range_to_varying (&vr);
1286 return;
1289 else
1291 /* If overflow does not wrap, saturate to the types min/max
1292 value. */
1293 wide_int type_min = wi::min_value (prec, sgn);
1294 wide_int type_max = wi::max_value (prec, sgn);
1295 if (min_ovf == wi::OVF_UNDERFLOW)
1296 vr.min = wide_int_to_tree (type, type_min);
1297 else if (min_ovf == wi::OVF_OVERFLOW)
1298 vr.min = wide_int_to_tree (type, type_max);
1299 else
1300 vr.min = wide_int_to_tree (type, wmin);
1302 if (max_ovf == wi::OVF_UNDERFLOW)
1303 vr.max = wide_int_to_tree (type, type_min);
1304 else if (max_ovf == wi::OVF_OVERFLOW)
1305 vr.max = wide_int_to_tree (type, type_max);
1306 else
1307 vr.max = wide_int_to_tree (type, wmax);
1311 /* Extract range information from a binary operation CODE based on
1312 the ranges of each of its operands *VR0 and *VR1 with resulting
1313 type EXPR_TYPE. The resulting range is stored in *VR. */
1315 void
1316 extract_range_from_binary_expr_1 (value_range *vr,
1317 enum tree_code code, tree expr_type,
1318 value_range *vr0_, value_range *vr1_)
1320 signop sign = TYPE_SIGN (expr_type);
1321 unsigned int prec = TYPE_PRECISION (expr_type);
1322 value_range vr0 = *vr0_, vr1 = *vr1_;
1323 value_range vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
1324 enum value_range_type type;
1325 tree min = NULL_TREE, max = NULL_TREE;
1326 int cmp;
1328 if (!INTEGRAL_TYPE_P (expr_type)
1329 && !POINTER_TYPE_P (expr_type))
1331 set_value_range_to_varying (vr);
1332 return;
1335 /* Not all binary expressions can be applied to ranges in a
1336 meaningful way. Handle only arithmetic operations. */
1337 if (code != PLUS_EXPR
1338 && code != MINUS_EXPR
1339 && code != POINTER_PLUS_EXPR
1340 && code != MULT_EXPR
1341 && code != TRUNC_DIV_EXPR
1342 && code != FLOOR_DIV_EXPR
1343 && code != CEIL_DIV_EXPR
1344 && code != EXACT_DIV_EXPR
1345 && code != ROUND_DIV_EXPR
1346 && code != TRUNC_MOD_EXPR
1347 && code != RSHIFT_EXPR
1348 && code != LSHIFT_EXPR
1349 && code != MIN_EXPR
1350 && code != MAX_EXPR
1351 && code != BIT_AND_EXPR
1352 && code != BIT_IOR_EXPR
1353 && code != BIT_XOR_EXPR)
1355 set_value_range_to_varying (vr);
1356 return;
1359 /* If both ranges are UNDEFINED, so is the result. */
1360 if (vr0.type == VR_UNDEFINED && vr1.type == VR_UNDEFINED)
1362 set_value_range_to_undefined (vr);
1363 return;
1365 /* If one of the ranges is UNDEFINED drop it to VARYING for the following
1366 code. At some point we may want to special-case operations that
1367 have UNDEFINED result for all or some value-ranges of the not UNDEFINED
1368 operand. */
1369 else if (vr0.type == VR_UNDEFINED)
1370 set_value_range_to_varying (&vr0);
1371 else if (vr1.type == VR_UNDEFINED)
1372 set_value_range_to_varying (&vr1);
1374 /* We get imprecise results from ranges_from_anti_range when
1375 code is EXACT_DIV_EXPR. We could mask out bits in the resulting
1376 range, but then we also need to hack up vrp_meet. It's just
1377 easier to special case when vr0 is ~[0,0] for EXACT_DIV_EXPR. */
1378 if (code == EXACT_DIV_EXPR
1379 && vr0.type == VR_ANTI_RANGE
1380 && vr0.min == vr0.max
1381 && integer_zerop (vr0.min))
1383 set_value_range_to_nonnull (vr, expr_type);
1384 return;
1387 /* Now canonicalize anti-ranges to ranges when they are not symbolic
1388 and express ~[] op X as ([]' op X) U ([]'' op X). */
1389 if (vr0.type == VR_ANTI_RANGE
1390 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
1392 extract_range_from_binary_expr_1 (vr, code, expr_type, &vrtem0, vr1_);
1393 if (vrtem1.type != VR_UNDEFINED)
1395 value_range vrres = VR_INITIALIZER;
1396 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
1397 &vrtem1, vr1_);
1398 vrp_meet (vr, &vrres);
1400 return;
1402 /* Likewise for X op ~[]. */
1403 if (vr1.type == VR_ANTI_RANGE
1404 && ranges_from_anti_range (&vr1, &vrtem0, &vrtem1))
1406 extract_range_from_binary_expr_1 (vr, code, expr_type, vr0_, &vrtem0);
1407 if (vrtem1.type != VR_UNDEFINED)
1409 value_range vrres = VR_INITIALIZER;
1410 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
1411 vr0_, &vrtem1);
1412 vrp_meet (vr, &vrres);
1414 return;
1417 /* The type of the resulting value range defaults to VR0.TYPE. */
1418 type = vr0.type;
1420 /* Refuse to operate on VARYING ranges, ranges of different kinds
1421 and symbolic ranges. As an exception, we allow BIT_{AND,IOR}
1422 because we may be able to derive a useful range even if one of
1423 the operands is VR_VARYING or symbolic range. Similarly for
1424 divisions, MIN/MAX and PLUS/MINUS.
1426 TODO, we may be able to derive anti-ranges in some cases. */
1427 if (code != BIT_AND_EXPR
1428 && code != BIT_IOR_EXPR
1429 && code != TRUNC_DIV_EXPR
1430 && code != FLOOR_DIV_EXPR
1431 && code != CEIL_DIV_EXPR
1432 && code != EXACT_DIV_EXPR
1433 && code != ROUND_DIV_EXPR
1434 && code != TRUNC_MOD_EXPR
1435 && code != MIN_EXPR
1436 && code != MAX_EXPR
1437 && code != PLUS_EXPR
1438 && code != MINUS_EXPR
1439 && code != RSHIFT_EXPR
1440 && (vr0.type == VR_VARYING
1441 || vr1.type == VR_VARYING
1442 || vr0.type != vr1.type
1443 || symbolic_range_p (&vr0)
1444 || symbolic_range_p (&vr1)))
1446 set_value_range_to_varying (vr);
1447 return;
1450 /* Now evaluate the expression to determine the new range. */
1451 if (POINTER_TYPE_P (expr_type))
1453 if (code == MIN_EXPR || code == MAX_EXPR)
1455 /* For MIN/MAX expressions with pointers, we only care about
1456 nullness, if both are non null, then the result is nonnull.
1457 If both are null, then the result is null. Otherwise they
1458 are varying. */
1459 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
1460 set_value_range_to_nonnull (vr, expr_type);
1461 else if (range_is_null (&vr0) && range_is_null (&vr1))
1462 set_value_range_to_null (vr, expr_type);
1463 else
1464 set_value_range_to_varying (vr);
1466 else if (code == POINTER_PLUS_EXPR)
1468 /* For pointer types, we are really only interested in asserting
1469 whether the expression evaluates to non-NULL. */
1470 if (range_is_nonnull (&vr0) || range_is_nonnull (&vr1))
1471 set_value_range_to_nonnull (vr, expr_type);
1472 else if (range_is_null (&vr0) && range_is_null (&vr1))
1473 set_value_range_to_null (vr, expr_type);
1474 else
1475 set_value_range_to_varying (vr);
1477 else if (code == BIT_AND_EXPR)
1479 /* For pointer types, we are really only interested in asserting
1480 whether the expression evaluates to non-NULL. */
1481 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
1482 set_value_range_to_nonnull (vr, expr_type);
1483 else if (range_is_null (&vr0) || range_is_null (&vr1))
1484 set_value_range_to_null (vr, expr_type);
1485 else
1486 set_value_range_to_varying (vr);
1488 else
1489 set_value_range_to_varying (vr);
1491 return;
1494 /* For integer ranges, apply the operation to each end of the
1495 range and see what we end up with. */
1496 if (code == PLUS_EXPR || code == MINUS_EXPR)
1498 const bool minus_p = (code == MINUS_EXPR);
1499 tree min_op0 = vr0.min;
1500 tree min_op1 = minus_p ? vr1.max : vr1.min;
1501 tree max_op0 = vr0.max;
1502 tree max_op1 = minus_p ? vr1.min : vr1.max;
1503 tree sym_min_op0 = NULL_TREE;
1504 tree sym_min_op1 = NULL_TREE;
1505 tree sym_max_op0 = NULL_TREE;
1506 tree sym_max_op1 = NULL_TREE;
1507 bool neg_min_op0, neg_min_op1, neg_max_op0, neg_max_op1;
1509 neg_min_op0 = neg_min_op1 = neg_max_op0 = neg_max_op1 = false;
1511 /* If we have a PLUS or MINUS with two VR_RANGEs, either constant or
1512 single-symbolic ranges, try to compute the precise resulting range,
1513 but only if we know that this resulting range will also be constant
1514 or single-symbolic. */
1515 if (vr0.type == VR_RANGE && vr1.type == VR_RANGE
1516 && (TREE_CODE (min_op0) == INTEGER_CST
1517 || (sym_min_op0
1518 = get_single_symbol (min_op0, &neg_min_op0, &min_op0)))
1519 && (TREE_CODE (min_op1) == INTEGER_CST
1520 || (sym_min_op1
1521 = get_single_symbol (min_op1, &neg_min_op1, &min_op1)))
1522 && (!(sym_min_op0 && sym_min_op1)
1523 || (sym_min_op0 == sym_min_op1
1524 && neg_min_op0 == (minus_p ? neg_min_op1 : !neg_min_op1)))
1525 && (TREE_CODE (max_op0) == INTEGER_CST
1526 || (sym_max_op0
1527 = get_single_symbol (max_op0, &neg_max_op0, &max_op0)))
1528 && (TREE_CODE (max_op1) == INTEGER_CST
1529 || (sym_max_op1
1530 = get_single_symbol (max_op1, &neg_max_op1, &max_op1)))
1531 && (!(sym_max_op0 && sym_max_op1)
1532 || (sym_max_op0 == sym_max_op1
1533 && neg_max_op0 == (minus_p ? neg_max_op1 : !neg_max_op1))))
1535 wide_int wmin, wmax;
1536 wi::overflow_type min_ovf = wi::OVF_NONE;
1537 wi::overflow_type max_ovf = wi::OVF_NONE;
1539 /* Build the bounds. */
1540 combine_bound (code, wmin, min_ovf, expr_type, min_op0, min_op1);
1541 combine_bound (code, wmax, max_ovf, expr_type, max_op0, max_op1);
1543 /* If we have overflow for the constant part and the resulting
1544 range will be symbolic, drop to VR_VARYING. */
1545 if (((bool)min_ovf && sym_min_op0 != sym_min_op1)
1546 || ((bool)max_ovf && sym_max_op0 != sym_max_op1))
1548 set_value_range_to_varying (vr);
1549 return;
1552 /* Adjust the range for possible overflow. */
1553 set_value_range_with_overflow (*vr, expr_type,
1554 wmin, wmax, min_ovf, max_ovf);
1555 if (vr->type == VR_VARYING)
1556 return;
1558 /* Build the symbolic bounds if needed. */
1559 adjust_symbolic_bound (vr->min, code, expr_type,
1560 sym_min_op0, sym_min_op1,
1561 neg_min_op0, neg_min_op1);
1562 adjust_symbolic_bound (vr->max, code, expr_type,
1563 sym_max_op0, sym_max_op1,
1564 neg_max_op0, neg_max_op1);
1565 /* ?? It would probably be cleaner to eliminate min/max/type
1566 entirely and hold these values in VR directly. */
1567 min = vr->min;
1568 max = vr->max;
1569 type = vr->type;
1571 else
1573 /* For other cases, for example if we have a PLUS_EXPR with two
1574 VR_ANTI_RANGEs, drop to VR_VARYING. It would take more effort
1575 to compute a precise range for such a case.
1576 ??? General even mixed range kind operations can be expressed
1577 by for example transforming ~[3, 5] + [1, 2] to range-only
1578 operations and a union primitive:
1579 [-INF, 2] + [1, 2] U [5, +INF] + [1, 2]
1580 [-INF+1, 4] U [6, +INF(OVF)]
1581 though usually the union is not exactly representable with
1582 a single range or anti-range as the above is
1583 [-INF+1, +INF(OVF)] intersected with ~[5, 5]
1584 but one could use a scheme similar to equivalences for this. */
1585 set_value_range_to_varying (vr);
1586 return;
1589 else if (code == MIN_EXPR
1590 || code == MAX_EXPR)
1592 if (vr0.type == VR_RANGE
1593 && !symbolic_range_p (&vr0))
1595 type = VR_RANGE;
1596 if (vr1.type == VR_RANGE
1597 && !symbolic_range_p (&vr1))
1599 /* For operations that make the resulting range directly
1600 proportional to the original ranges, apply the operation to
1601 the same end of each range. */
1602 min = int_const_binop (code, vr0.min, vr1.min);
1603 max = int_const_binop (code, vr0.max, vr1.max);
1605 else if (code == MIN_EXPR)
1607 min = vrp_val_min (expr_type);
1608 max = vr0.max;
1610 else if (code == MAX_EXPR)
1612 min = vr0.min;
1613 max = vrp_val_max (expr_type);
1616 else if (vr1.type == VR_RANGE
1617 && !symbolic_range_p (&vr1))
1619 type = VR_RANGE;
1620 if (code == MIN_EXPR)
1622 min = vrp_val_min (expr_type);
1623 max = vr1.max;
1625 else if (code == MAX_EXPR)
1627 min = vr1.min;
1628 max = vrp_val_max (expr_type);
1631 else
1633 set_value_range_to_varying (vr);
1634 return;
1637 else if (code == MULT_EXPR)
1639 if (!range_int_cst_p (&vr0)
1640 || !range_int_cst_p (&vr1))
1642 set_value_range_to_varying (vr);
1643 return;
1645 extract_range_from_multiplicative_op (vr, code, &vr0, &vr1);
1646 return;
1648 else if (code == RSHIFT_EXPR
1649 || code == LSHIFT_EXPR)
1651 if (range_int_cst_p (&vr1)
1652 && !vrp_shift_undefined_p (vr1, prec))
1654 if (code == RSHIFT_EXPR)
1656 /* Even if vr0 is VARYING or otherwise not usable, we can derive
1657 useful ranges just from the shift count. E.g.
1658 x >> 63 for signed 64-bit x is always [-1, 0]. */
1659 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
1661 vr0.type = type = VR_RANGE;
1662 vr0.min = vrp_val_min (expr_type);
1663 vr0.max = vrp_val_max (expr_type);
1665 extract_range_from_multiplicative_op (vr, code, &vr0, &vr1);
1666 return;
1668 else if (code == LSHIFT_EXPR
1669 && range_int_cst_p (&vr0))
1671 wide_int res_lb, res_ub;
1672 if (wide_int_range_lshift (res_lb, res_ub, sign, prec,
1673 wi::to_wide (vr0.min),
1674 wi::to_wide (vr0.max),
1675 wi::to_wide (vr1.min),
1676 wi::to_wide (vr1.max),
1677 TYPE_OVERFLOW_UNDEFINED (expr_type),
1678 TYPE_OVERFLOW_WRAPS (expr_type)))
1680 min = wide_int_to_tree (expr_type, res_lb);
1681 max = wide_int_to_tree (expr_type, res_ub);
1682 set_and_canonicalize_value_range (vr, VR_RANGE,
1683 min, max, NULL);
1684 return;
1688 set_value_range_to_varying (vr);
1689 return;
1691 else if (code == TRUNC_DIV_EXPR
1692 || code == FLOOR_DIV_EXPR
1693 || code == CEIL_DIV_EXPR
1694 || code == EXACT_DIV_EXPR
1695 || code == ROUND_DIV_EXPR)
1697 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
1699 /* For division, if op1 has VR_RANGE but op0 does not, something
1700 can be deduced just from that range. Say [min, max] / [4, max]
1701 gives [min / 4, max / 4] range. */
1702 if (vr1.type == VR_RANGE
1703 && !symbolic_range_p (&vr1)
1704 && range_includes_zero_p (vr1.min, vr1.max) == 0)
1706 vr0.type = type = VR_RANGE;
1707 vr0.min = vrp_val_min (expr_type);
1708 vr0.max = vrp_val_max (expr_type);
1710 else
1712 set_value_range_to_varying (vr);
1713 return;
1717 /* For divisions, if flag_non_call_exceptions is true, we must
1718 not eliminate a division by zero. */
1719 if (cfun->can_throw_non_call_exceptions
1720 && (vr1.type != VR_RANGE
1721 || range_includes_zero_p (vr1.min, vr1.max) != 0))
1723 set_value_range_to_varying (vr);
1724 return;
1727 /* For divisions, if op0 is VR_RANGE, we can deduce a range
1728 even if op1 is VR_VARYING, VR_ANTI_RANGE, symbolic or can
1729 include 0. */
1730 if (vr0.type == VR_RANGE
1731 && (vr1.type != VR_RANGE
1732 || range_includes_zero_p (vr1.min, vr1.max) != 0))
1734 tree zero = build_int_cst (TREE_TYPE (vr0.min), 0);
1735 int cmp;
1737 min = NULL_TREE;
1738 max = NULL_TREE;
1739 if (TYPE_UNSIGNED (expr_type)
1740 || value_range_nonnegative_p (&vr1))
1742 /* For unsigned division or when divisor is known
1743 to be non-negative, the range has to cover
1744 all numbers from 0 to max for positive max
1745 and all numbers from min to 0 for negative min. */
1746 cmp = compare_values (vr0.max, zero);
1747 if (cmp == -1)
1749 /* When vr0.max < 0, vr1.min != 0 and value
1750 ranges for dividend and divisor are available. */
1751 if (vr1.type == VR_RANGE
1752 && !symbolic_range_p (&vr0)
1753 && !symbolic_range_p (&vr1)
1754 && compare_values (vr1.min, zero) != 0)
1755 max = int_const_binop (code, vr0.max, vr1.min);
1756 else
1757 max = zero;
1759 else if (cmp == 0 || cmp == 1)
1760 max = vr0.max;
1761 else
1762 type = VR_VARYING;
1763 cmp = compare_values (vr0.min, zero);
1764 if (cmp == 1)
1766 /* For unsigned division when value ranges for dividend
1767 and divisor are available. */
1768 if (vr1.type == VR_RANGE
1769 && !symbolic_range_p (&vr0)
1770 && !symbolic_range_p (&vr1)
1771 && compare_values (vr1.max, zero) != 0)
1772 min = int_const_binop (code, vr0.min, vr1.max);
1773 else
1774 min = zero;
1776 else if (cmp == 0 || cmp == -1)
1777 min = vr0.min;
1778 else
1779 type = VR_VARYING;
1781 else
1783 /* Otherwise the range is -max .. max or min .. -min
1784 depending on which bound is bigger in absolute value,
1785 as the division can change the sign. */
1786 abs_extent_range (vr, vr0.min, vr0.max);
1787 return;
1789 if (type == VR_VARYING)
1791 set_value_range_to_varying (vr);
1792 return;
1795 else if (range_int_cst_p (&vr0) && range_int_cst_p (&vr1))
1797 extract_range_from_multiplicative_op (vr, code, &vr0, &vr1);
1798 return;
1801 else if (code == TRUNC_MOD_EXPR)
1803 if (range_is_null (&vr1))
1805 set_value_range_to_undefined (vr);
1806 return;
1808 wide_int wmin, wmax, tmp;
1809 wide_int vr0_min, vr0_max, vr1_min, vr1_max;
1810 extract_range_into_wide_ints (&vr0, sign, prec, &vr0_min, &vr0_max);
1811 extract_range_into_wide_ints (&vr1, sign, prec, &vr1_min, &vr1_max);
1812 wide_int_range_trunc_mod (wmin, wmax, sign, prec,
1813 vr0_min, vr0_max, vr1_min, vr1_max);
1814 min = wide_int_to_tree (expr_type, wmin);
1815 max = wide_int_to_tree (expr_type, wmax);
1816 set_value_range (vr, VR_RANGE, min, max, NULL);
1817 return;
1819 else if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR || code == BIT_XOR_EXPR)
1821 if (vrp_can_optimize_bit_op (vr, code, &vr0, &vr1))
1822 return;
1824 wide_int may_be_nonzero0, may_be_nonzero1;
1825 wide_int must_be_nonzero0, must_be_nonzero1;
1826 wide_int wmin, wmax;
1827 wide_int vr0_min, vr0_max, vr1_min, vr1_max;
1828 vrp_set_zero_nonzero_bits (expr_type, &vr0,
1829 &may_be_nonzero0, &must_be_nonzero0);
1830 vrp_set_zero_nonzero_bits (expr_type, &vr1,
1831 &may_be_nonzero1, &must_be_nonzero1);
1832 extract_range_into_wide_ints (&vr0, sign, prec, &vr0_min, &vr0_max);
1833 extract_range_into_wide_ints (&vr1, sign, prec, &vr1_min, &vr1_max);
1834 if (code == BIT_AND_EXPR)
1836 if (wide_int_range_bit_and (wmin, wmax, sign, prec,
1837 vr0_min, vr0_max,
1838 vr1_min, vr1_max,
1839 must_be_nonzero0,
1840 may_be_nonzero0,
1841 must_be_nonzero1,
1842 may_be_nonzero1))
1844 min = wide_int_to_tree (expr_type, wmin);
1845 max = wide_int_to_tree (expr_type, wmax);
1846 set_value_range (vr, VR_RANGE, min, max, NULL);
1848 else
1849 set_value_range_to_varying (vr);
1850 return;
1852 else if (code == BIT_IOR_EXPR)
1854 if (wide_int_range_bit_ior (wmin, wmax, sign,
1855 vr0_min, vr0_max,
1856 vr1_min, vr1_max,
1857 must_be_nonzero0,
1858 may_be_nonzero0,
1859 must_be_nonzero1,
1860 may_be_nonzero1))
1862 min = wide_int_to_tree (expr_type, wmin);
1863 max = wide_int_to_tree (expr_type, wmax);
1864 set_value_range (vr, VR_RANGE, min, max, NULL);
1866 else
1867 set_value_range_to_varying (vr);
1868 return;
1870 else if (code == BIT_XOR_EXPR)
1872 if (wide_int_range_bit_xor (wmin, wmax, sign, prec,
1873 must_be_nonzero0,
1874 may_be_nonzero0,
1875 must_be_nonzero1,
1876 may_be_nonzero1))
1878 min = wide_int_to_tree (expr_type, wmin);
1879 max = wide_int_to_tree (expr_type, wmax);
1880 set_value_range (vr, VR_RANGE, min, max, NULL);
1882 else
1883 set_value_range_to_varying (vr);
1884 return;
1887 else
1888 gcc_unreachable ();
1890 /* If either MIN or MAX overflowed, then set the resulting range to
1891 VARYING. */
1892 if (min == NULL_TREE
1893 || TREE_OVERFLOW_P (min)
1894 || max == NULL_TREE
1895 || TREE_OVERFLOW_P (max))
1897 set_value_range_to_varying (vr);
1898 return;
1901 /* We punt for [-INF, +INF].
1902 We learn nothing when we have INF on both sides.
1903 Note that we do accept [-INF, -INF] and [+INF, +INF]. */
1904 if (vrp_val_is_min (min) && vrp_val_is_max (max))
1906 set_value_range_to_varying (vr);
1907 return;
1910 cmp = compare_values (min, max);
1911 if (cmp == -2 || cmp == 1)
1913 /* If the new range has its limits swapped around (MIN > MAX),
1914 then the operation caused one of them to wrap around, mark
1915 the new range VARYING. */
1916 set_value_range_to_varying (vr);
1918 else
1919 set_value_range (vr, type, min, max, NULL);
1922 /* Calculates the absolute value of a range and puts the result in VR.
1923 VR0 is the input range. TYPE is the type of the resulting
1924 range. */
1926 static void
1927 extract_range_from_abs_expr (value_range &vr, tree type, value_range &vr0)
1929 /* Pass through vr0 in the easy cases. */
1930 if (TYPE_UNSIGNED (type)
1931 || value_range_nonnegative_p (&vr0))
1933 copy_value_range (&vr, &vr0);
1934 return;
1937 /* For the remaining varying or symbolic ranges we can't do anything
1938 useful. */
1939 if (vr0.type == VR_VARYING
1940 || symbolic_range_p (&vr0))
1942 set_value_range_to_varying (&vr);
1943 return;
1946 /* -TYPE_MIN_VALUE = TYPE_MIN_VALUE with flag_wrapv so we can't get a
1947 useful range. */
1948 if (!TYPE_OVERFLOW_UNDEFINED (type)
1949 && ((vr0.type == VR_RANGE
1950 && vrp_val_is_min (vr0.min))
1951 || (vr0.type == VR_ANTI_RANGE
1952 && !vrp_val_is_min (vr0.min))))
1954 set_value_range_to_varying (&vr);
1955 return;
1958 /* ABS_EXPR may flip the range around, if the original range
1959 included negative values. */
1960 tree min, max;
1961 if (!vrp_val_is_min (vr0.min))
1962 min = fold_unary_to_constant (ABS_EXPR, type, vr0.min);
1963 else
1964 min = TYPE_MAX_VALUE (type);
1966 if (!vrp_val_is_min (vr0.max))
1967 max = fold_unary_to_constant (ABS_EXPR, type, vr0.max);
1968 else
1969 max = TYPE_MAX_VALUE (type);
1971 int cmp = compare_values (min, max);
1972 gcc_assert (vr0.type != VR_ANTI_RANGE);
1974 /* If the range contains zero then we know that the minimum value in the
1975 range will be zero. */
1976 if (range_includes_zero_p (vr0.min, vr0.max) == 1)
1978 if (cmp == 1)
1979 max = min;
1980 min = build_int_cst (type, 0);
1982 else
1984 /* If the range was reversed, swap MIN and MAX. */
1985 if (cmp == 1)
1986 std::swap (min, max);
1989 cmp = compare_values (min, max);
1990 if (cmp == -2 || cmp == 1)
1992 /* If the new range has its limits swapped around (MIN > MAX),
1993 then the operation caused one of them to wrap around, mark
1994 the new range VARYING. */
1995 set_value_range_to_varying (&vr);
1997 else
1998 set_value_range (&vr, vr0.type, min, max, NULL);
2001 /* Extract range information from a unary operation CODE based on
2002 the range of its operand *VR0 with type OP0_TYPE with resulting type TYPE.
2003 The resulting range is stored in *VR. */
2005 void
2006 extract_range_from_unary_expr (value_range *vr,
2007 enum tree_code code, tree type,
2008 value_range *vr0_, tree op0_type)
2010 value_range vr0 = *vr0_, vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
2012 /* VRP only operates on integral and pointer types. */
2013 if (!(INTEGRAL_TYPE_P (op0_type)
2014 || POINTER_TYPE_P (op0_type))
2015 || !(INTEGRAL_TYPE_P (type)
2016 || POINTER_TYPE_P (type)))
2018 set_value_range_to_varying (vr);
2019 return;
2022 /* If VR0 is UNDEFINED, so is the result. */
2023 if (vr0.type == VR_UNDEFINED)
2025 set_value_range_to_undefined (vr);
2026 return;
2029 /* Handle operations that we express in terms of others. */
2030 if (code == PAREN_EXPR || code == OBJ_TYPE_REF)
2032 /* PAREN_EXPR and OBJ_TYPE_REF are simple copies. */
2033 copy_value_range (vr, &vr0);
2034 return;
2036 else if (code == NEGATE_EXPR)
2038 /* -X is simply 0 - X, so re-use existing code that also handles
2039 anti-ranges fine. */
2040 value_range zero = VR_INITIALIZER;
2041 set_value_range_to_value (&zero, build_int_cst (type, 0), NULL);
2042 extract_range_from_binary_expr_1 (vr, MINUS_EXPR, type, &zero, &vr0);
2043 return;
2045 else if (code == BIT_NOT_EXPR)
2047 /* ~X is simply -1 - X, so re-use existing code that also handles
2048 anti-ranges fine. */
2049 value_range minusone = VR_INITIALIZER;
2050 set_value_range_to_value (&minusone, build_int_cst (type, -1), NULL);
2051 extract_range_from_binary_expr_1 (vr, MINUS_EXPR,
2052 type, &minusone, &vr0);
2053 return;
2056 /* Now canonicalize anti-ranges to ranges when they are not symbolic
2057 and express op ~[] as (op []') U (op []''). */
2058 if (vr0.type == VR_ANTI_RANGE
2059 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
2061 extract_range_from_unary_expr (vr, code, type, &vrtem0, op0_type);
2062 if (vrtem1.type != VR_UNDEFINED)
2064 value_range vrres = VR_INITIALIZER;
2065 extract_range_from_unary_expr (&vrres, code, type,
2066 &vrtem1, op0_type);
2067 vrp_meet (vr, &vrres);
2069 return;
2072 if (CONVERT_EXPR_CODE_P (code))
2074 tree inner_type = op0_type;
2075 tree outer_type = type;
2077 /* If the expression evaluates to a pointer, we are only interested in
2078 determining if it evaluates to NULL [0, 0] or non-NULL (~[0, 0]). */
2079 if (POINTER_TYPE_P (type))
2081 if (range_is_nonnull (&vr0))
2082 set_value_range_to_nonnull (vr, type);
2083 else if (range_is_null (&vr0))
2084 set_value_range_to_null (vr, type);
2085 else
2086 set_value_range_to_varying (vr);
2087 return;
2090 /* If VR0 is varying and we increase the type precision, assume
2091 a full range for the following transformation. */
2092 if (vr0.type == VR_VARYING
2093 && INTEGRAL_TYPE_P (inner_type)
2094 && TYPE_PRECISION (inner_type) < TYPE_PRECISION (outer_type))
2096 vr0.type = VR_RANGE;
2097 vr0.min = TYPE_MIN_VALUE (inner_type);
2098 vr0.max = TYPE_MAX_VALUE (inner_type);
2101 /* If VR0 is a constant range or anti-range and the conversion is
2102 not truncating we can convert the min and max values and
2103 canonicalize the resulting range. Otherwise we can do the
2104 conversion if the size of the range is less than what the
2105 precision of the target type can represent and the range is
2106 not an anti-range. */
2107 if ((vr0.type == VR_RANGE
2108 || vr0.type == VR_ANTI_RANGE)
2109 && TREE_CODE (vr0.min) == INTEGER_CST
2110 && TREE_CODE (vr0.max) == INTEGER_CST
2111 && (TYPE_PRECISION (outer_type) >= TYPE_PRECISION (inner_type)
2112 || (vr0.type == VR_RANGE
2113 && integer_zerop (int_const_binop (RSHIFT_EXPR,
2114 int_const_binop (MINUS_EXPR, vr0.max, vr0.min),
2115 size_int (TYPE_PRECISION (outer_type)))))))
2117 tree new_min, new_max;
2118 new_min = force_fit_type (outer_type, wi::to_widest (vr0.min),
2119 0, false);
2120 new_max = force_fit_type (outer_type, wi::to_widest (vr0.max),
2121 0, false);
2122 set_and_canonicalize_value_range (vr, vr0.type,
2123 new_min, new_max, NULL);
2124 return;
2127 set_value_range_to_varying (vr);
2128 return;
2130 else if (code == ABS_EXPR)
2131 return extract_range_from_abs_expr (*vr, type, vr0);
2133 /* For unhandled operations fall back to varying. */
2134 set_value_range_to_varying (vr);
2135 return;
2138 /* Debugging dumps. */
2140 void dump_value_range (FILE *, const value_range *);
2141 void debug_value_range (value_range *);
2142 void dump_all_value_ranges (FILE *);
2143 void dump_vr_equiv (FILE *, bitmap);
2144 void debug_vr_equiv (bitmap);
2147 /* Dump value range VR to FILE. */
2149 void
2150 dump_value_range (FILE *file, const value_range *vr)
2152 if (vr == NULL)
2153 fprintf (file, "[]");
2154 else if (vr->type == VR_UNDEFINED)
2155 fprintf (file, "UNDEFINED");
2156 else if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
2158 tree type = TREE_TYPE (vr->min);
2160 fprintf (file, "%s[", (vr->type == VR_ANTI_RANGE) ? "~" : "");
2162 if (INTEGRAL_TYPE_P (type)
2163 && !TYPE_UNSIGNED (type)
2164 && vrp_val_is_min (vr->min))
2165 fprintf (file, "-INF");
2166 else
2167 print_generic_expr (file, vr->min);
2169 fprintf (file, ", ");
2171 if (INTEGRAL_TYPE_P (type)
2172 && vrp_val_is_max (vr->max))
2173 fprintf (file, "+INF");
2174 else
2175 print_generic_expr (file, vr->max);
2177 fprintf (file, "]");
2179 if (vr->equiv)
2181 bitmap_iterator bi;
2182 unsigned i, c = 0;
2184 fprintf (file, " EQUIVALENCES: { ");
2186 EXECUTE_IF_SET_IN_BITMAP (vr->equiv, 0, i, bi)
2188 print_generic_expr (file, ssa_name (i));
2189 fprintf (file, " ");
2190 c++;
2193 fprintf (file, "} (%u elements)", c);
2196 else if (vr->type == VR_VARYING)
2197 fprintf (file, "VARYING");
2198 else
2199 fprintf (file, "INVALID RANGE");
2203 /* Dump value range VR to stderr. */
2205 DEBUG_FUNCTION void
2206 debug_value_range (value_range *vr)
2208 dump_value_range (stderr, vr);
2209 fprintf (stderr, "\n");
2212 void
2213 value_range::dump ()
2215 debug_value_range (this);
2219 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
2220 create a new SSA name N and return the assertion assignment
2221 'N = ASSERT_EXPR <V, V OP W>'. */
2223 static gimple *
2224 build_assert_expr_for (tree cond, tree v)
2226 tree a;
2227 gassign *assertion;
2229 gcc_assert (TREE_CODE (v) == SSA_NAME
2230 && COMPARISON_CLASS_P (cond));
2232 a = build2 (ASSERT_EXPR, TREE_TYPE (v), v, cond);
2233 assertion = gimple_build_assign (NULL_TREE, a);
2235 /* The new ASSERT_EXPR, creates a new SSA name that replaces the
2236 operand of the ASSERT_EXPR. Create it so the new name and the old one
2237 are registered in the replacement table so that we can fix the SSA web
2238 after adding all the ASSERT_EXPRs. */
2239 tree new_def = create_new_def_for (v, assertion, NULL);
2240 /* Make sure we preserve abnormalness throughout an ASSERT_EXPR chain
2241 given we have to be able to fully propagate those out to re-create
2242 valid SSA when removing the asserts. */
2243 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (v))
2244 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_def) = 1;
2246 return assertion;
2250 /* Return false if EXPR is a predicate expression involving floating
2251 point values. */
2253 static inline bool
2254 fp_predicate (gimple *stmt)
2256 GIMPLE_CHECK (stmt, GIMPLE_COND);
2258 return FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)));
2261 /* If the range of values taken by OP can be inferred after STMT executes,
2262 return the comparison code (COMP_CODE_P) and value (VAL_P) that
2263 describes the inferred range. Return true if a range could be
2264 inferred. */
2266 bool
2267 infer_value_range (gimple *stmt, tree op, tree_code *comp_code_p, tree *val_p)
2269 *val_p = NULL_TREE;
2270 *comp_code_p = ERROR_MARK;
2272 /* Do not attempt to infer anything in names that flow through
2273 abnormal edges. */
2274 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
2275 return false;
2277 /* If STMT is the last statement of a basic block with no normal
2278 successors, there is no point inferring anything about any of its
2279 operands. We would not be able to find a proper insertion point
2280 for the assertion, anyway. */
2281 if (stmt_ends_bb_p (stmt))
2283 edge_iterator ei;
2284 edge e;
2286 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
2287 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
2288 break;
2289 if (e == NULL)
2290 return false;
2293 if (infer_nonnull_range (stmt, op))
2295 *val_p = build_int_cst (TREE_TYPE (op), 0);
2296 *comp_code_p = NE_EXPR;
2297 return true;
2300 return false;
2304 void dump_asserts_for (FILE *, tree);
2305 void debug_asserts_for (tree);
2306 void dump_all_asserts (FILE *);
2307 void debug_all_asserts (void);
2309 /* Dump all the registered assertions for NAME to FILE. */
2311 void
2312 dump_asserts_for (FILE *file, tree name)
2314 assert_locus *loc;
2316 fprintf (file, "Assertions to be inserted for ");
2317 print_generic_expr (file, name);
2318 fprintf (file, "\n");
2320 loc = asserts_for[SSA_NAME_VERSION (name)];
2321 while (loc)
2323 fprintf (file, "\t");
2324 print_gimple_stmt (file, gsi_stmt (loc->si), 0);
2325 fprintf (file, "\n\tBB #%d", loc->bb->index);
2326 if (loc->e)
2328 fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
2329 loc->e->dest->index);
2330 dump_edge_info (file, loc->e, dump_flags, 0);
2332 fprintf (file, "\n\tPREDICATE: ");
2333 print_generic_expr (file, loc->expr);
2334 fprintf (file, " %s ", get_tree_code_name (loc->comp_code));
2335 print_generic_expr (file, loc->val);
2336 fprintf (file, "\n\n");
2337 loc = loc->next;
2340 fprintf (file, "\n");
2344 /* Dump all the registered assertions for NAME to stderr. */
2346 DEBUG_FUNCTION void
2347 debug_asserts_for (tree name)
2349 dump_asserts_for (stderr, name);
2353 /* Dump all the registered assertions for all the names to FILE. */
2355 void
2356 dump_all_asserts (FILE *file)
2358 unsigned i;
2359 bitmap_iterator bi;
2361 fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
2362 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
2363 dump_asserts_for (file, ssa_name (i));
2364 fprintf (file, "\n");
2368 /* Dump all the registered assertions for all the names to stderr. */
2370 DEBUG_FUNCTION void
2371 debug_all_asserts (void)
2373 dump_all_asserts (stderr);
2376 /* Push the assert info for NAME, EXPR, COMP_CODE and VAL to ASSERTS. */
2378 static void
2379 add_assert_info (vec<assert_info> &asserts,
2380 tree name, tree expr, enum tree_code comp_code, tree val)
2382 assert_info info;
2383 info.comp_code = comp_code;
2384 info.name = name;
2385 if (TREE_OVERFLOW_P (val))
2386 val = drop_tree_overflow (val);
2387 info.val = val;
2388 info.expr = expr;
2389 asserts.safe_push (info);
2392 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
2393 'EXPR COMP_CODE VAL' at a location that dominates block BB or
2394 E->DEST, then register this location as a possible insertion point
2395 for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
2397 BB, E and SI provide the exact insertion point for the new
2398 ASSERT_EXPR. If BB is NULL, then the ASSERT_EXPR is to be inserted
2399 on edge E. Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
2400 BB. If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
2401 must not be NULL. */
2403 static void
2404 register_new_assert_for (tree name, tree expr,
2405 enum tree_code comp_code,
2406 tree val,
2407 basic_block bb,
2408 edge e,
2409 gimple_stmt_iterator si)
2411 assert_locus *n, *loc, *last_loc;
2412 basic_block dest_bb;
2414 gcc_checking_assert (bb == NULL || e == NULL);
2416 if (e == NULL)
2417 gcc_checking_assert (gimple_code (gsi_stmt (si)) != GIMPLE_COND
2418 && gimple_code (gsi_stmt (si)) != GIMPLE_SWITCH);
2420 /* Never build an assert comparing against an integer constant with
2421 TREE_OVERFLOW set. This confuses our undefined overflow warning
2422 machinery. */
2423 if (TREE_OVERFLOW_P (val))
2424 val = drop_tree_overflow (val);
2426 /* The new assertion A will be inserted at BB or E. We need to
2427 determine if the new location is dominated by a previously
2428 registered location for A. If we are doing an edge insertion,
2429 assume that A will be inserted at E->DEST. Note that this is not
2430 necessarily true.
2432 If E is a critical edge, it will be split. But even if E is
2433 split, the new block will dominate the same set of blocks that
2434 E->DEST dominates.
2436 The reverse, however, is not true, blocks dominated by E->DEST
2437 will not be dominated by the new block created to split E. So,
2438 if the insertion location is on a critical edge, we will not use
2439 the new location to move another assertion previously registered
2440 at a block dominated by E->DEST. */
2441 dest_bb = (bb) ? bb : e->dest;
2443 /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
2444 VAL at a block dominating DEST_BB, then we don't need to insert a new
2445 one. Similarly, if the same assertion already exists at a block
2446 dominated by DEST_BB and the new location is not on a critical
2447 edge, then update the existing location for the assertion (i.e.,
2448 move the assertion up in the dominance tree).
2450 Note, this is implemented as a simple linked list because there
2451 should not be more than a handful of assertions registered per
2452 name. If this becomes a performance problem, a table hashed by
2453 COMP_CODE and VAL could be implemented. */
2454 loc = asserts_for[SSA_NAME_VERSION (name)];
2455 last_loc = loc;
2456 while (loc)
2458 if (loc->comp_code == comp_code
2459 && (loc->val == val
2460 || operand_equal_p (loc->val, val, 0))
2461 && (loc->expr == expr
2462 || operand_equal_p (loc->expr, expr, 0)))
2464 /* If E is not a critical edge and DEST_BB
2465 dominates the existing location for the assertion, move
2466 the assertion up in the dominance tree by updating its
2467 location information. */
2468 if ((e == NULL || !EDGE_CRITICAL_P (e))
2469 && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
2471 loc->bb = dest_bb;
2472 loc->e = e;
2473 loc->si = si;
2474 return;
2478 /* Update the last node of the list and move to the next one. */
2479 last_loc = loc;
2480 loc = loc->next;
2483 /* If we didn't find an assertion already registered for
2484 NAME COMP_CODE VAL, add a new one at the end of the list of
2485 assertions associated with NAME. */
2486 n = XNEW (struct assert_locus);
2487 n->bb = dest_bb;
2488 n->e = e;
2489 n->si = si;
2490 n->comp_code = comp_code;
2491 n->val = val;
2492 n->expr = expr;
2493 n->next = NULL;
2495 if (last_loc)
2496 last_loc->next = n;
2497 else
2498 asserts_for[SSA_NAME_VERSION (name)] = n;
2500 bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
2503 /* (COND_OP0 COND_CODE COND_OP1) is a predicate which uses NAME.
2504 Extract a suitable test code and value and store them into *CODE_P and
2505 *VAL_P so the predicate is normalized to NAME *CODE_P *VAL_P.
2507 If no extraction was possible, return FALSE, otherwise return TRUE.
2509 If INVERT is true, then we invert the result stored into *CODE_P. */
2511 static bool
2512 extract_code_and_val_from_cond_with_ops (tree name, enum tree_code cond_code,
2513 tree cond_op0, tree cond_op1,
2514 bool invert, enum tree_code *code_p,
2515 tree *val_p)
2517 enum tree_code comp_code;
2518 tree val;
2520 /* Otherwise, we have a comparison of the form NAME COMP VAL
2521 or VAL COMP NAME. */
2522 if (name == cond_op1)
2524 /* If the predicate is of the form VAL COMP NAME, flip
2525 COMP around because we need to register NAME as the
2526 first operand in the predicate. */
2527 comp_code = swap_tree_comparison (cond_code);
2528 val = cond_op0;
2530 else if (name == cond_op0)
2532 /* The comparison is of the form NAME COMP VAL, so the
2533 comparison code remains unchanged. */
2534 comp_code = cond_code;
2535 val = cond_op1;
2537 else
2538 gcc_unreachable ();
2540 /* Invert the comparison code as necessary. */
2541 if (invert)
2542 comp_code = invert_tree_comparison (comp_code, 0);
2544 /* VRP only handles integral and pointer types. */
2545 if (! INTEGRAL_TYPE_P (TREE_TYPE (val))
2546 && ! POINTER_TYPE_P (TREE_TYPE (val)))
2547 return false;
2549 /* Do not register always-false predicates.
2550 FIXME: this works around a limitation in fold() when dealing with
2551 enumerations. Given 'enum { N1, N2 } x;', fold will not
2552 fold 'if (x > N2)' to 'if (0)'. */
2553 if ((comp_code == GT_EXPR || comp_code == LT_EXPR)
2554 && INTEGRAL_TYPE_P (TREE_TYPE (val)))
2556 tree min = TYPE_MIN_VALUE (TREE_TYPE (val));
2557 tree max = TYPE_MAX_VALUE (TREE_TYPE (val));
2559 if (comp_code == GT_EXPR
2560 && (!max
2561 || compare_values (val, max) == 0))
2562 return false;
2564 if (comp_code == LT_EXPR
2565 && (!min
2566 || compare_values (val, min) == 0))
2567 return false;
2569 *code_p = comp_code;
2570 *val_p = val;
2571 return true;
2574 /* Find out smallest RES where RES > VAL && (RES & MASK) == RES, if any
2575 (otherwise return VAL). VAL and MASK must be zero-extended for
2576 precision PREC. If SGNBIT is non-zero, first xor VAL with SGNBIT
2577 (to transform signed values into unsigned) and at the end xor
2578 SGNBIT back. */
2580 static wide_int
2581 masked_increment (const wide_int &val_in, const wide_int &mask,
2582 const wide_int &sgnbit, unsigned int prec)
2584 wide_int bit = wi::one (prec), res;
2585 unsigned int i;
2587 wide_int val = val_in ^ sgnbit;
2588 for (i = 0; i < prec; i++, bit += bit)
2590 res = mask;
2591 if ((res & bit) == 0)
2592 continue;
2593 res = bit - 1;
2594 res = wi::bit_and_not (val + bit, res);
2595 res &= mask;
2596 if (wi::gtu_p (res, val))
2597 return res ^ sgnbit;
2599 return val ^ sgnbit;
2602 /* Helper for overflow_comparison_p
2604 OP0 CODE OP1 is a comparison. Examine the comparison and potentially
2605 OP1's defining statement to see if it ultimately has the form
2606 OP0 CODE (OP0 PLUS INTEGER_CST)
2608 If so, return TRUE indicating this is an overflow test and store into
2609 *NEW_CST an updated constant that can be used in a narrowed range test.
2611 REVERSED indicates if the comparison was originally:
2613 OP1 CODE' OP0.
2615 This affects how we build the updated constant. */
2617 static bool
2618 overflow_comparison_p_1 (enum tree_code code, tree op0, tree op1,
2619 bool follow_assert_exprs, bool reversed, tree *new_cst)
2621 /* See if this is a relational operation between two SSA_NAMES with
2622 unsigned, overflow wrapping values. If so, check it more deeply. */
2623 if ((code == LT_EXPR || code == LE_EXPR
2624 || code == GE_EXPR || code == GT_EXPR)
2625 && TREE_CODE (op0) == SSA_NAME
2626 && TREE_CODE (op1) == SSA_NAME
2627 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
2628 && TYPE_UNSIGNED (TREE_TYPE (op0))
2629 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0)))
2631 gimple *op1_def = SSA_NAME_DEF_STMT (op1);
2633 /* If requested, follow any ASSERT_EXPRs backwards for OP1. */
2634 if (follow_assert_exprs)
2636 while (gimple_assign_single_p (op1_def)
2637 && TREE_CODE (gimple_assign_rhs1 (op1_def)) == ASSERT_EXPR)
2639 op1 = TREE_OPERAND (gimple_assign_rhs1 (op1_def), 0);
2640 if (TREE_CODE (op1) != SSA_NAME)
2641 break;
2642 op1_def = SSA_NAME_DEF_STMT (op1);
2646 /* Now look at the defining statement of OP1 to see if it adds
2647 or subtracts a nonzero constant from another operand. */
2648 if (op1_def
2649 && is_gimple_assign (op1_def)
2650 && gimple_assign_rhs_code (op1_def) == PLUS_EXPR
2651 && TREE_CODE (gimple_assign_rhs2 (op1_def)) == INTEGER_CST
2652 && !integer_zerop (gimple_assign_rhs2 (op1_def)))
2654 tree target = gimple_assign_rhs1 (op1_def);
2656 /* If requested, follow ASSERT_EXPRs backwards for op0 looking
2657 for one where TARGET appears on the RHS. */
2658 if (follow_assert_exprs)
2660 /* Now see if that "other operand" is op0, following the chain
2661 of ASSERT_EXPRs if necessary. */
2662 gimple *op0_def = SSA_NAME_DEF_STMT (op0);
2663 while (op0 != target
2664 && gimple_assign_single_p (op0_def)
2665 && TREE_CODE (gimple_assign_rhs1 (op0_def)) == ASSERT_EXPR)
2667 op0 = TREE_OPERAND (gimple_assign_rhs1 (op0_def), 0);
2668 if (TREE_CODE (op0) != SSA_NAME)
2669 break;
2670 op0_def = SSA_NAME_DEF_STMT (op0);
2674 /* If we did not find our target SSA_NAME, then this is not
2675 an overflow test. */
2676 if (op0 != target)
2677 return false;
2679 tree type = TREE_TYPE (op0);
2680 wide_int max = wi::max_value (TYPE_PRECISION (type), UNSIGNED);
2681 tree inc = gimple_assign_rhs2 (op1_def);
2682 if (reversed)
2683 *new_cst = wide_int_to_tree (type, max + wi::to_wide (inc));
2684 else
2685 *new_cst = wide_int_to_tree (type, max - wi::to_wide (inc));
2686 return true;
2689 return false;
2692 /* OP0 CODE OP1 is a comparison. Examine the comparison and potentially
2693 OP1's defining statement to see if it ultimately has the form
2694 OP0 CODE (OP0 PLUS INTEGER_CST)
2696 If so, return TRUE indicating this is an overflow test and store into
2697 *NEW_CST an updated constant that can be used in a narrowed range test.
2699 These statements are left as-is in the IL to facilitate discovery of
2700 {ADD,SUB}_OVERFLOW sequences later in the optimizer pipeline. But
2701 the alternate range representation is often useful within VRP. */
2703 bool
2704 overflow_comparison_p (tree_code code, tree name, tree val,
2705 bool use_equiv_p, tree *new_cst)
2707 if (overflow_comparison_p_1 (code, name, val, use_equiv_p, false, new_cst))
2708 return true;
2709 return overflow_comparison_p_1 (swap_tree_comparison (code), val, name,
2710 use_equiv_p, true, new_cst);
2714 /* Try to register an edge assertion for SSA name NAME on edge E for
2715 the condition COND contributing to the conditional jump pointed to by BSI.
2716 Invert the condition COND if INVERT is true. */
2718 static void
2719 register_edge_assert_for_2 (tree name, edge e,
2720 enum tree_code cond_code,
2721 tree cond_op0, tree cond_op1, bool invert,
2722 vec<assert_info> &asserts)
2724 tree val;
2725 enum tree_code comp_code;
2727 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
2728 cond_op0,
2729 cond_op1,
2730 invert, &comp_code, &val))
2731 return;
2733 /* Queue the assert. */
2734 tree x;
2735 if (overflow_comparison_p (comp_code, name, val, false, &x))
2737 enum tree_code new_code = ((comp_code == GT_EXPR || comp_code == GE_EXPR)
2738 ? GT_EXPR : LE_EXPR);
2739 add_assert_info (asserts, name, name, new_code, x);
2741 add_assert_info (asserts, name, name, comp_code, val);
2743 /* In the case of NAME <= CST and NAME being defined as
2744 NAME = (unsigned) NAME2 + CST2 we can assert NAME2 >= -CST2
2745 and NAME2 <= CST - CST2. We can do the same for NAME > CST.
2746 This catches range and anti-range tests. */
2747 if ((comp_code == LE_EXPR
2748 || comp_code == GT_EXPR)
2749 && TREE_CODE (val) == INTEGER_CST
2750 && TYPE_UNSIGNED (TREE_TYPE (val)))
2752 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
2753 tree cst2 = NULL_TREE, name2 = NULL_TREE, name3 = NULL_TREE;
2755 /* Extract CST2 from the (optional) addition. */
2756 if (is_gimple_assign (def_stmt)
2757 && gimple_assign_rhs_code (def_stmt) == PLUS_EXPR)
2759 name2 = gimple_assign_rhs1 (def_stmt);
2760 cst2 = gimple_assign_rhs2 (def_stmt);
2761 if (TREE_CODE (name2) == SSA_NAME
2762 && TREE_CODE (cst2) == INTEGER_CST)
2763 def_stmt = SSA_NAME_DEF_STMT (name2);
2766 /* Extract NAME2 from the (optional) sign-changing cast. */
2767 if (gimple_assign_cast_p (def_stmt))
2769 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt))
2770 && ! TYPE_UNSIGNED (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
2771 && (TYPE_PRECISION (gimple_expr_type (def_stmt))
2772 == TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))))
2773 name3 = gimple_assign_rhs1 (def_stmt);
2776 /* If name3 is used later, create an ASSERT_EXPR for it. */
2777 if (name3 != NULL_TREE
2778 && TREE_CODE (name3) == SSA_NAME
2779 && (cst2 == NULL_TREE
2780 || TREE_CODE (cst2) == INTEGER_CST)
2781 && INTEGRAL_TYPE_P (TREE_TYPE (name3)))
2783 tree tmp;
2785 /* Build an expression for the range test. */
2786 tmp = build1 (NOP_EXPR, TREE_TYPE (name), name3);
2787 if (cst2 != NULL_TREE)
2788 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
2790 if (dump_file)
2792 fprintf (dump_file, "Adding assert for ");
2793 print_generic_expr (dump_file, name3);
2794 fprintf (dump_file, " from ");
2795 print_generic_expr (dump_file, tmp);
2796 fprintf (dump_file, "\n");
2799 add_assert_info (asserts, name3, tmp, comp_code, val);
2802 /* If name2 is used later, create an ASSERT_EXPR for it. */
2803 if (name2 != NULL_TREE
2804 && TREE_CODE (name2) == SSA_NAME
2805 && TREE_CODE (cst2) == INTEGER_CST
2806 && INTEGRAL_TYPE_P (TREE_TYPE (name2)))
2808 tree tmp;
2810 /* Build an expression for the range test. */
2811 tmp = name2;
2812 if (TREE_TYPE (name) != TREE_TYPE (name2))
2813 tmp = build1 (NOP_EXPR, TREE_TYPE (name), tmp);
2814 if (cst2 != NULL_TREE)
2815 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
2817 if (dump_file)
2819 fprintf (dump_file, "Adding assert for ");
2820 print_generic_expr (dump_file, name2);
2821 fprintf (dump_file, " from ");
2822 print_generic_expr (dump_file, tmp);
2823 fprintf (dump_file, "\n");
2826 add_assert_info (asserts, name2, tmp, comp_code, val);
2830 /* In the case of post-in/decrement tests like if (i++) ... and uses
2831 of the in/decremented value on the edge the extra name we want to
2832 assert for is not on the def chain of the name compared. Instead
2833 it is in the set of use stmts.
2834 Similar cases happen for conversions that were simplified through
2835 fold_{sign_changed,widened}_comparison. */
2836 if ((comp_code == NE_EXPR
2837 || comp_code == EQ_EXPR)
2838 && TREE_CODE (val) == INTEGER_CST)
2840 imm_use_iterator ui;
2841 gimple *use_stmt;
2842 FOR_EACH_IMM_USE_STMT (use_stmt, ui, name)
2844 if (!is_gimple_assign (use_stmt))
2845 continue;
2847 /* Cut off to use-stmts that are dominating the predecessor. */
2848 if (!dominated_by_p (CDI_DOMINATORS, e->src, gimple_bb (use_stmt)))
2849 continue;
2851 tree name2 = gimple_assign_lhs (use_stmt);
2852 if (TREE_CODE (name2) != SSA_NAME)
2853 continue;
2855 enum tree_code code = gimple_assign_rhs_code (use_stmt);
2856 tree cst;
2857 if (code == PLUS_EXPR
2858 || code == MINUS_EXPR)
2860 cst = gimple_assign_rhs2 (use_stmt);
2861 if (TREE_CODE (cst) != INTEGER_CST)
2862 continue;
2863 cst = int_const_binop (code, val, cst);
2865 else if (CONVERT_EXPR_CODE_P (code))
2867 /* For truncating conversions we cannot record
2868 an inequality. */
2869 if (comp_code == NE_EXPR
2870 && (TYPE_PRECISION (TREE_TYPE (name2))
2871 < TYPE_PRECISION (TREE_TYPE (name))))
2872 continue;
2873 cst = fold_convert (TREE_TYPE (name2), val);
2875 else
2876 continue;
2878 if (TREE_OVERFLOW_P (cst))
2879 cst = drop_tree_overflow (cst);
2880 add_assert_info (asserts, name2, name2, comp_code, cst);
2884 if (TREE_CODE_CLASS (comp_code) == tcc_comparison
2885 && TREE_CODE (val) == INTEGER_CST)
2887 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
2888 tree name2 = NULL_TREE, names[2], cst2 = NULL_TREE;
2889 tree val2 = NULL_TREE;
2890 unsigned int prec = TYPE_PRECISION (TREE_TYPE (val));
2891 wide_int mask = wi::zero (prec);
2892 unsigned int nprec = prec;
2893 enum tree_code rhs_code = ERROR_MARK;
2895 if (is_gimple_assign (def_stmt))
2896 rhs_code = gimple_assign_rhs_code (def_stmt);
2898 /* In the case of NAME != CST1 where NAME = A +- CST2 we can
2899 assert that A != CST1 -+ CST2. */
2900 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
2901 && (rhs_code == PLUS_EXPR || rhs_code == MINUS_EXPR))
2903 tree op0 = gimple_assign_rhs1 (def_stmt);
2904 tree op1 = gimple_assign_rhs2 (def_stmt);
2905 if (TREE_CODE (op0) == SSA_NAME
2906 && TREE_CODE (op1) == INTEGER_CST)
2908 enum tree_code reverse_op = (rhs_code == PLUS_EXPR
2909 ? MINUS_EXPR : PLUS_EXPR);
2910 op1 = int_const_binop (reverse_op, val, op1);
2911 if (TREE_OVERFLOW (op1))
2912 op1 = drop_tree_overflow (op1);
2913 add_assert_info (asserts, op0, op0, comp_code, op1);
2917 /* Add asserts for NAME cmp CST and NAME being defined
2918 as NAME = (int) NAME2. */
2919 if (!TYPE_UNSIGNED (TREE_TYPE (val))
2920 && (comp_code == LE_EXPR || comp_code == LT_EXPR
2921 || comp_code == GT_EXPR || comp_code == GE_EXPR)
2922 && gimple_assign_cast_p (def_stmt))
2924 name2 = gimple_assign_rhs1 (def_stmt);
2925 if (CONVERT_EXPR_CODE_P (rhs_code)
2926 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
2927 && TYPE_UNSIGNED (TREE_TYPE (name2))
2928 && prec == TYPE_PRECISION (TREE_TYPE (name2))
2929 && (comp_code == LE_EXPR || comp_code == GT_EXPR
2930 || !tree_int_cst_equal (val,
2931 TYPE_MIN_VALUE (TREE_TYPE (val)))))
2933 tree tmp, cst;
2934 enum tree_code new_comp_code = comp_code;
2936 cst = fold_convert (TREE_TYPE (name2),
2937 TYPE_MIN_VALUE (TREE_TYPE (val)));
2938 /* Build an expression for the range test. */
2939 tmp = build2 (PLUS_EXPR, TREE_TYPE (name2), name2, cst);
2940 cst = fold_build2 (PLUS_EXPR, TREE_TYPE (name2), cst,
2941 fold_convert (TREE_TYPE (name2), val));
2942 if (comp_code == LT_EXPR || comp_code == GE_EXPR)
2944 new_comp_code = comp_code == LT_EXPR ? LE_EXPR : GT_EXPR;
2945 cst = fold_build2 (MINUS_EXPR, TREE_TYPE (name2), cst,
2946 build_int_cst (TREE_TYPE (name2), 1));
2949 if (dump_file)
2951 fprintf (dump_file, "Adding assert for ");
2952 print_generic_expr (dump_file, name2);
2953 fprintf (dump_file, " from ");
2954 print_generic_expr (dump_file, tmp);
2955 fprintf (dump_file, "\n");
2958 add_assert_info (asserts, name2, tmp, new_comp_code, cst);
2962 /* Add asserts for NAME cmp CST and NAME being defined as
2963 NAME = NAME2 >> CST2.
2965 Extract CST2 from the right shift. */
2966 if (rhs_code == RSHIFT_EXPR)
2968 name2 = gimple_assign_rhs1 (def_stmt);
2969 cst2 = gimple_assign_rhs2 (def_stmt);
2970 if (TREE_CODE (name2) == SSA_NAME
2971 && tree_fits_uhwi_p (cst2)
2972 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
2973 && IN_RANGE (tree_to_uhwi (cst2), 1, prec - 1)
2974 && type_has_mode_precision_p (TREE_TYPE (val)))
2976 mask = wi::mask (tree_to_uhwi (cst2), false, prec);
2977 val2 = fold_binary (LSHIFT_EXPR, TREE_TYPE (val), val, cst2);
2980 if (val2 != NULL_TREE
2981 && TREE_CODE (val2) == INTEGER_CST
2982 && simple_cst_equal (fold_build2 (RSHIFT_EXPR,
2983 TREE_TYPE (val),
2984 val2, cst2), val))
2986 enum tree_code new_comp_code = comp_code;
2987 tree tmp, new_val;
2989 tmp = name2;
2990 if (comp_code == EQ_EXPR || comp_code == NE_EXPR)
2992 if (!TYPE_UNSIGNED (TREE_TYPE (val)))
2994 tree type = build_nonstandard_integer_type (prec, 1);
2995 tmp = build1 (NOP_EXPR, type, name2);
2996 val2 = fold_convert (type, val2);
2998 tmp = fold_build2 (MINUS_EXPR, TREE_TYPE (tmp), tmp, val2);
2999 new_val = wide_int_to_tree (TREE_TYPE (tmp), mask);
3000 new_comp_code = comp_code == EQ_EXPR ? LE_EXPR : GT_EXPR;
3002 else if (comp_code == LT_EXPR || comp_code == GE_EXPR)
3004 wide_int minval
3005 = wi::min_value (prec, TYPE_SIGN (TREE_TYPE (val)));
3006 new_val = val2;
3007 if (minval == wi::to_wide (new_val))
3008 new_val = NULL_TREE;
3010 else
3012 wide_int maxval
3013 = wi::max_value (prec, TYPE_SIGN (TREE_TYPE (val)));
3014 mask |= wi::to_wide (val2);
3015 if (wi::eq_p (mask, maxval))
3016 new_val = NULL_TREE;
3017 else
3018 new_val = wide_int_to_tree (TREE_TYPE (val2), mask);
3021 if (new_val)
3023 if (dump_file)
3025 fprintf (dump_file, "Adding assert for ");
3026 print_generic_expr (dump_file, name2);
3027 fprintf (dump_file, " from ");
3028 print_generic_expr (dump_file, tmp);
3029 fprintf (dump_file, "\n");
3032 add_assert_info (asserts, name2, tmp, new_comp_code, new_val);
3036 /* Add asserts for NAME cmp CST and NAME being defined as
3037 NAME = NAME2 & CST2.
3039 Extract CST2 from the and.
3041 Also handle
3042 NAME = (unsigned) NAME2;
3043 casts where NAME's type is unsigned and has smaller precision
3044 than NAME2's type as if it was NAME = NAME2 & MASK. */
3045 names[0] = NULL_TREE;
3046 names[1] = NULL_TREE;
3047 cst2 = NULL_TREE;
3048 if (rhs_code == BIT_AND_EXPR
3049 || (CONVERT_EXPR_CODE_P (rhs_code)
3050 && INTEGRAL_TYPE_P (TREE_TYPE (val))
3051 && TYPE_UNSIGNED (TREE_TYPE (val))
3052 && TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
3053 > prec))
3055 name2 = gimple_assign_rhs1 (def_stmt);
3056 if (rhs_code == BIT_AND_EXPR)
3057 cst2 = gimple_assign_rhs2 (def_stmt);
3058 else
3060 cst2 = TYPE_MAX_VALUE (TREE_TYPE (val));
3061 nprec = TYPE_PRECISION (TREE_TYPE (name2));
3063 if (TREE_CODE (name2) == SSA_NAME
3064 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
3065 && TREE_CODE (cst2) == INTEGER_CST
3066 && !integer_zerop (cst2)
3067 && (nprec > 1
3068 || TYPE_UNSIGNED (TREE_TYPE (val))))
3070 gimple *def_stmt2 = SSA_NAME_DEF_STMT (name2);
3071 if (gimple_assign_cast_p (def_stmt2))
3073 names[1] = gimple_assign_rhs1 (def_stmt2);
3074 if (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt2))
3075 || !INTEGRAL_TYPE_P (TREE_TYPE (names[1]))
3076 || (TYPE_PRECISION (TREE_TYPE (name2))
3077 != TYPE_PRECISION (TREE_TYPE (names[1]))))
3078 names[1] = NULL_TREE;
3080 names[0] = name2;
3083 if (names[0] || names[1])
3085 wide_int minv, maxv, valv, cst2v;
3086 wide_int tem, sgnbit;
3087 bool valid_p = false, valn, cst2n;
3088 enum tree_code ccode = comp_code;
3090 valv = wide_int::from (wi::to_wide (val), nprec, UNSIGNED);
3091 cst2v = wide_int::from (wi::to_wide (cst2), nprec, UNSIGNED);
3092 valn = wi::neg_p (valv, TYPE_SIGN (TREE_TYPE (val)));
3093 cst2n = wi::neg_p (cst2v, TYPE_SIGN (TREE_TYPE (val)));
3094 /* If CST2 doesn't have most significant bit set,
3095 but VAL is negative, we have comparison like
3096 if ((x & 0x123) > -4) (always true). Just give up. */
3097 if (!cst2n && valn)
3098 ccode = ERROR_MARK;
3099 if (cst2n)
3100 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
3101 else
3102 sgnbit = wi::zero (nprec);
3103 minv = valv & cst2v;
3104 switch (ccode)
3106 case EQ_EXPR:
3107 /* Minimum unsigned value for equality is VAL & CST2
3108 (should be equal to VAL, otherwise we probably should
3109 have folded the comparison into false) and
3110 maximum unsigned value is VAL | ~CST2. */
3111 maxv = valv | ~cst2v;
3112 valid_p = true;
3113 break;
3115 case NE_EXPR:
3116 tem = valv | ~cst2v;
3117 /* If VAL is 0, handle (X & CST2) != 0 as (X & CST2) > 0U. */
3118 if (valv == 0)
3120 cst2n = false;
3121 sgnbit = wi::zero (nprec);
3122 goto gt_expr;
3124 /* If (VAL | ~CST2) is all ones, handle it as
3125 (X & CST2) < VAL. */
3126 if (tem == -1)
3128 cst2n = false;
3129 valn = false;
3130 sgnbit = wi::zero (nprec);
3131 goto lt_expr;
3133 if (!cst2n && wi::neg_p (cst2v))
3134 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
3135 if (sgnbit != 0)
3137 if (valv == sgnbit)
3139 cst2n = true;
3140 valn = true;
3141 goto gt_expr;
3143 if (tem == wi::mask (nprec - 1, false, nprec))
3145 cst2n = true;
3146 goto lt_expr;
3148 if (!cst2n)
3149 sgnbit = wi::zero (nprec);
3151 break;
3153 case GE_EXPR:
3154 /* Minimum unsigned value for >= if (VAL & CST2) == VAL
3155 is VAL and maximum unsigned value is ~0. For signed
3156 comparison, if CST2 doesn't have most significant bit
3157 set, handle it similarly. If CST2 has MSB set,
3158 the minimum is the same, and maximum is ~0U/2. */
3159 if (minv != valv)
3161 /* If (VAL & CST2) != VAL, X & CST2 can't be equal to
3162 VAL. */
3163 minv = masked_increment (valv, cst2v, sgnbit, nprec);
3164 if (minv == valv)
3165 break;
3167 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
3168 valid_p = true;
3169 break;
3171 case GT_EXPR:
3172 gt_expr:
3173 /* Find out smallest MINV where MINV > VAL
3174 && (MINV & CST2) == MINV, if any. If VAL is signed and
3175 CST2 has MSB set, compute it biased by 1 << (nprec - 1). */
3176 minv = masked_increment (valv, cst2v, sgnbit, nprec);
3177 if (minv == valv)
3178 break;
3179 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
3180 valid_p = true;
3181 break;
3183 case LE_EXPR:
3184 /* Minimum unsigned value for <= is 0 and maximum
3185 unsigned value is VAL | ~CST2 if (VAL & CST2) == VAL.
3186 Otherwise, find smallest VAL2 where VAL2 > VAL
3187 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
3188 as maximum.
3189 For signed comparison, if CST2 doesn't have most
3190 significant bit set, handle it similarly. If CST2 has
3191 MSB set, the maximum is the same and minimum is INT_MIN. */
3192 if (minv == valv)
3193 maxv = valv;
3194 else
3196 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
3197 if (maxv == valv)
3198 break;
3199 maxv -= 1;
3201 maxv |= ~cst2v;
3202 minv = sgnbit;
3203 valid_p = true;
3204 break;
3206 case LT_EXPR:
3207 lt_expr:
3208 /* Minimum unsigned value for < is 0 and maximum
3209 unsigned value is (VAL-1) | ~CST2 if (VAL & CST2) == VAL.
3210 Otherwise, find smallest VAL2 where VAL2 > VAL
3211 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
3212 as maximum.
3213 For signed comparison, if CST2 doesn't have most
3214 significant bit set, handle it similarly. If CST2 has
3215 MSB set, the maximum is the same and minimum is INT_MIN. */
3216 if (minv == valv)
3218 if (valv == sgnbit)
3219 break;
3220 maxv = valv;
3222 else
3224 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
3225 if (maxv == valv)
3226 break;
3228 maxv -= 1;
3229 maxv |= ~cst2v;
3230 minv = sgnbit;
3231 valid_p = true;
3232 break;
3234 default:
3235 break;
3237 if (valid_p
3238 && (maxv - minv) != -1)
3240 tree tmp, new_val, type;
3241 int i;
3243 for (i = 0; i < 2; i++)
3244 if (names[i])
3246 wide_int maxv2 = maxv;
3247 tmp = names[i];
3248 type = TREE_TYPE (names[i]);
3249 if (!TYPE_UNSIGNED (type))
3251 type = build_nonstandard_integer_type (nprec, 1);
3252 tmp = build1 (NOP_EXPR, type, names[i]);
3254 if (minv != 0)
3256 tmp = build2 (PLUS_EXPR, type, tmp,
3257 wide_int_to_tree (type, -minv));
3258 maxv2 = maxv - minv;
3260 new_val = wide_int_to_tree (type, maxv2);
3262 if (dump_file)
3264 fprintf (dump_file, "Adding assert for ");
3265 print_generic_expr (dump_file, names[i]);
3266 fprintf (dump_file, " from ");
3267 print_generic_expr (dump_file, tmp);
3268 fprintf (dump_file, "\n");
3271 add_assert_info (asserts, names[i], tmp, LE_EXPR, new_val);
3278 /* OP is an operand of a truth value expression which is known to have
3279 a particular value. Register any asserts for OP and for any
3280 operands in OP's defining statement.
3282 If CODE is EQ_EXPR, then we want to register OP is zero (false),
3283 if CODE is NE_EXPR, then we want to register OP is nonzero (true). */
3285 static void
3286 register_edge_assert_for_1 (tree op, enum tree_code code,
3287 edge e, vec<assert_info> &asserts)
3289 gimple *op_def;
3290 tree val;
3291 enum tree_code rhs_code;
3293 /* We only care about SSA_NAMEs. */
3294 if (TREE_CODE (op) != SSA_NAME)
3295 return;
3297 /* We know that OP will have a zero or nonzero value. */
3298 val = build_int_cst (TREE_TYPE (op), 0);
3299 add_assert_info (asserts, op, op, code, val);
3301 /* Now look at how OP is set. If it's set from a comparison,
3302 a truth operation or some bit operations, then we may be able
3303 to register information about the operands of that assignment. */
3304 op_def = SSA_NAME_DEF_STMT (op);
3305 if (gimple_code (op_def) != GIMPLE_ASSIGN)
3306 return;
3308 rhs_code = gimple_assign_rhs_code (op_def);
3310 if (TREE_CODE_CLASS (rhs_code) == tcc_comparison)
3312 bool invert = (code == EQ_EXPR ? true : false);
3313 tree op0 = gimple_assign_rhs1 (op_def);
3314 tree op1 = gimple_assign_rhs2 (op_def);
3316 if (TREE_CODE (op0) == SSA_NAME)
3317 register_edge_assert_for_2 (op0, e, rhs_code, op0, op1, invert, asserts);
3318 if (TREE_CODE (op1) == SSA_NAME)
3319 register_edge_assert_for_2 (op1, e, rhs_code, op0, op1, invert, asserts);
3321 else if ((code == NE_EXPR
3322 && gimple_assign_rhs_code (op_def) == BIT_AND_EXPR)
3323 || (code == EQ_EXPR
3324 && gimple_assign_rhs_code (op_def) == BIT_IOR_EXPR))
3326 /* Recurse on each operand. */
3327 tree op0 = gimple_assign_rhs1 (op_def);
3328 tree op1 = gimple_assign_rhs2 (op_def);
3329 if (TREE_CODE (op0) == SSA_NAME
3330 && has_single_use (op0))
3331 register_edge_assert_for_1 (op0, code, e, asserts);
3332 if (TREE_CODE (op1) == SSA_NAME
3333 && has_single_use (op1))
3334 register_edge_assert_for_1 (op1, code, e, asserts);
3336 else if (gimple_assign_rhs_code (op_def) == BIT_NOT_EXPR
3337 && TYPE_PRECISION (TREE_TYPE (gimple_assign_lhs (op_def))) == 1)
3339 /* Recurse, flipping CODE. */
3340 code = invert_tree_comparison (code, false);
3341 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
3343 else if (gimple_assign_rhs_code (op_def) == SSA_NAME)
3345 /* Recurse through the copy. */
3346 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
3348 else if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (op_def)))
3350 /* Recurse through the type conversion, unless it is a narrowing
3351 conversion or conversion from non-integral type. */
3352 tree rhs = gimple_assign_rhs1 (op_def);
3353 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs))
3354 && (TYPE_PRECISION (TREE_TYPE (rhs))
3355 <= TYPE_PRECISION (TREE_TYPE (op))))
3356 register_edge_assert_for_1 (rhs, code, e, asserts);
3360 /* Check if comparison
3361 NAME COND_OP INTEGER_CST
3362 has a form of
3363 (X & 11...100..0) COND_OP XX...X00...0
3364 Such comparison can yield assertions like
3365 X >= XX...X00...0
3366 X <= XX...X11...1
3367 in case of COND_OP being EQ_EXPR or
3368 X < XX...X00...0
3369 X > XX...X11...1
3370 in case of NE_EXPR. */
3372 static bool
3373 is_masked_range_test (tree name, tree valt, enum tree_code cond_code,
3374 tree *new_name, tree *low, enum tree_code *low_code,
3375 tree *high, enum tree_code *high_code)
3377 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3379 if (!is_gimple_assign (def_stmt)
3380 || gimple_assign_rhs_code (def_stmt) != BIT_AND_EXPR)
3381 return false;
3383 tree t = gimple_assign_rhs1 (def_stmt);
3384 tree maskt = gimple_assign_rhs2 (def_stmt);
3385 if (TREE_CODE (t) != SSA_NAME || TREE_CODE (maskt) != INTEGER_CST)
3386 return false;
3388 wi::tree_to_wide_ref mask = wi::to_wide (maskt);
3389 wide_int inv_mask = ~mask;
3390 /* Must have been removed by now so don't bother optimizing. */
3391 if (mask == 0 || inv_mask == 0)
3392 return false;
3394 /* Assume VALT is INTEGER_CST. */
3395 wi::tree_to_wide_ref val = wi::to_wide (valt);
3397 if ((inv_mask & (inv_mask + 1)) != 0
3398 || (val & mask) != val)
3399 return false;
3401 bool is_range = cond_code == EQ_EXPR;
3403 tree type = TREE_TYPE (t);
3404 wide_int min = wi::min_value (type),
3405 max = wi::max_value (type);
3407 if (is_range)
3409 *low_code = val == min ? ERROR_MARK : GE_EXPR;
3410 *high_code = val == max ? ERROR_MARK : LE_EXPR;
3412 else
3414 /* We can still generate assertion if one of alternatives
3415 is known to always be false. */
3416 if (val == min)
3418 *low_code = (enum tree_code) 0;
3419 *high_code = GT_EXPR;
3421 else if ((val | inv_mask) == max)
3423 *low_code = LT_EXPR;
3424 *high_code = (enum tree_code) 0;
3426 else
3427 return false;
3430 *new_name = t;
3431 *low = wide_int_to_tree (type, val);
3432 *high = wide_int_to_tree (type, val | inv_mask);
3434 return true;
3437 /* Try to register an edge assertion for SSA name NAME on edge E for
3438 the condition COND contributing to the conditional jump pointed to by
3439 SI. */
3441 void
3442 register_edge_assert_for (tree name, edge e,
3443 enum tree_code cond_code, tree cond_op0,
3444 tree cond_op1, vec<assert_info> &asserts)
3446 tree val;
3447 enum tree_code comp_code;
3448 bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
3450 /* Do not attempt to infer anything in names that flow through
3451 abnormal edges. */
3452 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
3453 return;
3455 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
3456 cond_op0, cond_op1,
3457 is_else_edge,
3458 &comp_code, &val))
3459 return;
3461 /* Register ASSERT_EXPRs for name. */
3462 register_edge_assert_for_2 (name, e, cond_code, cond_op0,
3463 cond_op1, is_else_edge, asserts);
3466 /* If COND is effectively an equality test of an SSA_NAME against
3467 the value zero or one, then we may be able to assert values
3468 for SSA_NAMEs which flow into COND. */
3470 /* In the case of NAME == 1 or NAME != 0, for BIT_AND_EXPR defining
3471 statement of NAME we can assert both operands of the BIT_AND_EXPR
3472 have nonzero value. */
3473 if (((comp_code == EQ_EXPR && integer_onep (val))
3474 || (comp_code == NE_EXPR && integer_zerop (val))))
3476 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3478 if (is_gimple_assign (def_stmt)
3479 && gimple_assign_rhs_code (def_stmt) == BIT_AND_EXPR)
3481 tree op0 = gimple_assign_rhs1 (def_stmt);
3482 tree op1 = gimple_assign_rhs2 (def_stmt);
3483 register_edge_assert_for_1 (op0, NE_EXPR, e, asserts);
3484 register_edge_assert_for_1 (op1, NE_EXPR, e, asserts);
3488 /* In the case of NAME == 0 or NAME != 1, for BIT_IOR_EXPR defining
3489 statement of NAME we can assert both operands of the BIT_IOR_EXPR
3490 have zero value. */
3491 if (((comp_code == EQ_EXPR && integer_zerop (val))
3492 || (comp_code == NE_EXPR && integer_onep (val))))
3494 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3496 /* For BIT_IOR_EXPR only if NAME == 0 both operands have
3497 necessarily zero value, or if type-precision is one. */
3498 if (is_gimple_assign (def_stmt)
3499 && (gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR
3500 && (TYPE_PRECISION (TREE_TYPE (name)) == 1
3501 || comp_code == EQ_EXPR)))
3503 tree op0 = gimple_assign_rhs1 (def_stmt);
3504 tree op1 = gimple_assign_rhs2 (def_stmt);
3505 register_edge_assert_for_1 (op0, EQ_EXPR, e, asserts);
3506 register_edge_assert_for_1 (op1, EQ_EXPR, e, asserts);
3510 /* Sometimes we can infer ranges from (NAME & MASK) == VALUE. */
3511 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
3512 && TREE_CODE (val) == INTEGER_CST)
3514 enum tree_code low_code, high_code;
3515 tree low, high;
3516 if (is_masked_range_test (name, val, comp_code, &name, &low,
3517 &low_code, &high, &high_code))
3519 if (low_code != ERROR_MARK)
3520 register_edge_assert_for_2 (name, e, low_code, name,
3521 low, /*invert*/false, asserts);
3522 if (high_code != ERROR_MARK)
3523 register_edge_assert_for_2 (name, e, high_code, name,
3524 high, /*invert*/false, asserts);
3529 /* Finish found ASSERTS for E and register them at GSI. */
3531 static void
3532 finish_register_edge_assert_for (edge e, gimple_stmt_iterator gsi,
3533 vec<assert_info> &asserts)
3535 for (unsigned i = 0; i < asserts.length (); ++i)
3536 /* Only register an ASSERT_EXPR if NAME was found in the sub-graph
3537 reachable from E. */
3538 if (live_on_edge (e, asserts[i].name))
3539 register_new_assert_for (asserts[i].name, asserts[i].expr,
3540 asserts[i].comp_code, asserts[i].val,
3541 NULL, e, gsi);
3546 /* Determine whether the outgoing edges of BB should receive an
3547 ASSERT_EXPR for each of the operands of BB's LAST statement.
3548 The last statement of BB must be a COND_EXPR.
3550 If any of the sub-graphs rooted at BB have an interesting use of
3551 the predicate operands, an assert location node is added to the
3552 list of assertions for the corresponding operands. */
3554 static void
3555 find_conditional_asserts (basic_block bb, gcond *last)
3557 gimple_stmt_iterator bsi;
3558 tree op;
3559 edge_iterator ei;
3560 edge e;
3561 ssa_op_iter iter;
3563 bsi = gsi_for_stmt (last);
3565 /* Look for uses of the operands in each of the sub-graphs
3566 rooted at BB. We need to check each of the outgoing edges
3567 separately, so that we know what kind of ASSERT_EXPR to
3568 insert. */
3569 FOR_EACH_EDGE (e, ei, bb->succs)
3571 if (e->dest == bb)
3572 continue;
3574 /* Register the necessary assertions for each operand in the
3575 conditional predicate. */
3576 auto_vec<assert_info, 8> asserts;
3577 FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
3578 register_edge_assert_for (op, e,
3579 gimple_cond_code (last),
3580 gimple_cond_lhs (last),
3581 gimple_cond_rhs (last), asserts);
3582 finish_register_edge_assert_for (e, bsi, asserts);
3586 struct case_info
3588 tree expr;
3589 basic_block bb;
3592 /* Compare two case labels sorting first by the destination bb index
3593 and then by the case value. */
3595 static int
3596 compare_case_labels (const void *p1, const void *p2)
3598 const struct case_info *ci1 = (const struct case_info *) p1;
3599 const struct case_info *ci2 = (const struct case_info *) p2;
3600 int idx1 = ci1->bb->index;
3601 int idx2 = ci2->bb->index;
3603 if (idx1 < idx2)
3604 return -1;
3605 else if (idx1 == idx2)
3607 /* Make sure the default label is first in a group. */
3608 if (!CASE_LOW (ci1->expr))
3609 return -1;
3610 else if (!CASE_LOW (ci2->expr))
3611 return 1;
3612 else
3613 return tree_int_cst_compare (CASE_LOW (ci1->expr),
3614 CASE_LOW (ci2->expr));
3616 else
3617 return 1;
3620 /* Determine whether the outgoing edges of BB should receive an
3621 ASSERT_EXPR for each of the operands of BB's LAST statement.
3622 The last statement of BB must be a SWITCH_EXPR.
3624 If any of the sub-graphs rooted at BB have an interesting use of
3625 the predicate operands, an assert location node is added to the
3626 list of assertions for the corresponding operands. */
3628 static void
3629 find_switch_asserts (basic_block bb, gswitch *last)
3631 gimple_stmt_iterator bsi;
3632 tree op;
3633 edge e;
3634 struct case_info *ci;
3635 size_t n = gimple_switch_num_labels (last);
3636 #if GCC_VERSION >= 4000
3637 unsigned int idx;
3638 #else
3639 /* Work around GCC 3.4 bug (PR 37086). */
3640 volatile unsigned int idx;
3641 #endif
3643 bsi = gsi_for_stmt (last);
3644 op = gimple_switch_index (last);
3645 if (TREE_CODE (op) != SSA_NAME)
3646 return;
3648 /* Build a vector of case labels sorted by destination label. */
3649 ci = XNEWVEC (struct case_info, n);
3650 for (idx = 0; idx < n; ++idx)
3652 ci[idx].expr = gimple_switch_label (last, idx);
3653 ci[idx].bb = label_to_block (CASE_LABEL (ci[idx].expr));
3655 edge default_edge = find_edge (bb, ci[0].bb);
3656 qsort (ci, n, sizeof (struct case_info), compare_case_labels);
3658 for (idx = 0; idx < n; ++idx)
3660 tree min, max;
3661 tree cl = ci[idx].expr;
3662 basic_block cbb = ci[idx].bb;
3664 min = CASE_LOW (cl);
3665 max = CASE_HIGH (cl);
3667 /* If there are multiple case labels with the same destination
3668 we need to combine them to a single value range for the edge. */
3669 if (idx + 1 < n && cbb == ci[idx + 1].bb)
3671 /* Skip labels until the last of the group. */
3672 do {
3673 ++idx;
3674 } while (idx < n && cbb == ci[idx].bb);
3675 --idx;
3677 /* Pick up the maximum of the case label range. */
3678 if (CASE_HIGH (ci[idx].expr))
3679 max = CASE_HIGH (ci[idx].expr);
3680 else
3681 max = CASE_LOW (ci[idx].expr);
3684 /* Can't extract a useful assertion out of a range that includes the
3685 default label. */
3686 if (min == NULL_TREE)
3687 continue;
3689 /* Find the edge to register the assert expr on. */
3690 e = find_edge (bb, cbb);
3692 /* Register the necessary assertions for the operand in the
3693 SWITCH_EXPR. */
3694 auto_vec<assert_info, 8> asserts;
3695 register_edge_assert_for (op, e,
3696 max ? GE_EXPR : EQ_EXPR,
3697 op, fold_convert (TREE_TYPE (op), min),
3698 asserts);
3699 if (max)
3700 register_edge_assert_for (op, e, LE_EXPR, op,
3701 fold_convert (TREE_TYPE (op), max),
3702 asserts);
3703 finish_register_edge_assert_for (e, bsi, asserts);
3706 XDELETEVEC (ci);
3708 if (!live_on_edge (default_edge, op))
3709 return;
3711 /* Now register along the default label assertions that correspond to the
3712 anti-range of each label. */
3713 int insertion_limit = PARAM_VALUE (PARAM_MAX_VRP_SWITCH_ASSERTIONS);
3714 if (insertion_limit == 0)
3715 return;
3717 /* We can't do this if the default case shares a label with another case. */
3718 tree default_cl = gimple_switch_default_label (last);
3719 for (idx = 1; idx < n; idx++)
3721 tree min, max;
3722 tree cl = gimple_switch_label (last, idx);
3723 if (CASE_LABEL (cl) == CASE_LABEL (default_cl))
3724 continue;
3726 min = CASE_LOW (cl);
3727 max = CASE_HIGH (cl);
3729 /* Combine contiguous case ranges to reduce the number of assertions
3730 to insert. */
3731 for (idx = idx + 1; idx < n; idx++)
3733 tree next_min, next_max;
3734 tree next_cl = gimple_switch_label (last, idx);
3735 if (CASE_LABEL (next_cl) == CASE_LABEL (default_cl))
3736 break;
3738 next_min = CASE_LOW (next_cl);
3739 next_max = CASE_HIGH (next_cl);
3741 wide_int difference = (wi::to_wide (next_min)
3742 - wi::to_wide (max ? max : min));
3743 if (wi::eq_p (difference, 1))
3744 max = next_max ? next_max : next_min;
3745 else
3746 break;
3748 idx--;
3750 if (max == NULL_TREE)
3752 /* Register the assertion OP != MIN. */
3753 auto_vec<assert_info, 8> asserts;
3754 min = fold_convert (TREE_TYPE (op), min);
3755 register_edge_assert_for (op, default_edge, NE_EXPR, op, min,
3756 asserts);
3757 finish_register_edge_assert_for (default_edge, bsi, asserts);
3759 else
3761 /* Register the assertion (unsigned)OP - MIN > (MAX - MIN),
3762 which will give OP the anti-range ~[MIN,MAX]. */
3763 tree uop = fold_convert (unsigned_type_for (TREE_TYPE (op)), op);
3764 min = fold_convert (TREE_TYPE (uop), min);
3765 max = fold_convert (TREE_TYPE (uop), max);
3767 tree lhs = fold_build2 (MINUS_EXPR, TREE_TYPE (uop), uop, min);
3768 tree rhs = int_const_binop (MINUS_EXPR, max, min);
3769 register_new_assert_for (op, lhs, GT_EXPR, rhs,
3770 NULL, default_edge, bsi);
3773 if (--insertion_limit == 0)
3774 break;
3779 /* Traverse all the statements in block BB looking for statements that
3780 may generate useful assertions for the SSA names in their operand.
3781 If a statement produces a useful assertion A for name N_i, then the
3782 list of assertions already generated for N_i is scanned to
3783 determine if A is actually needed.
3785 If N_i already had the assertion A at a location dominating the
3786 current location, then nothing needs to be done. Otherwise, the
3787 new location for A is recorded instead.
3789 1- For every statement S in BB, all the variables used by S are
3790 added to bitmap FOUND_IN_SUBGRAPH.
3792 2- If statement S uses an operand N in a way that exposes a known
3793 value range for N, then if N was not already generated by an
3794 ASSERT_EXPR, create a new assert location for N. For instance,
3795 if N is a pointer and the statement dereferences it, we can
3796 assume that N is not NULL.
3798 3- COND_EXPRs are a special case of #2. We can derive range
3799 information from the predicate but need to insert different
3800 ASSERT_EXPRs for each of the sub-graphs rooted at the
3801 conditional block. If the last statement of BB is a conditional
3802 expression of the form 'X op Y', then
3804 a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
3806 b) If the conditional is the only entry point to the sub-graph
3807 corresponding to the THEN_CLAUSE, recurse into it. On
3808 return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
3809 an ASSERT_EXPR is added for the corresponding variable.
3811 c) Repeat step (b) on the ELSE_CLAUSE.
3813 d) Mark X and Y in FOUND_IN_SUBGRAPH.
3815 For instance,
3817 if (a == 9)
3818 b = a;
3819 else
3820 b = c + 1;
3822 In this case, an assertion on the THEN clause is useful to
3823 determine that 'a' is always 9 on that edge. However, an assertion
3824 on the ELSE clause would be unnecessary.
3826 4- If BB does not end in a conditional expression, then we recurse
3827 into BB's dominator children.
3829 At the end of the recursive traversal, every SSA name will have a
3830 list of locations where ASSERT_EXPRs should be added. When a new
3831 location for name N is found, it is registered by calling
3832 register_new_assert_for. That function keeps track of all the
3833 registered assertions to prevent adding unnecessary assertions.
3834 For instance, if a pointer P_4 is dereferenced more than once in a
3835 dominator tree, only the location dominating all the dereference of
3836 P_4 will receive an ASSERT_EXPR. */
3838 static void
3839 find_assert_locations_1 (basic_block bb, sbitmap live)
3841 gimple *last;
3843 last = last_stmt (bb);
3845 /* If BB's last statement is a conditional statement involving integer
3846 operands, determine if we need to add ASSERT_EXPRs. */
3847 if (last
3848 && gimple_code (last) == GIMPLE_COND
3849 && !fp_predicate (last)
3850 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
3851 find_conditional_asserts (bb, as_a <gcond *> (last));
3853 /* If BB's last statement is a switch statement involving integer
3854 operands, determine if we need to add ASSERT_EXPRs. */
3855 if (last
3856 && gimple_code (last) == GIMPLE_SWITCH
3857 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
3858 find_switch_asserts (bb, as_a <gswitch *> (last));
3860 /* Traverse all the statements in BB marking used names and looking
3861 for statements that may infer assertions for their used operands. */
3862 for (gimple_stmt_iterator si = gsi_last_bb (bb); !gsi_end_p (si);
3863 gsi_prev (&si))
3865 gimple *stmt;
3866 tree op;
3867 ssa_op_iter i;
3869 stmt = gsi_stmt (si);
3871 if (is_gimple_debug (stmt))
3872 continue;
3874 /* See if we can derive an assertion for any of STMT's operands. */
3875 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
3877 tree value;
3878 enum tree_code comp_code;
3880 /* If op is not live beyond this stmt, do not bother to insert
3881 asserts for it. */
3882 if (!bitmap_bit_p (live, SSA_NAME_VERSION (op)))
3883 continue;
3885 /* If OP is used in such a way that we can infer a value
3886 range for it, and we don't find a previous assertion for
3887 it, create a new assertion location node for OP. */
3888 if (infer_value_range (stmt, op, &comp_code, &value))
3890 /* If we are able to infer a nonzero value range for OP,
3891 then walk backwards through the use-def chain to see if OP
3892 was set via a typecast.
3894 If so, then we can also infer a nonzero value range
3895 for the operand of the NOP_EXPR. */
3896 if (comp_code == NE_EXPR && integer_zerop (value))
3898 tree t = op;
3899 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
3901 while (is_gimple_assign (def_stmt)
3902 && CONVERT_EXPR_CODE_P
3903 (gimple_assign_rhs_code (def_stmt))
3904 && TREE_CODE
3905 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
3906 && POINTER_TYPE_P
3907 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
3909 t = gimple_assign_rhs1 (def_stmt);
3910 def_stmt = SSA_NAME_DEF_STMT (t);
3912 /* Note we want to register the assert for the
3913 operand of the NOP_EXPR after SI, not after the
3914 conversion. */
3915 if (bitmap_bit_p (live, SSA_NAME_VERSION (t)))
3916 register_new_assert_for (t, t, comp_code, value,
3917 bb, NULL, si);
3921 register_new_assert_for (op, op, comp_code, value, bb, NULL, si);
3925 /* Update live. */
3926 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
3927 bitmap_set_bit (live, SSA_NAME_VERSION (op));
3928 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_DEF)
3929 bitmap_clear_bit (live, SSA_NAME_VERSION (op));
3932 /* Traverse all PHI nodes in BB, updating live. */
3933 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
3934 gsi_next (&si))
3936 use_operand_p arg_p;
3937 ssa_op_iter i;
3938 gphi *phi = si.phi ();
3939 tree res = gimple_phi_result (phi);
3941 if (virtual_operand_p (res))
3942 continue;
3944 FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
3946 tree arg = USE_FROM_PTR (arg_p);
3947 if (TREE_CODE (arg) == SSA_NAME)
3948 bitmap_set_bit (live, SSA_NAME_VERSION (arg));
3951 bitmap_clear_bit (live, SSA_NAME_VERSION (res));
3955 /* Do an RPO walk over the function computing SSA name liveness
3956 on-the-fly and deciding on assert expressions to insert. */
3958 static void
3959 find_assert_locations (void)
3961 int *rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
3962 int *bb_rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
3963 int *last_rpo = XCNEWVEC (int, last_basic_block_for_fn (cfun));
3964 int rpo_cnt, i;
3966 live = XCNEWVEC (sbitmap, last_basic_block_for_fn (cfun));
3967 rpo_cnt = pre_and_rev_post_order_compute (NULL, rpo, false);
3968 for (i = 0; i < rpo_cnt; ++i)
3969 bb_rpo[rpo[i]] = i;
3971 /* Pre-seed loop latch liveness from loop header PHI nodes. Due to
3972 the order we compute liveness and insert asserts we otherwise
3973 fail to insert asserts into the loop latch. */
3974 loop_p loop;
3975 FOR_EACH_LOOP (loop, 0)
3977 i = loop->latch->index;
3978 unsigned int j = single_succ_edge (loop->latch)->dest_idx;
3979 for (gphi_iterator gsi = gsi_start_phis (loop->header);
3980 !gsi_end_p (gsi); gsi_next (&gsi))
3982 gphi *phi = gsi.phi ();
3983 if (virtual_operand_p (gimple_phi_result (phi)))
3984 continue;
3985 tree arg = gimple_phi_arg_def (phi, j);
3986 if (TREE_CODE (arg) == SSA_NAME)
3988 if (live[i] == NULL)
3990 live[i] = sbitmap_alloc (num_ssa_names);
3991 bitmap_clear (live[i]);
3993 bitmap_set_bit (live[i], SSA_NAME_VERSION (arg));
3998 for (i = rpo_cnt - 1; i >= 0; --i)
4000 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, rpo[i]);
4001 edge e;
4002 edge_iterator ei;
4004 if (!live[rpo[i]])
4006 live[rpo[i]] = sbitmap_alloc (num_ssa_names);
4007 bitmap_clear (live[rpo[i]]);
4010 /* Process BB and update the live information with uses in
4011 this block. */
4012 find_assert_locations_1 (bb, live[rpo[i]]);
4014 /* Merge liveness into the predecessor blocks and free it. */
4015 if (!bitmap_empty_p (live[rpo[i]]))
4017 int pred_rpo = i;
4018 FOR_EACH_EDGE (e, ei, bb->preds)
4020 int pred = e->src->index;
4021 if ((e->flags & EDGE_DFS_BACK) || pred == ENTRY_BLOCK)
4022 continue;
4024 if (!live[pred])
4026 live[pred] = sbitmap_alloc (num_ssa_names);
4027 bitmap_clear (live[pred]);
4029 bitmap_ior (live[pred], live[pred], live[rpo[i]]);
4031 if (bb_rpo[pred] < pred_rpo)
4032 pred_rpo = bb_rpo[pred];
4035 /* Record the RPO number of the last visited block that needs
4036 live information from this block. */
4037 last_rpo[rpo[i]] = pred_rpo;
4039 else
4041 sbitmap_free (live[rpo[i]]);
4042 live[rpo[i]] = NULL;
4045 /* We can free all successors live bitmaps if all their
4046 predecessors have been visited already. */
4047 FOR_EACH_EDGE (e, ei, bb->succs)
4048 if (last_rpo[e->dest->index] == i
4049 && live[e->dest->index])
4051 sbitmap_free (live[e->dest->index]);
4052 live[e->dest->index] = NULL;
4056 XDELETEVEC (rpo);
4057 XDELETEVEC (bb_rpo);
4058 XDELETEVEC (last_rpo);
4059 for (i = 0; i < last_basic_block_for_fn (cfun); ++i)
4060 if (live[i])
4061 sbitmap_free (live[i]);
4062 XDELETEVEC (live);
4065 /* Create an ASSERT_EXPR for NAME and insert it in the location
4066 indicated by LOC. Return true if we made any edge insertions. */
4068 static bool
4069 process_assert_insertions_for (tree name, assert_locus *loc)
4071 /* Build the comparison expression NAME_i COMP_CODE VAL. */
4072 gimple *stmt;
4073 tree cond;
4074 gimple *assert_stmt;
4075 edge_iterator ei;
4076 edge e;
4078 /* If we have X <=> X do not insert an assert expr for that. */
4079 if (loc->expr == loc->val)
4080 return false;
4082 cond = build2 (loc->comp_code, boolean_type_node, loc->expr, loc->val);
4083 assert_stmt = build_assert_expr_for (cond, name);
4084 if (loc->e)
4086 /* We have been asked to insert the assertion on an edge. This
4087 is used only by COND_EXPR and SWITCH_EXPR assertions. */
4088 gcc_checking_assert (gimple_code (gsi_stmt (loc->si)) == GIMPLE_COND
4089 || (gimple_code (gsi_stmt (loc->si))
4090 == GIMPLE_SWITCH));
4092 gsi_insert_on_edge (loc->e, assert_stmt);
4093 return true;
4096 /* If the stmt iterator points at the end then this is an insertion
4097 at the beginning of a block. */
4098 if (gsi_end_p (loc->si))
4100 gimple_stmt_iterator si = gsi_after_labels (loc->bb);
4101 gsi_insert_before (&si, assert_stmt, GSI_SAME_STMT);
4102 return false;
4105 /* Otherwise, we can insert right after LOC->SI iff the
4106 statement must not be the last statement in the block. */
4107 stmt = gsi_stmt (loc->si);
4108 if (!stmt_ends_bb_p (stmt))
4110 gsi_insert_after (&loc->si, assert_stmt, GSI_SAME_STMT);
4111 return false;
4114 /* If STMT must be the last statement in BB, we can only insert new
4115 assertions on the non-abnormal edge out of BB. Note that since
4116 STMT is not control flow, there may only be one non-abnormal/eh edge
4117 out of BB. */
4118 FOR_EACH_EDGE (e, ei, loc->bb->succs)
4119 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
4121 gsi_insert_on_edge (e, assert_stmt);
4122 return true;
4125 gcc_unreachable ();
4128 /* Qsort helper for sorting assert locations. If stable is true, don't
4129 use iterative_hash_expr because it can be unstable for -fcompare-debug,
4130 on the other side some pointers might be NULL. */
4132 template <bool stable>
4133 static int
4134 compare_assert_loc (const void *pa, const void *pb)
4136 assert_locus * const a = *(assert_locus * const *)pa;
4137 assert_locus * const b = *(assert_locus * const *)pb;
4139 /* If stable, some asserts might be optimized away already, sort
4140 them last. */
4141 if (stable)
4143 if (a == NULL)
4144 return b != NULL;
4145 else if (b == NULL)
4146 return -1;
4149 if (a->e == NULL && b->e != NULL)
4150 return 1;
4151 else if (a->e != NULL && b->e == NULL)
4152 return -1;
4154 /* After the above checks, we know that (a->e == NULL) == (b->e == NULL),
4155 no need to test both a->e and b->e. */
4157 /* Sort after destination index. */
4158 if (a->e == NULL)
4160 else if (a->e->dest->index > b->e->dest->index)
4161 return 1;
4162 else if (a->e->dest->index < b->e->dest->index)
4163 return -1;
4165 /* Sort after comp_code. */
4166 if (a->comp_code > b->comp_code)
4167 return 1;
4168 else if (a->comp_code < b->comp_code)
4169 return -1;
4171 hashval_t ha, hb;
4173 /* E.g. if a->val is ADDR_EXPR of a VAR_DECL, iterative_hash_expr
4174 uses DECL_UID of the VAR_DECL, so sorting might differ between
4175 -g and -g0. When doing the removal of redundant assert exprs
4176 and commonization to successors, this does not matter, but for
4177 the final sort needs to be stable. */
4178 if (stable)
4180 ha = 0;
4181 hb = 0;
4183 else
4185 ha = iterative_hash_expr (a->expr, iterative_hash_expr (a->val, 0));
4186 hb = iterative_hash_expr (b->expr, iterative_hash_expr (b->val, 0));
4189 /* Break the tie using hashing and source/bb index. */
4190 if (ha == hb)
4191 return (a->e != NULL
4192 ? a->e->src->index - b->e->src->index
4193 : a->bb->index - b->bb->index);
4194 return ha > hb ? 1 : -1;
4197 /* Process all the insertions registered for every name N_i registered
4198 in NEED_ASSERT_FOR. The list of assertions to be inserted are
4199 found in ASSERTS_FOR[i]. */
4201 static void
4202 process_assert_insertions (void)
4204 unsigned i;
4205 bitmap_iterator bi;
4206 bool update_edges_p = false;
4207 int num_asserts = 0;
4209 if (dump_file && (dump_flags & TDF_DETAILS))
4210 dump_all_asserts (dump_file);
4212 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
4214 assert_locus *loc = asserts_for[i];
4215 gcc_assert (loc);
4217 auto_vec<assert_locus *, 16> asserts;
4218 for (; loc; loc = loc->next)
4219 asserts.safe_push (loc);
4220 asserts.qsort (compare_assert_loc<false>);
4222 /* Push down common asserts to successors and remove redundant ones. */
4223 unsigned ecnt = 0;
4224 assert_locus *common = NULL;
4225 unsigned commonj = 0;
4226 for (unsigned j = 0; j < asserts.length (); ++j)
4228 loc = asserts[j];
4229 if (! loc->e)
4230 common = NULL;
4231 else if (! common
4232 || loc->e->dest != common->e->dest
4233 || loc->comp_code != common->comp_code
4234 || ! operand_equal_p (loc->val, common->val, 0)
4235 || ! operand_equal_p (loc->expr, common->expr, 0))
4237 commonj = j;
4238 common = loc;
4239 ecnt = 1;
4241 else if (loc->e == asserts[j-1]->e)
4243 /* Remove duplicate asserts. */
4244 if (commonj == j - 1)
4246 commonj = j;
4247 common = loc;
4249 free (asserts[j-1]);
4250 asserts[j-1] = NULL;
4252 else
4254 ecnt++;
4255 if (EDGE_COUNT (common->e->dest->preds) == ecnt)
4257 /* We have the same assertion on all incoming edges of a BB.
4258 Insert it at the beginning of that block. */
4259 loc->bb = loc->e->dest;
4260 loc->e = NULL;
4261 loc->si = gsi_none ();
4262 common = NULL;
4263 /* Clear asserts commoned. */
4264 for (; commonj != j; ++commonj)
4265 if (asserts[commonj])
4267 free (asserts[commonj]);
4268 asserts[commonj] = NULL;
4274 /* The asserts vector sorting above might be unstable for
4275 -fcompare-debug, sort again to ensure a stable sort. */
4276 asserts.qsort (compare_assert_loc<true>);
4277 for (unsigned j = 0; j < asserts.length (); ++j)
4279 loc = asserts[j];
4280 if (! loc)
4281 break;
4282 update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
4283 num_asserts++;
4284 free (loc);
4288 if (update_edges_p)
4289 gsi_commit_edge_inserts ();
4291 statistics_counter_event (cfun, "Number of ASSERT_EXPR expressions inserted",
4292 num_asserts);
4296 /* Traverse the flowgraph looking for conditional jumps to insert range
4297 expressions. These range expressions are meant to provide information
4298 to optimizations that need to reason in terms of value ranges. They
4299 will not be expanded into RTL. For instance, given:
4301 x = ...
4302 y = ...
4303 if (x < y)
4304 y = x - 2;
4305 else
4306 x = y + 3;
4308 this pass will transform the code into:
4310 x = ...
4311 y = ...
4312 if (x < y)
4314 x = ASSERT_EXPR <x, x < y>
4315 y = x - 2
4317 else
4319 y = ASSERT_EXPR <y, x >= y>
4320 x = y + 3
4323 The idea is that once copy and constant propagation have run, other
4324 optimizations will be able to determine what ranges of values can 'x'
4325 take in different paths of the code, simply by checking the reaching
4326 definition of 'x'. */
4328 static void
4329 insert_range_assertions (void)
4331 need_assert_for = BITMAP_ALLOC (NULL);
4332 asserts_for = XCNEWVEC (assert_locus *, num_ssa_names);
4334 calculate_dominance_info (CDI_DOMINATORS);
4336 find_assert_locations ();
4337 if (!bitmap_empty_p (need_assert_for))
4339 process_assert_insertions ();
4340 update_ssa (TODO_update_ssa_no_phi);
4343 if (dump_file && (dump_flags & TDF_DETAILS))
4345 fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
4346 dump_function_to_file (current_function_decl, dump_file, dump_flags);
4349 free (asserts_for);
4350 BITMAP_FREE (need_assert_for);
4353 class vrp_prop : public ssa_propagation_engine
4355 public:
4356 enum ssa_prop_result visit_stmt (gimple *, edge *, tree *) FINAL OVERRIDE;
4357 enum ssa_prop_result visit_phi (gphi *) FINAL OVERRIDE;
4359 void vrp_initialize (void);
4360 void vrp_finalize (bool);
4361 void check_all_array_refs (void);
4362 void check_array_ref (location_t, tree, bool);
4363 void check_mem_ref (location_t, tree, bool);
4364 void search_for_addr_array (tree, location_t);
4366 class vr_values vr_values;
4367 /* Temporary delegator to minimize code churn. */
4368 value_range *get_value_range (const_tree op)
4369 { return vr_values.get_value_range (op); }
4370 void set_defs_to_varying (gimple *stmt)
4371 { return vr_values.set_defs_to_varying (stmt); }
4372 void extract_range_from_stmt (gimple *stmt, edge *taken_edge_p,
4373 tree *output_p, value_range *vr)
4374 { vr_values.extract_range_from_stmt (stmt, taken_edge_p, output_p, vr); }
4375 bool update_value_range (const_tree op, value_range *vr)
4376 { return vr_values.update_value_range (op, vr); }
4377 void extract_range_basic (value_range *vr, gimple *stmt)
4378 { vr_values.extract_range_basic (vr, stmt); }
4379 void extract_range_from_phi_node (gphi *phi, value_range *vr)
4380 { vr_values.extract_range_from_phi_node (phi, vr); }
4382 /* Checks one ARRAY_REF in REF, located at LOCUS. Ignores flexible arrays
4383 and "struct" hacks. If VRP can determine that the
4384 array subscript is a constant, check if it is outside valid
4385 range. If the array subscript is a RANGE, warn if it is
4386 non-overlapping with valid range.
4387 IGNORE_OFF_BY_ONE is true if the ARRAY_REF is inside a ADDR_EXPR. */
4389 void
4390 vrp_prop::check_array_ref (location_t location, tree ref,
4391 bool ignore_off_by_one)
4393 value_range *vr = NULL;
4394 tree low_sub, up_sub;
4395 tree low_bound, up_bound, up_bound_p1;
4397 if (TREE_NO_WARNING (ref))
4398 return;
4400 low_sub = up_sub = TREE_OPERAND (ref, 1);
4401 up_bound = array_ref_up_bound (ref);
4403 if (!up_bound
4404 || TREE_CODE (up_bound) != INTEGER_CST
4405 || (warn_array_bounds < 2
4406 && array_at_struct_end_p (ref)))
4408 /* Accesses to trailing arrays via pointers may access storage
4409 beyond the types array bounds. For such arrays, or for flexible
4410 array members, as well as for other arrays of an unknown size,
4411 replace the upper bound with a more permissive one that assumes
4412 the size of the largest object is PTRDIFF_MAX. */
4413 tree eltsize = array_ref_element_size (ref);
4415 if (TREE_CODE (eltsize) != INTEGER_CST
4416 || integer_zerop (eltsize))
4418 up_bound = NULL_TREE;
4419 up_bound_p1 = NULL_TREE;
4421 else
4423 tree maxbound = TYPE_MAX_VALUE (ptrdiff_type_node);
4424 tree arg = TREE_OPERAND (ref, 0);
4425 poly_int64 off;
4427 if (get_addr_base_and_unit_offset (arg, &off) && known_gt (off, 0))
4428 maxbound = wide_int_to_tree (sizetype,
4429 wi::sub (wi::to_wide (maxbound),
4430 off));
4431 else
4432 maxbound = fold_convert (sizetype, maxbound);
4434 up_bound_p1 = int_const_binop (TRUNC_DIV_EXPR, maxbound, eltsize);
4436 up_bound = int_const_binop (MINUS_EXPR, up_bound_p1,
4437 build_int_cst (ptrdiff_type_node, 1));
4440 else
4441 up_bound_p1 = int_const_binop (PLUS_EXPR, up_bound,
4442 build_int_cst (TREE_TYPE (up_bound), 1));
4444 low_bound = array_ref_low_bound (ref);
4446 tree artype = TREE_TYPE (TREE_OPERAND (ref, 0));
4448 bool warned = false;
4450 /* Empty array. */
4451 if (up_bound && tree_int_cst_equal (low_bound, up_bound_p1))
4452 warned = warning_at (location, OPT_Warray_bounds,
4453 "array subscript %E is above array bounds of %qT",
4454 low_bound, artype);
4456 if (TREE_CODE (low_sub) == SSA_NAME)
4458 vr = get_value_range (low_sub);
4459 if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
4461 low_sub = vr->type == VR_RANGE ? vr->max : vr->min;
4462 up_sub = vr->type == VR_RANGE ? vr->min : vr->max;
4466 if (vr && vr->type == VR_ANTI_RANGE)
4468 if (up_bound
4469 && TREE_CODE (up_sub) == INTEGER_CST
4470 && (ignore_off_by_one
4471 ? tree_int_cst_lt (up_bound, up_sub)
4472 : tree_int_cst_le (up_bound, up_sub))
4473 && TREE_CODE (low_sub) == INTEGER_CST
4474 && tree_int_cst_le (low_sub, low_bound))
4475 warned = warning_at (location, OPT_Warray_bounds,
4476 "array subscript [%E, %E] is outside "
4477 "array bounds of %qT",
4478 low_sub, up_sub, artype);
4480 else if (up_bound
4481 && TREE_CODE (up_sub) == INTEGER_CST
4482 && (ignore_off_by_one
4483 ? !tree_int_cst_le (up_sub, up_bound_p1)
4484 : !tree_int_cst_le (up_sub, up_bound)))
4486 if (dump_file && (dump_flags & TDF_DETAILS))
4488 fprintf (dump_file, "Array bound warning for ");
4489 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
4490 fprintf (dump_file, "\n");
4492 warned = warning_at (location, OPT_Warray_bounds,
4493 "array subscript %E is above array bounds of %qT",
4494 up_sub, artype);
4496 else if (TREE_CODE (low_sub) == INTEGER_CST
4497 && tree_int_cst_lt (low_sub, low_bound))
4499 if (dump_file && (dump_flags & TDF_DETAILS))
4501 fprintf (dump_file, "Array bound warning for ");
4502 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
4503 fprintf (dump_file, "\n");
4505 warned = warning_at (location, OPT_Warray_bounds,
4506 "array subscript %E is below array bounds of %qT",
4507 low_sub, artype);
4510 if (warned)
4512 ref = TREE_OPERAND (ref, 0);
4514 if (DECL_P (ref))
4515 inform (DECL_SOURCE_LOCATION (ref), "while referencing %qD", ref);
4517 TREE_NO_WARNING (ref) = 1;
4521 /* Checks one MEM_REF in REF, located at LOCATION, for out-of-bounds
4522 references to string constants. If VRP can determine that the array
4523 subscript is a constant, check if it is outside valid range.
4524 If the array subscript is a RANGE, warn if it is non-overlapping
4525 with valid range.
4526 IGNORE_OFF_BY_ONE is true if the MEM_REF is inside an ADDR_EXPR
4527 (used to allow one-past-the-end indices for code that takes
4528 the address of the just-past-the-end element of an array). */
4530 void
4531 vrp_prop::check_mem_ref (location_t location, tree ref,
4532 bool ignore_off_by_one)
4534 if (TREE_NO_WARNING (ref))
4535 return;
4537 tree arg = TREE_OPERAND (ref, 0);
4538 /* The constant and variable offset of the reference. */
4539 tree cstoff = TREE_OPERAND (ref, 1);
4540 tree varoff = NULL_TREE;
4542 const offset_int maxobjsize = tree_to_shwi (max_object_size ());
4544 /* The array or string constant bounds in bytes. Initially set
4545 to [-MAXOBJSIZE - 1, MAXOBJSIZE] until a tighter bound is
4546 determined. */
4547 offset_int arrbounds[2] = { -maxobjsize - 1, maxobjsize };
4549 /* The minimum and maximum intermediate offset. For a reference
4550 to be valid, not only does the final offset/subscript must be
4551 in bounds but all intermediate offsets should be as well.
4552 GCC may be able to deal gracefully with such out-of-bounds
4553 offsets so the checking is only enbaled at -Warray-bounds=2
4554 where it may help detect bugs in uses of the intermediate
4555 offsets that could otherwise not be detectable. */
4556 offset_int ioff = wi::to_offset (fold_convert (ptrdiff_type_node, cstoff));
4557 offset_int extrema[2] = { 0, wi::abs (ioff) };
4559 /* The range of the byte offset into the reference. */
4560 offset_int offrange[2] = { 0, 0 };
4562 value_range *vr = NULL;
4564 /* Determine the offsets and increment OFFRANGE for the bounds of each.
4565 The loop computes the the range of the final offset for expressions
4566 such as (A + i0 + ... + iN)[CSTOFF] where i0 through iN are SSA_NAMEs
4567 in some range. */
4568 while (TREE_CODE (arg) == SSA_NAME)
4570 gimple *def = SSA_NAME_DEF_STMT (arg);
4571 if (!is_gimple_assign (def))
4572 break;
4574 tree_code code = gimple_assign_rhs_code (def);
4575 if (code == POINTER_PLUS_EXPR)
4577 arg = gimple_assign_rhs1 (def);
4578 varoff = gimple_assign_rhs2 (def);
4580 else if (code == ASSERT_EXPR)
4582 arg = TREE_OPERAND (gimple_assign_rhs1 (def), 0);
4583 continue;
4585 else
4586 return;
4588 /* VAROFF should always be a SSA_NAME here (and not even
4589 INTEGER_CST) but there's no point in taking chances. */
4590 if (TREE_CODE (varoff) != SSA_NAME)
4591 break;
4593 vr = get_value_range (varoff);
4594 if (!vr || vr->type == VR_UNDEFINED || !vr->min || !vr->max)
4595 break;
4597 if (TREE_CODE (vr->min) != INTEGER_CST
4598 || TREE_CODE (vr->max) != INTEGER_CST)
4599 break;
4601 if (vr->type == VR_RANGE)
4603 if (tree_int_cst_lt (vr->min, vr->max))
4605 offset_int min
4606 = wi::to_offset (fold_convert (ptrdiff_type_node, vr->min));
4607 offset_int max
4608 = wi::to_offset (fold_convert (ptrdiff_type_node, vr->max));
4609 if (min < max)
4611 offrange[0] += min;
4612 offrange[1] += max;
4614 else
4616 offrange[0] += max;
4617 offrange[1] += min;
4620 else
4622 /* Conservatively add [-MAXOBJSIZE -1, MAXOBJSIZE]
4623 to OFFRANGE. */
4624 offrange[0] += arrbounds[0];
4625 offrange[1] += arrbounds[1];
4628 else
4630 /* For an anti-range, analogously to the above, conservatively
4631 add [-MAXOBJSIZE -1, MAXOBJSIZE] to OFFRANGE. */
4632 offrange[0] += arrbounds[0];
4633 offrange[1] += arrbounds[1];
4636 /* Keep track of the minimum and maximum offset. */
4637 if (offrange[1] < 0 && offrange[1] < extrema[0])
4638 extrema[0] = offrange[1];
4639 if (offrange[0] > 0 && offrange[0] > extrema[1])
4640 extrema[1] = offrange[0];
4642 if (offrange[0] < arrbounds[0])
4643 offrange[0] = arrbounds[0];
4645 if (offrange[1] > arrbounds[1])
4646 offrange[1] = arrbounds[1];
4649 if (TREE_CODE (arg) == ADDR_EXPR)
4651 arg = TREE_OPERAND (arg, 0);
4652 if (TREE_CODE (arg) != STRING_CST
4653 && TREE_CODE (arg) != VAR_DECL)
4654 return;
4656 else
4657 return;
4659 /* The type of the object being referred to. It can be an array,
4660 string literal, or a non-array type when the MEM_REF represents
4661 a reference/subscript via a pointer to an object that is not
4662 an element of an array. References to members of structs and
4663 unions are excluded because MEM_REF doesn't make it possible
4664 to identify the member where the reference originated.
4665 Incomplete types are excluded as well because their size is
4666 not known. */
4667 tree reftype = TREE_TYPE (arg);
4668 if (POINTER_TYPE_P (reftype)
4669 || !COMPLETE_TYPE_P (reftype)
4670 || RECORD_OR_UNION_TYPE_P (reftype))
4671 return;
4673 offset_int eltsize;
4674 if (TREE_CODE (reftype) == ARRAY_TYPE)
4676 eltsize = wi::to_offset (TYPE_SIZE_UNIT (TREE_TYPE (reftype)));
4678 if (tree dom = TYPE_DOMAIN (reftype))
4680 tree bnds[] = { TYPE_MIN_VALUE (dom), TYPE_MAX_VALUE (dom) };
4681 if (array_at_struct_end_p (arg)
4682 || !bnds[0] || !bnds[1])
4684 arrbounds[0] = 0;
4685 arrbounds[1] = wi::lrshift (maxobjsize, wi::floor_log2 (eltsize));
4687 else
4689 arrbounds[0] = wi::to_offset (bnds[0]) * eltsize;
4690 arrbounds[1] = (wi::to_offset (bnds[1]) + 1) * eltsize;
4693 else
4695 arrbounds[0] = 0;
4696 arrbounds[1] = wi::lrshift (maxobjsize, wi::floor_log2 (eltsize));
4699 if (TREE_CODE (ref) == MEM_REF)
4701 /* For MEM_REF determine a tighter bound of the non-array
4702 element type. */
4703 tree eltype = TREE_TYPE (reftype);
4704 while (TREE_CODE (eltype) == ARRAY_TYPE)
4705 eltype = TREE_TYPE (eltype);
4706 eltsize = wi::to_offset (TYPE_SIZE_UNIT (eltype));
4709 else
4711 eltsize = 1;
4712 arrbounds[0] = 0;
4713 arrbounds[1] = wi::to_offset (TYPE_SIZE_UNIT (reftype));
4716 offrange[0] += ioff;
4717 offrange[1] += ioff;
4719 /* Compute the more permissive upper bound when IGNORE_OFF_BY_ONE
4720 is set (when taking the address of the one-past-last element
4721 of an array) but always use the stricter bound in diagnostics. */
4722 offset_int ubound = arrbounds[1];
4723 if (ignore_off_by_one)
4724 ubound += 1;
4726 if (offrange[0] >= ubound || offrange[1] < arrbounds[0])
4728 /* Treat a reference to a non-array object as one to an array
4729 of a single element. */
4730 if (TREE_CODE (reftype) != ARRAY_TYPE)
4731 reftype = build_array_type_nelts (reftype, 1);
4733 if (TREE_CODE (ref) == MEM_REF)
4735 /* Extract the element type out of MEM_REF and use its size
4736 to compute the index to print in the diagnostic; arrays
4737 in MEM_REF don't mean anything. */
4738 tree type = TREE_TYPE (ref);
4739 while (TREE_CODE (type) == ARRAY_TYPE)
4740 type = TREE_TYPE (type);
4741 tree size = TYPE_SIZE_UNIT (type);
4742 offrange[0] = offrange[0] / wi::to_offset (size);
4743 offrange[1] = offrange[1] / wi::to_offset (size);
4745 else
4747 /* For anything other than MEM_REF, compute the index to
4748 print in the diagnostic as the offset over element size. */
4749 offrange[0] = offrange[0] / eltsize;
4750 offrange[1] = offrange[1] / eltsize;
4753 bool warned;
4754 if (offrange[0] == offrange[1])
4755 warned = warning_at (location, OPT_Warray_bounds,
4756 "array subscript %wi is outside array bounds "
4757 "of %qT",
4758 offrange[0].to_shwi (), reftype);
4759 else
4760 warned = warning_at (location, OPT_Warray_bounds,
4761 "array subscript [%wi, %wi] is outside "
4762 "array bounds of %qT",
4763 offrange[0].to_shwi (),
4764 offrange[1].to_shwi (), reftype);
4765 if (warned && DECL_P (arg))
4766 inform (DECL_SOURCE_LOCATION (arg), "while referencing %qD", arg);
4768 TREE_NO_WARNING (ref) = 1;
4769 return;
4772 if (warn_array_bounds < 2)
4773 return;
4775 /* At level 2 check also intermediate offsets. */
4776 int i = 0;
4777 if (extrema[i] < -arrbounds[1] || extrema[i = 1] > ubound)
4779 HOST_WIDE_INT tmpidx = extrema[i].to_shwi () / eltsize.to_shwi ();
4781 warning_at (location, OPT_Warray_bounds,
4782 "intermediate array offset %wi is outside array bounds "
4783 "of %qT",
4784 tmpidx, reftype);
4785 TREE_NO_WARNING (ref) = 1;
4789 /* Searches if the expr T, located at LOCATION computes
4790 address of an ARRAY_REF, and call check_array_ref on it. */
4792 void
4793 vrp_prop::search_for_addr_array (tree t, location_t location)
4795 /* Check each ARRAY_REF and MEM_REF in the reference chain. */
4798 if (TREE_CODE (t) == ARRAY_REF)
4799 check_array_ref (location, t, true /*ignore_off_by_one*/);
4800 else if (TREE_CODE (t) == MEM_REF)
4801 check_mem_ref (location, t, true /*ignore_off_by_one*/);
4803 t = TREE_OPERAND (t, 0);
4805 while (handled_component_p (t) || TREE_CODE (t) == MEM_REF);
4807 if (TREE_CODE (t) != MEM_REF
4808 || TREE_CODE (TREE_OPERAND (t, 0)) != ADDR_EXPR
4809 || TREE_NO_WARNING (t))
4810 return;
4812 tree tem = TREE_OPERAND (TREE_OPERAND (t, 0), 0);
4813 tree low_bound, up_bound, el_sz;
4814 if (TREE_CODE (TREE_TYPE (tem)) != ARRAY_TYPE
4815 || TREE_CODE (TREE_TYPE (TREE_TYPE (tem))) == ARRAY_TYPE
4816 || !TYPE_DOMAIN (TREE_TYPE (tem)))
4817 return;
4819 low_bound = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
4820 up_bound = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
4821 el_sz = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (tem)));
4822 if (!low_bound
4823 || TREE_CODE (low_bound) != INTEGER_CST
4824 || !up_bound
4825 || TREE_CODE (up_bound) != INTEGER_CST
4826 || !el_sz
4827 || TREE_CODE (el_sz) != INTEGER_CST)
4828 return;
4830 offset_int idx;
4831 if (!mem_ref_offset (t).is_constant (&idx))
4832 return;
4834 bool warned = false;
4835 idx = wi::sdiv_trunc (idx, wi::to_offset (el_sz));
4836 if (idx < 0)
4838 if (dump_file && (dump_flags & TDF_DETAILS))
4840 fprintf (dump_file, "Array bound warning for ");
4841 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
4842 fprintf (dump_file, "\n");
4844 warned = warning_at (location, OPT_Warray_bounds,
4845 "array subscript %wi is below "
4846 "array bounds of %qT",
4847 idx.to_shwi (), TREE_TYPE (tem));
4849 else if (idx > (wi::to_offset (up_bound)
4850 - wi::to_offset (low_bound) + 1))
4852 if (dump_file && (dump_flags & TDF_DETAILS))
4854 fprintf (dump_file, "Array bound warning for ");
4855 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
4856 fprintf (dump_file, "\n");
4858 warned = warning_at (location, OPT_Warray_bounds,
4859 "array subscript %wu is above "
4860 "array bounds of %qT",
4861 idx.to_uhwi (), TREE_TYPE (tem));
4864 if (warned)
4866 if (DECL_P (t))
4867 inform (DECL_SOURCE_LOCATION (t), "while referencing %qD", t);
4869 TREE_NO_WARNING (t) = 1;
4873 /* walk_tree() callback that checks if *TP is
4874 an ARRAY_REF inside an ADDR_EXPR (in which an array
4875 subscript one outside the valid range is allowed). Call
4876 check_array_ref for each ARRAY_REF found. The location is
4877 passed in DATA. */
4879 static tree
4880 check_array_bounds (tree *tp, int *walk_subtree, void *data)
4882 tree t = *tp;
4883 struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
4884 location_t location;
4886 if (EXPR_HAS_LOCATION (t))
4887 location = EXPR_LOCATION (t);
4888 else
4889 location = gimple_location (wi->stmt);
4891 *walk_subtree = TRUE;
4893 vrp_prop *vrp_prop = (class vrp_prop *)wi->info;
4894 if (TREE_CODE (t) == ARRAY_REF)
4895 vrp_prop->check_array_ref (location, t, false /*ignore_off_by_one*/);
4896 else if (TREE_CODE (t) == MEM_REF)
4897 vrp_prop->check_mem_ref (location, t, false /*ignore_off_by_one*/);
4898 else if (TREE_CODE (t) == ADDR_EXPR)
4900 vrp_prop->search_for_addr_array (t, location);
4901 *walk_subtree = FALSE;
4904 return NULL_TREE;
4907 /* A dom_walker subclass for use by vrp_prop::check_all_array_refs,
4908 to walk over all statements of all reachable BBs and call
4909 check_array_bounds on them. */
4911 class check_array_bounds_dom_walker : public dom_walker
4913 public:
4914 check_array_bounds_dom_walker (vrp_prop *prop)
4915 : dom_walker (CDI_DOMINATORS,
4916 /* Discover non-executable edges, preserving EDGE_EXECUTABLE
4917 flags, so that we can merge in information on
4918 non-executable edges from vrp_folder . */
4919 REACHABLE_BLOCKS_PRESERVING_FLAGS),
4920 m_prop (prop) {}
4921 ~check_array_bounds_dom_walker () {}
4923 edge before_dom_children (basic_block) FINAL OVERRIDE;
4925 private:
4926 vrp_prop *m_prop;
4929 /* Implementation of dom_walker::before_dom_children.
4931 Walk over all statements of BB and call check_array_bounds on them,
4932 and determine if there's a unique successor edge. */
4934 edge
4935 check_array_bounds_dom_walker::before_dom_children (basic_block bb)
4937 gimple_stmt_iterator si;
4938 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
4940 gimple *stmt = gsi_stmt (si);
4941 struct walk_stmt_info wi;
4942 if (!gimple_has_location (stmt)
4943 || is_gimple_debug (stmt))
4944 continue;
4946 memset (&wi, 0, sizeof (wi));
4948 wi.info = m_prop;
4950 walk_gimple_op (stmt, check_array_bounds, &wi);
4953 /* Determine if there's a unique successor edge, and if so, return
4954 that back to dom_walker, ensuring that we don't visit blocks that
4955 became unreachable during the VRP propagation
4956 (PR tree-optimization/83312). */
4957 return find_taken_edge (bb, NULL_TREE);
4960 /* Walk over all statements of all reachable BBs and call check_array_bounds
4961 on them. */
4963 void
4964 vrp_prop::check_all_array_refs ()
4966 check_array_bounds_dom_walker w (this);
4967 w.walk (ENTRY_BLOCK_PTR_FOR_FN (cfun));
4970 /* Return true if all imm uses of VAR are either in STMT, or
4971 feed (optionally through a chain of single imm uses) GIMPLE_COND
4972 in basic block COND_BB. */
4974 static bool
4975 all_imm_uses_in_stmt_or_feed_cond (tree var, gimple *stmt, basic_block cond_bb)
4977 use_operand_p use_p, use2_p;
4978 imm_use_iterator iter;
4980 FOR_EACH_IMM_USE_FAST (use_p, iter, var)
4981 if (USE_STMT (use_p) != stmt)
4983 gimple *use_stmt = USE_STMT (use_p), *use_stmt2;
4984 if (is_gimple_debug (use_stmt))
4985 continue;
4986 while (is_gimple_assign (use_stmt)
4987 && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
4988 && single_imm_use (gimple_assign_lhs (use_stmt),
4989 &use2_p, &use_stmt2))
4990 use_stmt = use_stmt2;
4991 if (gimple_code (use_stmt) != GIMPLE_COND
4992 || gimple_bb (use_stmt) != cond_bb)
4993 return false;
4995 return true;
4998 /* Handle
4999 _4 = x_3 & 31;
5000 if (_4 != 0)
5001 goto <bb 6>;
5002 else
5003 goto <bb 7>;
5004 <bb 6>:
5005 __builtin_unreachable ();
5006 <bb 7>:
5007 x_5 = ASSERT_EXPR <x_3, ...>;
5008 If x_3 has no other immediate uses (checked by caller),
5009 var is the x_3 var from ASSERT_EXPR, we can clear low 5 bits
5010 from the non-zero bitmask. */
5012 void
5013 maybe_set_nonzero_bits (edge e, tree var)
5015 basic_block cond_bb = e->src;
5016 gimple *stmt = last_stmt (cond_bb);
5017 tree cst;
5019 if (stmt == NULL
5020 || gimple_code (stmt) != GIMPLE_COND
5021 || gimple_cond_code (stmt) != ((e->flags & EDGE_TRUE_VALUE)
5022 ? EQ_EXPR : NE_EXPR)
5023 || TREE_CODE (gimple_cond_lhs (stmt)) != SSA_NAME
5024 || !integer_zerop (gimple_cond_rhs (stmt)))
5025 return;
5027 stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt));
5028 if (!is_gimple_assign (stmt)
5029 || gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
5030 || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
5031 return;
5032 if (gimple_assign_rhs1 (stmt) != var)
5034 gimple *stmt2;
5036 if (TREE_CODE (gimple_assign_rhs1 (stmt)) != SSA_NAME)
5037 return;
5038 stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
5039 if (!gimple_assign_cast_p (stmt2)
5040 || gimple_assign_rhs1 (stmt2) != var
5041 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt2))
5042 || (TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (stmt)))
5043 != TYPE_PRECISION (TREE_TYPE (var))))
5044 return;
5046 cst = gimple_assign_rhs2 (stmt);
5047 set_nonzero_bits (var, wi::bit_and_not (get_nonzero_bits (var),
5048 wi::to_wide (cst)));
5051 /* Convert range assertion expressions into the implied copies and
5052 copy propagate away the copies. Doing the trivial copy propagation
5053 here avoids the need to run the full copy propagation pass after
5054 VRP.
5056 FIXME, this will eventually lead to copy propagation removing the
5057 names that had useful range information attached to them. For
5058 instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
5059 then N_i will have the range [3, +INF].
5061 However, by converting the assertion into the implied copy
5062 operation N_i = N_j, we will then copy-propagate N_j into the uses
5063 of N_i and lose the range information. We may want to hold on to
5064 ASSERT_EXPRs a little while longer as the ranges could be used in
5065 things like jump threading.
5067 The problem with keeping ASSERT_EXPRs around is that passes after
5068 VRP need to handle them appropriately.
5070 Another approach would be to make the range information a first
5071 class property of the SSA_NAME so that it can be queried from
5072 any pass. This is made somewhat more complex by the need for
5073 multiple ranges to be associated with one SSA_NAME. */
5075 static void
5076 remove_range_assertions (void)
5078 basic_block bb;
5079 gimple_stmt_iterator si;
5080 /* 1 if looking at ASSERT_EXPRs immediately at the beginning of
5081 a basic block preceeded by GIMPLE_COND branching to it and
5082 __builtin_trap, -1 if not yet checked, 0 otherwise. */
5083 int is_unreachable;
5085 /* Note that the BSI iterator bump happens at the bottom of the
5086 loop and no bump is necessary if we're removing the statement
5087 referenced by the current BSI. */
5088 FOR_EACH_BB_FN (bb, cfun)
5089 for (si = gsi_after_labels (bb), is_unreachable = -1; !gsi_end_p (si);)
5091 gimple *stmt = gsi_stmt (si);
5093 if (is_gimple_assign (stmt)
5094 && gimple_assign_rhs_code (stmt) == ASSERT_EXPR)
5096 tree lhs = gimple_assign_lhs (stmt);
5097 tree rhs = gimple_assign_rhs1 (stmt);
5098 tree var;
5100 var = ASSERT_EXPR_VAR (rhs);
5102 if (TREE_CODE (var) == SSA_NAME
5103 && !POINTER_TYPE_P (TREE_TYPE (lhs))
5104 && SSA_NAME_RANGE_INFO (lhs))
5106 if (is_unreachable == -1)
5108 is_unreachable = 0;
5109 if (single_pred_p (bb)
5110 && assert_unreachable_fallthru_edge_p
5111 (single_pred_edge (bb)))
5112 is_unreachable = 1;
5114 /* Handle
5115 if (x_7 >= 10 && x_7 < 20)
5116 __builtin_unreachable ();
5117 x_8 = ASSERT_EXPR <x_7, ...>;
5118 if the only uses of x_7 are in the ASSERT_EXPR and
5119 in the condition. In that case, we can copy the
5120 range info from x_8 computed in this pass also
5121 for x_7. */
5122 if (is_unreachable
5123 && all_imm_uses_in_stmt_or_feed_cond (var, stmt,
5124 single_pred (bb)))
5126 set_range_info (var, SSA_NAME_RANGE_TYPE (lhs),
5127 SSA_NAME_RANGE_INFO (lhs)->get_min (),
5128 SSA_NAME_RANGE_INFO (lhs)->get_max ());
5129 maybe_set_nonzero_bits (single_pred_edge (bb), var);
5133 /* Propagate the RHS into every use of the LHS. For SSA names
5134 also propagate abnormals as it merely restores the original
5135 IL in this case (an replace_uses_by would assert). */
5136 if (TREE_CODE (var) == SSA_NAME)
5138 imm_use_iterator iter;
5139 use_operand_p use_p;
5140 gimple *use_stmt;
5141 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
5142 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
5143 SET_USE (use_p, var);
5145 else
5146 replace_uses_by (lhs, var);
5148 /* And finally, remove the copy, it is not needed. */
5149 gsi_remove (&si, true);
5150 release_defs (stmt);
5152 else
5154 if (!is_gimple_debug (gsi_stmt (si)))
5155 is_unreachable = 0;
5156 gsi_next (&si);
5161 /* Return true if STMT is interesting for VRP. */
5163 bool
5164 stmt_interesting_for_vrp (gimple *stmt)
5166 if (gimple_code (stmt) == GIMPLE_PHI)
5168 tree res = gimple_phi_result (stmt);
5169 return (!virtual_operand_p (res)
5170 && (INTEGRAL_TYPE_P (TREE_TYPE (res))
5171 || POINTER_TYPE_P (TREE_TYPE (res))));
5173 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
5175 tree lhs = gimple_get_lhs (stmt);
5177 /* In general, assignments with virtual operands are not useful
5178 for deriving ranges, with the obvious exception of calls to
5179 builtin functions. */
5180 if (lhs && TREE_CODE (lhs) == SSA_NAME
5181 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
5182 || POINTER_TYPE_P (TREE_TYPE (lhs)))
5183 && (is_gimple_call (stmt)
5184 || !gimple_vuse (stmt)))
5185 return true;
5186 else if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
5187 switch (gimple_call_internal_fn (stmt))
5189 case IFN_ADD_OVERFLOW:
5190 case IFN_SUB_OVERFLOW:
5191 case IFN_MUL_OVERFLOW:
5192 case IFN_ATOMIC_COMPARE_EXCHANGE:
5193 /* These internal calls return _Complex integer type,
5194 but are interesting to VRP nevertheless. */
5195 if (lhs && TREE_CODE (lhs) == SSA_NAME)
5196 return true;
5197 break;
5198 default:
5199 break;
5202 else if (gimple_code (stmt) == GIMPLE_COND
5203 || gimple_code (stmt) == GIMPLE_SWITCH)
5204 return true;
5206 return false;
5209 /* Initialization required by ssa_propagate engine. */
5211 void
5212 vrp_prop::vrp_initialize ()
5214 basic_block bb;
5216 FOR_EACH_BB_FN (bb, cfun)
5218 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
5219 gsi_next (&si))
5221 gphi *phi = si.phi ();
5222 if (!stmt_interesting_for_vrp (phi))
5224 tree lhs = PHI_RESULT (phi);
5225 set_value_range_to_varying (get_value_range (lhs));
5226 prop_set_simulate_again (phi, false);
5228 else
5229 prop_set_simulate_again (phi, true);
5232 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
5233 gsi_next (&si))
5235 gimple *stmt = gsi_stmt (si);
5237 /* If the statement is a control insn, then we do not
5238 want to avoid simulating the statement once. Failure
5239 to do so means that those edges will never get added. */
5240 if (stmt_ends_bb_p (stmt))
5241 prop_set_simulate_again (stmt, true);
5242 else if (!stmt_interesting_for_vrp (stmt))
5244 set_defs_to_varying (stmt);
5245 prop_set_simulate_again (stmt, false);
5247 else
5248 prop_set_simulate_again (stmt, true);
5253 /* Searches the case label vector VEC for the index *IDX of the CASE_LABEL
5254 that includes the value VAL. The search is restricted to the range
5255 [START_IDX, n - 1] where n is the size of VEC.
5257 If there is a CASE_LABEL for VAL, its index is placed in IDX and true is
5258 returned.
5260 If there is no CASE_LABEL for VAL and there is one that is larger than VAL,
5261 it is placed in IDX and false is returned.
5263 If VAL is larger than any CASE_LABEL, n is placed on IDX and false is
5264 returned. */
5266 bool
5267 find_case_label_index (gswitch *stmt, size_t start_idx, tree val, size_t *idx)
5269 size_t n = gimple_switch_num_labels (stmt);
5270 size_t low, high;
5272 /* Find case label for minimum of the value range or the next one.
5273 At each iteration we are searching in [low, high - 1]. */
5275 for (low = start_idx, high = n; high != low; )
5277 tree t;
5278 int cmp;
5279 /* Note that i != high, so we never ask for n. */
5280 size_t i = (high + low) / 2;
5281 t = gimple_switch_label (stmt, i);
5283 /* Cache the result of comparing CASE_LOW and val. */
5284 cmp = tree_int_cst_compare (CASE_LOW (t), val);
5286 if (cmp == 0)
5288 /* Ranges cannot be empty. */
5289 *idx = i;
5290 return true;
5292 else if (cmp > 0)
5293 high = i;
5294 else
5296 low = i + 1;
5297 if (CASE_HIGH (t) != NULL
5298 && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
5300 *idx = i;
5301 return true;
5306 *idx = high;
5307 return false;
5310 /* Searches the case label vector VEC for the range of CASE_LABELs that is used
5311 for values between MIN and MAX. The first index is placed in MIN_IDX. The
5312 last index is placed in MAX_IDX. If the range of CASE_LABELs is empty
5313 then MAX_IDX < MIN_IDX.
5314 Returns true if the default label is not needed. */
5316 bool
5317 find_case_label_range (gswitch *stmt, tree min, tree max, size_t *min_idx,
5318 size_t *max_idx)
5320 size_t i, j;
5321 bool min_take_default = !find_case_label_index (stmt, 1, min, &i);
5322 bool max_take_default = !find_case_label_index (stmt, i, max, &j);
5324 if (i == j
5325 && min_take_default
5326 && max_take_default)
5328 /* Only the default case label reached.
5329 Return an empty range. */
5330 *min_idx = 1;
5331 *max_idx = 0;
5332 return false;
5334 else
5336 bool take_default = min_take_default || max_take_default;
5337 tree low, high;
5338 size_t k;
5340 if (max_take_default)
5341 j--;
5343 /* If the case label range is continuous, we do not need
5344 the default case label. Verify that. */
5345 high = CASE_LOW (gimple_switch_label (stmt, i));
5346 if (CASE_HIGH (gimple_switch_label (stmt, i)))
5347 high = CASE_HIGH (gimple_switch_label (stmt, i));
5348 for (k = i + 1; k <= j; ++k)
5350 low = CASE_LOW (gimple_switch_label (stmt, k));
5351 if (!integer_onep (int_const_binop (MINUS_EXPR, low, high)))
5353 take_default = true;
5354 break;
5356 high = low;
5357 if (CASE_HIGH (gimple_switch_label (stmt, k)))
5358 high = CASE_HIGH (gimple_switch_label (stmt, k));
5361 *min_idx = i;
5362 *max_idx = j;
5363 return !take_default;
5367 /* Evaluate statement STMT. If the statement produces a useful range,
5368 return SSA_PROP_INTERESTING and record the SSA name with the
5369 interesting range into *OUTPUT_P.
5371 If STMT is a conditional branch and we can determine its truth
5372 value, the taken edge is recorded in *TAKEN_EDGE_P.
5374 If STMT produces a varying value, return SSA_PROP_VARYING. */
5376 enum ssa_prop_result
5377 vrp_prop::visit_stmt (gimple *stmt, edge *taken_edge_p, tree *output_p)
5379 value_range vr = VR_INITIALIZER;
5380 tree lhs = gimple_get_lhs (stmt);
5381 extract_range_from_stmt (stmt, taken_edge_p, output_p, &vr);
5383 if (*output_p)
5385 if (update_value_range (*output_p, &vr))
5387 if (dump_file && (dump_flags & TDF_DETAILS))
5389 fprintf (dump_file, "Found new range for ");
5390 print_generic_expr (dump_file, *output_p);
5391 fprintf (dump_file, ": ");
5392 dump_value_range (dump_file, &vr);
5393 fprintf (dump_file, "\n");
5396 if (vr.type == VR_VARYING)
5397 return SSA_PROP_VARYING;
5399 return SSA_PROP_INTERESTING;
5401 return SSA_PROP_NOT_INTERESTING;
5404 if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
5405 switch (gimple_call_internal_fn (stmt))
5407 case IFN_ADD_OVERFLOW:
5408 case IFN_SUB_OVERFLOW:
5409 case IFN_MUL_OVERFLOW:
5410 case IFN_ATOMIC_COMPARE_EXCHANGE:
5411 /* These internal calls return _Complex integer type,
5412 which VRP does not track, but the immediate uses
5413 thereof might be interesting. */
5414 if (lhs && TREE_CODE (lhs) == SSA_NAME)
5416 imm_use_iterator iter;
5417 use_operand_p use_p;
5418 enum ssa_prop_result res = SSA_PROP_VARYING;
5420 set_value_range_to_varying (get_value_range (lhs));
5422 FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
5424 gimple *use_stmt = USE_STMT (use_p);
5425 if (!is_gimple_assign (use_stmt))
5426 continue;
5427 enum tree_code rhs_code = gimple_assign_rhs_code (use_stmt);
5428 if (rhs_code != REALPART_EXPR && rhs_code != IMAGPART_EXPR)
5429 continue;
5430 tree rhs1 = gimple_assign_rhs1 (use_stmt);
5431 tree use_lhs = gimple_assign_lhs (use_stmt);
5432 if (TREE_CODE (rhs1) != rhs_code
5433 || TREE_OPERAND (rhs1, 0) != lhs
5434 || TREE_CODE (use_lhs) != SSA_NAME
5435 || !stmt_interesting_for_vrp (use_stmt)
5436 || (!INTEGRAL_TYPE_P (TREE_TYPE (use_lhs))
5437 || !TYPE_MIN_VALUE (TREE_TYPE (use_lhs))
5438 || !TYPE_MAX_VALUE (TREE_TYPE (use_lhs))))
5439 continue;
5441 /* If there is a change in the value range for any of the
5442 REALPART_EXPR/IMAGPART_EXPR immediate uses, return
5443 SSA_PROP_INTERESTING. If there are any REALPART_EXPR
5444 or IMAGPART_EXPR immediate uses, but none of them have
5445 a change in their value ranges, return
5446 SSA_PROP_NOT_INTERESTING. If there are no
5447 {REAL,IMAG}PART_EXPR uses at all,
5448 return SSA_PROP_VARYING. */
5449 value_range new_vr = VR_INITIALIZER;
5450 extract_range_basic (&new_vr, use_stmt);
5451 value_range *old_vr = get_value_range (use_lhs);
5452 if (old_vr->type != new_vr.type
5453 || !vrp_operand_equal_p (old_vr->min, new_vr.min)
5454 || !vrp_operand_equal_p (old_vr->max, new_vr.max)
5455 || !vrp_bitmap_equal_p (old_vr->equiv, new_vr.equiv))
5456 res = SSA_PROP_INTERESTING;
5457 else
5458 res = SSA_PROP_NOT_INTERESTING;
5459 BITMAP_FREE (new_vr.equiv);
5460 if (res == SSA_PROP_INTERESTING)
5462 *output_p = lhs;
5463 return res;
5467 return res;
5469 break;
5470 default:
5471 break;
5474 /* All other statements produce nothing of interest for VRP, so mark
5475 their outputs varying and prevent further simulation. */
5476 set_defs_to_varying (stmt);
5478 return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
5481 /* Union the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
5482 { VR1TYPE, VR0MIN, VR0MAX } and store the result
5483 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
5484 possible such range. The resulting range is not canonicalized. */
5486 static void
5487 union_ranges (enum value_range_type *vr0type,
5488 tree *vr0min, tree *vr0max,
5489 enum value_range_type vr1type,
5490 tree vr1min, tree vr1max)
5492 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
5493 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
5495 /* [] is vr0, () is vr1 in the following classification comments. */
5496 if (mineq && maxeq)
5498 /* [( )] */
5499 if (*vr0type == vr1type)
5500 /* Nothing to do for equal ranges. */
5502 else if ((*vr0type == VR_RANGE
5503 && vr1type == VR_ANTI_RANGE)
5504 || (*vr0type == VR_ANTI_RANGE
5505 && vr1type == VR_RANGE))
5507 /* For anti-range with range union the result is varying. */
5508 goto give_up;
5510 else
5511 gcc_unreachable ();
5513 else if (operand_less_p (*vr0max, vr1min) == 1
5514 || operand_less_p (vr1max, *vr0min) == 1)
5516 /* [ ] ( ) or ( ) [ ]
5517 If the ranges have an empty intersection, result of the union
5518 operation is the anti-range or if both are anti-ranges
5519 it covers all. */
5520 if (*vr0type == VR_ANTI_RANGE
5521 && vr1type == VR_ANTI_RANGE)
5522 goto give_up;
5523 else if (*vr0type == VR_ANTI_RANGE
5524 && vr1type == VR_RANGE)
5526 else if (*vr0type == VR_RANGE
5527 && vr1type == VR_ANTI_RANGE)
5529 *vr0type = vr1type;
5530 *vr0min = vr1min;
5531 *vr0max = vr1max;
5533 else if (*vr0type == VR_RANGE
5534 && vr1type == VR_RANGE)
5536 /* The result is the convex hull of both ranges. */
5537 if (operand_less_p (*vr0max, vr1min) == 1)
5539 /* If the result can be an anti-range, create one. */
5540 if (TREE_CODE (*vr0max) == INTEGER_CST
5541 && TREE_CODE (vr1min) == INTEGER_CST
5542 && vrp_val_is_min (*vr0min)
5543 && vrp_val_is_max (vr1max))
5545 tree min = int_const_binop (PLUS_EXPR,
5546 *vr0max,
5547 build_int_cst (TREE_TYPE (*vr0max), 1));
5548 tree max = int_const_binop (MINUS_EXPR,
5549 vr1min,
5550 build_int_cst (TREE_TYPE (vr1min), 1));
5551 if (!operand_less_p (max, min))
5553 *vr0type = VR_ANTI_RANGE;
5554 *vr0min = min;
5555 *vr0max = max;
5557 else
5558 *vr0max = vr1max;
5560 else
5561 *vr0max = vr1max;
5563 else
5565 /* If the result can be an anti-range, create one. */
5566 if (TREE_CODE (vr1max) == INTEGER_CST
5567 && TREE_CODE (*vr0min) == INTEGER_CST
5568 && vrp_val_is_min (vr1min)
5569 && vrp_val_is_max (*vr0max))
5571 tree min = int_const_binop (PLUS_EXPR,
5572 vr1max,
5573 build_int_cst (TREE_TYPE (vr1max), 1));
5574 tree max = int_const_binop (MINUS_EXPR,
5575 *vr0min,
5576 build_int_cst (TREE_TYPE (*vr0min), 1));
5577 if (!operand_less_p (max, min))
5579 *vr0type = VR_ANTI_RANGE;
5580 *vr0min = min;
5581 *vr0max = max;
5583 else
5584 *vr0min = vr1min;
5586 else
5587 *vr0min = vr1min;
5590 else
5591 gcc_unreachable ();
5593 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
5594 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
5596 /* [ ( ) ] or [( ) ] or [ ( )] */
5597 if (*vr0type == VR_RANGE
5598 && vr1type == VR_RANGE)
5600 else if (*vr0type == VR_ANTI_RANGE
5601 && vr1type == VR_ANTI_RANGE)
5603 *vr0type = vr1type;
5604 *vr0min = vr1min;
5605 *vr0max = vr1max;
5607 else if (*vr0type == VR_ANTI_RANGE
5608 && vr1type == VR_RANGE)
5610 /* Arbitrarily choose the right or left gap. */
5611 if (!mineq && TREE_CODE (vr1min) == INTEGER_CST)
5612 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5613 build_int_cst (TREE_TYPE (vr1min), 1));
5614 else if (!maxeq && TREE_CODE (vr1max) == INTEGER_CST)
5615 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5616 build_int_cst (TREE_TYPE (vr1max), 1));
5617 else
5618 goto give_up;
5620 else if (*vr0type == VR_RANGE
5621 && vr1type == VR_ANTI_RANGE)
5622 /* The result covers everything. */
5623 goto give_up;
5624 else
5625 gcc_unreachable ();
5627 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
5628 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
5630 /* ( [ ] ) or ([ ] ) or ( [ ]) */
5631 if (*vr0type == VR_RANGE
5632 && vr1type == VR_RANGE)
5634 *vr0type = vr1type;
5635 *vr0min = vr1min;
5636 *vr0max = vr1max;
5638 else if (*vr0type == VR_ANTI_RANGE
5639 && vr1type == VR_ANTI_RANGE)
5641 else if (*vr0type == VR_RANGE
5642 && vr1type == VR_ANTI_RANGE)
5644 *vr0type = VR_ANTI_RANGE;
5645 if (!mineq && TREE_CODE (*vr0min) == INTEGER_CST)
5647 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5648 build_int_cst (TREE_TYPE (*vr0min), 1));
5649 *vr0min = vr1min;
5651 else if (!maxeq && TREE_CODE (*vr0max) == INTEGER_CST)
5653 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5654 build_int_cst (TREE_TYPE (*vr0max), 1));
5655 *vr0max = vr1max;
5657 else
5658 goto give_up;
5660 else if (*vr0type == VR_ANTI_RANGE
5661 && vr1type == VR_RANGE)
5662 /* The result covers everything. */
5663 goto give_up;
5664 else
5665 gcc_unreachable ();
5667 else if ((operand_less_p (vr1min, *vr0max) == 1
5668 || operand_equal_p (vr1min, *vr0max, 0))
5669 && operand_less_p (*vr0min, vr1min) == 1
5670 && operand_less_p (*vr0max, vr1max) == 1)
5672 /* [ ( ] ) or [ ]( ) */
5673 if (*vr0type == VR_RANGE
5674 && vr1type == VR_RANGE)
5675 *vr0max = vr1max;
5676 else if (*vr0type == VR_ANTI_RANGE
5677 && vr1type == VR_ANTI_RANGE)
5678 *vr0min = vr1min;
5679 else if (*vr0type == VR_ANTI_RANGE
5680 && vr1type == VR_RANGE)
5682 if (TREE_CODE (vr1min) == INTEGER_CST)
5683 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5684 build_int_cst (TREE_TYPE (vr1min), 1));
5685 else
5686 goto give_up;
5688 else if (*vr0type == VR_RANGE
5689 && vr1type == VR_ANTI_RANGE)
5691 if (TREE_CODE (*vr0max) == INTEGER_CST)
5693 *vr0type = vr1type;
5694 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5695 build_int_cst (TREE_TYPE (*vr0max), 1));
5696 *vr0max = vr1max;
5698 else
5699 goto give_up;
5701 else
5702 gcc_unreachable ();
5704 else if ((operand_less_p (*vr0min, vr1max) == 1
5705 || operand_equal_p (*vr0min, vr1max, 0))
5706 && operand_less_p (vr1min, *vr0min) == 1
5707 && operand_less_p (vr1max, *vr0max) == 1)
5709 /* ( [ ) ] or ( )[ ] */
5710 if (*vr0type == VR_RANGE
5711 && vr1type == VR_RANGE)
5712 *vr0min = vr1min;
5713 else if (*vr0type == VR_ANTI_RANGE
5714 && vr1type == VR_ANTI_RANGE)
5715 *vr0max = vr1max;
5716 else if (*vr0type == VR_ANTI_RANGE
5717 && vr1type == VR_RANGE)
5719 if (TREE_CODE (vr1max) == INTEGER_CST)
5720 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5721 build_int_cst (TREE_TYPE (vr1max), 1));
5722 else
5723 goto give_up;
5725 else if (*vr0type == VR_RANGE
5726 && vr1type == VR_ANTI_RANGE)
5728 if (TREE_CODE (*vr0min) == INTEGER_CST)
5730 *vr0type = vr1type;
5731 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5732 build_int_cst (TREE_TYPE (*vr0min), 1));
5733 *vr0min = vr1min;
5735 else
5736 goto give_up;
5738 else
5739 gcc_unreachable ();
5741 else
5742 goto give_up;
5744 return;
5746 give_up:
5747 *vr0type = VR_VARYING;
5748 *vr0min = NULL_TREE;
5749 *vr0max = NULL_TREE;
5752 /* Intersect the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
5753 { VR1TYPE, VR0MIN, VR0MAX } and store the result
5754 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
5755 possible such range. The resulting range is not canonicalized. */
5757 static void
5758 intersect_ranges (enum value_range_type *vr0type,
5759 tree *vr0min, tree *vr0max,
5760 enum value_range_type vr1type,
5761 tree vr1min, tree vr1max)
5763 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
5764 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
5766 /* [] is vr0, () is vr1 in the following classification comments. */
5767 if (mineq && maxeq)
5769 /* [( )] */
5770 if (*vr0type == vr1type)
5771 /* Nothing to do for equal ranges. */
5773 else if ((*vr0type == VR_RANGE
5774 && vr1type == VR_ANTI_RANGE)
5775 || (*vr0type == VR_ANTI_RANGE
5776 && vr1type == VR_RANGE))
5778 /* For anti-range with range intersection the result is empty. */
5779 *vr0type = VR_UNDEFINED;
5780 *vr0min = NULL_TREE;
5781 *vr0max = NULL_TREE;
5783 else
5784 gcc_unreachable ();
5786 else if (operand_less_p (*vr0max, vr1min) == 1
5787 || operand_less_p (vr1max, *vr0min) == 1)
5789 /* [ ] ( ) or ( ) [ ]
5790 If the ranges have an empty intersection, the result of the
5791 intersect operation is the range for intersecting an
5792 anti-range with a range or empty when intersecting two ranges. */
5793 if (*vr0type == VR_RANGE
5794 && vr1type == VR_ANTI_RANGE)
5796 else if (*vr0type == VR_ANTI_RANGE
5797 && vr1type == VR_RANGE)
5799 *vr0type = vr1type;
5800 *vr0min = vr1min;
5801 *vr0max = vr1max;
5803 else if (*vr0type == VR_RANGE
5804 && vr1type == VR_RANGE)
5806 *vr0type = VR_UNDEFINED;
5807 *vr0min = NULL_TREE;
5808 *vr0max = NULL_TREE;
5810 else if (*vr0type == VR_ANTI_RANGE
5811 && vr1type == VR_ANTI_RANGE)
5813 /* If the anti-ranges are adjacent to each other merge them. */
5814 if (TREE_CODE (*vr0max) == INTEGER_CST
5815 && TREE_CODE (vr1min) == INTEGER_CST
5816 && operand_less_p (*vr0max, vr1min) == 1
5817 && integer_onep (int_const_binop (MINUS_EXPR,
5818 vr1min, *vr0max)))
5819 *vr0max = vr1max;
5820 else if (TREE_CODE (vr1max) == INTEGER_CST
5821 && TREE_CODE (*vr0min) == INTEGER_CST
5822 && operand_less_p (vr1max, *vr0min) == 1
5823 && integer_onep (int_const_binop (MINUS_EXPR,
5824 *vr0min, vr1max)))
5825 *vr0min = vr1min;
5826 /* Else arbitrarily take VR0. */
5829 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
5830 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
5832 /* [ ( ) ] or [( ) ] or [ ( )] */
5833 if (*vr0type == VR_RANGE
5834 && vr1type == VR_RANGE)
5836 /* If both are ranges the result is the inner one. */
5837 *vr0type = vr1type;
5838 *vr0min = vr1min;
5839 *vr0max = vr1max;
5841 else if (*vr0type == VR_RANGE
5842 && vr1type == VR_ANTI_RANGE)
5844 /* Choose the right gap if the left one is empty. */
5845 if (mineq)
5847 if (TREE_CODE (vr1max) != INTEGER_CST)
5848 *vr0min = vr1max;
5849 else if (TYPE_PRECISION (TREE_TYPE (vr1max)) == 1
5850 && !TYPE_UNSIGNED (TREE_TYPE (vr1max)))
5851 *vr0min
5852 = int_const_binop (MINUS_EXPR, vr1max,
5853 build_int_cst (TREE_TYPE (vr1max), -1));
5854 else
5855 *vr0min
5856 = int_const_binop (PLUS_EXPR, vr1max,
5857 build_int_cst (TREE_TYPE (vr1max), 1));
5859 /* Choose the left gap if the right one is empty. */
5860 else if (maxeq)
5862 if (TREE_CODE (vr1min) != INTEGER_CST)
5863 *vr0max = vr1min;
5864 else if (TYPE_PRECISION (TREE_TYPE (vr1min)) == 1
5865 && !TYPE_UNSIGNED (TREE_TYPE (vr1min)))
5866 *vr0max
5867 = int_const_binop (PLUS_EXPR, vr1min,
5868 build_int_cst (TREE_TYPE (vr1min), -1));
5869 else
5870 *vr0max
5871 = int_const_binop (MINUS_EXPR, vr1min,
5872 build_int_cst (TREE_TYPE (vr1min), 1));
5874 /* Choose the anti-range if the range is effectively varying. */
5875 else if (vrp_val_is_min (*vr0min)
5876 && vrp_val_is_max (*vr0max))
5878 *vr0type = vr1type;
5879 *vr0min = vr1min;
5880 *vr0max = vr1max;
5882 /* Else choose the range. */
5884 else if (*vr0type == VR_ANTI_RANGE
5885 && vr1type == VR_ANTI_RANGE)
5886 /* If both are anti-ranges the result is the outer one. */
5888 else if (*vr0type == VR_ANTI_RANGE
5889 && vr1type == VR_RANGE)
5891 /* The intersection is empty. */
5892 *vr0type = VR_UNDEFINED;
5893 *vr0min = NULL_TREE;
5894 *vr0max = NULL_TREE;
5896 else
5897 gcc_unreachable ();
5899 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
5900 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
5902 /* ( [ ] ) or ([ ] ) or ( [ ]) */
5903 if (*vr0type == VR_RANGE
5904 && vr1type == VR_RANGE)
5905 /* Choose the inner range. */
5907 else if (*vr0type == VR_ANTI_RANGE
5908 && vr1type == VR_RANGE)
5910 /* Choose the right gap if the left is empty. */
5911 if (mineq)
5913 *vr0type = VR_RANGE;
5914 if (TREE_CODE (*vr0max) != INTEGER_CST)
5915 *vr0min = *vr0max;
5916 else if (TYPE_PRECISION (TREE_TYPE (*vr0max)) == 1
5917 && !TYPE_UNSIGNED (TREE_TYPE (*vr0max)))
5918 *vr0min
5919 = int_const_binop (MINUS_EXPR, *vr0max,
5920 build_int_cst (TREE_TYPE (*vr0max), -1));
5921 else
5922 *vr0min
5923 = int_const_binop (PLUS_EXPR, *vr0max,
5924 build_int_cst (TREE_TYPE (*vr0max), 1));
5925 *vr0max = vr1max;
5927 /* Choose the left gap if the right is empty. */
5928 else if (maxeq)
5930 *vr0type = VR_RANGE;
5931 if (TREE_CODE (*vr0min) != INTEGER_CST)
5932 *vr0max = *vr0min;
5933 else if (TYPE_PRECISION (TREE_TYPE (*vr0min)) == 1
5934 && !TYPE_UNSIGNED (TREE_TYPE (*vr0min)))
5935 *vr0max
5936 = int_const_binop (PLUS_EXPR, *vr0min,
5937 build_int_cst (TREE_TYPE (*vr0min), -1));
5938 else
5939 *vr0max
5940 = int_const_binop (MINUS_EXPR, *vr0min,
5941 build_int_cst (TREE_TYPE (*vr0min), 1));
5942 *vr0min = vr1min;
5944 /* Choose the anti-range if the range is effectively varying. */
5945 else if (vrp_val_is_min (vr1min)
5946 && vrp_val_is_max (vr1max))
5948 /* Choose the anti-range if it is ~[0,0], that range is special
5949 enough to special case when vr1's range is relatively wide.
5950 At least for types bigger than int - this covers pointers
5951 and arguments to functions like ctz. */
5952 else if (*vr0min == *vr0max
5953 && integer_zerop (*vr0min)
5954 && ((TYPE_PRECISION (TREE_TYPE (*vr0min))
5955 >= TYPE_PRECISION (integer_type_node))
5956 || POINTER_TYPE_P (TREE_TYPE (*vr0min)))
5957 && TREE_CODE (vr1max) == INTEGER_CST
5958 && TREE_CODE (vr1min) == INTEGER_CST
5959 && (wi::clz (wi::to_wide (vr1max) - wi::to_wide (vr1min))
5960 < TYPE_PRECISION (TREE_TYPE (*vr0min)) / 2))
5962 /* Else choose the range. */
5963 else
5965 *vr0type = vr1type;
5966 *vr0min = vr1min;
5967 *vr0max = vr1max;
5970 else if (*vr0type == VR_ANTI_RANGE
5971 && vr1type == VR_ANTI_RANGE)
5973 /* If both are anti-ranges the result is the outer one. */
5974 *vr0type = vr1type;
5975 *vr0min = vr1min;
5976 *vr0max = vr1max;
5978 else if (vr1type == VR_ANTI_RANGE
5979 && *vr0type == VR_RANGE)
5981 /* The intersection is empty. */
5982 *vr0type = VR_UNDEFINED;
5983 *vr0min = NULL_TREE;
5984 *vr0max = NULL_TREE;
5986 else
5987 gcc_unreachable ();
5989 else if ((operand_less_p (vr1min, *vr0max) == 1
5990 || operand_equal_p (vr1min, *vr0max, 0))
5991 && operand_less_p (*vr0min, vr1min) == 1)
5993 /* [ ( ] ) or [ ]( ) */
5994 if (*vr0type == VR_ANTI_RANGE
5995 && vr1type == VR_ANTI_RANGE)
5996 *vr0max = vr1max;
5997 else if (*vr0type == VR_RANGE
5998 && vr1type == VR_RANGE)
5999 *vr0min = vr1min;
6000 else if (*vr0type == VR_RANGE
6001 && vr1type == VR_ANTI_RANGE)
6003 if (TREE_CODE (vr1min) == INTEGER_CST)
6004 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
6005 build_int_cst (TREE_TYPE (vr1min), 1));
6006 else
6007 *vr0max = vr1min;
6009 else if (*vr0type == VR_ANTI_RANGE
6010 && vr1type == VR_RANGE)
6012 *vr0type = VR_RANGE;
6013 if (TREE_CODE (*vr0max) == INTEGER_CST)
6014 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
6015 build_int_cst (TREE_TYPE (*vr0max), 1));
6016 else
6017 *vr0min = *vr0max;
6018 *vr0max = vr1max;
6020 else
6021 gcc_unreachable ();
6023 else if ((operand_less_p (*vr0min, vr1max) == 1
6024 || operand_equal_p (*vr0min, vr1max, 0))
6025 && operand_less_p (vr1min, *vr0min) == 1)
6027 /* ( [ ) ] or ( )[ ] */
6028 if (*vr0type == VR_ANTI_RANGE
6029 && vr1type == VR_ANTI_RANGE)
6030 *vr0min = vr1min;
6031 else if (*vr0type == VR_RANGE
6032 && vr1type == VR_RANGE)
6033 *vr0max = vr1max;
6034 else if (*vr0type == VR_RANGE
6035 && vr1type == VR_ANTI_RANGE)
6037 if (TREE_CODE (vr1max) == INTEGER_CST)
6038 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
6039 build_int_cst (TREE_TYPE (vr1max), 1));
6040 else
6041 *vr0min = vr1max;
6043 else if (*vr0type == VR_ANTI_RANGE
6044 && vr1type == VR_RANGE)
6046 *vr0type = VR_RANGE;
6047 if (TREE_CODE (*vr0min) == INTEGER_CST)
6048 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
6049 build_int_cst (TREE_TYPE (*vr0min), 1));
6050 else
6051 *vr0max = *vr0min;
6052 *vr0min = vr1min;
6054 else
6055 gcc_unreachable ();
6058 /* As a fallback simply use { *VRTYPE, *VR0MIN, *VR0MAX } as
6059 result for the intersection. That's always a conservative
6060 correct estimate unless VR1 is a constant singleton range
6061 in which case we choose that. */
6062 if (vr1type == VR_RANGE
6063 && is_gimple_min_invariant (vr1min)
6064 && vrp_operand_equal_p (vr1min, vr1max))
6066 *vr0type = vr1type;
6067 *vr0min = vr1min;
6068 *vr0max = vr1max;
6071 return;
6075 /* Intersect the two value-ranges *VR0 and *VR1 and store the result
6076 in *VR0. This may not be the smallest possible such range. */
6078 static void
6079 vrp_intersect_ranges_1 (value_range *vr0, value_range *vr1)
6081 value_range saved;
6083 /* If either range is VR_VARYING the other one wins. */
6084 if (vr1->type == VR_VARYING)
6085 return;
6086 if (vr0->type == VR_VARYING)
6088 copy_value_range (vr0, vr1);
6089 return;
6092 /* When either range is VR_UNDEFINED the resulting range is
6093 VR_UNDEFINED, too. */
6094 if (vr0->type == VR_UNDEFINED)
6095 return;
6096 if (vr1->type == VR_UNDEFINED)
6098 set_value_range_to_undefined (vr0);
6099 return;
6102 /* Save the original vr0 so we can return it as conservative intersection
6103 result when our worker turns things to varying. */
6104 saved = *vr0;
6105 intersect_ranges (&vr0->type, &vr0->min, &vr0->max,
6106 vr1->type, vr1->min, vr1->max);
6107 /* Make sure to canonicalize the result though as the inversion of a
6108 VR_RANGE can still be a VR_RANGE. */
6109 set_and_canonicalize_value_range (vr0, vr0->type,
6110 vr0->min, vr0->max, vr0->equiv);
6111 /* If that failed, use the saved original VR0. */
6112 if (vr0->type == VR_VARYING)
6114 *vr0 = saved;
6115 return;
6117 /* If the result is VR_UNDEFINED there is no need to mess with
6118 the equivalencies. */
6119 if (vr0->type == VR_UNDEFINED)
6120 return;
6122 /* The resulting set of equivalences for range intersection is the union of
6123 the two sets. */
6124 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
6125 bitmap_ior_into (vr0->equiv, vr1->equiv);
6126 else if (vr1->equiv && !vr0->equiv)
6128 /* All equivalence bitmaps are allocated from the same obstack. So
6129 we can use the obstack associated with VR to allocate vr0->equiv. */
6130 vr0->equiv = BITMAP_ALLOC (vr1->equiv->obstack);
6131 bitmap_copy (vr0->equiv, vr1->equiv);
6135 void
6136 vrp_intersect_ranges (value_range *vr0, value_range *vr1)
6138 if (dump_file && (dump_flags & TDF_DETAILS))
6140 fprintf (dump_file, "Intersecting\n ");
6141 dump_value_range (dump_file, vr0);
6142 fprintf (dump_file, "\nand\n ");
6143 dump_value_range (dump_file, vr1);
6144 fprintf (dump_file, "\n");
6146 vrp_intersect_ranges_1 (vr0, vr1);
6147 if (dump_file && (dump_flags & TDF_DETAILS))
6149 fprintf (dump_file, "to\n ");
6150 dump_value_range (dump_file, vr0);
6151 fprintf (dump_file, "\n");
6155 /* Meet operation for value ranges. Given two value ranges VR0 and
6156 VR1, store in VR0 a range that contains both VR0 and VR1. This
6157 may not be the smallest possible such range. */
6159 static void
6160 vrp_meet_1 (value_range *vr0, const value_range *vr1)
6162 value_range saved;
6164 if (vr0->type == VR_UNDEFINED)
6166 set_value_range (vr0, vr1->type, vr1->min, vr1->max, vr1->equiv);
6167 return;
6170 if (vr1->type == VR_UNDEFINED)
6172 /* VR0 already has the resulting range. */
6173 return;
6176 if (vr0->type == VR_VARYING)
6178 /* Nothing to do. VR0 already has the resulting range. */
6179 return;
6182 if (vr1->type == VR_VARYING)
6184 set_value_range_to_varying (vr0);
6185 return;
6188 saved = *vr0;
6189 union_ranges (&vr0->type, &vr0->min, &vr0->max,
6190 vr1->type, vr1->min, vr1->max);
6191 if (vr0->type == VR_VARYING)
6193 /* Failed to find an efficient meet. Before giving up and setting
6194 the result to VARYING, see if we can at least derive a useful
6195 anti-range. FIXME, all this nonsense about distinguishing
6196 anti-ranges from ranges is necessary because of the odd
6197 semantics of range_includes_zero_p and friends. */
6198 if (((saved.type == VR_RANGE
6199 && range_includes_zero_p (saved.min, saved.max) == 0)
6200 || (saved.type == VR_ANTI_RANGE
6201 && range_includes_zero_p (saved.min, saved.max) == 1))
6202 && ((vr1->type == VR_RANGE
6203 && range_includes_zero_p (vr1->min, vr1->max) == 0)
6204 || (vr1->type == VR_ANTI_RANGE
6205 && range_includes_zero_p (vr1->min, vr1->max) == 1)))
6207 set_value_range_to_nonnull (vr0, TREE_TYPE (saved.min));
6209 /* Since this meet operation did not result from the meeting of
6210 two equivalent names, VR0 cannot have any equivalences. */
6211 if (vr0->equiv)
6212 bitmap_clear (vr0->equiv);
6213 return;
6216 set_value_range_to_varying (vr0);
6217 return;
6219 set_and_canonicalize_value_range (vr0, vr0->type, vr0->min, vr0->max,
6220 vr0->equiv);
6221 if (vr0->type == VR_VARYING)
6222 return;
6224 /* The resulting set of equivalences is always the intersection of
6225 the two sets. */
6226 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
6227 bitmap_and_into (vr0->equiv, vr1->equiv);
6228 else if (vr0->equiv && !vr1->equiv)
6229 bitmap_clear (vr0->equiv);
6232 void
6233 vrp_meet (value_range *vr0, const value_range *vr1)
6235 if (dump_file && (dump_flags & TDF_DETAILS))
6237 fprintf (dump_file, "Meeting\n ");
6238 dump_value_range (dump_file, vr0);
6239 fprintf (dump_file, "\nand\n ");
6240 dump_value_range (dump_file, vr1);
6241 fprintf (dump_file, "\n");
6243 vrp_meet_1 (vr0, vr1);
6244 if (dump_file && (dump_flags & TDF_DETAILS))
6246 fprintf (dump_file, "to\n ");
6247 dump_value_range (dump_file, vr0);
6248 fprintf (dump_file, "\n");
6253 /* Visit all arguments for PHI node PHI that flow through executable
6254 edges. If a valid value range can be derived from all the incoming
6255 value ranges, set a new range for the LHS of PHI. */
6257 enum ssa_prop_result
6258 vrp_prop::visit_phi (gphi *phi)
6260 tree lhs = PHI_RESULT (phi);
6261 value_range vr_result = VR_INITIALIZER;
6262 extract_range_from_phi_node (phi, &vr_result);
6263 if (update_value_range (lhs, &vr_result))
6265 if (dump_file && (dump_flags & TDF_DETAILS))
6267 fprintf (dump_file, "Found new range for ");
6268 print_generic_expr (dump_file, lhs);
6269 fprintf (dump_file, ": ");
6270 dump_value_range (dump_file, &vr_result);
6271 fprintf (dump_file, "\n");
6274 if (vr_result.type == VR_VARYING)
6275 return SSA_PROP_VARYING;
6277 return SSA_PROP_INTERESTING;
6280 /* Nothing changed, don't add outgoing edges. */
6281 return SSA_PROP_NOT_INTERESTING;
6284 class vrp_folder : public substitute_and_fold_engine
6286 public:
6287 tree get_value (tree) FINAL OVERRIDE;
6288 bool fold_stmt (gimple_stmt_iterator *) FINAL OVERRIDE;
6289 bool fold_predicate_in (gimple_stmt_iterator *);
6291 class vr_values *vr_values;
6293 /* Delegators. */
6294 tree vrp_evaluate_conditional (tree_code code, tree op0,
6295 tree op1, gimple *stmt)
6296 { return vr_values->vrp_evaluate_conditional (code, op0, op1, stmt); }
6297 bool simplify_stmt_using_ranges (gimple_stmt_iterator *gsi)
6298 { return vr_values->simplify_stmt_using_ranges (gsi); }
6299 tree op_with_constant_singleton_value_range (tree op)
6300 { return vr_values->op_with_constant_singleton_value_range (op); }
6303 /* If the statement pointed by SI has a predicate whose value can be
6304 computed using the value range information computed by VRP, compute
6305 its value and return true. Otherwise, return false. */
6307 bool
6308 vrp_folder::fold_predicate_in (gimple_stmt_iterator *si)
6310 bool assignment_p = false;
6311 tree val;
6312 gimple *stmt = gsi_stmt (*si);
6314 if (is_gimple_assign (stmt)
6315 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
6317 assignment_p = true;
6318 val = vrp_evaluate_conditional (gimple_assign_rhs_code (stmt),
6319 gimple_assign_rhs1 (stmt),
6320 gimple_assign_rhs2 (stmt),
6321 stmt);
6323 else if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
6324 val = vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
6325 gimple_cond_lhs (cond_stmt),
6326 gimple_cond_rhs (cond_stmt),
6327 stmt);
6328 else
6329 return false;
6331 if (val)
6333 if (assignment_p)
6334 val = fold_convert (gimple_expr_type (stmt), val);
6336 if (dump_file)
6338 fprintf (dump_file, "Folding predicate ");
6339 print_gimple_expr (dump_file, stmt, 0);
6340 fprintf (dump_file, " to ");
6341 print_generic_expr (dump_file, val);
6342 fprintf (dump_file, "\n");
6345 if (is_gimple_assign (stmt))
6346 gimple_assign_set_rhs_from_tree (si, val);
6347 else
6349 gcc_assert (gimple_code (stmt) == GIMPLE_COND);
6350 gcond *cond_stmt = as_a <gcond *> (stmt);
6351 if (integer_zerop (val))
6352 gimple_cond_make_false (cond_stmt);
6353 else if (integer_onep (val))
6354 gimple_cond_make_true (cond_stmt);
6355 else
6356 gcc_unreachable ();
6359 return true;
6362 return false;
6365 /* Callback for substitute_and_fold folding the stmt at *SI. */
6367 bool
6368 vrp_folder::fold_stmt (gimple_stmt_iterator *si)
6370 if (fold_predicate_in (si))
6371 return true;
6373 return simplify_stmt_using_ranges (si);
6376 /* If OP has a value range with a single constant value return that,
6377 otherwise return NULL_TREE. This returns OP itself if OP is a
6378 constant.
6380 Implemented as a pure wrapper right now, but this will change. */
6382 tree
6383 vrp_folder::get_value (tree op)
6385 return op_with_constant_singleton_value_range (op);
6388 /* Return the LHS of any ASSERT_EXPR where OP appears as the first
6389 argument to the ASSERT_EXPR and in which the ASSERT_EXPR dominates
6390 BB. If no such ASSERT_EXPR is found, return OP. */
6392 static tree
6393 lhs_of_dominating_assert (tree op, basic_block bb, gimple *stmt)
6395 imm_use_iterator imm_iter;
6396 gimple *use_stmt;
6397 use_operand_p use_p;
6399 if (TREE_CODE (op) == SSA_NAME)
6401 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, op)
6403 use_stmt = USE_STMT (use_p);
6404 if (use_stmt != stmt
6405 && gimple_assign_single_p (use_stmt)
6406 && TREE_CODE (gimple_assign_rhs1 (use_stmt)) == ASSERT_EXPR
6407 && TREE_OPERAND (gimple_assign_rhs1 (use_stmt), 0) == op
6408 && dominated_by_p (CDI_DOMINATORS, bb, gimple_bb (use_stmt)))
6409 return gimple_assign_lhs (use_stmt);
6412 return op;
6415 /* A hack. */
6416 static class vr_values *x_vr_values;
6418 /* A trivial wrapper so that we can present the generic jump threading
6419 code with a simple API for simplifying statements. STMT is the
6420 statement we want to simplify, WITHIN_STMT provides the location
6421 for any overflow warnings. */
6423 static tree
6424 simplify_stmt_for_jump_threading (gimple *stmt, gimple *within_stmt,
6425 class avail_exprs_stack *avail_exprs_stack ATTRIBUTE_UNUSED,
6426 basic_block bb)
6428 /* First see if the conditional is in the hash table. */
6429 tree cached_lhs = avail_exprs_stack->lookup_avail_expr (stmt, false, true);
6430 if (cached_lhs && is_gimple_min_invariant (cached_lhs))
6431 return cached_lhs;
6433 vr_values *vr_values = x_vr_values;
6434 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
6436 tree op0 = gimple_cond_lhs (cond_stmt);
6437 op0 = lhs_of_dominating_assert (op0, bb, stmt);
6439 tree op1 = gimple_cond_rhs (cond_stmt);
6440 op1 = lhs_of_dominating_assert (op1, bb, stmt);
6442 return vr_values->vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
6443 op0, op1, within_stmt);
6446 /* We simplify a switch statement by trying to determine which case label
6447 will be taken. If we are successful then we return the corresponding
6448 CASE_LABEL_EXPR. */
6449 if (gswitch *switch_stmt = dyn_cast <gswitch *> (stmt))
6451 tree op = gimple_switch_index (switch_stmt);
6452 if (TREE_CODE (op) != SSA_NAME)
6453 return NULL_TREE;
6455 op = lhs_of_dominating_assert (op, bb, stmt);
6457 value_range *vr = vr_values->get_value_range (op);
6458 if ((vr->type != VR_RANGE && vr->type != VR_ANTI_RANGE)
6459 || symbolic_range_p (vr))
6460 return NULL_TREE;
6462 if (vr->type == VR_RANGE)
6464 size_t i, j;
6465 /* Get the range of labels that contain a part of the operand's
6466 value range. */
6467 find_case_label_range (switch_stmt, vr->min, vr->max, &i, &j);
6469 /* Is there only one such label? */
6470 if (i == j)
6472 tree label = gimple_switch_label (switch_stmt, i);
6474 /* The i'th label will be taken only if the value range of the
6475 operand is entirely within the bounds of this label. */
6476 if (CASE_HIGH (label) != NULL_TREE
6477 ? (tree_int_cst_compare (CASE_LOW (label), vr->min) <= 0
6478 && tree_int_cst_compare (CASE_HIGH (label), vr->max) >= 0)
6479 : (tree_int_cst_equal (CASE_LOW (label), vr->min)
6480 && tree_int_cst_equal (vr->min, vr->max)))
6481 return label;
6484 /* If there are no such labels then the default label will be
6485 taken. */
6486 if (i > j)
6487 return gimple_switch_label (switch_stmt, 0);
6490 if (vr->type == VR_ANTI_RANGE)
6492 unsigned n = gimple_switch_num_labels (switch_stmt);
6493 tree min_label = gimple_switch_label (switch_stmt, 1);
6494 tree max_label = gimple_switch_label (switch_stmt, n - 1);
6496 /* The default label will be taken only if the anti-range of the
6497 operand is entirely outside the bounds of all the (non-default)
6498 case labels. */
6499 if (tree_int_cst_compare (vr->min, CASE_LOW (min_label)) <= 0
6500 && (CASE_HIGH (max_label) != NULL_TREE
6501 ? tree_int_cst_compare (vr->max, CASE_HIGH (max_label)) >= 0
6502 : tree_int_cst_compare (vr->max, CASE_LOW (max_label)) >= 0))
6503 return gimple_switch_label (switch_stmt, 0);
6506 return NULL_TREE;
6509 if (gassign *assign_stmt = dyn_cast <gassign *> (stmt))
6511 tree lhs = gimple_assign_lhs (assign_stmt);
6512 if (TREE_CODE (lhs) == SSA_NAME
6513 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
6514 || POINTER_TYPE_P (TREE_TYPE (lhs)))
6515 && stmt_interesting_for_vrp (stmt))
6517 edge dummy_e;
6518 tree dummy_tree;
6519 value_range new_vr = VR_INITIALIZER;
6520 vr_values->extract_range_from_stmt (stmt, &dummy_e,
6521 &dummy_tree, &new_vr);
6522 if (range_int_cst_singleton_p (&new_vr))
6523 return new_vr.min;
6527 return NULL_TREE;
6530 class vrp_dom_walker : public dom_walker
6532 public:
6533 vrp_dom_walker (cdi_direction direction,
6534 class const_and_copies *const_and_copies,
6535 class avail_exprs_stack *avail_exprs_stack)
6536 : dom_walker (direction, REACHABLE_BLOCKS),
6537 m_const_and_copies (const_and_copies),
6538 m_avail_exprs_stack (avail_exprs_stack),
6539 m_dummy_cond (NULL) {}
6541 virtual edge before_dom_children (basic_block);
6542 virtual void after_dom_children (basic_block);
6544 class vr_values *vr_values;
6546 private:
6547 class const_and_copies *m_const_and_copies;
6548 class avail_exprs_stack *m_avail_exprs_stack;
6550 gcond *m_dummy_cond;
6554 /* Called before processing dominator children of BB. We want to look
6555 at ASSERT_EXPRs and record information from them in the appropriate
6556 tables.
6558 We could look at other statements here. It's not seen as likely
6559 to significantly increase the jump threads we discover. */
6561 edge
6562 vrp_dom_walker::before_dom_children (basic_block bb)
6564 gimple_stmt_iterator gsi;
6566 m_avail_exprs_stack->push_marker ();
6567 m_const_and_copies->push_marker ();
6568 for (gsi = gsi_start_nondebug_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
6570 gimple *stmt = gsi_stmt (gsi);
6571 if (gimple_assign_single_p (stmt)
6572 && TREE_CODE (gimple_assign_rhs1 (stmt)) == ASSERT_EXPR)
6574 tree rhs1 = gimple_assign_rhs1 (stmt);
6575 tree cond = TREE_OPERAND (rhs1, 1);
6576 tree inverted = invert_truthvalue (cond);
6577 vec<cond_equivalence> p;
6578 p.create (3);
6579 record_conditions (&p, cond, inverted);
6580 for (unsigned int i = 0; i < p.length (); i++)
6581 m_avail_exprs_stack->record_cond (&p[i]);
6583 tree lhs = gimple_assign_lhs (stmt);
6584 m_const_and_copies->record_const_or_copy (lhs,
6585 TREE_OPERAND (rhs1, 0));
6586 p.release ();
6587 continue;
6589 break;
6591 return NULL;
6594 /* Called after processing dominator children of BB. This is where we
6595 actually call into the threader. */
6596 void
6597 vrp_dom_walker::after_dom_children (basic_block bb)
6599 if (!m_dummy_cond)
6600 m_dummy_cond = gimple_build_cond (NE_EXPR,
6601 integer_zero_node, integer_zero_node,
6602 NULL, NULL);
6604 x_vr_values = vr_values;
6605 thread_outgoing_edges (bb, m_dummy_cond, m_const_and_copies,
6606 m_avail_exprs_stack, NULL,
6607 simplify_stmt_for_jump_threading);
6608 x_vr_values = NULL;
6610 m_avail_exprs_stack->pop_to_marker ();
6611 m_const_and_copies->pop_to_marker ();
6614 /* Blocks which have more than one predecessor and more than
6615 one successor present jump threading opportunities, i.e.,
6616 when the block is reached from a specific predecessor, we
6617 may be able to determine which of the outgoing edges will
6618 be traversed. When this optimization applies, we are able
6619 to avoid conditionals at runtime and we may expose secondary
6620 optimization opportunities.
6622 This routine is effectively a driver for the generic jump
6623 threading code. It basically just presents the generic code
6624 with edges that may be suitable for jump threading.
6626 Unlike DOM, we do not iterate VRP if jump threading was successful.
6627 While iterating may expose new opportunities for VRP, it is expected
6628 those opportunities would be very limited and the compile time cost
6629 to expose those opportunities would be significant.
6631 As jump threading opportunities are discovered, they are registered
6632 for later realization. */
6634 static void
6635 identify_jump_threads (class vr_values *vr_values)
6637 int i;
6638 edge e;
6640 /* Ugh. When substituting values earlier in this pass we can
6641 wipe the dominance information. So rebuild the dominator
6642 information as we need it within the jump threading code. */
6643 calculate_dominance_info (CDI_DOMINATORS);
6645 /* We do not allow VRP information to be used for jump threading
6646 across a back edge in the CFG. Otherwise it becomes too
6647 difficult to avoid eliminating loop exit tests. Of course
6648 EDGE_DFS_BACK is not accurate at this time so we have to
6649 recompute it. */
6650 mark_dfs_back_edges ();
6652 /* Do not thread across edges we are about to remove. Just marking
6653 them as EDGE_IGNORE will do. */
6654 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
6655 e->flags |= EDGE_IGNORE;
6657 /* Allocate our unwinder stack to unwind any temporary equivalences
6658 that might be recorded. */
6659 const_and_copies *equiv_stack = new const_and_copies ();
6661 hash_table<expr_elt_hasher> *avail_exprs
6662 = new hash_table<expr_elt_hasher> (1024);
6663 avail_exprs_stack *avail_exprs_stack
6664 = new class avail_exprs_stack (avail_exprs);
6666 vrp_dom_walker walker (CDI_DOMINATORS, equiv_stack, avail_exprs_stack);
6667 walker.vr_values = vr_values;
6668 walker.walk (cfun->cfg->x_entry_block_ptr);
6670 /* Clear EDGE_IGNORE. */
6671 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
6672 e->flags &= ~EDGE_IGNORE;
6674 /* We do not actually update the CFG or SSA graphs at this point as
6675 ASSERT_EXPRs are still in the IL and cfg cleanup code does not yet
6676 handle ASSERT_EXPRs gracefully. */
6677 delete equiv_stack;
6678 delete avail_exprs;
6679 delete avail_exprs_stack;
6682 /* Traverse all the blocks folding conditionals with known ranges. */
6684 void
6685 vrp_prop::vrp_finalize (bool warn_array_bounds_p)
6687 size_t i;
6689 /* We have completed propagating through the lattice. */
6690 vr_values.set_lattice_propagation_complete ();
6692 if (dump_file)
6694 fprintf (dump_file, "\nValue ranges after VRP:\n\n");
6695 vr_values.dump_all_value_ranges (dump_file);
6696 fprintf (dump_file, "\n");
6699 /* Set value range to non pointer SSA_NAMEs. */
6700 for (i = 0; i < num_ssa_names; i++)
6702 tree name = ssa_name (i);
6703 if (!name)
6704 continue;
6706 value_range *vr = get_value_range (name);
6707 if (!name
6708 || (vr->type == VR_VARYING)
6709 || (vr->type == VR_UNDEFINED)
6710 || (TREE_CODE (vr->min) != INTEGER_CST)
6711 || (TREE_CODE (vr->max) != INTEGER_CST))
6712 continue;
6714 if (POINTER_TYPE_P (TREE_TYPE (name))
6715 && ((vr->type == VR_RANGE
6716 && range_includes_zero_p (vr->min, vr->max) == 0)
6717 || (vr->type == VR_ANTI_RANGE
6718 && range_includes_zero_p (vr->min, vr->max) == 1)))
6719 set_ptr_nonnull (name);
6720 else if (!POINTER_TYPE_P (TREE_TYPE (name)))
6721 set_range_info (name, vr->type,
6722 wi::to_wide (vr->min),
6723 wi::to_wide (vr->max));
6726 /* If we're checking array refs, we want to merge information on
6727 the executability of each edge between vrp_folder and the
6728 check_array_bounds_dom_walker: each can clear the
6729 EDGE_EXECUTABLE flag on edges, in different ways.
6731 Hence, if we're going to call check_all_array_refs, set
6732 the flag on every edge now, rather than in
6733 check_array_bounds_dom_walker's ctor; vrp_folder may clear
6734 it from some edges. */
6735 if (warn_array_bounds && warn_array_bounds_p)
6736 set_all_edges_as_executable (cfun);
6738 class vrp_folder vrp_folder;
6739 vrp_folder.vr_values = &vr_values;
6740 vrp_folder.substitute_and_fold ();
6742 if (warn_array_bounds && warn_array_bounds_p)
6743 check_all_array_refs ();
6746 /* Main entry point to VRP (Value Range Propagation). This pass is
6747 loosely based on J. R. C. Patterson, ``Accurate Static Branch
6748 Prediction by Value Range Propagation,'' in SIGPLAN Conference on
6749 Programming Language Design and Implementation, pp. 67-78, 1995.
6750 Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
6752 This is essentially an SSA-CCP pass modified to deal with ranges
6753 instead of constants.
6755 While propagating ranges, we may find that two or more SSA name
6756 have equivalent, though distinct ranges. For instance,
6758 1 x_9 = p_3->a;
6759 2 p_4 = ASSERT_EXPR <p_3, p_3 != 0>
6760 3 if (p_4 == q_2)
6761 4 p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
6762 5 endif
6763 6 if (q_2)
6765 In the code above, pointer p_5 has range [q_2, q_2], but from the
6766 code we can also determine that p_5 cannot be NULL and, if q_2 had
6767 a non-varying range, p_5's range should also be compatible with it.
6769 These equivalences are created by two expressions: ASSERT_EXPR and
6770 copy operations. Since p_5 is an assertion on p_4, and p_4 was the
6771 result of another assertion, then we can use the fact that p_5 and
6772 p_4 are equivalent when evaluating p_5's range.
6774 Together with value ranges, we also propagate these equivalences
6775 between names so that we can take advantage of information from
6776 multiple ranges when doing final replacement. Note that this
6777 equivalency relation is transitive but not symmetric.
6779 In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
6780 cannot assert that q_2 is equivalent to p_5 because q_2 may be used
6781 in contexts where that assertion does not hold (e.g., in line 6).
6783 TODO, the main difference between this pass and Patterson's is that
6784 we do not propagate edge probabilities. We only compute whether
6785 edges can be taken or not. That is, instead of having a spectrum
6786 of jump probabilities between 0 and 1, we only deal with 0, 1 and
6787 DON'T KNOW. In the future, it may be worthwhile to propagate
6788 probabilities to aid branch prediction. */
6790 static unsigned int
6791 execute_vrp (bool warn_array_bounds_p)
6793 int i;
6794 edge e;
6795 switch_update *su;
6797 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
6798 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
6799 scev_initialize ();
6801 /* ??? This ends up using stale EDGE_DFS_BACK for liveness computation.
6802 Inserting assertions may split edges which will invalidate
6803 EDGE_DFS_BACK. */
6804 insert_range_assertions ();
6806 to_remove_edges.create (10);
6807 to_update_switch_stmts.create (5);
6808 threadedge_initialize_values ();
6810 /* For visiting PHI nodes we need EDGE_DFS_BACK computed. */
6811 mark_dfs_back_edges ();
6813 class vrp_prop vrp_prop;
6814 vrp_prop.vrp_initialize ();
6815 vrp_prop.ssa_propagate ();
6816 vrp_prop.vrp_finalize (warn_array_bounds_p);
6818 /* We must identify jump threading opportunities before we release
6819 the datastructures built by VRP. */
6820 identify_jump_threads (&vrp_prop.vr_values);
6822 /* A comparison of an SSA_NAME against a constant where the SSA_NAME
6823 was set by a type conversion can often be rewritten to use the
6824 RHS of the type conversion.
6826 However, doing so inhibits jump threading through the comparison.
6827 So that transformation is not performed until after jump threading
6828 is complete. */
6829 basic_block bb;
6830 FOR_EACH_BB_FN (bb, cfun)
6832 gimple *last = last_stmt (bb);
6833 if (last && gimple_code (last) == GIMPLE_COND)
6834 vrp_prop.vr_values.simplify_cond_using_ranges_2 (as_a <gcond *> (last));
6837 free_numbers_of_iterations_estimates (cfun);
6839 /* ASSERT_EXPRs must be removed before finalizing jump threads
6840 as finalizing jump threads calls the CFG cleanup code which
6841 does not properly handle ASSERT_EXPRs. */
6842 remove_range_assertions ();
6844 /* If we exposed any new variables, go ahead and put them into
6845 SSA form now, before we handle jump threading. This simplifies
6846 interactions between rewriting of _DECL nodes into SSA form
6847 and rewriting SSA_NAME nodes into SSA form after block
6848 duplication and CFG manipulation. */
6849 update_ssa (TODO_update_ssa);
6851 /* We identified all the jump threading opportunities earlier, but could
6852 not transform the CFG at that time. This routine transforms the
6853 CFG and arranges for the dominator tree to be rebuilt if necessary.
6855 Note the SSA graph update will occur during the normal TODO
6856 processing by the pass manager. */
6857 thread_through_all_blocks (false);
6859 /* Remove dead edges from SWITCH_EXPR optimization. This leaves the
6860 CFG in a broken state and requires a cfg_cleanup run. */
6861 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
6862 remove_edge (e);
6863 /* Update SWITCH_EXPR case label vector. */
6864 FOR_EACH_VEC_ELT (to_update_switch_stmts, i, su)
6866 size_t j;
6867 size_t n = TREE_VEC_LENGTH (su->vec);
6868 tree label;
6869 gimple_switch_set_num_labels (su->stmt, n);
6870 for (j = 0; j < n; j++)
6871 gimple_switch_set_label (su->stmt, j, TREE_VEC_ELT (su->vec, j));
6872 /* As we may have replaced the default label with a regular one
6873 make sure to make it a real default label again. This ensures
6874 optimal expansion. */
6875 label = gimple_switch_label (su->stmt, 0);
6876 CASE_LOW (label) = NULL_TREE;
6877 CASE_HIGH (label) = NULL_TREE;
6880 if (to_remove_edges.length () > 0)
6882 free_dominance_info (CDI_DOMINATORS);
6883 loops_state_set (LOOPS_NEED_FIXUP);
6886 to_remove_edges.release ();
6887 to_update_switch_stmts.release ();
6888 threadedge_finalize_values ();
6890 scev_finalize ();
6891 loop_optimizer_finalize ();
6892 return 0;
6895 namespace {
6897 const pass_data pass_data_vrp =
6899 GIMPLE_PASS, /* type */
6900 "vrp", /* name */
6901 OPTGROUP_NONE, /* optinfo_flags */
6902 TV_TREE_VRP, /* tv_id */
6903 PROP_ssa, /* properties_required */
6904 0, /* properties_provided */
6905 0, /* properties_destroyed */
6906 0, /* todo_flags_start */
6907 ( TODO_cleanup_cfg | TODO_update_ssa ), /* todo_flags_finish */
6910 class pass_vrp : public gimple_opt_pass
6912 public:
6913 pass_vrp (gcc::context *ctxt)
6914 : gimple_opt_pass (pass_data_vrp, ctxt), warn_array_bounds_p (false)
6917 /* opt_pass methods: */
6918 opt_pass * clone () { return new pass_vrp (m_ctxt); }
6919 void set_pass_param (unsigned int n, bool param)
6921 gcc_assert (n == 0);
6922 warn_array_bounds_p = param;
6924 virtual bool gate (function *) { return flag_tree_vrp != 0; }
6925 virtual unsigned int execute (function *)
6926 { return execute_vrp (warn_array_bounds_p); }
6928 private:
6929 bool warn_array_bounds_p;
6930 }; // class pass_vrp
6932 } // anon namespace
6934 gimple_opt_pass *
6935 make_pass_vrp (gcc::context *ctxt)
6937 return new pass_vrp (ctxt);
6941 /* Worker for determine_value_range. */
6943 static void
6944 determine_value_range_1 (value_range *vr, tree expr)
6946 if (BINARY_CLASS_P (expr))
6948 value_range vr0 = VR_INITIALIZER, vr1 = VR_INITIALIZER;
6949 determine_value_range_1 (&vr0, TREE_OPERAND (expr, 0));
6950 determine_value_range_1 (&vr1, TREE_OPERAND (expr, 1));
6951 extract_range_from_binary_expr_1 (vr, TREE_CODE (expr), TREE_TYPE (expr),
6952 &vr0, &vr1);
6954 else if (UNARY_CLASS_P (expr))
6956 value_range vr0 = VR_INITIALIZER;
6957 determine_value_range_1 (&vr0, TREE_OPERAND (expr, 0));
6958 extract_range_from_unary_expr (vr, TREE_CODE (expr), TREE_TYPE (expr),
6959 &vr0, TREE_TYPE (TREE_OPERAND (expr, 0)));
6961 else if (TREE_CODE (expr) == INTEGER_CST)
6962 set_value_range_to_value (vr, expr, NULL);
6963 else
6965 value_range_type kind;
6966 wide_int min, max;
6967 /* For SSA names try to extract range info computed by VRP. Otherwise
6968 fall back to varying. */
6969 if (TREE_CODE (expr) == SSA_NAME
6970 && INTEGRAL_TYPE_P (TREE_TYPE (expr))
6971 && (kind = get_range_info (expr, &min, &max)) != VR_VARYING)
6972 set_value_range (vr, kind, wide_int_to_tree (TREE_TYPE (expr), min),
6973 wide_int_to_tree (TREE_TYPE (expr), max), NULL);
6974 else
6975 set_value_range_to_varying (vr);
6979 /* Compute a value-range for EXPR and set it in *MIN and *MAX. Return
6980 the determined range type. */
6982 value_range_type
6983 determine_value_range (tree expr, wide_int *min, wide_int *max)
6985 value_range vr = VR_INITIALIZER;
6986 determine_value_range_1 (&vr, expr);
6987 if ((vr.type == VR_RANGE
6988 || vr.type == VR_ANTI_RANGE)
6989 && !symbolic_range_p (&vr))
6991 *min = wi::to_wide (vr.min);
6992 *max = wi::to_wide (vr.max);
6993 return vr.type;
6996 return VR_VARYING;