2018-02-09 Sebastian Perta <sebastian.perta@renesas.com>
[official-gcc.git] / gcc / tree-vrp.c
blobcba58e0279108293a2e8b923941512ded35bdac3
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"
71 /* Set of SSA names found live during the RPO traversal of the function
72 for still active basic-blocks. */
73 static sbitmap *live;
75 /* Return true if the SSA name NAME is live on the edge E. */
77 static bool
78 live_on_edge (edge e, tree name)
80 return (live[e->dest->index]
81 && bitmap_bit_p (live[e->dest->index], SSA_NAME_VERSION (name)));
84 /* Location information for ASSERT_EXPRs. Each instance of this
85 structure describes an ASSERT_EXPR for an SSA name. Since a single
86 SSA name may have more than one assertion associated with it, these
87 locations are kept in a linked list attached to the corresponding
88 SSA name. */
89 struct assert_locus
91 /* Basic block where the assertion would be inserted. */
92 basic_block bb;
94 /* Some assertions need to be inserted on an edge (e.g., assertions
95 generated by COND_EXPRs). In those cases, BB will be NULL. */
96 edge e;
98 /* Pointer to the statement that generated this assertion. */
99 gimple_stmt_iterator si;
101 /* Predicate code for the ASSERT_EXPR. Must be COMPARISON_CLASS_P. */
102 enum tree_code comp_code;
104 /* Value being compared against. */
105 tree val;
107 /* Expression to compare. */
108 tree expr;
110 /* Next node in the linked list. */
111 assert_locus *next;
114 /* If bit I is present, it means that SSA name N_i has a list of
115 assertions that should be inserted in the IL. */
116 static bitmap need_assert_for;
118 /* Array of locations lists where to insert assertions. ASSERTS_FOR[I]
119 holds a list of ASSERT_LOCUS_T nodes that describe where
120 ASSERT_EXPRs for SSA name N_I should be inserted. */
121 static assert_locus **asserts_for;
123 vec<edge> to_remove_edges;
124 vec<switch_update> to_update_switch_stmts;
127 /* Return the maximum value for TYPE. */
129 tree
130 vrp_val_max (const_tree type)
132 if (!INTEGRAL_TYPE_P (type))
133 return NULL_TREE;
135 return TYPE_MAX_VALUE (type);
138 /* Return the minimum value for TYPE. */
140 tree
141 vrp_val_min (const_tree type)
143 if (!INTEGRAL_TYPE_P (type))
144 return NULL_TREE;
146 return TYPE_MIN_VALUE (type);
149 /* Return whether VAL is equal to the maximum value of its type.
150 We can't do a simple equality comparison with TYPE_MAX_VALUE because
151 C typedefs and Ada subtypes can produce types whose TYPE_MAX_VALUE
152 is not == to the integer constant with the same value in the type. */
154 bool
155 vrp_val_is_max (const_tree val)
157 tree type_max = vrp_val_max (TREE_TYPE (val));
158 return (val == type_max
159 || (type_max != NULL_TREE
160 && operand_equal_p (val, type_max, 0)));
163 /* Return whether VAL is equal to the minimum value of its type. */
165 bool
166 vrp_val_is_min (const_tree val)
168 tree type_min = vrp_val_min (TREE_TYPE (val));
169 return (val == type_min
170 || (type_min != NULL_TREE
171 && operand_equal_p (val, type_min, 0)));
174 /* VR_TYPE describes a range with mininum value *MIN and maximum
175 value *MAX. Restrict the range to the set of values that have
176 no bits set outside NONZERO_BITS. Update *MIN and *MAX and
177 return the new range type.
179 SGN gives the sign of the values described by the range. */
181 enum value_range_type
182 intersect_range_with_nonzero_bits (enum value_range_type vr_type,
183 wide_int *min, wide_int *max,
184 const wide_int &nonzero_bits,
185 signop sgn)
187 if (vr_type == VR_RANGE)
189 *max = wi::round_down_for_mask (*max, nonzero_bits);
191 /* Check that the range contains at least one valid value. */
192 if (wi::gt_p (*min, *max, sgn))
193 return VR_UNDEFINED;
195 *min = wi::round_up_for_mask (*min, nonzero_bits);
196 gcc_checking_assert (wi::le_p (*min, *max, sgn));
198 if (vr_type == VR_ANTI_RANGE)
200 *max = wi::round_up_for_mask (*max, nonzero_bits);
202 /* If the calculation wrapped, we now have a VR_RANGE whose
203 lower bound is *MAX and whose upper bound is *MIN. */
204 if (wi::gt_p (*min, *max, sgn))
206 std::swap (*min, *max);
207 *max = wi::round_down_for_mask (*max, nonzero_bits);
208 gcc_checking_assert (wi::le_p (*min, *max, sgn));
209 return VR_RANGE;
212 *min = wi::round_down_for_mask (*min, nonzero_bits);
213 gcc_checking_assert (wi::le_p (*min, *max, sgn));
215 /* Check whether we now have an empty set of values. */
216 if (*min - 1 == *max)
217 return VR_UNDEFINED;
219 return vr_type;
222 /* Set value range VR to VR_UNDEFINED. */
224 static inline void
225 set_value_range_to_undefined (value_range *vr)
227 vr->type = VR_UNDEFINED;
228 vr->min = vr->max = NULL_TREE;
229 if (vr->equiv)
230 bitmap_clear (vr->equiv);
233 /* Set value range VR to VR_VARYING. */
235 void
236 set_value_range_to_varying (value_range *vr)
238 vr->type = VR_VARYING;
239 vr->min = vr->max = NULL_TREE;
240 if (vr->equiv)
241 bitmap_clear (vr->equiv);
244 /* Set value range VR to {T, MIN, MAX, EQUIV}. */
246 void
247 set_value_range (value_range *vr, enum value_range_type t, tree min,
248 tree max, bitmap equiv)
250 /* Check the validity of the range. */
251 if (flag_checking
252 && (t == VR_RANGE || t == VR_ANTI_RANGE))
254 int cmp;
256 gcc_assert (min && max);
258 gcc_assert (!TREE_OVERFLOW_P (min) && !TREE_OVERFLOW_P (max));
260 if (INTEGRAL_TYPE_P (TREE_TYPE (min)) && t == VR_ANTI_RANGE)
261 gcc_assert (!vrp_val_is_min (min) || !vrp_val_is_max (max));
263 cmp = compare_values (min, max);
264 gcc_assert (cmp == 0 || cmp == -1 || cmp == -2);
267 if (flag_checking
268 && (t == VR_UNDEFINED || t == VR_VARYING))
270 gcc_assert (min == NULL_TREE && max == NULL_TREE);
271 gcc_assert (equiv == NULL || bitmap_empty_p (equiv));
274 vr->type = t;
275 vr->min = min;
276 vr->max = max;
278 /* Since updating the equivalence set involves deep copying the
279 bitmaps, only do it if absolutely necessary.
281 All equivalence bitmaps are allocated from the same obstack. So
282 we can use the obstack associated with EQUIV to allocate vr->equiv. */
283 if (vr->equiv == NULL
284 && equiv != NULL)
285 vr->equiv = BITMAP_ALLOC (equiv->obstack);
287 if (equiv != vr->equiv)
289 if (equiv && !bitmap_empty_p (equiv))
290 bitmap_copy (vr->equiv, equiv);
291 else
292 bitmap_clear (vr->equiv);
297 /* Set value range VR to the canonical form of {T, MIN, MAX, EQUIV}.
298 This means adjusting T, MIN and MAX representing the case of a
299 wrapping range with MAX < MIN covering [MIN, type_max] U [type_min, MAX]
300 as anti-rage ~[MAX+1, MIN-1]. Likewise for wrapping anti-ranges.
301 In corner cases where MAX+1 or MIN-1 wraps this will fall back
302 to varying.
303 This routine exists to ease canonicalization in the case where we
304 extract ranges from var + CST op limit. */
306 void
307 set_and_canonicalize_value_range (value_range *vr, enum value_range_type t,
308 tree min, tree max, bitmap equiv)
310 /* Use the canonical setters for VR_UNDEFINED and VR_VARYING. */
311 if (t == VR_UNDEFINED)
313 set_value_range_to_undefined (vr);
314 return;
316 else if (t == VR_VARYING)
318 set_value_range_to_varying (vr);
319 return;
322 /* Nothing to canonicalize for symbolic ranges. */
323 if (TREE_CODE (min) != INTEGER_CST
324 || TREE_CODE (max) != INTEGER_CST)
326 set_value_range (vr, t, min, max, equiv);
327 return;
330 /* Wrong order for min and max, to swap them and the VR type we need
331 to adjust them. */
332 if (tree_int_cst_lt (max, min))
334 tree one, tmp;
336 /* For one bit precision if max < min, then the swapped
337 range covers all values, so for VR_RANGE it is varying and
338 for VR_ANTI_RANGE empty range, so drop to varying as well. */
339 if (TYPE_PRECISION (TREE_TYPE (min)) == 1)
341 set_value_range_to_varying (vr);
342 return;
345 one = build_int_cst (TREE_TYPE (min), 1);
346 tmp = int_const_binop (PLUS_EXPR, max, one);
347 max = int_const_binop (MINUS_EXPR, min, one);
348 min = tmp;
350 /* There's one corner case, if we had [C+1, C] before we now have
351 that again. But this represents an empty value range, so drop
352 to varying in this case. */
353 if (tree_int_cst_lt (max, min))
355 set_value_range_to_varying (vr);
356 return;
359 t = t == VR_RANGE ? VR_ANTI_RANGE : VR_RANGE;
362 /* Anti-ranges that can be represented as ranges should be so. */
363 if (t == VR_ANTI_RANGE)
365 bool is_min = vrp_val_is_min (min);
366 bool is_max = vrp_val_is_max (max);
368 if (is_min && is_max)
370 /* We cannot deal with empty ranges, drop to varying.
371 ??? This could be VR_UNDEFINED instead. */
372 set_value_range_to_varying (vr);
373 return;
375 else if (TYPE_PRECISION (TREE_TYPE (min)) == 1
376 && (is_min || is_max))
378 /* Non-empty boolean ranges can always be represented
379 as a singleton range. */
380 if (is_min)
381 min = max = vrp_val_max (TREE_TYPE (min));
382 else
383 min = max = vrp_val_min (TREE_TYPE (min));
384 t = VR_RANGE;
386 else if (is_min
387 /* As a special exception preserve non-null ranges. */
388 && !(TYPE_UNSIGNED (TREE_TYPE (min))
389 && integer_zerop (max)))
391 tree one = build_int_cst (TREE_TYPE (max), 1);
392 min = int_const_binop (PLUS_EXPR, max, one);
393 max = vrp_val_max (TREE_TYPE (max));
394 t = VR_RANGE;
396 else if (is_max)
398 tree one = build_int_cst (TREE_TYPE (min), 1);
399 max = int_const_binop (MINUS_EXPR, min, one);
400 min = vrp_val_min (TREE_TYPE (min));
401 t = VR_RANGE;
405 /* Do not drop [-INF(OVF), +INF(OVF)] to varying. (OVF) has to be sticky
406 to make sure VRP iteration terminates, otherwise we can get into
407 oscillations. */
409 set_value_range (vr, t, min, max, equiv);
412 /* Copy value range FROM into value range TO. */
414 void
415 copy_value_range (value_range *to, value_range *from)
417 set_value_range (to, from->type, from->min, from->max, from->equiv);
420 /* Set value range VR to a single value. This function is only called
421 with values we get from statements, and exists to clear the
422 TREE_OVERFLOW flag. */
424 void
425 set_value_range_to_value (value_range *vr, tree val, bitmap equiv)
427 gcc_assert (is_gimple_min_invariant (val));
428 if (TREE_OVERFLOW_P (val))
429 val = drop_tree_overflow (val);
430 set_value_range (vr, VR_RANGE, val, val, equiv);
433 /* Set value range VR to a non-NULL range of type TYPE. */
435 void
436 set_value_range_to_nonnull (value_range *vr, tree type)
438 tree zero = build_int_cst (type, 0);
439 set_value_range (vr, VR_ANTI_RANGE, zero, zero, vr->equiv);
443 /* Set value range VR to a NULL range of type TYPE. */
445 void
446 set_value_range_to_null (value_range *vr, tree type)
448 set_value_range_to_value (vr, build_int_cst (type, 0), vr->equiv);
452 /* If abs (min) < abs (max), set VR to [-max, max], if
453 abs (min) >= abs (max), set VR to [-min, min]. */
455 static void
456 abs_extent_range (value_range *vr, tree min, tree max)
458 int cmp;
460 gcc_assert (TREE_CODE (min) == INTEGER_CST);
461 gcc_assert (TREE_CODE (max) == INTEGER_CST);
462 gcc_assert (INTEGRAL_TYPE_P (TREE_TYPE (min)));
463 gcc_assert (!TYPE_UNSIGNED (TREE_TYPE (min)));
464 min = fold_unary (ABS_EXPR, TREE_TYPE (min), min);
465 max = fold_unary (ABS_EXPR, TREE_TYPE (max), max);
466 if (TREE_OVERFLOW (min) || TREE_OVERFLOW (max))
468 set_value_range_to_varying (vr);
469 return;
471 cmp = compare_values (min, max);
472 if (cmp == -1)
473 min = fold_unary (NEGATE_EXPR, TREE_TYPE (min), max);
474 else if (cmp == 0 || cmp == 1)
476 max = min;
477 min = fold_unary (NEGATE_EXPR, TREE_TYPE (min), min);
479 else
481 set_value_range_to_varying (vr);
482 return;
484 set_and_canonicalize_value_range (vr, VR_RANGE, min, max, NULL);
487 /* Return true, if VAL1 and VAL2 are equal values for VRP purposes. */
489 bool
490 vrp_operand_equal_p (const_tree val1, const_tree val2)
492 if (val1 == val2)
493 return true;
494 if (!val1 || !val2 || !operand_equal_p (val1, val2, 0))
495 return false;
496 return true;
499 /* Return true, if the bitmaps B1 and B2 are equal. */
501 bool
502 vrp_bitmap_equal_p (const_bitmap b1, const_bitmap b2)
504 return (b1 == b2
505 || ((!b1 || bitmap_empty_p (b1))
506 && (!b2 || bitmap_empty_p (b2)))
507 || (b1 && b2
508 && bitmap_equal_p (b1, b2)));
511 /* Return true if VR is ~[0, 0]. */
513 bool
514 range_is_nonnull (value_range *vr)
516 return vr->type == VR_ANTI_RANGE
517 && integer_zerop (vr->min)
518 && integer_zerop (vr->max);
522 /* Return true if VR is [0, 0]. */
524 static inline bool
525 range_is_null (value_range *vr)
527 return vr->type == VR_RANGE
528 && integer_zerop (vr->min)
529 && integer_zerop (vr->max);
532 /* Return true if max and min of VR are INTEGER_CST. It's not necessary
533 a singleton. */
535 bool
536 range_int_cst_p (value_range *vr)
538 return (vr->type == VR_RANGE
539 && TREE_CODE (vr->max) == INTEGER_CST
540 && TREE_CODE (vr->min) == INTEGER_CST);
543 /* Return true if VR is a INTEGER_CST singleton. */
545 bool
546 range_int_cst_singleton_p (value_range *vr)
548 return (range_int_cst_p (vr)
549 && tree_int_cst_equal (vr->min, vr->max));
552 /* Return true if value range VR involves at least one symbol. */
554 bool
555 symbolic_range_p (value_range *vr)
557 return (!is_gimple_min_invariant (vr->min)
558 || !is_gimple_min_invariant (vr->max));
561 /* Return the single symbol (an SSA_NAME) contained in T if any, or NULL_TREE
562 otherwise. We only handle additive operations and set NEG to true if the
563 symbol is negated and INV to the invariant part, if any. */
565 tree
566 get_single_symbol (tree t, bool *neg, tree *inv)
568 bool neg_;
569 tree inv_;
571 *inv = NULL_TREE;
572 *neg = false;
574 if (TREE_CODE (t) == PLUS_EXPR
575 || TREE_CODE (t) == POINTER_PLUS_EXPR
576 || TREE_CODE (t) == MINUS_EXPR)
578 if (is_gimple_min_invariant (TREE_OPERAND (t, 0)))
580 neg_ = (TREE_CODE (t) == MINUS_EXPR);
581 inv_ = TREE_OPERAND (t, 0);
582 t = TREE_OPERAND (t, 1);
584 else if (is_gimple_min_invariant (TREE_OPERAND (t, 1)))
586 neg_ = false;
587 inv_ = TREE_OPERAND (t, 1);
588 t = TREE_OPERAND (t, 0);
590 else
591 return NULL_TREE;
593 else
595 neg_ = false;
596 inv_ = NULL_TREE;
599 if (TREE_CODE (t) == NEGATE_EXPR)
601 t = TREE_OPERAND (t, 0);
602 neg_ = !neg_;
605 if (TREE_CODE (t) != SSA_NAME)
606 return NULL_TREE;
608 if (inv_ && TREE_OVERFLOW_P (inv_))
609 inv_ = drop_tree_overflow (inv_);
611 *neg = neg_;
612 *inv = inv_;
613 return t;
616 /* The reverse operation: build a symbolic expression with TYPE
617 from symbol SYM, negated according to NEG, and invariant INV. */
619 static tree
620 build_symbolic_expr (tree type, tree sym, bool neg, tree inv)
622 const bool pointer_p = POINTER_TYPE_P (type);
623 tree t = sym;
625 if (neg)
626 t = build1 (NEGATE_EXPR, type, t);
628 if (integer_zerop (inv))
629 return t;
631 return build2 (pointer_p ? POINTER_PLUS_EXPR : PLUS_EXPR, type, t, inv);
634 /* Return
635 1 if VAL < VAL2
636 0 if !(VAL < VAL2)
637 -2 if those are incomparable. */
639 operand_less_p (tree val, tree val2)
641 /* LT is folded faster than GE and others. Inline the common case. */
642 if (TREE_CODE (val) == INTEGER_CST && TREE_CODE (val2) == INTEGER_CST)
643 return tree_int_cst_lt (val, val2);
644 else
646 tree tcmp;
648 fold_defer_overflow_warnings ();
650 tcmp = fold_binary_to_constant (LT_EXPR, boolean_type_node, val, val2);
652 fold_undefer_and_ignore_overflow_warnings ();
654 if (!tcmp
655 || TREE_CODE (tcmp) != INTEGER_CST)
656 return -2;
658 if (!integer_zerop (tcmp))
659 return 1;
662 return 0;
665 /* Compare two values VAL1 and VAL2. Return
667 -2 if VAL1 and VAL2 cannot be compared at compile-time,
668 -1 if VAL1 < VAL2,
669 0 if VAL1 == VAL2,
670 +1 if VAL1 > VAL2, and
671 +2 if VAL1 != VAL2
673 This is similar to tree_int_cst_compare but supports pointer values
674 and values that cannot be compared at compile time.
676 If STRICT_OVERFLOW_P is not NULL, then set *STRICT_OVERFLOW_P to
677 true if the return value is only valid if we assume that signed
678 overflow is undefined. */
681 compare_values_warnv (tree val1, tree val2, bool *strict_overflow_p)
683 if (val1 == val2)
684 return 0;
686 /* Below we rely on the fact that VAL1 and VAL2 are both pointers or
687 both integers. */
688 gcc_assert (POINTER_TYPE_P (TREE_TYPE (val1))
689 == POINTER_TYPE_P (TREE_TYPE (val2)));
691 /* Convert the two values into the same type. This is needed because
692 sizetype causes sign extension even for unsigned types. */
693 val2 = fold_convert (TREE_TYPE (val1), val2);
694 STRIP_USELESS_TYPE_CONVERSION (val2);
696 const bool overflow_undefined
697 = INTEGRAL_TYPE_P (TREE_TYPE (val1))
698 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1));
699 tree inv1, inv2;
700 bool neg1, neg2;
701 tree sym1 = get_single_symbol (val1, &neg1, &inv1);
702 tree sym2 = get_single_symbol (val2, &neg2, &inv2);
704 /* If VAL1 and VAL2 are of the form '[-]NAME [+ CST]', return -1 or +1
705 accordingly. If VAL1 and VAL2 don't use the same name, return -2. */
706 if (sym1 && sym2)
708 /* Both values must use the same name with the same sign. */
709 if (sym1 != sym2 || neg1 != neg2)
710 return -2;
712 /* [-]NAME + CST == [-]NAME + CST. */
713 if (inv1 == inv2)
714 return 0;
716 /* If overflow is defined we cannot simplify more. */
717 if (!overflow_undefined)
718 return -2;
720 if (strict_overflow_p != NULL
721 /* Symbolic range building sets TREE_NO_WARNING to declare
722 that overflow doesn't happen. */
723 && (!inv1 || !TREE_NO_WARNING (val1))
724 && (!inv2 || !TREE_NO_WARNING (val2)))
725 *strict_overflow_p = true;
727 if (!inv1)
728 inv1 = build_int_cst (TREE_TYPE (val1), 0);
729 if (!inv2)
730 inv2 = build_int_cst (TREE_TYPE (val2), 0);
732 return wi::cmp (wi::to_wide (inv1), wi::to_wide (inv2),
733 TYPE_SIGN (TREE_TYPE (val1)));
736 const bool cst1 = is_gimple_min_invariant (val1);
737 const bool cst2 = is_gimple_min_invariant (val2);
739 /* If one is of the form '[-]NAME + CST' and the other is constant, then
740 it might be possible to say something depending on the constants. */
741 if ((sym1 && inv1 && cst2) || (sym2 && inv2 && cst1))
743 if (!overflow_undefined)
744 return -2;
746 if (strict_overflow_p != NULL
747 /* Symbolic range building sets TREE_NO_WARNING to declare
748 that overflow doesn't happen. */
749 && (!sym1 || !TREE_NO_WARNING (val1))
750 && (!sym2 || !TREE_NO_WARNING (val2)))
751 *strict_overflow_p = true;
753 const signop sgn = TYPE_SIGN (TREE_TYPE (val1));
754 tree cst = cst1 ? val1 : val2;
755 tree inv = cst1 ? inv2 : inv1;
757 /* Compute the difference between the constants. If it overflows or
758 underflows, this means that we can trivially compare the NAME with
759 it and, consequently, the two values with each other. */
760 wide_int diff = wi::to_wide (cst) - wi::to_wide (inv);
761 if (wi::cmp (0, wi::to_wide (inv), sgn)
762 != wi::cmp (diff, wi::to_wide (cst), sgn))
764 const int res = wi::cmp (wi::to_wide (cst), wi::to_wide (inv), sgn);
765 return cst1 ? res : -res;
768 return -2;
771 /* We cannot say anything more for non-constants. */
772 if (!cst1 || !cst2)
773 return -2;
775 if (!POINTER_TYPE_P (TREE_TYPE (val1)))
777 /* We cannot compare overflowed values. */
778 if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
779 return -2;
781 if (TREE_CODE (val1) == INTEGER_CST
782 && TREE_CODE (val2) == INTEGER_CST)
783 return tree_int_cst_compare (val1, val2);
785 if (poly_int_tree_p (val1) && poly_int_tree_p (val2))
787 if (known_eq (wi::to_poly_widest (val1),
788 wi::to_poly_widest (val2)))
789 return 0;
790 if (known_lt (wi::to_poly_widest (val1),
791 wi::to_poly_widest (val2)))
792 return -1;
793 if (known_gt (wi::to_poly_widest (val1),
794 wi::to_poly_widest (val2)))
795 return 1;
798 return -2;
800 else
802 tree t;
804 /* First see if VAL1 and VAL2 are not the same. */
805 if (val1 == val2 || operand_equal_p (val1, val2, 0))
806 return 0;
808 /* If VAL1 is a lower address than VAL2, return -1. */
809 if (operand_less_p (val1, val2) == 1)
810 return -1;
812 /* If VAL1 is a higher address than VAL2, return +1. */
813 if (operand_less_p (val2, val1) == 1)
814 return 1;
816 /* If VAL1 is different than VAL2, return +2.
817 For integer constants we either have already returned -1 or 1
818 or they are equivalent. We still might succeed in proving
819 something about non-trivial operands. */
820 if (TREE_CODE (val1) != INTEGER_CST
821 || TREE_CODE (val2) != INTEGER_CST)
823 t = fold_binary_to_constant (NE_EXPR, boolean_type_node, val1, val2);
824 if (t && integer_onep (t))
825 return 2;
828 return -2;
832 /* Compare values like compare_values_warnv. */
835 compare_values (tree val1, tree val2)
837 bool sop;
838 return compare_values_warnv (val1, val2, &sop);
842 /* Return 1 if VAL is inside value range MIN <= VAL <= MAX,
843 0 if VAL is not inside [MIN, MAX],
844 -2 if we cannot tell either way.
846 Benchmark compile/20001226-1.c compilation time after changing this
847 function. */
850 value_inside_range (tree val, tree min, tree max)
852 int cmp1, cmp2;
854 cmp1 = operand_less_p (val, min);
855 if (cmp1 == -2)
856 return -2;
857 if (cmp1 == 1)
858 return 0;
860 cmp2 = operand_less_p (max, val);
861 if (cmp2 == -2)
862 return -2;
864 return !cmp2;
868 /* Return true if value ranges VR0 and VR1 have a non-empty
869 intersection.
871 Benchmark compile/20001226-1.c compilation time after changing this
872 function.
875 static inline bool
876 value_ranges_intersect_p (value_range *vr0, value_range *vr1)
878 /* The value ranges do not intersect if the maximum of the first range is
879 less than the minimum of the second range or vice versa.
880 When those relations are unknown, we can't do any better. */
881 if (operand_less_p (vr0->max, vr1->min) != 0)
882 return false;
883 if (operand_less_p (vr1->max, vr0->min) != 0)
884 return false;
885 return true;
889 /* Return 1 if [MIN, MAX] includes the value zero, 0 if it does not
890 include the value zero, -2 if we cannot tell. */
893 range_includes_zero_p (tree min, tree max)
895 tree zero = build_int_cst (TREE_TYPE (min), 0);
896 return value_inside_range (zero, min, max);
899 /* Return true if *VR is know to only contain nonnegative values. */
901 static inline bool
902 value_range_nonnegative_p (value_range *vr)
904 /* Testing for VR_ANTI_RANGE is not useful here as any anti-range
905 which would return a useful value should be encoded as a
906 VR_RANGE. */
907 if (vr->type == VR_RANGE)
909 int result = compare_values (vr->min, integer_zero_node);
910 return (result == 0 || result == 1);
913 return false;
916 /* If *VR has a value rante that is a single constant value return that,
917 otherwise return NULL_TREE. */
919 tree
920 value_range_constant_singleton (value_range *vr)
922 if (vr->type == VR_RANGE
923 && vrp_operand_equal_p (vr->min, vr->max)
924 && is_gimple_min_invariant (vr->min))
925 return vr->min;
927 return NULL_TREE;
930 /* Wrapper around int_const_binop. Return true if we can compute the
931 result; i.e. if the operation doesn't overflow or if the overflow is
932 undefined. In the latter case (if the operation overflows and
933 overflow is undefined), then adjust the result to be -INF or +INF
934 depending on CODE, VAL1 and VAL2. Return the value in *RES.
936 Return false for division by zero, for which the result is
937 indeterminate. */
939 static bool
940 vrp_int_const_binop (enum tree_code code, tree val1, tree val2, wide_int *res)
942 bool overflow = false;
943 signop sign = TYPE_SIGN (TREE_TYPE (val1));
945 switch (code)
947 case RSHIFT_EXPR:
948 case LSHIFT_EXPR:
950 wide_int wval2 = wi::to_wide (val2, TYPE_PRECISION (TREE_TYPE (val1)));
951 if (wi::neg_p (wval2))
953 wval2 = -wval2;
954 if (code == RSHIFT_EXPR)
955 code = LSHIFT_EXPR;
956 else
957 code = RSHIFT_EXPR;
960 if (code == RSHIFT_EXPR)
961 /* It's unclear from the C standard whether shifts can overflow.
962 The following code ignores overflow; perhaps a C standard
963 interpretation ruling is needed. */
964 *res = wi::rshift (wi::to_wide (val1), wval2, sign);
965 else
966 *res = wi::lshift (wi::to_wide (val1), wval2);
967 break;
970 case MULT_EXPR:
971 *res = wi::mul (wi::to_wide (val1),
972 wi::to_wide (val2), sign, &overflow);
973 break;
975 case TRUNC_DIV_EXPR:
976 case EXACT_DIV_EXPR:
977 if (val2 == 0)
978 return false;
979 else
980 *res = wi::div_trunc (wi::to_wide (val1),
981 wi::to_wide (val2), sign, &overflow);
982 break;
984 case FLOOR_DIV_EXPR:
985 if (val2 == 0)
986 return false;
987 *res = wi::div_floor (wi::to_wide (val1),
988 wi::to_wide (val2), sign, &overflow);
989 break;
991 case CEIL_DIV_EXPR:
992 if (val2 == 0)
993 return false;
994 *res = wi::div_ceil (wi::to_wide (val1),
995 wi::to_wide (val2), sign, &overflow);
996 break;
998 case ROUND_DIV_EXPR:
999 if (val2 == 0)
1000 return false;
1001 *res = wi::div_round (wi::to_wide (val1),
1002 wi::to_wide (val2), sign, &overflow);
1003 break;
1005 default:
1006 gcc_unreachable ();
1009 if (overflow
1010 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1)))
1012 /* If the operation overflowed return -INF or +INF depending
1013 on the operation and the combination of signs of the operands. */
1014 int sgn1 = tree_int_cst_sgn (val1);
1015 int sgn2 = tree_int_cst_sgn (val2);
1017 /* Notice that we only need to handle the restricted set of
1018 operations handled by extract_range_from_binary_expr.
1019 Among them, only multiplication, addition and subtraction
1020 can yield overflow without overflown operands because we
1021 are working with integral types only... except in the
1022 case VAL1 = -INF and VAL2 = -1 which overflows to +INF
1023 for division too. */
1025 /* For multiplication, the sign of the overflow is given
1026 by the comparison of the signs of the operands. */
1027 if ((code == MULT_EXPR && sgn1 == sgn2)
1028 /* For addition, the operands must be of the same sign
1029 to yield an overflow. Its sign is therefore that
1030 of one of the operands, for example the first. */
1031 || (code == PLUS_EXPR && sgn1 >= 0)
1032 /* For subtraction, operands must be of
1033 different signs to yield an overflow. Its sign is
1034 therefore that of the first operand or the opposite of
1035 that of the second operand. A first operand of 0 counts
1036 as positive here, for the corner case 0 - (-INF), which
1037 overflows, but must yield +INF. */
1038 || (code == MINUS_EXPR && sgn1 >= 0)
1039 /* For division, the only case is -INF / -1 = +INF. */
1040 || code == TRUNC_DIV_EXPR
1041 || code == FLOOR_DIV_EXPR
1042 || code == CEIL_DIV_EXPR
1043 || code == EXACT_DIV_EXPR
1044 || code == ROUND_DIV_EXPR)
1045 *res = wi::max_value (TYPE_PRECISION (TREE_TYPE (val1)),
1046 TYPE_SIGN (TREE_TYPE (val1)));
1047 else
1048 *res = wi::min_value (TYPE_PRECISION (TREE_TYPE (val1)),
1049 TYPE_SIGN (TREE_TYPE (val1)));
1050 return true;
1053 return !overflow;
1057 /* For range VR compute two wide_int bitmasks. In *MAY_BE_NONZERO
1058 bitmask if some bit is unset, it means for all numbers in the range
1059 the bit is 0, otherwise it might be 0 or 1. In *MUST_BE_NONZERO
1060 bitmask if some bit is set, it means for all numbers in the range
1061 the bit is 1, otherwise it might be 0 or 1. */
1063 bool
1064 zero_nonzero_bits_from_vr (const tree expr_type,
1065 value_range *vr,
1066 wide_int *may_be_nonzero,
1067 wide_int *must_be_nonzero)
1069 *may_be_nonzero = wi::minus_one (TYPE_PRECISION (expr_type));
1070 *must_be_nonzero = wi::zero (TYPE_PRECISION (expr_type));
1071 if (!range_int_cst_p (vr))
1072 return false;
1074 if (range_int_cst_singleton_p (vr))
1076 *may_be_nonzero = wi::to_wide (vr->min);
1077 *must_be_nonzero = *may_be_nonzero;
1079 else if (tree_int_cst_sgn (vr->min) >= 0
1080 || tree_int_cst_sgn (vr->max) < 0)
1082 wide_int xor_mask = wi::to_wide (vr->min) ^ wi::to_wide (vr->max);
1083 *may_be_nonzero = wi::to_wide (vr->min) | wi::to_wide (vr->max);
1084 *must_be_nonzero = wi::to_wide (vr->min) & wi::to_wide (vr->max);
1085 if (xor_mask != 0)
1087 wide_int mask = wi::mask (wi::floor_log2 (xor_mask), false,
1088 may_be_nonzero->get_precision ());
1089 *may_be_nonzero = *may_be_nonzero | mask;
1090 *must_be_nonzero = wi::bit_and_not (*must_be_nonzero, mask);
1094 return true;
1097 /* Create two value-ranges in *VR0 and *VR1 from the anti-range *AR
1098 so that *VR0 U *VR1 == *AR. Returns true if that is possible,
1099 false otherwise. If *AR can be represented with a single range
1100 *VR1 will be VR_UNDEFINED. */
1102 static bool
1103 ranges_from_anti_range (value_range *ar,
1104 value_range *vr0, value_range *vr1)
1106 tree type = TREE_TYPE (ar->min);
1108 vr0->type = VR_UNDEFINED;
1109 vr1->type = VR_UNDEFINED;
1111 if (ar->type != VR_ANTI_RANGE
1112 || TREE_CODE (ar->min) != INTEGER_CST
1113 || TREE_CODE (ar->max) != INTEGER_CST
1114 || !vrp_val_min (type)
1115 || !vrp_val_max (type))
1116 return false;
1118 if (!vrp_val_is_min (ar->min))
1120 vr0->type = VR_RANGE;
1121 vr0->min = vrp_val_min (type);
1122 vr0->max = wide_int_to_tree (type, wi::to_wide (ar->min) - 1);
1124 if (!vrp_val_is_max (ar->max))
1126 vr1->type = VR_RANGE;
1127 vr1->min = wide_int_to_tree (type, wi::to_wide (ar->max) + 1);
1128 vr1->max = vrp_val_max (type);
1130 if (vr0->type == VR_UNDEFINED)
1132 *vr0 = *vr1;
1133 vr1->type = VR_UNDEFINED;
1136 return vr0->type != VR_UNDEFINED;
1139 /* Helper to extract a value-range *VR for a multiplicative operation
1140 *VR0 CODE *VR1. */
1142 static void
1143 extract_range_from_multiplicative_op_1 (value_range *vr,
1144 enum tree_code code,
1145 value_range *vr0, value_range *vr1)
1147 enum value_range_type rtype;
1148 wide_int val, min, max;
1149 tree type;
1151 /* Multiplications, divisions and shifts are a bit tricky to handle,
1152 depending on the mix of signs we have in the two ranges, we
1153 need to operate on different values to get the minimum and
1154 maximum values for the new range. One approach is to figure
1155 out all the variations of range combinations and do the
1156 operations.
1158 However, this involves several calls to compare_values and it
1159 is pretty convoluted. It's simpler to do the 4 operations
1160 (MIN0 OP MIN1, MIN0 OP MAX1, MAX0 OP MIN1 and MAX0 OP MAX0 OP
1161 MAX1) and then figure the smallest and largest values to form
1162 the new range. */
1163 gcc_assert (code == MULT_EXPR
1164 || code == TRUNC_DIV_EXPR
1165 || code == FLOOR_DIV_EXPR
1166 || code == CEIL_DIV_EXPR
1167 || code == EXACT_DIV_EXPR
1168 || code == ROUND_DIV_EXPR
1169 || code == RSHIFT_EXPR
1170 || code == LSHIFT_EXPR);
1171 gcc_assert (vr0->type == VR_RANGE
1172 && vr0->type == vr1->type);
1174 rtype = vr0->type;
1175 type = TREE_TYPE (vr0->min);
1176 signop sgn = TYPE_SIGN (type);
1178 /* Compute the 4 cross operations and their minimum and maximum value. */
1179 if (!vrp_int_const_binop (code, vr0->min, vr1->min, &val))
1181 set_value_range_to_varying (vr);
1182 return;
1184 min = max = val;
1186 if (vr1->max != vr1->min)
1188 if (!vrp_int_const_binop (code, vr0->min, vr1->max, &val))
1190 set_value_range_to_varying (vr);
1191 return;
1193 if (wi::lt_p (val, min, sgn))
1194 min = val;
1195 else if (wi::gt_p (val, max, sgn))
1196 max = val;
1199 if (vr0->max != vr0->min)
1201 if (!vrp_int_const_binop (code, vr0->max, vr1->min, &val))
1203 set_value_range_to_varying (vr);
1204 return;
1206 if (wi::lt_p (val, min, sgn))
1207 min = val;
1208 else if (wi::gt_p (val, max, sgn))
1209 max = val;
1212 if (vr0->min != vr0->max && vr1->min != vr1->max)
1214 if (!vrp_int_const_binop (code, vr0->max, vr1->max, &val))
1216 set_value_range_to_varying (vr);
1217 return;
1219 if (wi::lt_p (val, min, sgn))
1220 min = val;
1221 else if (wi::gt_p (val, max, sgn))
1222 max = val;
1225 /* If the new range has its limits swapped around (MIN > MAX),
1226 then the operation caused one of them to wrap around, mark
1227 the new range VARYING. */
1228 if (wi::gt_p (min, max, sgn))
1230 set_value_range_to_varying (vr);
1231 return;
1234 /* We punt for [-INF, +INF].
1235 We learn nothing when we have INF on both sides.
1236 Note that we do accept [-INF, -INF] and [+INF, +INF]. */
1237 if (wi::eq_p (min, wi::min_value (TYPE_PRECISION (type), sgn))
1238 && wi::eq_p (max, wi::max_value (TYPE_PRECISION (type), sgn)))
1240 set_value_range_to_varying (vr);
1241 return;
1244 set_value_range (vr, rtype,
1245 wide_int_to_tree (type, min),
1246 wide_int_to_tree (type, max), NULL);
1249 /* Extract range information from a binary operation CODE based on
1250 the ranges of each of its operands *VR0 and *VR1 with resulting
1251 type EXPR_TYPE. The resulting range is stored in *VR. */
1253 void
1254 extract_range_from_binary_expr_1 (value_range *vr,
1255 enum tree_code code, tree expr_type,
1256 value_range *vr0_, value_range *vr1_)
1258 value_range vr0 = *vr0_, vr1 = *vr1_;
1259 value_range vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
1260 enum value_range_type type;
1261 tree min = NULL_TREE, max = NULL_TREE;
1262 int cmp;
1264 if (!INTEGRAL_TYPE_P (expr_type)
1265 && !POINTER_TYPE_P (expr_type))
1267 set_value_range_to_varying (vr);
1268 return;
1271 /* Not all binary expressions can be applied to ranges in a
1272 meaningful way. Handle only arithmetic operations. */
1273 if (code != PLUS_EXPR
1274 && code != MINUS_EXPR
1275 && code != POINTER_PLUS_EXPR
1276 && code != MULT_EXPR
1277 && code != TRUNC_DIV_EXPR
1278 && code != FLOOR_DIV_EXPR
1279 && code != CEIL_DIV_EXPR
1280 && code != EXACT_DIV_EXPR
1281 && code != ROUND_DIV_EXPR
1282 && code != TRUNC_MOD_EXPR
1283 && code != RSHIFT_EXPR
1284 && code != LSHIFT_EXPR
1285 && code != MIN_EXPR
1286 && code != MAX_EXPR
1287 && code != BIT_AND_EXPR
1288 && code != BIT_IOR_EXPR
1289 && code != BIT_XOR_EXPR)
1291 set_value_range_to_varying (vr);
1292 return;
1295 /* If both ranges are UNDEFINED, so is the result. */
1296 if (vr0.type == VR_UNDEFINED && vr1.type == VR_UNDEFINED)
1298 set_value_range_to_undefined (vr);
1299 return;
1301 /* If one of the ranges is UNDEFINED drop it to VARYING for the following
1302 code. At some point we may want to special-case operations that
1303 have UNDEFINED result for all or some value-ranges of the not UNDEFINED
1304 operand. */
1305 else if (vr0.type == VR_UNDEFINED)
1306 set_value_range_to_varying (&vr0);
1307 else if (vr1.type == VR_UNDEFINED)
1308 set_value_range_to_varying (&vr1);
1310 /* We get imprecise results from ranges_from_anti_range when
1311 code is EXACT_DIV_EXPR. We could mask out bits in the resulting
1312 range, but then we also need to hack up vrp_meet. It's just
1313 easier to special case when vr0 is ~[0,0] for EXACT_DIV_EXPR. */
1314 if (code == EXACT_DIV_EXPR
1315 && vr0.type == VR_ANTI_RANGE
1316 && vr0.min == vr0.max
1317 && integer_zerop (vr0.min))
1319 set_value_range_to_nonnull (vr, expr_type);
1320 return;
1323 /* Now canonicalize anti-ranges to ranges when they are not symbolic
1324 and express ~[] op X as ([]' op X) U ([]'' op X). */
1325 if (vr0.type == VR_ANTI_RANGE
1326 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
1328 extract_range_from_binary_expr_1 (vr, code, expr_type, &vrtem0, vr1_);
1329 if (vrtem1.type != VR_UNDEFINED)
1331 value_range vrres = VR_INITIALIZER;
1332 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
1333 &vrtem1, vr1_);
1334 vrp_meet (vr, &vrres);
1336 return;
1338 /* Likewise for X op ~[]. */
1339 if (vr1.type == VR_ANTI_RANGE
1340 && ranges_from_anti_range (&vr1, &vrtem0, &vrtem1))
1342 extract_range_from_binary_expr_1 (vr, code, expr_type, vr0_, &vrtem0);
1343 if (vrtem1.type != VR_UNDEFINED)
1345 value_range vrres = VR_INITIALIZER;
1346 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
1347 vr0_, &vrtem1);
1348 vrp_meet (vr, &vrres);
1350 return;
1353 /* The type of the resulting value range defaults to VR0.TYPE. */
1354 type = vr0.type;
1356 /* Refuse to operate on VARYING ranges, ranges of different kinds
1357 and symbolic ranges. As an exception, we allow BIT_{AND,IOR}
1358 because we may be able to derive a useful range even if one of
1359 the operands is VR_VARYING or symbolic range. Similarly for
1360 divisions, MIN/MAX and PLUS/MINUS.
1362 TODO, we may be able to derive anti-ranges in some cases. */
1363 if (code != BIT_AND_EXPR
1364 && code != BIT_IOR_EXPR
1365 && code != TRUNC_DIV_EXPR
1366 && code != FLOOR_DIV_EXPR
1367 && code != CEIL_DIV_EXPR
1368 && code != EXACT_DIV_EXPR
1369 && code != ROUND_DIV_EXPR
1370 && code != TRUNC_MOD_EXPR
1371 && code != MIN_EXPR
1372 && code != MAX_EXPR
1373 && code != PLUS_EXPR
1374 && code != MINUS_EXPR
1375 && code != RSHIFT_EXPR
1376 && (vr0.type == VR_VARYING
1377 || vr1.type == VR_VARYING
1378 || vr0.type != vr1.type
1379 || symbolic_range_p (&vr0)
1380 || symbolic_range_p (&vr1)))
1382 set_value_range_to_varying (vr);
1383 return;
1386 /* Now evaluate the expression to determine the new range. */
1387 if (POINTER_TYPE_P (expr_type))
1389 if (code == MIN_EXPR || code == MAX_EXPR)
1391 /* For MIN/MAX expressions with pointers, we only care about
1392 nullness, if both are non null, then the result is nonnull.
1393 If both are null, then the result is null. Otherwise they
1394 are varying. */
1395 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
1396 set_value_range_to_nonnull (vr, expr_type);
1397 else if (range_is_null (&vr0) && range_is_null (&vr1))
1398 set_value_range_to_null (vr, expr_type);
1399 else
1400 set_value_range_to_varying (vr);
1402 else if (code == POINTER_PLUS_EXPR)
1404 /* For pointer types, we are really only interested in asserting
1405 whether the expression evaluates to non-NULL. */
1406 if (range_is_nonnull (&vr0) || range_is_nonnull (&vr1))
1407 set_value_range_to_nonnull (vr, expr_type);
1408 else if (range_is_null (&vr0) && range_is_null (&vr1))
1409 set_value_range_to_null (vr, expr_type);
1410 else
1411 set_value_range_to_varying (vr);
1413 else if (code == BIT_AND_EXPR)
1415 /* For pointer types, we are really only interested in asserting
1416 whether the expression evaluates to non-NULL. */
1417 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
1418 set_value_range_to_nonnull (vr, expr_type);
1419 else if (range_is_null (&vr0) || range_is_null (&vr1))
1420 set_value_range_to_null (vr, expr_type);
1421 else
1422 set_value_range_to_varying (vr);
1424 else
1425 set_value_range_to_varying (vr);
1427 return;
1430 /* For integer ranges, apply the operation to each end of the
1431 range and see what we end up with. */
1432 if (code == PLUS_EXPR || code == MINUS_EXPR)
1434 const bool minus_p = (code == MINUS_EXPR);
1435 tree min_op0 = vr0.min;
1436 tree min_op1 = minus_p ? vr1.max : vr1.min;
1437 tree max_op0 = vr0.max;
1438 tree max_op1 = minus_p ? vr1.min : vr1.max;
1439 tree sym_min_op0 = NULL_TREE;
1440 tree sym_min_op1 = NULL_TREE;
1441 tree sym_max_op0 = NULL_TREE;
1442 tree sym_max_op1 = NULL_TREE;
1443 bool neg_min_op0, neg_min_op1, neg_max_op0, neg_max_op1;
1445 /* If we have a PLUS or MINUS with two VR_RANGEs, either constant or
1446 single-symbolic ranges, try to compute the precise resulting range,
1447 but only if we know that this resulting range will also be constant
1448 or single-symbolic. */
1449 if (vr0.type == VR_RANGE && vr1.type == VR_RANGE
1450 && (TREE_CODE (min_op0) == INTEGER_CST
1451 || (sym_min_op0
1452 = get_single_symbol (min_op0, &neg_min_op0, &min_op0)))
1453 && (TREE_CODE (min_op1) == INTEGER_CST
1454 || (sym_min_op1
1455 = get_single_symbol (min_op1, &neg_min_op1, &min_op1)))
1456 && (!(sym_min_op0 && sym_min_op1)
1457 || (sym_min_op0 == sym_min_op1
1458 && neg_min_op0 == (minus_p ? neg_min_op1 : !neg_min_op1)))
1459 && (TREE_CODE (max_op0) == INTEGER_CST
1460 || (sym_max_op0
1461 = get_single_symbol (max_op0, &neg_max_op0, &max_op0)))
1462 && (TREE_CODE (max_op1) == INTEGER_CST
1463 || (sym_max_op1
1464 = get_single_symbol (max_op1, &neg_max_op1, &max_op1)))
1465 && (!(sym_max_op0 && sym_max_op1)
1466 || (sym_max_op0 == sym_max_op1
1467 && neg_max_op0 == (minus_p ? neg_max_op1 : !neg_max_op1))))
1469 const signop sgn = TYPE_SIGN (expr_type);
1470 const unsigned int prec = TYPE_PRECISION (expr_type);
1471 wide_int type_min, type_max, wmin, wmax;
1472 int min_ovf = 0;
1473 int max_ovf = 0;
1475 /* Get the lower and upper bounds of the type. */
1476 if (TYPE_OVERFLOW_WRAPS (expr_type))
1478 type_min = wi::min_value (prec, sgn);
1479 type_max = wi::max_value (prec, sgn);
1481 else
1483 type_min = wi::to_wide (vrp_val_min (expr_type));
1484 type_max = wi::to_wide (vrp_val_max (expr_type));
1487 /* Combine the lower bounds, if any. */
1488 if (min_op0 && min_op1)
1490 if (minus_p)
1492 wmin = wi::to_wide (min_op0) - wi::to_wide (min_op1);
1494 /* Check for overflow. */
1495 if (wi::cmp (0, wi::to_wide (min_op1), sgn)
1496 != wi::cmp (wmin, wi::to_wide (min_op0), sgn))
1497 min_ovf = wi::cmp (wi::to_wide (min_op0),
1498 wi::to_wide (min_op1), sgn);
1500 else
1502 wmin = wi::to_wide (min_op0) + wi::to_wide (min_op1);
1504 /* Check for overflow. */
1505 if (wi::cmp (wi::to_wide (min_op1), 0, sgn)
1506 != wi::cmp (wmin, wi::to_wide (min_op0), sgn))
1507 min_ovf = wi::cmp (wi::to_wide (min_op0), wmin, sgn);
1510 else if (min_op0)
1511 wmin = wi::to_wide (min_op0);
1512 else if (min_op1)
1514 if (minus_p)
1516 wmin = -wi::to_wide (min_op1);
1518 /* Check for overflow. */
1519 if (sgn == SIGNED
1520 && wi::neg_p (wi::to_wide (min_op1))
1521 && wi::neg_p (wmin))
1522 min_ovf = 1;
1523 else if (sgn == UNSIGNED && wi::to_wide (min_op1) != 0)
1524 min_ovf = -1;
1526 else
1527 wmin = wi::to_wide (min_op1);
1529 else
1530 wmin = wi::shwi (0, prec);
1532 /* Combine the upper bounds, if any. */
1533 if (max_op0 && max_op1)
1535 if (minus_p)
1537 wmax = wi::to_wide (max_op0) - wi::to_wide (max_op1);
1539 /* Check for overflow. */
1540 if (wi::cmp (0, wi::to_wide (max_op1), sgn)
1541 != wi::cmp (wmax, wi::to_wide (max_op0), sgn))
1542 max_ovf = wi::cmp (wi::to_wide (max_op0),
1543 wi::to_wide (max_op1), sgn);
1545 else
1547 wmax = wi::to_wide (max_op0) + wi::to_wide (max_op1);
1549 if (wi::cmp (wi::to_wide (max_op1), 0, sgn)
1550 != wi::cmp (wmax, wi::to_wide (max_op0), sgn))
1551 max_ovf = wi::cmp (wi::to_wide (max_op0), wmax, sgn);
1554 else if (max_op0)
1555 wmax = wi::to_wide (max_op0);
1556 else if (max_op1)
1558 if (minus_p)
1560 wmax = -wi::to_wide (max_op1);
1562 /* Check for overflow. */
1563 if (sgn == SIGNED
1564 && wi::neg_p (wi::to_wide (max_op1))
1565 && wi::neg_p (wmax))
1566 max_ovf = 1;
1567 else if (sgn == UNSIGNED && wi::to_wide (max_op1) != 0)
1568 max_ovf = -1;
1570 else
1571 wmax = wi::to_wide (max_op1);
1573 else
1574 wmax = wi::shwi (0, prec);
1576 /* Check for type overflow. */
1577 if (min_ovf == 0)
1579 if (wi::cmp (wmin, type_min, sgn) == -1)
1580 min_ovf = -1;
1581 else if (wi::cmp (wmin, type_max, sgn) == 1)
1582 min_ovf = 1;
1584 if (max_ovf == 0)
1586 if (wi::cmp (wmax, type_min, sgn) == -1)
1587 max_ovf = -1;
1588 else if (wi::cmp (wmax, type_max, sgn) == 1)
1589 max_ovf = 1;
1592 /* If we have overflow for the constant part and the resulting
1593 range will be symbolic, drop to VR_VARYING. */
1594 if ((min_ovf && sym_min_op0 != sym_min_op1)
1595 || (max_ovf && sym_max_op0 != sym_max_op1))
1597 set_value_range_to_varying (vr);
1598 return;
1601 if (TYPE_OVERFLOW_WRAPS (expr_type))
1603 /* If overflow wraps, truncate the values and adjust the
1604 range kind and bounds appropriately. */
1605 wide_int tmin = wide_int::from (wmin, prec, sgn);
1606 wide_int tmax = wide_int::from (wmax, prec, sgn);
1607 if (min_ovf == max_ovf)
1609 /* No overflow or both overflow or underflow. The
1610 range kind stays VR_RANGE. */
1611 min = wide_int_to_tree (expr_type, tmin);
1612 max = wide_int_to_tree (expr_type, tmax);
1614 else if ((min_ovf == -1 && max_ovf == 0)
1615 || (max_ovf == 1 && min_ovf == 0))
1617 /* Min underflow or max overflow. The range kind
1618 changes to VR_ANTI_RANGE. */
1619 bool covers = false;
1620 wide_int tem = tmin;
1621 type = VR_ANTI_RANGE;
1622 tmin = tmax + 1;
1623 if (wi::cmp (tmin, tmax, sgn) < 0)
1624 covers = true;
1625 tmax = tem - 1;
1626 if (wi::cmp (tmax, tem, sgn) > 0)
1627 covers = true;
1628 /* If the anti-range would cover nothing, drop to varying.
1629 Likewise if the anti-range bounds are outside of the
1630 types values. */
1631 if (covers || wi::cmp (tmin, tmax, sgn) > 0)
1633 set_value_range_to_varying (vr);
1634 return;
1636 min = wide_int_to_tree (expr_type, tmin);
1637 max = wide_int_to_tree (expr_type, tmax);
1639 else
1641 /* Other underflow and/or overflow, drop to VR_VARYING. */
1642 set_value_range_to_varying (vr);
1643 return;
1646 else
1648 /* If overflow does not wrap, saturate to the types min/max
1649 value. */
1650 if (min_ovf == -1)
1651 min = wide_int_to_tree (expr_type, type_min);
1652 else if (min_ovf == 1)
1653 min = wide_int_to_tree (expr_type, type_max);
1654 else
1655 min = wide_int_to_tree (expr_type, wmin);
1657 if (max_ovf == -1)
1658 max = wide_int_to_tree (expr_type, type_min);
1659 else if (max_ovf == 1)
1660 max = wide_int_to_tree (expr_type, type_max);
1661 else
1662 max = wide_int_to_tree (expr_type, wmax);
1665 /* If the result lower bound is constant, we're done;
1666 otherwise, build the symbolic lower bound. */
1667 if (sym_min_op0 == sym_min_op1)
1669 else if (sym_min_op0)
1670 min = build_symbolic_expr (expr_type, sym_min_op0,
1671 neg_min_op0, min);
1672 else if (sym_min_op1)
1674 /* We may not negate if that might introduce
1675 undefined overflow. */
1676 if (! minus_p
1677 || neg_min_op1
1678 || TYPE_OVERFLOW_WRAPS (expr_type))
1679 min = build_symbolic_expr (expr_type, sym_min_op1,
1680 neg_min_op1 ^ minus_p, min);
1681 else
1682 min = NULL_TREE;
1685 /* Likewise for the upper bound. */
1686 if (sym_max_op0 == sym_max_op1)
1688 else if (sym_max_op0)
1689 max = build_symbolic_expr (expr_type, sym_max_op0,
1690 neg_max_op0, max);
1691 else if (sym_max_op1)
1693 /* We may not negate if that might introduce
1694 undefined overflow. */
1695 if (! minus_p
1696 || neg_max_op1
1697 || TYPE_OVERFLOW_WRAPS (expr_type))
1698 max = build_symbolic_expr (expr_type, sym_max_op1,
1699 neg_max_op1 ^ minus_p, max);
1700 else
1701 max = NULL_TREE;
1704 else
1706 /* For other cases, for example if we have a PLUS_EXPR with two
1707 VR_ANTI_RANGEs, drop to VR_VARYING. It would take more effort
1708 to compute a precise range for such a case.
1709 ??? General even mixed range kind operations can be expressed
1710 by for example transforming ~[3, 5] + [1, 2] to range-only
1711 operations and a union primitive:
1712 [-INF, 2] + [1, 2] U [5, +INF] + [1, 2]
1713 [-INF+1, 4] U [6, +INF(OVF)]
1714 though usually the union is not exactly representable with
1715 a single range or anti-range as the above is
1716 [-INF+1, +INF(OVF)] intersected with ~[5, 5]
1717 but one could use a scheme similar to equivalences for this. */
1718 set_value_range_to_varying (vr);
1719 return;
1722 else if (code == MIN_EXPR
1723 || code == MAX_EXPR)
1725 if (vr0.type == VR_RANGE
1726 && !symbolic_range_p (&vr0))
1728 type = VR_RANGE;
1729 if (vr1.type == VR_RANGE
1730 && !symbolic_range_p (&vr1))
1732 /* For operations that make the resulting range directly
1733 proportional to the original ranges, apply the operation to
1734 the same end of each range. */
1735 min = int_const_binop (code, vr0.min, vr1.min);
1736 max = int_const_binop (code, vr0.max, vr1.max);
1738 else if (code == MIN_EXPR)
1740 min = vrp_val_min (expr_type);
1741 max = vr0.max;
1743 else if (code == MAX_EXPR)
1745 min = vr0.min;
1746 max = vrp_val_max (expr_type);
1749 else if (vr1.type == VR_RANGE
1750 && !symbolic_range_p (&vr1))
1752 type = VR_RANGE;
1753 if (code == MIN_EXPR)
1755 min = vrp_val_min (expr_type);
1756 max = vr1.max;
1758 else if (code == MAX_EXPR)
1760 min = vr1.min;
1761 max = vrp_val_max (expr_type);
1764 else
1766 set_value_range_to_varying (vr);
1767 return;
1770 else if (code == MULT_EXPR)
1772 /* Fancy code so that with unsigned, [-3,-1]*[-3,-1] does not
1773 drop to varying. This test requires 2*prec bits if both
1774 operands are signed and 2*prec + 2 bits if either is not. */
1776 signop sign = TYPE_SIGN (expr_type);
1777 unsigned int prec = TYPE_PRECISION (expr_type);
1779 if (!range_int_cst_p (&vr0)
1780 || !range_int_cst_p (&vr1))
1782 set_value_range_to_varying (vr);
1783 return;
1786 if (TYPE_OVERFLOW_WRAPS (expr_type))
1788 typedef FIXED_WIDE_INT (WIDE_INT_MAX_PRECISION * 2) vrp_int;
1789 typedef generic_wide_int
1790 <wi::extended_tree <WIDE_INT_MAX_PRECISION * 2> > vrp_int_cst;
1791 vrp_int sizem1 = wi::mask <vrp_int> (prec, false);
1792 vrp_int size = sizem1 + 1;
1794 /* Extend the values using the sign of the result to PREC2.
1795 From here on out, everthing is just signed math no matter
1796 what the input types were. */
1797 vrp_int min0 = vrp_int_cst (vr0.min);
1798 vrp_int max0 = vrp_int_cst (vr0.max);
1799 vrp_int min1 = vrp_int_cst (vr1.min);
1800 vrp_int max1 = vrp_int_cst (vr1.max);
1801 /* Canonicalize the intervals. */
1802 if (sign == UNSIGNED)
1804 if (wi::ltu_p (size, min0 + max0))
1806 min0 -= size;
1807 max0 -= size;
1810 if (wi::ltu_p (size, min1 + max1))
1812 min1 -= size;
1813 max1 -= size;
1817 vrp_int prod0 = min0 * min1;
1818 vrp_int prod1 = min0 * max1;
1819 vrp_int prod2 = max0 * min1;
1820 vrp_int prod3 = max0 * max1;
1822 /* Sort the 4 products so that min is in prod0 and max is in
1823 prod3. */
1824 /* min0min1 > max0max1 */
1825 if (prod0 > prod3)
1826 std::swap (prod0, prod3);
1828 /* min0max1 > max0min1 */
1829 if (prod1 > prod2)
1830 std::swap (prod1, prod2);
1832 if (prod0 > prod1)
1833 std::swap (prod0, prod1);
1835 if (prod2 > prod3)
1836 std::swap (prod2, prod3);
1838 /* diff = max - min. */
1839 prod2 = prod3 - prod0;
1840 if (wi::geu_p (prod2, sizem1))
1842 /* the range covers all values. */
1843 set_value_range_to_varying (vr);
1844 return;
1847 /* The following should handle the wrapping and selecting
1848 VR_ANTI_RANGE for us. */
1849 min = wide_int_to_tree (expr_type, prod0);
1850 max = wide_int_to_tree (expr_type, prod3);
1851 set_and_canonicalize_value_range (vr, VR_RANGE, min, max, NULL);
1852 return;
1855 /* If we have an unsigned MULT_EXPR with two VR_ANTI_RANGEs,
1856 drop to VR_VARYING. It would take more effort to compute a
1857 precise range for such a case. For example, if we have
1858 op0 == 65536 and op1 == 65536 with their ranges both being
1859 ~[0,0] on a 32-bit machine, we would have op0 * op1 == 0, so
1860 we cannot claim that the product is in ~[0,0]. Note that we
1861 are guaranteed to have vr0.type == vr1.type at this
1862 point. */
1863 if (vr0.type == VR_ANTI_RANGE
1864 && !TYPE_OVERFLOW_UNDEFINED (expr_type))
1866 set_value_range_to_varying (vr);
1867 return;
1870 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
1871 return;
1873 else if (code == RSHIFT_EXPR
1874 || code == LSHIFT_EXPR)
1876 /* If we have a RSHIFT_EXPR with any shift values outside [0..prec-1],
1877 then drop to VR_VARYING. Outside of this range we get undefined
1878 behavior from the shift operation. We cannot even trust
1879 SHIFT_COUNT_TRUNCATED at this stage, because that applies to rtl
1880 shifts, and the operation at the tree level may be widened. */
1881 if (range_int_cst_p (&vr1)
1882 && compare_tree_int (vr1.min, 0) >= 0
1883 && compare_tree_int (vr1.max, TYPE_PRECISION (expr_type)) == -1)
1885 if (code == RSHIFT_EXPR)
1887 /* Even if vr0 is VARYING or otherwise not usable, we can derive
1888 useful ranges just from the shift count. E.g.
1889 x >> 63 for signed 64-bit x is always [-1, 0]. */
1890 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
1892 vr0.type = type = VR_RANGE;
1893 vr0.min = vrp_val_min (expr_type);
1894 vr0.max = vrp_val_max (expr_type);
1896 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
1897 return;
1899 /* We can map lshifts by constants to MULT_EXPR handling. */
1900 else if (code == LSHIFT_EXPR
1901 && range_int_cst_singleton_p (&vr1))
1903 bool saved_flag_wrapv;
1904 value_range vr1p = VR_INITIALIZER;
1905 vr1p.type = VR_RANGE;
1906 vr1p.min = (wide_int_to_tree
1907 (expr_type,
1908 wi::set_bit_in_zero (tree_to_shwi (vr1.min),
1909 TYPE_PRECISION (expr_type))));
1910 vr1p.max = vr1p.min;
1911 /* We have to use a wrapping multiply though as signed overflow
1912 on lshifts is implementation defined in C89. */
1913 saved_flag_wrapv = flag_wrapv;
1914 flag_wrapv = 1;
1915 extract_range_from_binary_expr_1 (vr, MULT_EXPR, expr_type,
1916 &vr0, &vr1p);
1917 flag_wrapv = saved_flag_wrapv;
1918 return;
1920 else if (code == LSHIFT_EXPR
1921 && range_int_cst_p (&vr0))
1923 int prec = TYPE_PRECISION (expr_type);
1924 int overflow_pos = prec;
1925 int bound_shift;
1926 wide_int low_bound, high_bound;
1927 bool uns = TYPE_UNSIGNED (expr_type);
1928 bool in_bounds = false;
1930 if (!uns)
1931 overflow_pos -= 1;
1933 bound_shift = overflow_pos - tree_to_shwi (vr1.max);
1934 /* If bound_shift == HOST_BITS_PER_WIDE_INT, the llshift can
1935 overflow. However, for that to happen, vr1.max needs to be
1936 zero, which means vr1 is a singleton range of zero, which
1937 means it should be handled by the previous LSHIFT_EXPR
1938 if-clause. */
1939 wide_int bound = wi::set_bit_in_zero (bound_shift, prec);
1940 wide_int complement = ~(bound - 1);
1942 if (uns)
1944 low_bound = bound;
1945 high_bound = complement;
1946 if (wi::ltu_p (wi::to_wide (vr0.max), low_bound))
1948 /* [5, 6] << [1, 2] == [10, 24]. */
1949 /* We're shifting out only zeroes, the value increases
1950 monotonically. */
1951 in_bounds = true;
1953 else if (wi::ltu_p (high_bound, wi::to_wide (vr0.min)))
1955 /* [0xffffff00, 0xffffffff] << [1, 2]
1956 == [0xfffffc00, 0xfffffffe]. */
1957 /* We're shifting out only ones, the value decreases
1958 monotonically. */
1959 in_bounds = true;
1962 else
1964 /* [-1, 1] << [1, 2] == [-4, 4]. */
1965 low_bound = complement;
1966 high_bound = bound;
1967 if (wi::lts_p (wi::to_wide (vr0.max), high_bound)
1968 && wi::lts_p (low_bound, wi::to_wide (vr0.min)))
1970 /* For non-negative numbers, we're shifting out only
1971 zeroes, the value increases monotonically.
1972 For negative numbers, we're shifting out only ones, the
1973 value decreases monotomically. */
1974 in_bounds = true;
1978 if (in_bounds)
1980 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
1981 return;
1985 set_value_range_to_varying (vr);
1986 return;
1988 else if (code == TRUNC_DIV_EXPR
1989 || code == FLOOR_DIV_EXPR
1990 || code == CEIL_DIV_EXPR
1991 || code == EXACT_DIV_EXPR
1992 || code == ROUND_DIV_EXPR)
1994 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
1996 /* For division, if op1 has VR_RANGE but op0 does not, something
1997 can be deduced just from that range. Say [min, max] / [4, max]
1998 gives [min / 4, max / 4] range. */
1999 if (vr1.type == VR_RANGE
2000 && !symbolic_range_p (&vr1)
2001 && range_includes_zero_p (vr1.min, vr1.max) == 0)
2003 vr0.type = type = VR_RANGE;
2004 vr0.min = vrp_val_min (expr_type);
2005 vr0.max = vrp_val_max (expr_type);
2007 else
2009 set_value_range_to_varying (vr);
2010 return;
2014 /* For divisions, if flag_non_call_exceptions is true, we must
2015 not eliminate a division by zero. */
2016 if (cfun->can_throw_non_call_exceptions
2017 && (vr1.type != VR_RANGE
2018 || range_includes_zero_p (vr1.min, vr1.max) != 0))
2020 set_value_range_to_varying (vr);
2021 return;
2024 /* For divisions, if op0 is VR_RANGE, we can deduce a range
2025 even if op1 is VR_VARYING, VR_ANTI_RANGE, symbolic or can
2026 include 0. */
2027 if (vr0.type == VR_RANGE
2028 && (vr1.type != VR_RANGE
2029 || range_includes_zero_p (vr1.min, vr1.max) != 0))
2031 tree zero = build_int_cst (TREE_TYPE (vr0.min), 0);
2032 int cmp;
2034 min = NULL_TREE;
2035 max = NULL_TREE;
2036 if (TYPE_UNSIGNED (expr_type)
2037 || value_range_nonnegative_p (&vr1))
2039 /* For unsigned division or when divisor is known
2040 to be non-negative, the range has to cover
2041 all numbers from 0 to max for positive max
2042 and all numbers from min to 0 for negative min. */
2043 cmp = compare_values (vr0.max, zero);
2044 if (cmp == -1)
2046 /* When vr0.max < 0, vr1.min != 0 and value
2047 ranges for dividend and divisor are available. */
2048 if (vr1.type == VR_RANGE
2049 && !symbolic_range_p (&vr0)
2050 && !symbolic_range_p (&vr1)
2051 && compare_values (vr1.min, zero) != 0)
2052 max = int_const_binop (code, vr0.max, vr1.min);
2053 else
2054 max = zero;
2056 else if (cmp == 0 || cmp == 1)
2057 max = vr0.max;
2058 else
2059 type = VR_VARYING;
2060 cmp = compare_values (vr0.min, zero);
2061 if (cmp == 1)
2063 /* For unsigned division when value ranges for dividend
2064 and divisor are available. */
2065 if (vr1.type == VR_RANGE
2066 && !symbolic_range_p (&vr0)
2067 && !symbolic_range_p (&vr1)
2068 && compare_values (vr1.max, zero) != 0)
2069 min = int_const_binop (code, vr0.min, vr1.max);
2070 else
2071 min = zero;
2073 else if (cmp == 0 || cmp == -1)
2074 min = vr0.min;
2075 else
2076 type = VR_VARYING;
2078 else
2080 /* Otherwise the range is -max .. max or min .. -min
2081 depending on which bound is bigger in absolute value,
2082 as the division can change the sign. */
2083 abs_extent_range (vr, vr0.min, vr0.max);
2084 return;
2086 if (type == VR_VARYING)
2088 set_value_range_to_varying (vr);
2089 return;
2092 else if (range_int_cst_p (&vr0) && range_int_cst_p (&vr1))
2094 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2095 return;
2098 else if (code == TRUNC_MOD_EXPR)
2100 if (range_is_null (&vr1))
2102 set_value_range_to_undefined (vr);
2103 return;
2105 /* ABS (A % B) < ABS (B) and either
2106 0 <= A % B <= A or A <= A % B <= 0. */
2107 type = VR_RANGE;
2108 signop sgn = TYPE_SIGN (expr_type);
2109 unsigned int prec = TYPE_PRECISION (expr_type);
2110 wide_int wmin, wmax, tmp;
2111 if (vr1.type == VR_RANGE && !symbolic_range_p (&vr1))
2113 wmax = wi::to_wide (vr1.max) - 1;
2114 if (sgn == SIGNED)
2116 tmp = -1 - wi::to_wide (vr1.min);
2117 wmax = wi::smax (wmax, tmp);
2120 else
2122 wmax = wi::max_value (prec, sgn);
2123 /* X % INT_MIN may be INT_MAX. */
2124 if (sgn == UNSIGNED)
2125 wmax = wmax - 1;
2128 if (sgn == UNSIGNED)
2129 wmin = wi::zero (prec);
2130 else
2132 wmin = -wmax;
2133 if (vr0.type == VR_RANGE && TREE_CODE (vr0.min) == INTEGER_CST)
2135 tmp = wi::to_wide (vr0.min);
2136 if (wi::gts_p (tmp, 0))
2137 tmp = wi::zero (prec);
2138 wmin = wi::smax (wmin, tmp);
2142 if (vr0.type == VR_RANGE && TREE_CODE (vr0.max) == INTEGER_CST)
2144 tmp = wi::to_wide (vr0.max);
2145 if (sgn == SIGNED && wi::neg_p (tmp))
2146 tmp = wi::zero (prec);
2147 wmax = wi::min (wmax, tmp, sgn);
2150 min = wide_int_to_tree (expr_type, wmin);
2151 max = wide_int_to_tree (expr_type, wmax);
2153 else if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR || code == BIT_XOR_EXPR)
2155 bool int_cst_range0, int_cst_range1;
2156 wide_int may_be_nonzero0, may_be_nonzero1;
2157 wide_int must_be_nonzero0, must_be_nonzero1;
2159 int_cst_range0 = zero_nonzero_bits_from_vr (expr_type, &vr0,
2160 &may_be_nonzero0,
2161 &must_be_nonzero0);
2162 int_cst_range1 = zero_nonzero_bits_from_vr (expr_type, &vr1,
2163 &may_be_nonzero1,
2164 &must_be_nonzero1);
2166 if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR)
2168 value_range *vr0p = NULL, *vr1p = NULL;
2169 if (range_int_cst_singleton_p (&vr1))
2171 vr0p = &vr0;
2172 vr1p = &vr1;
2174 else if (range_int_cst_singleton_p (&vr0))
2176 vr0p = &vr1;
2177 vr1p = &vr0;
2179 /* For op & or | attempt to optimize:
2180 [x, y] op z into [x op z, y op z]
2181 if z is a constant which (for op | its bitwise not) has n
2182 consecutive least significant bits cleared followed by m 1
2183 consecutive bits set immediately above it and either
2184 m + n == precision, or (x >> (m + n)) == (y >> (m + n)).
2185 The least significant n bits of all the values in the range are
2186 cleared or set, the m bits above it are preserved and any bits
2187 above these are required to be the same for all values in the
2188 range. */
2189 if (vr0p && range_int_cst_p (vr0p))
2191 wide_int w = wi::to_wide (vr1p->min);
2192 int m = 0, n = 0;
2193 if (code == BIT_IOR_EXPR)
2194 w = ~w;
2195 if (wi::eq_p (w, 0))
2196 n = TYPE_PRECISION (expr_type);
2197 else
2199 n = wi::ctz (w);
2200 w = ~(w | wi::mask (n, false, w.get_precision ()));
2201 if (wi::eq_p (w, 0))
2202 m = TYPE_PRECISION (expr_type) - n;
2203 else
2204 m = wi::ctz (w) - n;
2206 wide_int mask = wi::mask (m + n, true, w.get_precision ());
2207 if ((mask & wi::to_wide (vr0p->min))
2208 == (mask & wi::to_wide (vr0p->max)))
2210 min = int_const_binop (code, vr0p->min, vr1p->min);
2211 max = int_const_binop (code, vr0p->max, vr1p->min);
2216 type = VR_RANGE;
2217 if (min && max)
2218 /* Optimized above already. */;
2219 else if (code == BIT_AND_EXPR)
2221 min = wide_int_to_tree (expr_type,
2222 must_be_nonzero0 & must_be_nonzero1);
2223 wide_int wmax = may_be_nonzero0 & may_be_nonzero1;
2224 /* If both input ranges contain only negative values we can
2225 truncate the result range maximum to the minimum of the
2226 input range maxima. */
2227 if (int_cst_range0 && int_cst_range1
2228 && tree_int_cst_sgn (vr0.max) < 0
2229 && tree_int_cst_sgn (vr1.max) < 0)
2231 wmax = wi::min (wmax, wi::to_wide (vr0.max),
2232 TYPE_SIGN (expr_type));
2233 wmax = wi::min (wmax, wi::to_wide (vr1.max),
2234 TYPE_SIGN (expr_type));
2236 /* If either input range contains only non-negative values
2237 we can truncate the result range maximum to the respective
2238 maximum of the input range. */
2239 if (int_cst_range0 && tree_int_cst_sgn (vr0.min) >= 0)
2240 wmax = wi::min (wmax, wi::to_wide (vr0.max),
2241 TYPE_SIGN (expr_type));
2242 if (int_cst_range1 && tree_int_cst_sgn (vr1.min) >= 0)
2243 wmax = wi::min (wmax, wi::to_wide (vr1.max),
2244 TYPE_SIGN (expr_type));
2245 max = wide_int_to_tree (expr_type, wmax);
2246 cmp = compare_values (min, max);
2247 /* PR68217: In case of signed & sign-bit-CST should
2248 result in [-INF, 0] instead of [-INF, INF]. */
2249 if (cmp == -2 || cmp == 1)
2251 wide_int sign_bit
2252 = wi::set_bit_in_zero (TYPE_PRECISION (expr_type) - 1,
2253 TYPE_PRECISION (expr_type));
2254 if (!TYPE_UNSIGNED (expr_type)
2255 && ((int_cst_range0
2256 && value_range_constant_singleton (&vr0)
2257 && !wi::cmps (wi::to_wide (vr0.min), sign_bit))
2258 || (int_cst_range1
2259 && value_range_constant_singleton (&vr1)
2260 && !wi::cmps (wi::to_wide (vr1.min), sign_bit))))
2262 min = TYPE_MIN_VALUE (expr_type);
2263 max = build_int_cst (expr_type, 0);
2267 else if (code == BIT_IOR_EXPR)
2269 max = wide_int_to_tree (expr_type,
2270 may_be_nonzero0 | may_be_nonzero1);
2271 wide_int wmin = must_be_nonzero0 | must_be_nonzero1;
2272 /* If the input ranges contain only positive values we can
2273 truncate the minimum of the result range to the maximum
2274 of the input range minima. */
2275 if (int_cst_range0 && int_cst_range1
2276 && tree_int_cst_sgn (vr0.min) >= 0
2277 && tree_int_cst_sgn (vr1.min) >= 0)
2279 wmin = wi::max (wmin, wi::to_wide (vr0.min),
2280 TYPE_SIGN (expr_type));
2281 wmin = wi::max (wmin, wi::to_wide (vr1.min),
2282 TYPE_SIGN (expr_type));
2284 /* If either input range contains only negative values
2285 we can truncate the minimum of the result range to the
2286 respective minimum range. */
2287 if (int_cst_range0 && tree_int_cst_sgn (vr0.max) < 0)
2288 wmin = wi::max (wmin, wi::to_wide (vr0.min),
2289 TYPE_SIGN (expr_type));
2290 if (int_cst_range1 && tree_int_cst_sgn (vr1.max) < 0)
2291 wmin = wi::max (wmin, wi::to_wide (vr1.min),
2292 TYPE_SIGN (expr_type));
2293 min = wide_int_to_tree (expr_type, wmin);
2295 else if (code == BIT_XOR_EXPR)
2297 wide_int result_zero_bits = ((must_be_nonzero0 & must_be_nonzero1)
2298 | ~(may_be_nonzero0 | may_be_nonzero1));
2299 wide_int result_one_bits
2300 = (wi::bit_and_not (must_be_nonzero0, may_be_nonzero1)
2301 | wi::bit_and_not (must_be_nonzero1, may_be_nonzero0));
2302 max = wide_int_to_tree (expr_type, ~result_zero_bits);
2303 min = wide_int_to_tree (expr_type, result_one_bits);
2304 /* If the range has all positive or all negative values the
2305 result is better than VARYING. */
2306 if (tree_int_cst_sgn (min) < 0
2307 || tree_int_cst_sgn (max) >= 0)
2309 else
2310 max = min = NULL_TREE;
2313 else
2314 gcc_unreachable ();
2316 /* If either MIN or MAX overflowed, then set the resulting range to
2317 VARYING. */
2318 if (min == NULL_TREE
2319 || TREE_OVERFLOW_P (min)
2320 || max == NULL_TREE
2321 || TREE_OVERFLOW_P (max))
2323 set_value_range_to_varying (vr);
2324 return;
2327 /* We punt for [-INF, +INF].
2328 We learn nothing when we have INF on both sides.
2329 Note that we do accept [-INF, -INF] and [+INF, +INF]. */
2330 if (vrp_val_is_min (min) && vrp_val_is_max (max))
2332 set_value_range_to_varying (vr);
2333 return;
2336 cmp = compare_values (min, max);
2337 if (cmp == -2 || cmp == 1)
2339 /* If the new range has its limits swapped around (MIN > MAX),
2340 then the operation caused one of them to wrap around, mark
2341 the new range VARYING. */
2342 set_value_range_to_varying (vr);
2344 else
2345 set_value_range (vr, type, min, max, NULL);
2348 /* Extract range information from a unary operation CODE based on
2349 the range of its operand *VR0 with type OP0_TYPE with resulting type TYPE.
2350 The resulting range is stored in *VR. */
2352 void
2353 extract_range_from_unary_expr (value_range *vr,
2354 enum tree_code code, tree type,
2355 value_range *vr0_, tree op0_type)
2357 value_range vr0 = *vr0_, vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
2359 /* VRP only operates on integral and pointer types. */
2360 if (!(INTEGRAL_TYPE_P (op0_type)
2361 || POINTER_TYPE_P (op0_type))
2362 || !(INTEGRAL_TYPE_P (type)
2363 || POINTER_TYPE_P (type)))
2365 set_value_range_to_varying (vr);
2366 return;
2369 /* If VR0 is UNDEFINED, so is the result. */
2370 if (vr0.type == VR_UNDEFINED)
2372 set_value_range_to_undefined (vr);
2373 return;
2376 /* Handle operations that we express in terms of others. */
2377 if (code == PAREN_EXPR || code == OBJ_TYPE_REF)
2379 /* PAREN_EXPR and OBJ_TYPE_REF are simple copies. */
2380 copy_value_range (vr, &vr0);
2381 return;
2383 else if (code == NEGATE_EXPR)
2385 /* -X is simply 0 - X, so re-use existing code that also handles
2386 anti-ranges fine. */
2387 value_range zero = VR_INITIALIZER;
2388 set_value_range_to_value (&zero, build_int_cst (type, 0), NULL);
2389 extract_range_from_binary_expr_1 (vr, MINUS_EXPR, type, &zero, &vr0);
2390 return;
2392 else if (code == BIT_NOT_EXPR)
2394 /* ~X is simply -1 - X, so re-use existing code that also handles
2395 anti-ranges fine. */
2396 value_range minusone = VR_INITIALIZER;
2397 set_value_range_to_value (&minusone, build_int_cst (type, -1), NULL);
2398 extract_range_from_binary_expr_1 (vr, MINUS_EXPR,
2399 type, &minusone, &vr0);
2400 return;
2403 /* Now canonicalize anti-ranges to ranges when they are not symbolic
2404 and express op ~[] as (op []') U (op []''). */
2405 if (vr0.type == VR_ANTI_RANGE
2406 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
2408 extract_range_from_unary_expr (vr, code, type, &vrtem0, op0_type);
2409 if (vrtem1.type != VR_UNDEFINED)
2411 value_range vrres = VR_INITIALIZER;
2412 extract_range_from_unary_expr (&vrres, code, type,
2413 &vrtem1, op0_type);
2414 vrp_meet (vr, &vrres);
2416 return;
2419 if (CONVERT_EXPR_CODE_P (code))
2421 tree inner_type = op0_type;
2422 tree outer_type = type;
2424 /* If the expression evaluates to a pointer, we are only interested in
2425 determining if it evaluates to NULL [0, 0] or non-NULL (~[0, 0]). */
2426 if (POINTER_TYPE_P (type))
2428 if (range_is_nonnull (&vr0))
2429 set_value_range_to_nonnull (vr, type);
2430 else if (range_is_null (&vr0))
2431 set_value_range_to_null (vr, type);
2432 else
2433 set_value_range_to_varying (vr);
2434 return;
2437 /* If VR0 is varying and we increase the type precision, assume
2438 a full range for the following transformation. */
2439 if (vr0.type == VR_VARYING
2440 && INTEGRAL_TYPE_P (inner_type)
2441 && TYPE_PRECISION (inner_type) < TYPE_PRECISION (outer_type))
2443 vr0.type = VR_RANGE;
2444 vr0.min = TYPE_MIN_VALUE (inner_type);
2445 vr0.max = TYPE_MAX_VALUE (inner_type);
2448 /* If VR0 is a constant range or anti-range and the conversion is
2449 not truncating we can convert the min and max values and
2450 canonicalize the resulting range. Otherwise we can do the
2451 conversion if the size of the range is less than what the
2452 precision of the target type can represent and the range is
2453 not an anti-range. */
2454 if ((vr0.type == VR_RANGE
2455 || vr0.type == VR_ANTI_RANGE)
2456 && TREE_CODE (vr0.min) == INTEGER_CST
2457 && TREE_CODE (vr0.max) == INTEGER_CST
2458 && (TYPE_PRECISION (outer_type) >= TYPE_PRECISION (inner_type)
2459 || (vr0.type == VR_RANGE
2460 && integer_zerop (int_const_binop (RSHIFT_EXPR,
2461 int_const_binop (MINUS_EXPR, vr0.max, vr0.min),
2462 size_int (TYPE_PRECISION (outer_type)))))))
2464 tree new_min, new_max;
2465 new_min = force_fit_type (outer_type, wi::to_widest (vr0.min),
2466 0, false);
2467 new_max = force_fit_type (outer_type, wi::to_widest (vr0.max),
2468 0, false);
2469 set_and_canonicalize_value_range (vr, vr0.type,
2470 new_min, new_max, NULL);
2471 return;
2474 set_value_range_to_varying (vr);
2475 return;
2477 else if (code == ABS_EXPR)
2479 tree min, max;
2480 int cmp;
2482 /* Pass through vr0 in the easy cases. */
2483 if (TYPE_UNSIGNED (type)
2484 || value_range_nonnegative_p (&vr0))
2486 copy_value_range (vr, &vr0);
2487 return;
2490 /* For the remaining varying or symbolic ranges we can't do anything
2491 useful. */
2492 if (vr0.type == VR_VARYING
2493 || symbolic_range_p (&vr0))
2495 set_value_range_to_varying (vr);
2496 return;
2499 /* -TYPE_MIN_VALUE = TYPE_MIN_VALUE with flag_wrapv so we can't get a
2500 useful range. */
2501 if (!TYPE_OVERFLOW_UNDEFINED (type)
2502 && ((vr0.type == VR_RANGE
2503 && vrp_val_is_min (vr0.min))
2504 || (vr0.type == VR_ANTI_RANGE
2505 && !vrp_val_is_min (vr0.min))))
2507 set_value_range_to_varying (vr);
2508 return;
2511 /* ABS_EXPR may flip the range around, if the original range
2512 included negative values. */
2513 if (!vrp_val_is_min (vr0.min))
2514 min = fold_unary_to_constant (code, type, vr0.min);
2515 else
2516 min = TYPE_MAX_VALUE (type);
2518 if (!vrp_val_is_min (vr0.max))
2519 max = fold_unary_to_constant (code, type, vr0.max);
2520 else
2521 max = TYPE_MAX_VALUE (type);
2523 cmp = compare_values (min, max);
2525 /* If a VR_ANTI_RANGEs contains zero, then we have
2526 ~[-INF, min(MIN, MAX)]. */
2527 if (vr0.type == VR_ANTI_RANGE)
2529 if (range_includes_zero_p (vr0.min, vr0.max) == 1)
2531 /* Take the lower of the two values. */
2532 if (cmp != 1)
2533 max = min;
2535 /* Create ~[-INF, min (abs(MIN), abs(MAX))]
2536 or ~[-INF + 1, min (abs(MIN), abs(MAX))] when
2537 flag_wrapv is set and the original anti-range doesn't include
2538 TYPE_MIN_VALUE, remember -TYPE_MIN_VALUE = TYPE_MIN_VALUE. */
2539 if (TYPE_OVERFLOW_WRAPS (type))
2541 tree type_min_value = TYPE_MIN_VALUE (type);
2543 min = (vr0.min != type_min_value
2544 ? int_const_binop (PLUS_EXPR, type_min_value,
2545 build_int_cst (TREE_TYPE (type_min_value), 1))
2546 : type_min_value);
2548 else
2549 min = TYPE_MIN_VALUE (type);
2551 else
2553 /* All else has failed, so create the range [0, INF], even for
2554 flag_wrapv since TYPE_MIN_VALUE is in the original
2555 anti-range. */
2556 vr0.type = VR_RANGE;
2557 min = build_int_cst (type, 0);
2558 max = TYPE_MAX_VALUE (type);
2562 /* If the range contains zero then we know that the minimum value in the
2563 range will be zero. */
2564 else if (range_includes_zero_p (vr0.min, vr0.max) == 1)
2566 if (cmp == 1)
2567 max = min;
2568 min = build_int_cst (type, 0);
2570 else
2572 /* If the range was reversed, swap MIN and MAX. */
2573 if (cmp == 1)
2574 std::swap (min, max);
2577 cmp = compare_values (min, max);
2578 if (cmp == -2 || cmp == 1)
2580 /* If the new range has its limits swapped around (MIN > MAX),
2581 then the operation caused one of them to wrap around, mark
2582 the new range VARYING. */
2583 set_value_range_to_varying (vr);
2585 else
2586 set_value_range (vr, vr0.type, min, max, NULL);
2587 return;
2590 /* For unhandled operations fall back to varying. */
2591 set_value_range_to_varying (vr);
2592 return;
2595 /* Debugging dumps. */
2597 void dump_value_range (FILE *, const value_range *);
2598 void debug_value_range (value_range *);
2599 void dump_all_value_ranges (FILE *);
2600 void dump_vr_equiv (FILE *, bitmap);
2601 void debug_vr_equiv (bitmap);
2604 /* Dump value range VR to FILE. */
2606 void
2607 dump_value_range (FILE *file, const value_range *vr)
2609 if (vr == NULL)
2610 fprintf (file, "[]");
2611 else if (vr->type == VR_UNDEFINED)
2612 fprintf (file, "UNDEFINED");
2613 else if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
2615 tree type = TREE_TYPE (vr->min);
2617 fprintf (file, "%s[", (vr->type == VR_ANTI_RANGE) ? "~" : "");
2619 if (INTEGRAL_TYPE_P (type)
2620 && !TYPE_UNSIGNED (type)
2621 && vrp_val_is_min (vr->min))
2622 fprintf (file, "-INF");
2623 else
2624 print_generic_expr (file, vr->min);
2626 fprintf (file, ", ");
2628 if (INTEGRAL_TYPE_P (type)
2629 && vrp_val_is_max (vr->max))
2630 fprintf (file, "+INF");
2631 else
2632 print_generic_expr (file, vr->max);
2634 fprintf (file, "]");
2636 if (vr->equiv)
2638 bitmap_iterator bi;
2639 unsigned i, c = 0;
2641 fprintf (file, " EQUIVALENCES: { ");
2643 EXECUTE_IF_SET_IN_BITMAP (vr->equiv, 0, i, bi)
2645 print_generic_expr (file, ssa_name (i));
2646 fprintf (file, " ");
2647 c++;
2650 fprintf (file, "} (%u elements)", c);
2653 else if (vr->type == VR_VARYING)
2654 fprintf (file, "VARYING");
2655 else
2656 fprintf (file, "INVALID RANGE");
2660 /* Dump value range VR to stderr. */
2662 DEBUG_FUNCTION void
2663 debug_value_range (value_range *vr)
2665 dump_value_range (stderr, vr);
2666 fprintf (stderr, "\n");
2670 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
2671 create a new SSA name N and return the assertion assignment
2672 'N = ASSERT_EXPR <V, V OP W>'. */
2674 static gimple *
2675 build_assert_expr_for (tree cond, tree v)
2677 tree a;
2678 gassign *assertion;
2680 gcc_assert (TREE_CODE (v) == SSA_NAME
2681 && COMPARISON_CLASS_P (cond));
2683 a = build2 (ASSERT_EXPR, TREE_TYPE (v), v, cond);
2684 assertion = gimple_build_assign (NULL_TREE, a);
2686 /* The new ASSERT_EXPR, creates a new SSA name that replaces the
2687 operand of the ASSERT_EXPR. Create it so the new name and the old one
2688 are registered in the replacement table so that we can fix the SSA web
2689 after adding all the ASSERT_EXPRs. */
2690 tree new_def = create_new_def_for (v, assertion, NULL);
2691 /* Make sure we preserve abnormalness throughout an ASSERT_EXPR chain
2692 given we have to be able to fully propagate those out to re-create
2693 valid SSA when removing the asserts. */
2694 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (v))
2695 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_def) = 1;
2697 return assertion;
2701 /* Return false if EXPR is a predicate expression involving floating
2702 point values. */
2704 static inline bool
2705 fp_predicate (gimple *stmt)
2707 GIMPLE_CHECK (stmt, GIMPLE_COND);
2709 return FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)));
2712 /* If the range of values taken by OP can be inferred after STMT executes,
2713 return the comparison code (COMP_CODE_P) and value (VAL_P) that
2714 describes the inferred range. Return true if a range could be
2715 inferred. */
2717 bool
2718 infer_value_range (gimple *stmt, tree op, tree_code *comp_code_p, tree *val_p)
2720 *val_p = NULL_TREE;
2721 *comp_code_p = ERROR_MARK;
2723 /* Do not attempt to infer anything in names that flow through
2724 abnormal edges. */
2725 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
2726 return false;
2728 /* If STMT is the last statement of a basic block with no normal
2729 successors, there is no point inferring anything about any of its
2730 operands. We would not be able to find a proper insertion point
2731 for the assertion, anyway. */
2732 if (stmt_ends_bb_p (stmt))
2734 edge_iterator ei;
2735 edge e;
2737 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
2738 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
2739 break;
2740 if (e == NULL)
2741 return false;
2744 if (infer_nonnull_range (stmt, op))
2746 *val_p = build_int_cst (TREE_TYPE (op), 0);
2747 *comp_code_p = NE_EXPR;
2748 return true;
2751 return false;
2755 void dump_asserts_for (FILE *, tree);
2756 void debug_asserts_for (tree);
2757 void dump_all_asserts (FILE *);
2758 void debug_all_asserts (void);
2760 /* Dump all the registered assertions for NAME to FILE. */
2762 void
2763 dump_asserts_for (FILE *file, tree name)
2765 assert_locus *loc;
2767 fprintf (file, "Assertions to be inserted for ");
2768 print_generic_expr (file, name);
2769 fprintf (file, "\n");
2771 loc = asserts_for[SSA_NAME_VERSION (name)];
2772 while (loc)
2774 fprintf (file, "\t");
2775 print_gimple_stmt (file, gsi_stmt (loc->si), 0);
2776 fprintf (file, "\n\tBB #%d", loc->bb->index);
2777 if (loc->e)
2779 fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
2780 loc->e->dest->index);
2781 dump_edge_info (file, loc->e, dump_flags, 0);
2783 fprintf (file, "\n\tPREDICATE: ");
2784 print_generic_expr (file, loc->expr);
2785 fprintf (file, " %s ", get_tree_code_name (loc->comp_code));
2786 print_generic_expr (file, loc->val);
2787 fprintf (file, "\n\n");
2788 loc = loc->next;
2791 fprintf (file, "\n");
2795 /* Dump all the registered assertions for NAME to stderr. */
2797 DEBUG_FUNCTION void
2798 debug_asserts_for (tree name)
2800 dump_asserts_for (stderr, name);
2804 /* Dump all the registered assertions for all the names to FILE. */
2806 void
2807 dump_all_asserts (FILE *file)
2809 unsigned i;
2810 bitmap_iterator bi;
2812 fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
2813 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
2814 dump_asserts_for (file, ssa_name (i));
2815 fprintf (file, "\n");
2819 /* Dump all the registered assertions for all the names to stderr. */
2821 DEBUG_FUNCTION void
2822 debug_all_asserts (void)
2824 dump_all_asserts (stderr);
2827 /* Push the assert info for NAME, EXPR, COMP_CODE and VAL to ASSERTS. */
2829 static void
2830 add_assert_info (vec<assert_info> &asserts,
2831 tree name, tree expr, enum tree_code comp_code, tree val)
2833 assert_info info;
2834 info.comp_code = comp_code;
2835 info.name = name;
2836 if (TREE_OVERFLOW_P (val))
2837 val = drop_tree_overflow (val);
2838 info.val = val;
2839 info.expr = expr;
2840 asserts.safe_push (info);
2843 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
2844 'EXPR COMP_CODE VAL' at a location that dominates block BB or
2845 E->DEST, then register this location as a possible insertion point
2846 for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
2848 BB, E and SI provide the exact insertion point for the new
2849 ASSERT_EXPR. If BB is NULL, then the ASSERT_EXPR is to be inserted
2850 on edge E. Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
2851 BB. If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
2852 must not be NULL. */
2854 static void
2855 register_new_assert_for (tree name, tree expr,
2856 enum tree_code comp_code,
2857 tree val,
2858 basic_block bb,
2859 edge e,
2860 gimple_stmt_iterator si)
2862 assert_locus *n, *loc, *last_loc;
2863 basic_block dest_bb;
2865 gcc_checking_assert (bb == NULL || e == NULL);
2867 if (e == NULL)
2868 gcc_checking_assert (gimple_code (gsi_stmt (si)) != GIMPLE_COND
2869 && gimple_code (gsi_stmt (si)) != GIMPLE_SWITCH);
2871 /* Never build an assert comparing against an integer constant with
2872 TREE_OVERFLOW set. This confuses our undefined overflow warning
2873 machinery. */
2874 if (TREE_OVERFLOW_P (val))
2875 val = drop_tree_overflow (val);
2877 /* The new assertion A will be inserted at BB or E. We need to
2878 determine if the new location is dominated by a previously
2879 registered location for A. If we are doing an edge insertion,
2880 assume that A will be inserted at E->DEST. Note that this is not
2881 necessarily true.
2883 If E is a critical edge, it will be split. But even if E is
2884 split, the new block will dominate the same set of blocks that
2885 E->DEST dominates.
2887 The reverse, however, is not true, blocks dominated by E->DEST
2888 will not be dominated by the new block created to split E. So,
2889 if the insertion location is on a critical edge, we will not use
2890 the new location to move another assertion previously registered
2891 at a block dominated by E->DEST. */
2892 dest_bb = (bb) ? bb : e->dest;
2894 /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
2895 VAL at a block dominating DEST_BB, then we don't need to insert a new
2896 one. Similarly, if the same assertion already exists at a block
2897 dominated by DEST_BB and the new location is not on a critical
2898 edge, then update the existing location for the assertion (i.e.,
2899 move the assertion up in the dominance tree).
2901 Note, this is implemented as a simple linked list because there
2902 should not be more than a handful of assertions registered per
2903 name. If this becomes a performance problem, a table hashed by
2904 COMP_CODE and VAL could be implemented. */
2905 loc = asserts_for[SSA_NAME_VERSION (name)];
2906 last_loc = loc;
2907 while (loc)
2909 if (loc->comp_code == comp_code
2910 && (loc->val == val
2911 || operand_equal_p (loc->val, val, 0))
2912 && (loc->expr == expr
2913 || operand_equal_p (loc->expr, expr, 0)))
2915 /* If E is not a critical edge and DEST_BB
2916 dominates the existing location for the assertion, move
2917 the assertion up in the dominance tree by updating its
2918 location information. */
2919 if ((e == NULL || !EDGE_CRITICAL_P (e))
2920 && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
2922 loc->bb = dest_bb;
2923 loc->e = e;
2924 loc->si = si;
2925 return;
2929 /* Update the last node of the list and move to the next one. */
2930 last_loc = loc;
2931 loc = loc->next;
2934 /* If we didn't find an assertion already registered for
2935 NAME COMP_CODE VAL, add a new one at the end of the list of
2936 assertions associated with NAME. */
2937 n = XNEW (struct assert_locus);
2938 n->bb = dest_bb;
2939 n->e = e;
2940 n->si = si;
2941 n->comp_code = comp_code;
2942 n->val = val;
2943 n->expr = expr;
2944 n->next = NULL;
2946 if (last_loc)
2947 last_loc->next = n;
2948 else
2949 asserts_for[SSA_NAME_VERSION (name)] = n;
2951 bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
2954 /* (COND_OP0 COND_CODE COND_OP1) is a predicate which uses NAME.
2955 Extract a suitable test code and value and store them into *CODE_P and
2956 *VAL_P so the predicate is normalized to NAME *CODE_P *VAL_P.
2958 If no extraction was possible, return FALSE, otherwise return TRUE.
2960 If INVERT is true, then we invert the result stored into *CODE_P. */
2962 static bool
2963 extract_code_and_val_from_cond_with_ops (tree name, enum tree_code cond_code,
2964 tree cond_op0, tree cond_op1,
2965 bool invert, enum tree_code *code_p,
2966 tree *val_p)
2968 enum tree_code comp_code;
2969 tree val;
2971 /* Otherwise, we have a comparison of the form NAME COMP VAL
2972 or VAL COMP NAME. */
2973 if (name == cond_op1)
2975 /* If the predicate is of the form VAL COMP NAME, flip
2976 COMP around because we need to register NAME as the
2977 first operand in the predicate. */
2978 comp_code = swap_tree_comparison (cond_code);
2979 val = cond_op0;
2981 else if (name == cond_op0)
2983 /* The comparison is of the form NAME COMP VAL, so the
2984 comparison code remains unchanged. */
2985 comp_code = cond_code;
2986 val = cond_op1;
2988 else
2989 gcc_unreachable ();
2991 /* Invert the comparison code as necessary. */
2992 if (invert)
2993 comp_code = invert_tree_comparison (comp_code, 0);
2995 /* VRP only handles integral and pointer types. */
2996 if (! INTEGRAL_TYPE_P (TREE_TYPE (val))
2997 && ! POINTER_TYPE_P (TREE_TYPE (val)))
2998 return false;
3000 /* Do not register always-false predicates.
3001 FIXME: this works around a limitation in fold() when dealing with
3002 enumerations. Given 'enum { N1, N2 } x;', fold will not
3003 fold 'if (x > N2)' to 'if (0)'. */
3004 if ((comp_code == GT_EXPR || comp_code == LT_EXPR)
3005 && INTEGRAL_TYPE_P (TREE_TYPE (val)))
3007 tree min = TYPE_MIN_VALUE (TREE_TYPE (val));
3008 tree max = TYPE_MAX_VALUE (TREE_TYPE (val));
3010 if (comp_code == GT_EXPR
3011 && (!max
3012 || compare_values (val, max) == 0))
3013 return false;
3015 if (comp_code == LT_EXPR
3016 && (!min
3017 || compare_values (val, min) == 0))
3018 return false;
3020 *code_p = comp_code;
3021 *val_p = val;
3022 return true;
3025 /* Find out smallest RES where RES > VAL && (RES & MASK) == RES, if any
3026 (otherwise return VAL). VAL and MASK must be zero-extended for
3027 precision PREC. If SGNBIT is non-zero, first xor VAL with SGNBIT
3028 (to transform signed values into unsigned) and at the end xor
3029 SGNBIT back. */
3031 static wide_int
3032 masked_increment (const wide_int &val_in, const wide_int &mask,
3033 const wide_int &sgnbit, unsigned int prec)
3035 wide_int bit = wi::one (prec), res;
3036 unsigned int i;
3038 wide_int val = val_in ^ sgnbit;
3039 for (i = 0; i < prec; i++, bit += bit)
3041 res = mask;
3042 if ((res & bit) == 0)
3043 continue;
3044 res = bit - 1;
3045 res = wi::bit_and_not (val + bit, res);
3046 res &= mask;
3047 if (wi::gtu_p (res, val))
3048 return res ^ sgnbit;
3050 return val ^ sgnbit;
3053 /* Helper for overflow_comparison_p
3055 OP0 CODE OP1 is a comparison. Examine the comparison and potentially
3056 OP1's defining statement to see if it ultimately has the form
3057 OP0 CODE (OP0 PLUS INTEGER_CST)
3059 If so, return TRUE indicating this is an overflow test and store into
3060 *NEW_CST an updated constant that can be used in a narrowed range test.
3062 REVERSED indicates if the comparison was originally:
3064 OP1 CODE' OP0.
3066 This affects how we build the updated constant. */
3068 static bool
3069 overflow_comparison_p_1 (enum tree_code code, tree op0, tree op1,
3070 bool follow_assert_exprs, bool reversed, tree *new_cst)
3072 /* See if this is a relational operation between two SSA_NAMES with
3073 unsigned, overflow wrapping values. If so, check it more deeply. */
3074 if ((code == LT_EXPR || code == LE_EXPR
3075 || code == GE_EXPR || code == GT_EXPR)
3076 && TREE_CODE (op0) == SSA_NAME
3077 && TREE_CODE (op1) == SSA_NAME
3078 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
3079 && TYPE_UNSIGNED (TREE_TYPE (op0))
3080 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0)))
3082 gimple *op1_def = SSA_NAME_DEF_STMT (op1);
3084 /* If requested, follow any ASSERT_EXPRs backwards for OP1. */
3085 if (follow_assert_exprs)
3087 while (gimple_assign_single_p (op1_def)
3088 && TREE_CODE (gimple_assign_rhs1 (op1_def)) == ASSERT_EXPR)
3090 op1 = TREE_OPERAND (gimple_assign_rhs1 (op1_def), 0);
3091 if (TREE_CODE (op1) != SSA_NAME)
3092 break;
3093 op1_def = SSA_NAME_DEF_STMT (op1);
3097 /* Now look at the defining statement of OP1 to see if it adds
3098 or subtracts a nonzero constant from another operand. */
3099 if (op1_def
3100 && is_gimple_assign (op1_def)
3101 && gimple_assign_rhs_code (op1_def) == PLUS_EXPR
3102 && TREE_CODE (gimple_assign_rhs2 (op1_def)) == INTEGER_CST
3103 && !integer_zerop (gimple_assign_rhs2 (op1_def)))
3105 tree target = gimple_assign_rhs1 (op1_def);
3107 /* If requested, follow ASSERT_EXPRs backwards for op0 looking
3108 for one where TARGET appears on the RHS. */
3109 if (follow_assert_exprs)
3111 /* Now see if that "other operand" is op0, following the chain
3112 of ASSERT_EXPRs if necessary. */
3113 gimple *op0_def = SSA_NAME_DEF_STMT (op0);
3114 while (op0 != target
3115 && gimple_assign_single_p (op0_def)
3116 && TREE_CODE (gimple_assign_rhs1 (op0_def)) == ASSERT_EXPR)
3118 op0 = TREE_OPERAND (gimple_assign_rhs1 (op0_def), 0);
3119 if (TREE_CODE (op0) != SSA_NAME)
3120 break;
3121 op0_def = SSA_NAME_DEF_STMT (op0);
3125 /* If we did not find our target SSA_NAME, then this is not
3126 an overflow test. */
3127 if (op0 != target)
3128 return false;
3130 tree type = TREE_TYPE (op0);
3131 wide_int max = wi::max_value (TYPE_PRECISION (type), UNSIGNED);
3132 tree inc = gimple_assign_rhs2 (op1_def);
3133 if (reversed)
3134 *new_cst = wide_int_to_tree (type, max + wi::to_wide (inc));
3135 else
3136 *new_cst = wide_int_to_tree (type, max - wi::to_wide (inc));
3137 return true;
3140 return false;
3143 /* OP0 CODE OP1 is a comparison. Examine the comparison and potentially
3144 OP1's defining statement to see if it ultimately has the form
3145 OP0 CODE (OP0 PLUS INTEGER_CST)
3147 If so, return TRUE indicating this is an overflow test and store into
3148 *NEW_CST an updated constant that can be used in a narrowed range test.
3150 These statements are left as-is in the IL to facilitate discovery of
3151 {ADD,SUB}_OVERFLOW sequences later in the optimizer pipeline. But
3152 the alternate range representation is often useful within VRP. */
3154 bool
3155 overflow_comparison_p (tree_code code, tree name, tree val,
3156 bool use_equiv_p, tree *new_cst)
3158 if (overflow_comparison_p_1 (code, name, val, use_equiv_p, false, new_cst))
3159 return true;
3160 return overflow_comparison_p_1 (swap_tree_comparison (code), val, name,
3161 use_equiv_p, true, new_cst);
3165 /* Try to register an edge assertion for SSA name NAME on edge E for
3166 the condition COND contributing to the conditional jump pointed to by BSI.
3167 Invert the condition COND if INVERT is true. */
3169 static void
3170 register_edge_assert_for_2 (tree name, edge e,
3171 enum tree_code cond_code,
3172 tree cond_op0, tree cond_op1, bool invert,
3173 vec<assert_info> &asserts)
3175 tree val;
3176 enum tree_code comp_code;
3178 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
3179 cond_op0,
3180 cond_op1,
3181 invert, &comp_code, &val))
3182 return;
3184 /* Queue the assert. */
3185 tree x;
3186 if (overflow_comparison_p (comp_code, name, val, false, &x))
3188 enum tree_code new_code = ((comp_code == GT_EXPR || comp_code == GE_EXPR)
3189 ? GT_EXPR : LE_EXPR);
3190 add_assert_info (asserts, name, name, new_code, x);
3192 add_assert_info (asserts, name, name, comp_code, val);
3194 /* In the case of NAME <= CST and NAME being defined as
3195 NAME = (unsigned) NAME2 + CST2 we can assert NAME2 >= -CST2
3196 and NAME2 <= CST - CST2. We can do the same for NAME > CST.
3197 This catches range and anti-range tests. */
3198 if ((comp_code == LE_EXPR
3199 || comp_code == GT_EXPR)
3200 && TREE_CODE (val) == INTEGER_CST
3201 && TYPE_UNSIGNED (TREE_TYPE (val)))
3203 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3204 tree cst2 = NULL_TREE, name2 = NULL_TREE, name3 = NULL_TREE;
3206 /* Extract CST2 from the (optional) addition. */
3207 if (is_gimple_assign (def_stmt)
3208 && gimple_assign_rhs_code (def_stmt) == PLUS_EXPR)
3210 name2 = gimple_assign_rhs1 (def_stmt);
3211 cst2 = gimple_assign_rhs2 (def_stmt);
3212 if (TREE_CODE (name2) == SSA_NAME
3213 && TREE_CODE (cst2) == INTEGER_CST)
3214 def_stmt = SSA_NAME_DEF_STMT (name2);
3217 /* Extract NAME2 from the (optional) sign-changing cast. */
3218 if (gimple_assign_cast_p (def_stmt))
3220 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt))
3221 && ! TYPE_UNSIGNED (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
3222 && (TYPE_PRECISION (gimple_expr_type (def_stmt))
3223 == TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))))
3224 name3 = gimple_assign_rhs1 (def_stmt);
3227 /* If name3 is used later, create an ASSERT_EXPR for it. */
3228 if (name3 != NULL_TREE
3229 && TREE_CODE (name3) == SSA_NAME
3230 && (cst2 == NULL_TREE
3231 || TREE_CODE (cst2) == INTEGER_CST)
3232 && INTEGRAL_TYPE_P (TREE_TYPE (name3)))
3234 tree tmp;
3236 /* Build an expression for the range test. */
3237 tmp = build1 (NOP_EXPR, TREE_TYPE (name), name3);
3238 if (cst2 != NULL_TREE)
3239 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
3241 if (dump_file)
3243 fprintf (dump_file, "Adding assert for ");
3244 print_generic_expr (dump_file, name3);
3245 fprintf (dump_file, " from ");
3246 print_generic_expr (dump_file, tmp);
3247 fprintf (dump_file, "\n");
3250 add_assert_info (asserts, name3, tmp, comp_code, val);
3253 /* If name2 is used later, create an ASSERT_EXPR for it. */
3254 if (name2 != NULL_TREE
3255 && TREE_CODE (name2) == SSA_NAME
3256 && TREE_CODE (cst2) == INTEGER_CST
3257 && INTEGRAL_TYPE_P (TREE_TYPE (name2)))
3259 tree tmp;
3261 /* Build an expression for the range test. */
3262 tmp = name2;
3263 if (TREE_TYPE (name) != TREE_TYPE (name2))
3264 tmp = build1 (NOP_EXPR, TREE_TYPE (name), tmp);
3265 if (cst2 != NULL_TREE)
3266 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
3268 if (dump_file)
3270 fprintf (dump_file, "Adding assert for ");
3271 print_generic_expr (dump_file, name2);
3272 fprintf (dump_file, " from ");
3273 print_generic_expr (dump_file, tmp);
3274 fprintf (dump_file, "\n");
3277 add_assert_info (asserts, name2, tmp, comp_code, val);
3281 /* In the case of post-in/decrement tests like if (i++) ... and uses
3282 of the in/decremented value on the edge the extra name we want to
3283 assert for is not on the def chain of the name compared. Instead
3284 it is in the set of use stmts.
3285 Similar cases happen for conversions that were simplified through
3286 fold_{sign_changed,widened}_comparison. */
3287 if ((comp_code == NE_EXPR
3288 || comp_code == EQ_EXPR)
3289 && TREE_CODE (val) == INTEGER_CST)
3291 imm_use_iterator ui;
3292 gimple *use_stmt;
3293 FOR_EACH_IMM_USE_STMT (use_stmt, ui, name)
3295 if (!is_gimple_assign (use_stmt))
3296 continue;
3298 /* Cut off to use-stmts that are dominating the predecessor. */
3299 if (!dominated_by_p (CDI_DOMINATORS, e->src, gimple_bb (use_stmt)))
3300 continue;
3302 tree name2 = gimple_assign_lhs (use_stmt);
3303 if (TREE_CODE (name2) != SSA_NAME)
3304 continue;
3306 enum tree_code code = gimple_assign_rhs_code (use_stmt);
3307 tree cst;
3308 if (code == PLUS_EXPR
3309 || code == MINUS_EXPR)
3311 cst = gimple_assign_rhs2 (use_stmt);
3312 if (TREE_CODE (cst) != INTEGER_CST)
3313 continue;
3314 cst = int_const_binop (code, val, cst);
3316 else if (CONVERT_EXPR_CODE_P (code))
3318 /* For truncating conversions we cannot record
3319 an inequality. */
3320 if (comp_code == NE_EXPR
3321 && (TYPE_PRECISION (TREE_TYPE (name2))
3322 < TYPE_PRECISION (TREE_TYPE (name))))
3323 continue;
3324 cst = fold_convert (TREE_TYPE (name2), val);
3326 else
3327 continue;
3329 if (TREE_OVERFLOW_P (cst))
3330 cst = drop_tree_overflow (cst);
3331 add_assert_info (asserts, name2, name2, comp_code, cst);
3335 if (TREE_CODE_CLASS (comp_code) == tcc_comparison
3336 && TREE_CODE (val) == INTEGER_CST)
3338 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3339 tree name2 = NULL_TREE, names[2], cst2 = NULL_TREE;
3340 tree val2 = NULL_TREE;
3341 unsigned int prec = TYPE_PRECISION (TREE_TYPE (val));
3342 wide_int mask = wi::zero (prec);
3343 unsigned int nprec = prec;
3344 enum tree_code rhs_code = ERROR_MARK;
3346 if (is_gimple_assign (def_stmt))
3347 rhs_code = gimple_assign_rhs_code (def_stmt);
3349 /* In the case of NAME != CST1 where NAME = A +- CST2 we can
3350 assert that A != CST1 -+ CST2. */
3351 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
3352 && (rhs_code == PLUS_EXPR || rhs_code == MINUS_EXPR))
3354 tree op0 = gimple_assign_rhs1 (def_stmt);
3355 tree op1 = gimple_assign_rhs2 (def_stmt);
3356 if (TREE_CODE (op0) == SSA_NAME
3357 && TREE_CODE (op1) == INTEGER_CST)
3359 enum tree_code reverse_op = (rhs_code == PLUS_EXPR
3360 ? MINUS_EXPR : PLUS_EXPR);
3361 op1 = int_const_binop (reverse_op, val, op1);
3362 if (TREE_OVERFLOW (op1))
3363 op1 = drop_tree_overflow (op1);
3364 add_assert_info (asserts, op0, op0, comp_code, op1);
3368 /* Add asserts for NAME cmp CST and NAME being defined
3369 as NAME = (int) NAME2. */
3370 if (!TYPE_UNSIGNED (TREE_TYPE (val))
3371 && (comp_code == LE_EXPR || comp_code == LT_EXPR
3372 || comp_code == GT_EXPR || comp_code == GE_EXPR)
3373 && gimple_assign_cast_p (def_stmt))
3375 name2 = gimple_assign_rhs1 (def_stmt);
3376 if (CONVERT_EXPR_CODE_P (rhs_code)
3377 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
3378 && TYPE_UNSIGNED (TREE_TYPE (name2))
3379 && prec == TYPE_PRECISION (TREE_TYPE (name2))
3380 && (comp_code == LE_EXPR || comp_code == GT_EXPR
3381 || !tree_int_cst_equal (val,
3382 TYPE_MIN_VALUE (TREE_TYPE (val)))))
3384 tree tmp, cst;
3385 enum tree_code new_comp_code = comp_code;
3387 cst = fold_convert (TREE_TYPE (name2),
3388 TYPE_MIN_VALUE (TREE_TYPE (val)));
3389 /* Build an expression for the range test. */
3390 tmp = build2 (PLUS_EXPR, TREE_TYPE (name2), name2, cst);
3391 cst = fold_build2 (PLUS_EXPR, TREE_TYPE (name2), cst,
3392 fold_convert (TREE_TYPE (name2), val));
3393 if (comp_code == LT_EXPR || comp_code == GE_EXPR)
3395 new_comp_code = comp_code == LT_EXPR ? LE_EXPR : GT_EXPR;
3396 cst = fold_build2 (MINUS_EXPR, TREE_TYPE (name2), cst,
3397 build_int_cst (TREE_TYPE (name2), 1));
3400 if (dump_file)
3402 fprintf (dump_file, "Adding assert for ");
3403 print_generic_expr (dump_file, name2);
3404 fprintf (dump_file, " from ");
3405 print_generic_expr (dump_file, tmp);
3406 fprintf (dump_file, "\n");
3409 add_assert_info (asserts, name2, tmp, new_comp_code, cst);
3413 /* Add asserts for NAME cmp CST and NAME being defined as
3414 NAME = NAME2 >> CST2.
3416 Extract CST2 from the right shift. */
3417 if (rhs_code == RSHIFT_EXPR)
3419 name2 = gimple_assign_rhs1 (def_stmt);
3420 cst2 = gimple_assign_rhs2 (def_stmt);
3421 if (TREE_CODE (name2) == SSA_NAME
3422 && tree_fits_uhwi_p (cst2)
3423 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
3424 && IN_RANGE (tree_to_uhwi (cst2), 1, prec - 1)
3425 && type_has_mode_precision_p (TREE_TYPE (val)))
3427 mask = wi::mask (tree_to_uhwi (cst2), false, prec);
3428 val2 = fold_binary (LSHIFT_EXPR, TREE_TYPE (val), val, cst2);
3431 if (val2 != NULL_TREE
3432 && TREE_CODE (val2) == INTEGER_CST
3433 && simple_cst_equal (fold_build2 (RSHIFT_EXPR,
3434 TREE_TYPE (val),
3435 val2, cst2), val))
3437 enum tree_code new_comp_code = comp_code;
3438 tree tmp, new_val;
3440 tmp = name2;
3441 if (comp_code == EQ_EXPR || comp_code == NE_EXPR)
3443 if (!TYPE_UNSIGNED (TREE_TYPE (val)))
3445 tree type = build_nonstandard_integer_type (prec, 1);
3446 tmp = build1 (NOP_EXPR, type, name2);
3447 val2 = fold_convert (type, val2);
3449 tmp = fold_build2 (MINUS_EXPR, TREE_TYPE (tmp), tmp, val2);
3450 new_val = wide_int_to_tree (TREE_TYPE (tmp), mask);
3451 new_comp_code = comp_code == EQ_EXPR ? LE_EXPR : GT_EXPR;
3453 else if (comp_code == LT_EXPR || comp_code == GE_EXPR)
3455 wide_int minval
3456 = wi::min_value (prec, TYPE_SIGN (TREE_TYPE (val)));
3457 new_val = val2;
3458 if (minval == wi::to_wide (new_val))
3459 new_val = NULL_TREE;
3461 else
3463 wide_int maxval
3464 = wi::max_value (prec, TYPE_SIGN (TREE_TYPE (val)));
3465 mask |= wi::to_wide (val2);
3466 if (wi::eq_p (mask, maxval))
3467 new_val = NULL_TREE;
3468 else
3469 new_val = wide_int_to_tree (TREE_TYPE (val2), mask);
3472 if (new_val)
3474 if (dump_file)
3476 fprintf (dump_file, "Adding assert for ");
3477 print_generic_expr (dump_file, name2);
3478 fprintf (dump_file, " from ");
3479 print_generic_expr (dump_file, tmp);
3480 fprintf (dump_file, "\n");
3483 add_assert_info (asserts, name2, tmp, new_comp_code, new_val);
3487 /* Add asserts for NAME cmp CST and NAME being defined as
3488 NAME = NAME2 & CST2.
3490 Extract CST2 from the and.
3492 Also handle
3493 NAME = (unsigned) NAME2;
3494 casts where NAME's type is unsigned and has smaller precision
3495 than NAME2's type as if it was NAME = NAME2 & MASK. */
3496 names[0] = NULL_TREE;
3497 names[1] = NULL_TREE;
3498 cst2 = NULL_TREE;
3499 if (rhs_code == BIT_AND_EXPR
3500 || (CONVERT_EXPR_CODE_P (rhs_code)
3501 && INTEGRAL_TYPE_P (TREE_TYPE (val))
3502 && TYPE_UNSIGNED (TREE_TYPE (val))
3503 && TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
3504 > prec))
3506 name2 = gimple_assign_rhs1 (def_stmt);
3507 if (rhs_code == BIT_AND_EXPR)
3508 cst2 = gimple_assign_rhs2 (def_stmt);
3509 else
3511 cst2 = TYPE_MAX_VALUE (TREE_TYPE (val));
3512 nprec = TYPE_PRECISION (TREE_TYPE (name2));
3514 if (TREE_CODE (name2) == SSA_NAME
3515 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
3516 && TREE_CODE (cst2) == INTEGER_CST
3517 && !integer_zerop (cst2)
3518 && (nprec > 1
3519 || TYPE_UNSIGNED (TREE_TYPE (val))))
3521 gimple *def_stmt2 = SSA_NAME_DEF_STMT (name2);
3522 if (gimple_assign_cast_p (def_stmt2))
3524 names[1] = gimple_assign_rhs1 (def_stmt2);
3525 if (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt2))
3526 || !INTEGRAL_TYPE_P (TREE_TYPE (names[1]))
3527 || (TYPE_PRECISION (TREE_TYPE (name2))
3528 != TYPE_PRECISION (TREE_TYPE (names[1]))))
3529 names[1] = NULL_TREE;
3531 names[0] = name2;
3534 if (names[0] || names[1])
3536 wide_int minv, maxv, valv, cst2v;
3537 wide_int tem, sgnbit;
3538 bool valid_p = false, valn, cst2n;
3539 enum tree_code ccode = comp_code;
3541 valv = wide_int::from (wi::to_wide (val), nprec, UNSIGNED);
3542 cst2v = wide_int::from (wi::to_wide (cst2), nprec, UNSIGNED);
3543 valn = wi::neg_p (valv, TYPE_SIGN (TREE_TYPE (val)));
3544 cst2n = wi::neg_p (cst2v, TYPE_SIGN (TREE_TYPE (val)));
3545 /* If CST2 doesn't have most significant bit set,
3546 but VAL is negative, we have comparison like
3547 if ((x & 0x123) > -4) (always true). Just give up. */
3548 if (!cst2n && valn)
3549 ccode = ERROR_MARK;
3550 if (cst2n)
3551 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
3552 else
3553 sgnbit = wi::zero (nprec);
3554 minv = valv & cst2v;
3555 switch (ccode)
3557 case EQ_EXPR:
3558 /* Minimum unsigned value for equality is VAL & CST2
3559 (should be equal to VAL, otherwise we probably should
3560 have folded the comparison into false) and
3561 maximum unsigned value is VAL | ~CST2. */
3562 maxv = valv | ~cst2v;
3563 valid_p = true;
3564 break;
3566 case NE_EXPR:
3567 tem = valv | ~cst2v;
3568 /* If VAL is 0, handle (X & CST2) != 0 as (X & CST2) > 0U. */
3569 if (valv == 0)
3571 cst2n = false;
3572 sgnbit = wi::zero (nprec);
3573 goto gt_expr;
3575 /* If (VAL | ~CST2) is all ones, handle it as
3576 (X & CST2) < VAL. */
3577 if (tem == -1)
3579 cst2n = false;
3580 valn = false;
3581 sgnbit = wi::zero (nprec);
3582 goto lt_expr;
3584 if (!cst2n && wi::neg_p (cst2v))
3585 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
3586 if (sgnbit != 0)
3588 if (valv == sgnbit)
3590 cst2n = true;
3591 valn = true;
3592 goto gt_expr;
3594 if (tem == wi::mask (nprec - 1, false, nprec))
3596 cst2n = true;
3597 goto lt_expr;
3599 if (!cst2n)
3600 sgnbit = wi::zero (nprec);
3602 break;
3604 case GE_EXPR:
3605 /* Minimum unsigned value for >= if (VAL & CST2) == VAL
3606 is VAL and maximum unsigned value is ~0. For signed
3607 comparison, if CST2 doesn't have most significant bit
3608 set, handle it similarly. If CST2 has MSB set,
3609 the minimum is the same, and maximum is ~0U/2. */
3610 if (minv != valv)
3612 /* If (VAL & CST2) != VAL, X & CST2 can't be equal to
3613 VAL. */
3614 minv = masked_increment (valv, cst2v, sgnbit, nprec);
3615 if (minv == valv)
3616 break;
3618 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
3619 valid_p = true;
3620 break;
3622 case GT_EXPR:
3623 gt_expr:
3624 /* Find out smallest MINV where MINV > VAL
3625 && (MINV & CST2) == MINV, if any. If VAL is signed and
3626 CST2 has MSB set, compute it biased by 1 << (nprec - 1). */
3627 minv = masked_increment (valv, cst2v, sgnbit, nprec);
3628 if (minv == valv)
3629 break;
3630 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
3631 valid_p = true;
3632 break;
3634 case LE_EXPR:
3635 /* Minimum unsigned value for <= is 0 and maximum
3636 unsigned value is VAL | ~CST2 if (VAL & CST2) == VAL.
3637 Otherwise, find smallest VAL2 where VAL2 > VAL
3638 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
3639 as maximum.
3640 For signed comparison, if CST2 doesn't have most
3641 significant bit set, handle it similarly. If CST2 has
3642 MSB set, the maximum is the same and minimum is INT_MIN. */
3643 if (minv == valv)
3644 maxv = valv;
3645 else
3647 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
3648 if (maxv == valv)
3649 break;
3650 maxv -= 1;
3652 maxv |= ~cst2v;
3653 minv = sgnbit;
3654 valid_p = true;
3655 break;
3657 case LT_EXPR:
3658 lt_expr:
3659 /* Minimum unsigned value for < is 0 and maximum
3660 unsigned value is (VAL-1) | ~CST2 if (VAL & CST2) == VAL.
3661 Otherwise, find smallest VAL2 where VAL2 > VAL
3662 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
3663 as maximum.
3664 For signed comparison, if CST2 doesn't have most
3665 significant bit set, handle it similarly. If CST2 has
3666 MSB set, the maximum is the same and minimum is INT_MIN. */
3667 if (minv == valv)
3669 if (valv == sgnbit)
3670 break;
3671 maxv = valv;
3673 else
3675 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
3676 if (maxv == valv)
3677 break;
3679 maxv -= 1;
3680 maxv |= ~cst2v;
3681 minv = sgnbit;
3682 valid_p = true;
3683 break;
3685 default:
3686 break;
3688 if (valid_p
3689 && (maxv - minv) != -1)
3691 tree tmp, new_val, type;
3692 int i;
3694 for (i = 0; i < 2; i++)
3695 if (names[i])
3697 wide_int maxv2 = maxv;
3698 tmp = names[i];
3699 type = TREE_TYPE (names[i]);
3700 if (!TYPE_UNSIGNED (type))
3702 type = build_nonstandard_integer_type (nprec, 1);
3703 tmp = build1 (NOP_EXPR, type, names[i]);
3705 if (minv != 0)
3707 tmp = build2 (PLUS_EXPR, type, tmp,
3708 wide_int_to_tree (type, -minv));
3709 maxv2 = maxv - minv;
3711 new_val = wide_int_to_tree (type, maxv2);
3713 if (dump_file)
3715 fprintf (dump_file, "Adding assert for ");
3716 print_generic_expr (dump_file, names[i]);
3717 fprintf (dump_file, " from ");
3718 print_generic_expr (dump_file, tmp);
3719 fprintf (dump_file, "\n");
3722 add_assert_info (asserts, names[i], tmp, LE_EXPR, new_val);
3729 /* OP is an operand of a truth value expression which is known to have
3730 a particular value. Register any asserts for OP and for any
3731 operands in OP's defining statement.
3733 If CODE is EQ_EXPR, then we want to register OP is zero (false),
3734 if CODE is NE_EXPR, then we want to register OP is nonzero (true). */
3736 static void
3737 register_edge_assert_for_1 (tree op, enum tree_code code,
3738 edge e, vec<assert_info> &asserts)
3740 gimple *op_def;
3741 tree val;
3742 enum tree_code rhs_code;
3744 /* We only care about SSA_NAMEs. */
3745 if (TREE_CODE (op) != SSA_NAME)
3746 return;
3748 /* We know that OP will have a zero or nonzero value. */
3749 val = build_int_cst (TREE_TYPE (op), 0);
3750 add_assert_info (asserts, op, op, code, val);
3752 /* Now look at how OP is set. If it's set from a comparison,
3753 a truth operation or some bit operations, then we may be able
3754 to register information about the operands of that assignment. */
3755 op_def = SSA_NAME_DEF_STMT (op);
3756 if (gimple_code (op_def) != GIMPLE_ASSIGN)
3757 return;
3759 rhs_code = gimple_assign_rhs_code (op_def);
3761 if (TREE_CODE_CLASS (rhs_code) == tcc_comparison)
3763 bool invert = (code == EQ_EXPR ? true : false);
3764 tree op0 = gimple_assign_rhs1 (op_def);
3765 tree op1 = gimple_assign_rhs2 (op_def);
3767 if (TREE_CODE (op0) == SSA_NAME)
3768 register_edge_assert_for_2 (op0, e, rhs_code, op0, op1, invert, asserts);
3769 if (TREE_CODE (op1) == SSA_NAME)
3770 register_edge_assert_for_2 (op1, e, rhs_code, op0, op1, invert, asserts);
3772 else if ((code == NE_EXPR
3773 && gimple_assign_rhs_code (op_def) == BIT_AND_EXPR)
3774 || (code == EQ_EXPR
3775 && gimple_assign_rhs_code (op_def) == BIT_IOR_EXPR))
3777 /* Recurse on each operand. */
3778 tree op0 = gimple_assign_rhs1 (op_def);
3779 tree op1 = gimple_assign_rhs2 (op_def);
3780 if (TREE_CODE (op0) == SSA_NAME
3781 && has_single_use (op0))
3782 register_edge_assert_for_1 (op0, code, e, asserts);
3783 if (TREE_CODE (op1) == SSA_NAME
3784 && has_single_use (op1))
3785 register_edge_assert_for_1 (op1, code, e, asserts);
3787 else if (gimple_assign_rhs_code (op_def) == BIT_NOT_EXPR
3788 && TYPE_PRECISION (TREE_TYPE (gimple_assign_lhs (op_def))) == 1)
3790 /* Recurse, flipping CODE. */
3791 code = invert_tree_comparison (code, false);
3792 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
3794 else if (gimple_assign_rhs_code (op_def) == SSA_NAME)
3796 /* Recurse through the copy. */
3797 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
3799 else if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (op_def)))
3801 /* Recurse through the type conversion, unless it is a narrowing
3802 conversion or conversion from non-integral type. */
3803 tree rhs = gimple_assign_rhs1 (op_def);
3804 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs))
3805 && (TYPE_PRECISION (TREE_TYPE (rhs))
3806 <= TYPE_PRECISION (TREE_TYPE (op))))
3807 register_edge_assert_for_1 (rhs, code, e, asserts);
3811 /* Check if comparison
3812 NAME COND_OP INTEGER_CST
3813 has a form of
3814 (X & 11...100..0) COND_OP XX...X00...0
3815 Such comparison can yield assertions like
3816 X >= XX...X00...0
3817 X <= XX...X11...1
3818 in case of COND_OP being NE_EXPR or
3819 X < XX...X00...0
3820 X > XX...X11...1
3821 in case of EQ_EXPR. */
3823 static bool
3824 is_masked_range_test (tree name, tree valt, enum tree_code cond_code,
3825 tree *new_name, tree *low, enum tree_code *low_code,
3826 tree *high, enum tree_code *high_code)
3828 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3830 if (!is_gimple_assign (def_stmt)
3831 || gimple_assign_rhs_code (def_stmt) != BIT_AND_EXPR)
3832 return false;
3834 tree t = gimple_assign_rhs1 (def_stmt);
3835 tree maskt = gimple_assign_rhs2 (def_stmt);
3836 if (TREE_CODE (t) != SSA_NAME || TREE_CODE (maskt) != INTEGER_CST)
3837 return false;
3839 wi::tree_to_wide_ref mask = wi::to_wide (maskt);
3840 wide_int inv_mask = ~mask;
3841 /* Assume VALT is INTEGER_CST. */
3842 wi::tree_to_wide_ref val = wi::to_wide (valt);
3844 if ((inv_mask & (inv_mask + 1)) != 0
3845 || (val & mask) != val)
3846 return false;
3848 bool is_range = cond_code == EQ_EXPR;
3850 tree type = TREE_TYPE (t);
3851 wide_int min = wi::min_value (type),
3852 max = wi::max_value (type);
3854 if (is_range)
3856 *low_code = val == min ? ERROR_MARK : GE_EXPR;
3857 *high_code = val == max ? ERROR_MARK : LE_EXPR;
3859 else
3861 /* We can still generate assertion if one of alternatives
3862 is known to always be false. */
3863 if (val == min)
3865 *low_code = (enum tree_code) 0;
3866 *high_code = GT_EXPR;
3868 else if ((val | inv_mask) == max)
3870 *low_code = LT_EXPR;
3871 *high_code = (enum tree_code) 0;
3873 else
3874 return false;
3877 *new_name = t;
3878 *low = wide_int_to_tree (type, val);
3879 *high = wide_int_to_tree (type, val | inv_mask);
3881 if (wi::neg_p (val, TYPE_SIGN (type)))
3882 std::swap (*low, *high);
3884 return true;
3887 /* Try to register an edge assertion for SSA name NAME on edge E for
3888 the condition COND contributing to the conditional jump pointed to by
3889 SI. */
3891 void
3892 register_edge_assert_for (tree name, edge e,
3893 enum tree_code cond_code, tree cond_op0,
3894 tree cond_op1, vec<assert_info> &asserts)
3896 tree val;
3897 enum tree_code comp_code;
3898 bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
3900 /* Do not attempt to infer anything in names that flow through
3901 abnormal edges. */
3902 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
3903 return;
3905 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
3906 cond_op0, cond_op1,
3907 is_else_edge,
3908 &comp_code, &val))
3909 return;
3911 /* Register ASSERT_EXPRs for name. */
3912 register_edge_assert_for_2 (name, e, cond_code, cond_op0,
3913 cond_op1, is_else_edge, asserts);
3916 /* If COND is effectively an equality test of an SSA_NAME against
3917 the value zero or one, then we may be able to assert values
3918 for SSA_NAMEs which flow into COND. */
3920 /* In the case of NAME == 1 or NAME != 0, for BIT_AND_EXPR defining
3921 statement of NAME we can assert both operands of the BIT_AND_EXPR
3922 have nonzero value. */
3923 if (((comp_code == EQ_EXPR && integer_onep (val))
3924 || (comp_code == NE_EXPR && integer_zerop (val))))
3926 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3928 if (is_gimple_assign (def_stmt)
3929 && gimple_assign_rhs_code (def_stmt) == BIT_AND_EXPR)
3931 tree op0 = gimple_assign_rhs1 (def_stmt);
3932 tree op1 = gimple_assign_rhs2 (def_stmt);
3933 register_edge_assert_for_1 (op0, NE_EXPR, e, asserts);
3934 register_edge_assert_for_1 (op1, NE_EXPR, e, asserts);
3938 /* In the case of NAME == 0 or NAME != 1, for BIT_IOR_EXPR defining
3939 statement of NAME we can assert both operands of the BIT_IOR_EXPR
3940 have zero value. */
3941 if (((comp_code == EQ_EXPR && integer_zerop (val))
3942 || (comp_code == NE_EXPR && integer_onep (val))))
3944 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3946 /* For BIT_IOR_EXPR only if NAME == 0 both operands have
3947 necessarily zero value, or if type-precision is one. */
3948 if (is_gimple_assign (def_stmt)
3949 && (gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR
3950 && (TYPE_PRECISION (TREE_TYPE (name)) == 1
3951 || comp_code == EQ_EXPR)))
3953 tree op0 = gimple_assign_rhs1 (def_stmt);
3954 tree op1 = gimple_assign_rhs2 (def_stmt);
3955 register_edge_assert_for_1 (op0, EQ_EXPR, e, asserts);
3956 register_edge_assert_for_1 (op1, EQ_EXPR, e, asserts);
3960 /* Sometimes we can infer ranges from (NAME & MASK) == VALUE. */
3961 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
3962 && TREE_CODE (val) == INTEGER_CST)
3964 enum tree_code low_code, high_code;
3965 tree low, high;
3966 if (is_masked_range_test (name, val, comp_code, &name, &low,
3967 &low_code, &high, &high_code))
3969 if (low_code != ERROR_MARK)
3970 register_edge_assert_for_2 (name, e, low_code, name,
3971 low, /*invert*/false, asserts);
3972 if (high_code != ERROR_MARK)
3973 register_edge_assert_for_2 (name, e, high_code, name,
3974 high, /*invert*/false, asserts);
3979 /* Finish found ASSERTS for E and register them at GSI. */
3981 static void
3982 finish_register_edge_assert_for (edge e, gimple_stmt_iterator gsi,
3983 vec<assert_info> &asserts)
3985 for (unsigned i = 0; i < asserts.length (); ++i)
3986 /* Only register an ASSERT_EXPR if NAME was found in the sub-graph
3987 reachable from E. */
3988 if (live_on_edge (e, asserts[i].name))
3989 register_new_assert_for (asserts[i].name, asserts[i].expr,
3990 asserts[i].comp_code, asserts[i].val,
3991 NULL, e, gsi);
3996 /* Determine whether the outgoing edges of BB should receive an
3997 ASSERT_EXPR for each of the operands of BB's LAST statement.
3998 The last statement of BB must be a COND_EXPR.
4000 If any of the sub-graphs rooted at BB have an interesting use of
4001 the predicate operands, an assert location node is added to the
4002 list of assertions for the corresponding operands. */
4004 static void
4005 find_conditional_asserts (basic_block bb, gcond *last)
4007 gimple_stmt_iterator bsi;
4008 tree op;
4009 edge_iterator ei;
4010 edge e;
4011 ssa_op_iter iter;
4013 bsi = gsi_for_stmt (last);
4015 /* Look for uses of the operands in each of the sub-graphs
4016 rooted at BB. We need to check each of the outgoing edges
4017 separately, so that we know what kind of ASSERT_EXPR to
4018 insert. */
4019 FOR_EACH_EDGE (e, ei, bb->succs)
4021 if (e->dest == bb)
4022 continue;
4024 /* Register the necessary assertions for each operand in the
4025 conditional predicate. */
4026 auto_vec<assert_info, 8> asserts;
4027 FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
4028 register_edge_assert_for (op, e,
4029 gimple_cond_code (last),
4030 gimple_cond_lhs (last),
4031 gimple_cond_rhs (last), asserts);
4032 finish_register_edge_assert_for (e, bsi, asserts);
4036 struct case_info
4038 tree expr;
4039 basic_block bb;
4042 /* Compare two case labels sorting first by the destination bb index
4043 and then by the case value. */
4045 static int
4046 compare_case_labels (const void *p1, const void *p2)
4048 const struct case_info *ci1 = (const struct case_info *) p1;
4049 const struct case_info *ci2 = (const struct case_info *) p2;
4050 int idx1 = ci1->bb->index;
4051 int idx2 = ci2->bb->index;
4053 if (idx1 < idx2)
4054 return -1;
4055 else if (idx1 == idx2)
4057 /* Make sure the default label is first in a group. */
4058 if (!CASE_LOW (ci1->expr))
4059 return -1;
4060 else if (!CASE_LOW (ci2->expr))
4061 return 1;
4062 else
4063 return tree_int_cst_compare (CASE_LOW (ci1->expr),
4064 CASE_LOW (ci2->expr));
4066 else
4067 return 1;
4070 /* Determine whether the outgoing edges of BB should receive an
4071 ASSERT_EXPR for each of the operands of BB's LAST statement.
4072 The last statement of BB must be a SWITCH_EXPR.
4074 If any of the sub-graphs rooted at BB have an interesting use of
4075 the predicate operands, an assert location node is added to the
4076 list of assertions for the corresponding operands. */
4078 static void
4079 find_switch_asserts (basic_block bb, gswitch *last)
4081 gimple_stmt_iterator bsi;
4082 tree op;
4083 edge e;
4084 struct case_info *ci;
4085 size_t n = gimple_switch_num_labels (last);
4086 #if GCC_VERSION >= 4000
4087 unsigned int idx;
4088 #else
4089 /* Work around GCC 3.4 bug (PR 37086). */
4090 volatile unsigned int idx;
4091 #endif
4093 bsi = gsi_for_stmt (last);
4094 op = gimple_switch_index (last);
4095 if (TREE_CODE (op) != SSA_NAME)
4096 return;
4098 /* Build a vector of case labels sorted by destination label. */
4099 ci = XNEWVEC (struct case_info, n);
4100 for (idx = 0; idx < n; ++idx)
4102 ci[idx].expr = gimple_switch_label (last, idx);
4103 ci[idx].bb = label_to_block (CASE_LABEL (ci[idx].expr));
4105 edge default_edge = find_edge (bb, ci[0].bb);
4106 qsort (ci, n, sizeof (struct case_info), compare_case_labels);
4108 for (idx = 0; idx < n; ++idx)
4110 tree min, max;
4111 tree cl = ci[idx].expr;
4112 basic_block cbb = ci[idx].bb;
4114 min = CASE_LOW (cl);
4115 max = CASE_HIGH (cl);
4117 /* If there are multiple case labels with the same destination
4118 we need to combine them to a single value range for the edge. */
4119 if (idx + 1 < n && cbb == ci[idx + 1].bb)
4121 /* Skip labels until the last of the group. */
4122 do {
4123 ++idx;
4124 } while (idx < n && cbb == ci[idx].bb);
4125 --idx;
4127 /* Pick up the maximum of the case label range. */
4128 if (CASE_HIGH (ci[idx].expr))
4129 max = CASE_HIGH (ci[idx].expr);
4130 else
4131 max = CASE_LOW (ci[idx].expr);
4134 /* Can't extract a useful assertion out of a range that includes the
4135 default label. */
4136 if (min == NULL_TREE)
4137 continue;
4139 /* Find the edge to register the assert expr on. */
4140 e = find_edge (bb, cbb);
4142 /* Register the necessary assertions for the operand in the
4143 SWITCH_EXPR. */
4144 auto_vec<assert_info, 8> asserts;
4145 register_edge_assert_for (op, e,
4146 max ? GE_EXPR : EQ_EXPR,
4147 op, fold_convert (TREE_TYPE (op), min),
4148 asserts);
4149 if (max)
4150 register_edge_assert_for (op, e, LE_EXPR, op,
4151 fold_convert (TREE_TYPE (op), max),
4152 asserts);
4153 finish_register_edge_assert_for (e, bsi, asserts);
4156 XDELETEVEC (ci);
4158 if (!live_on_edge (default_edge, op))
4159 return;
4161 /* Now register along the default label assertions that correspond to the
4162 anti-range of each label. */
4163 int insertion_limit = PARAM_VALUE (PARAM_MAX_VRP_SWITCH_ASSERTIONS);
4164 if (insertion_limit == 0)
4165 return;
4167 /* We can't do this if the default case shares a label with another case. */
4168 tree default_cl = gimple_switch_default_label (last);
4169 for (idx = 1; idx < n; idx++)
4171 tree min, max;
4172 tree cl = gimple_switch_label (last, idx);
4173 if (CASE_LABEL (cl) == CASE_LABEL (default_cl))
4174 continue;
4176 min = CASE_LOW (cl);
4177 max = CASE_HIGH (cl);
4179 /* Combine contiguous case ranges to reduce the number of assertions
4180 to insert. */
4181 for (idx = idx + 1; idx < n; idx++)
4183 tree next_min, next_max;
4184 tree next_cl = gimple_switch_label (last, idx);
4185 if (CASE_LABEL (next_cl) == CASE_LABEL (default_cl))
4186 break;
4188 next_min = CASE_LOW (next_cl);
4189 next_max = CASE_HIGH (next_cl);
4191 wide_int difference = (wi::to_wide (next_min)
4192 - wi::to_wide (max ? max : min));
4193 if (wi::eq_p (difference, 1))
4194 max = next_max ? next_max : next_min;
4195 else
4196 break;
4198 idx--;
4200 if (max == NULL_TREE)
4202 /* Register the assertion OP != MIN. */
4203 auto_vec<assert_info, 8> asserts;
4204 min = fold_convert (TREE_TYPE (op), min);
4205 register_edge_assert_for (op, default_edge, NE_EXPR, op, min,
4206 asserts);
4207 finish_register_edge_assert_for (default_edge, bsi, asserts);
4209 else
4211 /* Register the assertion (unsigned)OP - MIN > (MAX - MIN),
4212 which will give OP the anti-range ~[MIN,MAX]. */
4213 tree uop = fold_convert (unsigned_type_for (TREE_TYPE (op)), op);
4214 min = fold_convert (TREE_TYPE (uop), min);
4215 max = fold_convert (TREE_TYPE (uop), max);
4217 tree lhs = fold_build2 (MINUS_EXPR, TREE_TYPE (uop), uop, min);
4218 tree rhs = int_const_binop (MINUS_EXPR, max, min);
4219 register_new_assert_for (op, lhs, GT_EXPR, rhs,
4220 NULL, default_edge, bsi);
4223 if (--insertion_limit == 0)
4224 break;
4229 /* Traverse all the statements in block BB looking for statements that
4230 may generate useful assertions for the SSA names in their operand.
4231 If a statement produces a useful assertion A for name N_i, then the
4232 list of assertions already generated for N_i is scanned to
4233 determine if A is actually needed.
4235 If N_i already had the assertion A at a location dominating the
4236 current location, then nothing needs to be done. Otherwise, the
4237 new location for A is recorded instead.
4239 1- For every statement S in BB, all the variables used by S are
4240 added to bitmap FOUND_IN_SUBGRAPH.
4242 2- If statement S uses an operand N in a way that exposes a known
4243 value range for N, then if N was not already generated by an
4244 ASSERT_EXPR, create a new assert location for N. For instance,
4245 if N is a pointer and the statement dereferences it, we can
4246 assume that N is not NULL.
4248 3- COND_EXPRs are a special case of #2. We can derive range
4249 information from the predicate but need to insert different
4250 ASSERT_EXPRs for each of the sub-graphs rooted at the
4251 conditional block. If the last statement of BB is a conditional
4252 expression of the form 'X op Y', then
4254 a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
4256 b) If the conditional is the only entry point to the sub-graph
4257 corresponding to the THEN_CLAUSE, recurse into it. On
4258 return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
4259 an ASSERT_EXPR is added for the corresponding variable.
4261 c) Repeat step (b) on the ELSE_CLAUSE.
4263 d) Mark X and Y in FOUND_IN_SUBGRAPH.
4265 For instance,
4267 if (a == 9)
4268 b = a;
4269 else
4270 b = c + 1;
4272 In this case, an assertion on the THEN clause is useful to
4273 determine that 'a' is always 9 on that edge. However, an assertion
4274 on the ELSE clause would be unnecessary.
4276 4- If BB does not end in a conditional expression, then we recurse
4277 into BB's dominator children.
4279 At the end of the recursive traversal, every SSA name will have a
4280 list of locations where ASSERT_EXPRs should be added. When a new
4281 location for name N is found, it is registered by calling
4282 register_new_assert_for. That function keeps track of all the
4283 registered assertions to prevent adding unnecessary assertions.
4284 For instance, if a pointer P_4 is dereferenced more than once in a
4285 dominator tree, only the location dominating all the dereference of
4286 P_4 will receive an ASSERT_EXPR. */
4288 static void
4289 find_assert_locations_1 (basic_block bb, sbitmap live)
4291 gimple *last;
4293 last = last_stmt (bb);
4295 /* If BB's last statement is a conditional statement involving integer
4296 operands, determine if we need to add ASSERT_EXPRs. */
4297 if (last
4298 && gimple_code (last) == GIMPLE_COND
4299 && !fp_predicate (last)
4300 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
4301 find_conditional_asserts (bb, as_a <gcond *> (last));
4303 /* If BB's last statement is a switch statement involving integer
4304 operands, determine if we need to add ASSERT_EXPRs. */
4305 if (last
4306 && gimple_code (last) == GIMPLE_SWITCH
4307 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
4308 find_switch_asserts (bb, as_a <gswitch *> (last));
4310 /* Traverse all the statements in BB marking used names and looking
4311 for statements that may infer assertions for their used operands. */
4312 for (gimple_stmt_iterator si = gsi_last_bb (bb); !gsi_end_p (si);
4313 gsi_prev (&si))
4315 gimple *stmt;
4316 tree op;
4317 ssa_op_iter i;
4319 stmt = gsi_stmt (si);
4321 if (is_gimple_debug (stmt))
4322 continue;
4324 /* See if we can derive an assertion for any of STMT's operands. */
4325 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
4327 tree value;
4328 enum tree_code comp_code;
4330 /* If op is not live beyond this stmt, do not bother to insert
4331 asserts for it. */
4332 if (!bitmap_bit_p (live, SSA_NAME_VERSION (op)))
4333 continue;
4335 /* If OP is used in such a way that we can infer a value
4336 range for it, and we don't find a previous assertion for
4337 it, create a new assertion location node for OP. */
4338 if (infer_value_range (stmt, op, &comp_code, &value))
4340 /* If we are able to infer a nonzero value range for OP,
4341 then walk backwards through the use-def chain to see if OP
4342 was set via a typecast.
4344 If so, then we can also infer a nonzero value range
4345 for the operand of the NOP_EXPR. */
4346 if (comp_code == NE_EXPR && integer_zerop (value))
4348 tree t = op;
4349 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
4351 while (is_gimple_assign (def_stmt)
4352 && CONVERT_EXPR_CODE_P
4353 (gimple_assign_rhs_code (def_stmt))
4354 && TREE_CODE
4355 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
4356 && POINTER_TYPE_P
4357 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
4359 t = gimple_assign_rhs1 (def_stmt);
4360 def_stmt = SSA_NAME_DEF_STMT (t);
4362 /* Note we want to register the assert for the
4363 operand of the NOP_EXPR after SI, not after the
4364 conversion. */
4365 if (bitmap_bit_p (live, SSA_NAME_VERSION (t)))
4366 register_new_assert_for (t, t, comp_code, value,
4367 bb, NULL, si);
4371 register_new_assert_for (op, op, comp_code, value, bb, NULL, si);
4375 /* Update live. */
4376 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
4377 bitmap_set_bit (live, SSA_NAME_VERSION (op));
4378 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_DEF)
4379 bitmap_clear_bit (live, SSA_NAME_VERSION (op));
4382 /* Traverse all PHI nodes in BB, updating live. */
4383 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
4384 gsi_next (&si))
4386 use_operand_p arg_p;
4387 ssa_op_iter i;
4388 gphi *phi = si.phi ();
4389 tree res = gimple_phi_result (phi);
4391 if (virtual_operand_p (res))
4392 continue;
4394 FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
4396 tree arg = USE_FROM_PTR (arg_p);
4397 if (TREE_CODE (arg) == SSA_NAME)
4398 bitmap_set_bit (live, SSA_NAME_VERSION (arg));
4401 bitmap_clear_bit (live, SSA_NAME_VERSION (res));
4405 /* Do an RPO walk over the function computing SSA name liveness
4406 on-the-fly and deciding on assert expressions to insert. */
4408 static void
4409 find_assert_locations (void)
4411 int *rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
4412 int *bb_rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
4413 int *last_rpo = XCNEWVEC (int, last_basic_block_for_fn (cfun));
4414 int rpo_cnt, i;
4416 live = XCNEWVEC (sbitmap, last_basic_block_for_fn (cfun));
4417 rpo_cnt = pre_and_rev_post_order_compute (NULL, rpo, false);
4418 for (i = 0; i < rpo_cnt; ++i)
4419 bb_rpo[rpo[i]] = i;
4421 /* Pre-seed loop latch liveness from loop header PHI nodes. Due to
4422 the order we compute liveness and insert asserts we otherwise
4423 fail to insert asserts into the loop latch. */
4424 loop_p loop;
4425 FOR_EACH_LOOP (loop, 0)
4427 i = loop->latch->index;
4428 unsigned int j = single_succ_edge (loop->latch)->dest_idx;
4429 for (gphi_iterator gsi = gsi_start_phis (loop->header);
4430 !gsi_end_p (gsi); gsi_next (&gsi))
4432 gphi *phi = gsi.phi ();
4433 if (virtual_operand_p (gimple_phi_result (phi)))
4434 continue;
4435 tree arg = gimple_phi_arg_def (phi, j);
4436 if (TREE_CODE (arg) == SSA_NAME)
4438 if (live[i] == NULL)
4440 live[i] = sbitmap_alloc (num_ssa_names);
4441 bitmap_clear (live[i]);
4443 bitmap_set_bit (live[i], SSA_NAME_VERSION (arg));
4448 for (i = rpo_cnt - 1; i >= 0; --i)
4450 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, rpo[i]);
4451 edge e;
4452 edge_iterator ei;
4454 if (!live[rpo[i]])
4456 live[rpo[i]] = sbitmap_alloc (num_ssa_names);
4457 bitmap_clear (live[rpo[i]]);
4460 /* Process BB and update the live information with uses in
4461 this block. */
4462 find_assert_locations_1 (bb, live[rpo[i]]);
4464 /* Merge liveness into the predecessor blocks and free it. */
4465 if (!bitmap_empty_p (live[rpo[i]]))
4467 int pred_rpo = i;
4468 FOR_EACH_EDGE (e, ei, bb->preds)
4470 int pred = e->src->index;
4471 if ((e->flags & EDGE_DFS_BACK) || pred == ENTRY_BLOCK)
4472 continue;
4474 if (!live[pred])
4476 live[pred] = sbitmap_alloc (num_ssa_names);
4477 bitmap_clear (live[pred]);
4479 bitmap_ior (live[pred], live[pred], live[rpo[i]]);
4481 if (bb_rpo[pred] < pred_rpo)
4482 pred_rpo = bb_rpo[pred];
4485 /* Record the RPO number of the last visited block that needs
4486 live information from this block. */
4487 last_rpo[rpo[i]] = pred_rpo;
4489 else
4491 sbitmap_free (live[rpo[i]]);
4492 live[rpo[i]] = NULL;
4495 /* We can free all successors live bitmaps if all their
4496 predecessors have been visited already. */
4497 FOR_EACH_EDGE (e, ei, bb->succs)
4498 if (last_rpo[e->dest->index] == i
4499 && live[e->dest->index])
4501 sbitmap_free (live[e->dest->index]);
4502 live[e->dest->index] = NULL;
4506 XDELETEVEC (rpo);
4507 XDELETEVEC (bb_rpo);
4508 XDELETEVEC (last_rpo);
4509 for (i = 0; i < last_basic_block_for_fn (cfun); ++i)
4510 if (live[i])
4511 sbitmap_free (live[i]);
4512 XDELETEVEC (live);
4515 /* Create an ASSERT_EXPR for NAME and insert it in the location
4516 indicated by LOC. Return true if we made any edge insertions. */
4518 static bool
4519 process_assert_insertions_for (tree name, assert_locus *loc)
4521 /* Build the comparison expression NAME_i COMP_CODE VAL. */
4522 gimple *stmt;
4523 tree cond;
4524 gimple *assert_stmt;
4525 edge_iterator ei;
4526 edge e;
4528 /* If we have X <=> X do not insert an assert expr for that. */
4529 if (loc->expr == loc->val)
4530 return false;
4532 cond = build2 (loc->comp_code, boolean_type_node, loc->expr, loc->val);
4533 assert_stmt = build_assert_expr_for (cond, name);
4534 if (loc->e)
4536 /* We have been asked to insert the assertion on an edge. This
4537 is used only by COND_EXPR and SWITCH_EXPR assertions. */
4538 gcc_checking_assert (gimple_code (gsi_stmt (loc->si)) == GIMPLE_COND
4539 || (gimple_code (gsi_stmt (loc->si))
4540 == GIMPLE_SWITCH));
4542 gsi_insert_on_edge (loc->e, assert_stmt);
4543 return true;
4546 /* If the stmt iterator points at the end then this is an insertion
4547 at the beginning of a block. */
4548 if (gsi_end_p (loc->si))
4550 gimple_stmt_iterator si = gsi_after_labels (loc->bb);
4551 gsi_insert_before (&si, assert_stmt, GSI_SAME_STMT);
4552 return false;
4555 /* Otherwise, we can insert right after LOC->SI iff the
4556 statement must not be the last statement in the block. */
4557 stmt = gsi_stmt (loc->si);
4558 if (!stmt_ends_bb_p (stmt))
4560 gsi_insert_after (&loc->si, assert_stmt, GSI_SAME_STMT);
4561 return false;
4564 /* If STMT must be the last statement in BB, we can only insert new
4565 assertions on the non-abnormal edge out of BB. Note that since
4566 STMT is not control flow, there may only be one non-abnormal/eh edge
4567 out of BB. */
4568 FOR_EACH_EDGE (e, ei, loc->bb->succs)
4569 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
4571 gsi_insert_on_edge (e, assert_stmt);
4572 return true;
4575 gcc_unreachable ();
4578 /* Qsort helper for sorting assert locations. If stable is true, don't
4579 use iterative_hash_expr because it can be unstable for -fcompare-debug,
4580 on the other side some pointers might be NULL. */
4582 template <bool stable>
4583 static int
4584 compare_assert_loc (const void *pa, const void *pb)
4586 assert_locus * const a = *(assert_locus * const *)pa;
4587 assert_locus * const b = *(assert_locus * const *)pb;
4589 /* If stable, some asserts might be optimized away already, sort
4590 them last. */
4591 if (stable)
4593 if (a == NULL)
4594 return b != NULL;
4595 else if (b == NULL)
4596 return -1;
4599 if (a->e == NULL && b->e != NULL)
4600 return 1;
4601 else if (a->e != NULL && b->e == NULL)
4602 return -1;
4604 /* After the above checks, we know that (a->e == NULL) == (b->e == NULL),
4605 no need to test both a->e and b->e. */
4607 /* Sort after destination index. */
4608 if (a->e == NULL)
4610 else if (a->e->dest->index > b->e->dest->index)
4611 return 1;
4612 else if (a->e->dest->index < b->e->dest->index)
4613 return -1;
4615 /* Sort after comp_code. */
4616 if (a->comp_code > b->comp_code)
4617 return 1;
4618 else if (a->comp_code < b->comp_code)
4619 return -1;
4621 hashval_t ha, hb;
4623 /* E.g. if a->val is ADDR_EXPR of a VAR_DECL, iterative_hash_expr
4624 uses DECL_UID of the VAR_DECL, so sorting might differ between
4625 -g and -g0. When doing the removal of redundant assert exprs
4626 and commonization to successors, this does not matter, but for
4627 the final sort needs to be stable. */
4628 if (stable)
4630 ha = 0;
4631 hb = 0;
4633 else
4635 ha = iterative_hash_expr (a->expr, iterative_hash_expr (a->val, 0));
4636 hb = iterative_hash_expr (b->expr, iterative_hash_expr (b->val, 0));
4639 /* Break the tie using hashing and source/bb index. */
4640 if (ha == hb)
4641 return (a->e != NULL
4642 ? a->e->src->index - b->e->src->index
4643 : a->bb->index - b->bb->index);
4644 return ha > hb ? 1 : -1;
4647 /* Process all the insertions registered for every name N_i registered
4648 in NEED_ASSERT_FOR. The list of assertions to be inserted are
4649 found in ASSERTS_FOR[i]. */
4651 static void
4652 process_assert_insertions (void)
4654 unsigned i;
4655 bitmap_iterator bi;
4656 bool update_edges_p = false;
4657 int num_asserts = 0;
4659 if (dump_file && (dump_flags & TDF_DETAILS))
4660 dump_all_asserts (dump_file);
4662 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
4664 assert_locus *loc = asserts_for[i];
4665 gcc_assert (loc);
4667 auto_vec<assert_locus *, 16> asserts;
4668 for (; loc; loc = loc->next)
4669 asserts.safe_push (loc);
4670 asserts.qsort (compare_assert_loc<false>);
4672 /* Push down common asserts to successors and remove redundant ones. */
4673 unsigned ecnt = 0;
4674 assert_locus *common = NULL;
4675 unsigned commonj = 0;
4676 for (unsigned j = 0; j < asserts.length (); ++j)
4678 loc = asserts[j];
4679 if (! loc->e)
4680 common = NULL;
4681 else if (! common
4682 || loc->e->dest != common->e->dest
4683 || loc->comp_code != common->comp_code
4684 || ! operand_equal_p (loc->val, common->val, 0)
4685 || ! operand_equal_p (loc->expr, common->expr, 0))
4687 commonj = j;
4688 common = loc;
4689 ecnt = 1;
4691 else if (loc->e == asserts[j-1]->e)
4693 /* Remove duplicate asserts. */
4694 if (commonj == j - 1)
4696 commonj = j;
4697 common = loc;
4699 free (asserts[j-1]);
4700 asserts[j-1] = NULL;
4702 else
4704 ecnt++;
4705 if (EDGE_COUNT (common->e->dest->preds) == ecnt)
4707 /* We have the same assertion on all incoming edges of a BB.
4708 Insert it at the beginning of that block. */
4709 loc->bb = loc->e->dest;
4710 loc->e = NULL;
4711 loc->si = gsi_none ();
4712 common = NULL;
4713 /* Clear asserts commoned. */
4714 for (; commonj != j; ++commonj)
4715 if (asserts[commonj])
4717 free (asserts[commonj]);
4718 asserts[commonj] = NULL;
4724 /* The asserts vector sorting above might be unstable for
4725 -fcompare-debug, sort again to ensure a stable sort. */
4726 asserts.qsort (compare_assert_loc<true>);
4727 for (unsigned j = 0; j < asserts.length (); ++j)
4729 loc = asserts[j];
4730 if (! loc)
4731 break;
4732 update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
4733 num_asserts++;
4734 free (loc);
4738 if (update_edges_p)
4739 gsi_commit_edge_inserts ();
4741 statistics_counter_event (cfun, "Number of ASSERT_EXPR expressions inserted",
4742 num_asserts);
4746 /* Traverse the flowgraph looking for conditional jumps to insert range
4747 expressions. These range expressions are meant to provide information
4748 to optimizations that need to reason in terms of value ranges. They
4749 will not be expanded into RTL. For instance, given:
4751 x = ...
4752 y = ...
4753 if (x < y)
4754 y = x - 2;
4755 else
4756 x = y + 3;
4758 this pass will transform the code into:
4760 x = ...
4761 y = ...
4762 if (x < y)
4764 x = ASSERT_EXPR <x, x < y>
4765 y = x - 2
4767 else
4769 y = ASSERT_EXPR <y, x >= y>
4770 x = y + 3
4773 The idea is that once copy and constant propagation have run, other
4774 optimizations will be able to determine what ranges of values can 'x'
4775 take in different paths of the code, simply by checking the reaching
4776 definition of 'x'. */
4778 static void
4779 insert_range_assertions (void)
4781 need_assert_for = BITMAP_ALLOC (NULL);
4782 asserts_for = XCNEWVEC (assert_locus *, num_ssa_names);
4784 calculate_dominance_info (CDI_DOMINATORS);
4786 find_assert_locations ();
4787 if (!bitmap_empty_p (need_assert_for))
4789 process_assert_insertions ();
4790 update_ssa (TODO_update_ssa_no_phi);
4793 if (dump_file && (dump_flags & TDF_DETAILS))
4795 fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
4796 dump_function_to_file (current_function_decl, dump_file, dump_flags);
4799 free (asserts_for);
4800 BITMAP_FREE (need_assert_for);
4803 class vrp_prop : public ssa_propagation_engine
4805 public:
4806 enum ssa_prop_result visit_stmt (gimple *, edge *, tree *) FINAL OVERRIDE;
4807 enum ssa_prop_result visit_phi (gphi *) FINAL OVERRIDE;
4809 void vrp_initialize (void);
4810 void vrp_finalize (bool);
4811 void check_all_array_refs (void);
4812 void check_array_ref (location_t, tree, bool);
4813 void search_for_addr_array (tree, location_t);
4815 class vr_values vr_values;
4816 /* Temporary delegator to minimize code churn. */
4817 value_range *get_value_range (const_tree op)
4818 { return vr_values.get_value_range (op); }
4819 void set_defs_to_varying (gimple *stmt)
4820 { return vr_values.set_defs_to_varying (stmt); }
4821 void extract_range_from_stmt (gimple *stmt, edge *taken_edge_p,
4822 tree *output_p, value_range *vr)
4823 { vr_values.extract_range_from_stmt (stmt, taken_edge_p, output_p, vr); }
4824 bool update_value_range (const_tree op, value_range *vr)
4825 { return vr_values.update_value_range (op, vr); }
4826 void extract_range_basic (value_range *vr, gimple *stmt)
4827 { vr_values.extract_range_basic (vr, stmt); }
4828 void extract_range_from_phi_node (gphi *phi, value_range *vr)
4829 { vr_values.extract_range_from_phi_node (phi, vr); }
4831 /* Checks one ARRAY_REF in REF, located at LOCUS. Ignores flexible arrays
4832 and "struct" hacks. If VRP can determine that the
4833 array subscript is a constant, check if it is outside valid
4834 range. If the array subscript is a RANGE, warn if it is
4835 non-overlapping with valid range.
4836 IGNORE_OFF_BY_ONE is true if the ARRAY_REF is inside a ADDR_EXPR. */
4838 void
4839 vrp_prop::check_array_ref (location_t location, tree ref,
4840 bool ignore_off_by_one)
4842 value_range *vr = NULL;
4843 tree low_sub, up_sub;
4844 tree low_bound, up_bound, up_bound_p1;
4846 if (TREE_NO_WARNING (ref))
4847 return;
4849 low_sub = up_sub = TREE_OPERAND (ref, 1);
4850 up_bound = array_ref_up_bound (ref);
4852 if (!up_bound
4853 || TREE_CODE (up_bound) != INTEGER_CST
4854 || (warn_array_bounds < 2
4855 && array_at_struct_end_p (ref)))
4857 /* Accesses to trailing arrays via pointers may access storage
4858 beyond the types array bounds. For such arrays, or for flexible
4859 array members, as well as for other arrays of an unknown size,
4860 replace the upper bound with a more permissive one that assumes
4861 the size of the largest object is PTRDIFF_MAX. */
4862 tree eltsize = array_ref_element_size (ref);
4864 if (TREE_CODE (eltsize) != INTEGER_CST
4865 || integer_zerop (eltsize))
4867 up_bound = NULL_TREE;
4868 up_bound_p1 = NULL_TREE;
4870 else
4872 tree maxbound = TYPE_MAX_VALUE (ptrdiff_type_node);
4873 tree arg = TREE_OPERAND (ref, 0);
4874 poly_int64 off;
4876 if (get_addr_base_and_unit_offset (arg, &off) && known_gt (off, 0))
4877 maxbound = wide_int_to_tree (sizetype,
4878 wi::sub (wi::to_wide (maxbound),
4879 off));
4880 else
4881 maxbound = fold_convert (sizetype, maxbound);
4883 up_bound_p1 = int_const_binop (TRUNC_DIV_EXPR, maxbound, eltsize);
4885 up_bound = int_const_binop (MINUS_EXPR, up_bound_p1,
4886 build_int_cst (ptrdiff_type_node, 1));
4889 else
4890 up_bound_p1 = int_const_binop (PLUS_EXPR, up_bound,
4891 build_int_cst (TREE_TYPE (up_bound), 1));
4893 low_bound = array_ref_low_bound (ref);
4895 tree artype = TREE_TYPE (TREE_OPERAND (ref, 0));
4897 /* Empty array. */
4898 if (up_bound && tree_int_cst_equal (low_bound, up_bound_p1))
4900 warning_at (location, OPT_Warray_bounds,
4901 "array subscript %E is above array bounds of %qT",
4902 low_bound, artype);
4903 TREE_NO_WARNING (ref) = 1;
4906 if (TREE_CODE (low_sub) == SSA_NAME)
4908 vr = get_value_range (low_sub);
4909 if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
4911 low_sub = vr->type == VR_RANGE ? vr->max : vr->min;
4912 up_sub = vr->type == VR_RANGE ? vr->min : vr->max;
4916 if (vr && vr->type == VR_ANTI_RANGE)
4918 if (up_bound
4919 && TREE_CODE (up_sub) == INTEGER_CST
4920 && (ignore_off_by_one
4921 ? tree_int_cst_lt (up_bound, up_sub)
4922 : tree_int_cst_le (up_bound, up_sub))
4923 && TREE_CODE (low_sub) == INTEGER_CST
4924 && tree_int_cst_le (low_sub, low_bound))
4926 warning_at (location, OPT_Warray_bounds,
4927 "array subscript [%E, %E] is outside array bounds of %qT",
4928 low_sub, up_sub, artype);
4929 TREE_NO_WARNING (ref) = 1;
4932 else if (up_bound
4933 && TREE_CODE (up_sub) == INTEGER_CST
4934 && (ignore_off_by_one
4935 ? !tree_int_cst_le (up_sub, up_bound_p1)
4936 : !tree_int_cst_le (up_sub, up_bound)))
4938 if (dump_file && (dump_flags & TDF_DETAILS))
4940 fprintf (dump_file, "Array bound warning for ");
4941 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
4942 fprintf (dump_file, "\n");
4944 warning_at (location, OPT_Warray_bounds,
4945 "array subscript %E is above array bounds of %qT",
4946 up_sub, artype);
4947 TREE_NO_WARNING (ref) = 1;
4949 else if (TREE_CODE (low_sub) == INTEGER_CST
4950 && tree_int_cst_lt (low_sub, low_bound))
4952 if (dump_file && (dump_flags & TDF_DETAILS))
4954 fprintf (dump_file, "Array bound warning for ");
4955 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
4956 fprintf (dump_file, "\n");
4958 warning_at (location, OPT_Warray_bounds,
4959 "array subscript %E is below array bounds of %qT",
4960 low_sub, artype);
4961 TREE_NO_WARNING (ref) = 1;
4965 /* Searches if the expr T, located at LOCATION computes
4966 address of an ARRAY_REF, and call check_array_ref on it. */
4968 void
4969 vrp_prop::search_for_addr_array (tree t, location_t location)
4971 /* Check each ARRAY_REFs in the reference chain. */
4974 if (TREE_CODE (t) == ARRAY_REF)
4975 check_array_ref (location, t, true /*ignore_off_by_one*/);
4977 t = TREE_OPERAND (t, 0);
4979 while (handled_component_p (t));
4981 if (TREE_CODE (t) == MEM_REF
4982 && TREE_CODE (TREE_OPERAND (t, 0)) == ADDR_EXPR
4983 && !TREE_NO_WARNING (t))
4985 tree tem = TREE_OPERAND (TREE_OPERAND (t, 0), 0);
4986 tree low_bound, up_bound, el_sz;
4987 offset_int idx;
4988 if (TREE_CODE (TREE_TYPE (tem)) != ARRAY_TYPE
4989 || TREE_CODE (TREE_TYPE (TREE_TYPE (tem))) == ARRAY_TYPE
4990 || !TYPE_DOMAIN (TREE_TYPE (tem)))
4991 return;
4993 low_bound = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
4994 up_bound = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
4995 el_sz = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (tem)));
4996 if (!low_bound
4997 || TREE_CODE (low_bound) != INTEGER_CST
4998 || !up_bound
4999 || TREE_CODE (up_bound) != INTEGER_CST
5000 || !el_sz
5001 || TREE_CODE (el_sz) != INTEGER_CST)
5002 return;
5004 if (!mem_ref_offset (t).is_constant (&idx))
5005 return;
5007 idx = wi::sdiv_trunc (idx, wi::to_offset (el_sz));
5008 if (idx < 0)
5010 if (dump_file && (dump_flags & TDF_DETAILS))
5012 fprintf (dump_file, "Array bound warning for ");
5013 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
5014 fprintf (dump_file, "\n");
5016 warning_at (location, OPT_Warray_bounds,
5017 "array subscript %wi is below array bounds of %qT",
5018 idx.to_shwi (), TREE_TYPE (tem));
5019 TREE_NO_WARNING (t) = 1;
5021 else if (idx > (wi::to_offset (up_bound)
5022 - wi::to_offset (low_bound) + 1))
5024 if (dump_file && (dump_flags & TDF_DETAILS))
5026 fprintf (dump_file, "Array bound warning for ");
5027 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
5028 fprintf (dump_file, "\n");
5030 warning_at (location, OPT_Warray_bounds,
5031 "array subscript %wu is above array bounds of %qT",
5032 idx.to_uhwi (), TREE_TYPE (tem));
5033 TREE_NO_WARNING (t) = 1;
5038 /* walk_tree() callback that checks if *TP is
5039 an ARRAY_REF inside an ADDR_EXPR (in which an array
5040 subscript one outside the valid range is allowed). Call
5041 check_array_ref for each ARRAY_REF found. The location is
5042 passed in DATA. */
5044 static tree
5045 check_array_bounds (tree *tp, int *walk_subtree, void *data)
5047 tree t = *tp;
5048 struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
5049 location_t location;
5051 if (EXPR_HAS_LOCATION (t))
5052 location = EXPR_LOCATION (t);
5053 else
5054 location = gimple_location (wi->stmt);
5056 *walk_subtree = TRUE;
5058 vrp_prop *vrp_prop = (class vrp_prop *)wi->info;
5059 if (TREE_CODE (t) == ARRAY_REF)
5060 vrp_prop->check_array_ref (location, t, false /*ignore_off_by_one*/);
5062 else if (TREE_CODE (t) == ADDR_EXPR)
5064 vrp_prop->search_for_addr_array (t, location);
5065 *walk_subtree = FALSE;
5068 return NULL_TREE;
5071 /* A dom_walker subclass for use by vrp_prop::check_all_array_refs,
5072 to walk over all statements of all reachable BBs and call
5073 check_array_bounds on them. */
5075 class check_array_bounds_dom_walker : public dom_walker
5077 public:
5078 check_array_bounds_dom_walker (vrp_prop *prop)
5079 : dom_walker (CDI_DOMINATORS,
5080 /* Discover non-executable edges, preserving EDGE_EXECUTABLE
5081 flags, so that we can merge in information on
5082 non-executable edges from vrp_folder . */
5083 REACHABLE_BLOCKS_PRESERVING_FLAGS),
5084 m_prop (prop) {}
5085 ~check_array_bounds_dom_walker () {}
5087 edge before_dom_children (basic_block) FINAL OVERRIDE;
5089 private:
5090 vrp_prop *m_prop;
5093 /* Implementation of dom_walker::before_dom_children.
5095 Walk over all statements of BB and call check_array_bounds on them,
5096 and determine if there's a unique successor edge. */
5098 edge
5099 check_array_bounds_dom_walker::before_dom_children (basic_block bb)
5101 gimple_stmt_iterator si;
5102 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
5104 gimple *stmt = gsi_stmt (si);
5105 struct walk_stmt_info wi;
5106 if (!gimple_has_location (stmt)
5107 || is_gimple_debug (stmt))
5108 continue;
5110 memset (&wi, 0, sizeof (wi));
5112 wi.info = m_prop;
5114 walk_gimple_op (stmt, check_array_bounds, &wi);
5117 /* Determine if there's a unique successor edge, and if so, return
5118 that back to dom_walker, ensuring that we don't visit blocks that
5119 became unreachable during the VRP propagation
5120 (PR tree-optimization/83312). */
5121 return find_taken_edge (bb, NULL_TREE);
5124 /* Walk over all statements of all reachable BBs and call check_array_bounds
5125 on them. */
5127 void
5128 vrp_prop::check_all_array_refs ()
5130 check_array_bounds_dom_walker w (this);
5131 w.walk (ENTRY_BLOCK_PTR_FOR_FN (cfun));
5134 /* Return true if all imm uses of VAR are either in STMT, or
5135 feed (optionally through a chain of single imm uses) GIMPLE_COND
5136 in basic block COND_BB. */
5138 static bool
5139 all_imm_uses_in_stmt_or_feed_cond (tree var, gimple *stmt, basic_block cond_bb)
5141 use_operand_p use_p, use2_p;
5142 imm_use_iterator iter;
5144 FOR_EACH_IMM_USE_FAST (use_p, iter, var)
5145 if (USE_STMT (use_p) != stmt)
5147 gimple *use_stmt = USE_STMT (use_p), *use_stmt2;
5148 if (is_gimple_debug (use_stmt))
5149 continue;
5150 while (is_gimple_assign (use_stmt)
5151 && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
5152 && single_imm_use (gimple_assign_lhs (use_stmt),
5153 &use2_p, &use_stmt2))
5154 use_stmt = use_stmt2;
5155 if (gimple_code (use_stmt) != GIMPLE_COND
5156 || gimple_bb (use_stmt) != cond_bb)
5157 return false;
5159 return true;
5162 /* Handle
5163 _4 = x_3 & 31;
5164 if (_4 != 0)
5165 goto <bb 6>;
5166 else
5167 goto <bb 7>;
5168 <bb 6>:
5169 __builtin_unreachable ();
5170 <bb 7>:
5171 x_5 = ASSERT_EXPR <x_3, ...>;
5172 If x_3 has no other immediate uses (checked by caller),
5173 var is the x_3 var from ASSERT_EXPR, we can clear low 5 bits
5174 from the non-zero bitmask. */
5176 void
5177 maybe_set_nonzero_bits (edge e, tree var)
5179 basic_block cond_bb = e->src;
5180 gimple *stmt = last_stmt (cond_bb);
5181 tree cst;
5183 if (stmt == NULL
5184 || gimple_code (stmt) != GIMPLE_COND
5185 || gimple_cond_code (stmt) != ((e->flags & EDGE_TRUE_VALUE)
5186 ? EQ_EXPR : NE_EXPR)
5187 || TREE_CODE (gimple_cond_lhs (stmt)) != SSA_NAME
5188 || !integer_zerop (gimple_cond_rhs (stmt)))
5189 return;
5191 stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt));
5192 if (!is_gimple_assign (stmt)
5193 || gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
5194 || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
5195 return;
5196 if (gimple_assign_rhs1 (stmt) != var)
5198 gimple *stmt2;
5200 if (TREE_CODE (gimple_assign_rhs1 (stmt)) != SSA_NAME)
5201 return;
5202 stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
5203 if (!gimple_assign_cast_p (stmt2)
5204 || gimple_assign_rhs1 (stmt2) != var
5205 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt2))
5206 || (TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (stmt)))
5207 != TYPE_PRECISION (TREE_TYPE (var))))
5208 return;
5210 cst = gimple_assign_rhs2 (stmt);
5211 set_nonzero_bits (var, wi::bit_and_not (get_nonzero_bits (var),
5212 wi::to_wide (cst)));
5215 /* Convert range assertion expressions into the implied copies and
5216 copy propagate away the copies. Doing the trivial copy propagation
5217 here avoids the need to run the full copy propagation pass after
5218 VRP.
5220 FIXME, this will eventually lead to copy propagation removing the
5221 names that had useful range information attached to them. For
5222 instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
5223 then N_i will have the range [3, +INF].
5225 However, by converting the assertion into the implied copy
5226 operation N_i = N_j, we will then copy-propagate N_j into the uses
5227 of N_i and lose the range information. We may want to hold on to
5228 ASSERT_EXPRs a little while longer as the ranges could be used in
5229 things like jump threading.
5231 The problem with keeping ASSERT_EXPRs around is that passes after
5232 VRP need to handle them appropriately.
5234 Another approach would be to make the range information a first
5235 class property of the SSA_NAME so that it can be queried from
5236 any pass. This is made somewhat more complex by the need for
5237 multiple ranges to be associated with one SSA_NAME. */
5239 static void
5240 remove_range_assertions (void)
5242 basic_block bb;
5243 gimple_stmt_iterator si;
5244 /* 1 if looking at ASSERT_EXPRs immediately at the beginning of
5245 a basic block preceeded by GIMPLE_COND branching to it and
5246 __builtin_trap, -1 if not yet checked, 0 otherwise. */
5247 int is_unreachable;
5249 /* Note that the BSI iterator bump happens at the bottom of the
5250 loop and no bump is necessary if we're removing the statement
5251 referenced by the current BSI. */
5252 FOR_EACH_BB_FN (bb, cfun)
5253 for (si = gsi_after_labels (bb), is_unreachable = -1; !gsi_end_p (si);)
5255 gimple *stmt = gsi_stmt (si);
5257 if (is_gimple_assign (stmt)
5258 && gimple_assign_rhs_code (stmt) == ASSERT_EXPR)
5260 tree lhs = gimple_assign_lhs (stmt);
5261 tree rhs = gimple_assign_rhs1 (stmt);
5262 tree var;
5264 var = ASSERT_EXPR_VAR (rhs);
5266 if (TREE_CODE (var) == SSA_NAME
5267 && !POINTER_TYPE_P (TREE_TYPE (lhs))
5268 && SSA_NAME_RANGE_INFO (lhs))
5270 if (is_unreachable == -1)
5272 is_unreachable = 0;
5273 if (single_pred_p (bb)
5274 && assert_unreachable_fallthru_edge_p
5275 (single_pred_edge (bb)))
5276 is_unreachable = 1;
5278 /* Handle
5279 if (x_7 >= 10 && x_7 < 20)
5280 __builtin_unreachable ();
5281 x_8 = ASSERT_EXPR <x_7, ...>;
5282 if the only uses of x_7 are in the ASSERT_EXPR and
5283 in the condition. In that case, we can copy the
5284 range info from x_8 computed in this pass also
5285 for x_7. */
5286 if (is_unreachable
5287 && all_imm_uses_in_stmt_or_feed_cond (var, stmt,
5288 single_pred (bb)))
5290 set_range_info (var, SSA_NAME_RANGE_TYPE (lhs),
5291 SSA_NAME_RANGE_INFO (lhs)->get_min (),
5292 SSA_NAME_RANGE_INFO (lhs)->get_max ());
5293 maybe_set_nonzero_bits (single_pred_edge (bb), var);
5297 /* Propagate the RHS into every use of the LHS. For SSA names
5298 also propagate abnormals as it merely restores the original
5299 IL in this case (an replace_uses_by would assert). */
5300 if (TREE_CODE (var) == SSA_NAME)
5302 imm_use_iterator iter;
5303 use_operand_p use_p;
5304 gimple *use_stmt;
5305 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
5306 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
5307 SET_USE (use_p, var);
5309 else
5310 replace_uses_by (lhs, var);
5312 /* And finally, remove the copy, it is not needed. */
5313 gsi_remove (&si, true);
5314 release_defs (stmt);
5316 else
5318 if (!is_gimple_debug (gsi_stmt (si)))
5319 is_unreachable = 0;
5320 gsi_next (&si);
5325 /* Return true if STMT is interesting for VRP. */
5327 bool
5328 stmt_interesting_for_vrp (gimple *stmt)
5330 if (gimple_code (stmt) == GIMPLE_PHI)
5332 tree res = gimple_phi_result (stmt);
5333 return (!virtual_operand_p (res)
5334 && (INTEGRAL_TYPE_P (TREE_TYPE (res))
5335 || POINTER_TYPE_P (TREE_TYPE (res))));
5337 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
5339 tree lhs = gimple_get_lhs (stmt);
5341 /* In general, assignments with virtual operands are not useful
5342 for deriving ranges, with the obvious exception of calls to
5343 builtin functions. */
5344 if (lhs && TREE_CODE (lhs) == SSA_NAME
5345 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
5346 || POINTER_TYPE_P (TREE_TYPE (lhs)))
5347 && (is_gimple_call (stmt)
5348 || !gimple_vuse (stmt)))
5349 return true;
5350 else if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
5351 switch (gimple_call_internal_fn (stmt))
5353 case IFN_ADD_OVERFLOW:
5354 case IFN_SUB_OVERFLOW:
5355 case IFN_MUL_OVERFLOW:
5356 case IFN_ATOMIC_COMPARE_EXCHANGE:
5357 /* These internal calls return _Complex integer type,
5358 but are interesting to VRP nevertheless. */
5359 if (lhs && TREE_CODE (lhs) == SSA_NAME)
5360 return true;
5361 break;
5362 default:
5363 break;
5366 else if (gimple_code (stmt) == GIMPLE_COND
5367 || gimple_code (stmt) == GIMPLE_SWITCH)
5368 return true;
5370 return false;
5373 /* Initialization required by ssa_propagate engine. */
5375 void
5376 vrp_prop::vrp_initialize ()
5378 basic_block bb;
5380 FOR_EACH_BB_FN (bb, cfun)
5382 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
5383 gsi_next (&si))
5385 gphi *phi = si.phi ();
5386 if (!stmt_interesting_for_vrp (phi))
5388 tree lhs = PHI_RESULT (phi);
5389 set_value_range_to_varying (get_value_range (lhs));
5390 prop_set_simulate_again (phi, false);
5392 else
5393 prop_set_simulate_again (phi, true);
5396 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
5397 gsi_next (&si))
5399 gimple *stmt = gsi_stmt (si);
5401 /* If the statement is a control insn, then we do not
5402 want to avoid simulating the statement once. Failure
5403 to do so means that those edges will never get added. */
5404 if (stmt_ends_bb_p (stmt))
5405 prop_set_simulate_again (stmt, true);
5406 else if (!stmt_interesting_for_vrp (stmt))
5408 set_defs_to_varying (stmt);
5409 prop_set_simulate_again (stmt, false);
5411 else
5412 prop_set_simulate_again (stmt, true);
5417 /* Searches the case label vector VEC for the index *IDX of the CASE_LABEL
5418 that includes the value VAL. The search is restricted to the range
5419 [START_IDX, n - 1] where n is the size of VEC.
5421 If there is a CASE_LABEL for VAL, its index is placed in IDX and true is
5422 returned.
5424 If there is no CASE_LABEL for VAL and there is one that is larger than VAL,
5425 it is placed in IDX and false is returned.
5427 If VAL is larger than any CASE_LABEL, n is placed on IDX and false is
5428 returned. */
5430 bool
5431 find_case_label_index (gswitch *stmt, size_t start_idx, tree val, size_t *idx)
5433 size_t n = gimple_switch_num_labels (stmt);
5434 size_t low, high;
5436 /* Find case label for minimum of the value range or the next one.
5437 At each iteration we are searching in [low, high - 1]. */
5439 for (low = start_idx, high = n; high != low; )
5441 tree t;
5442 int cmp;
5443 /* Note that i != high, so we never ask for n. */
5444 size_t i = (high + low) / 2;
5445 t = gimple_switch_label (stmt, i);
5447 /* Cache the result of comparing CASE_LOW and val. */
5448 cmp = tree_int_cst_compare (CASE_LOW (t), val);
5450 if (cmp == 0)
5452 /* Ranges cannot be empty. */
5453 *idx = i;
5454 return true;
5456 else if (cmp > 0)
5457 high = i;
5458 else
5460 low = i + 1;
5461 if (CASE_HIGH (t) != NULL
5462 && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
5464 *idx = i;
5465 return true;
5470 *idx = high;
5471 return false;
5474 /* Searches the case label vector VEC for the range of CASE_LABELs that is used
5475 for values between MIN and MAX. The first index is placed in MIN_IDX. The
5476 last index is placed in MAX_IDX. If the range of CASE_LABELs is empty
5477 then MAX_IDX < MIN_IDX.
5478 Returns true if the default label is not needed. */
5480 bool
5481 find_case_label_range (gswitch *stmt, tree min, tree max, size_t *min_idx,
5482 size_t *max_idx)
5484 size_t i, j;
5485 bool min_take_default = !find_case_label_index (stmt, 1, min, &i);
5486 bool max_take_default = !find_case_label_index (stmt, i, max, &j);
5488 if (i == j
5489 && min_take_default
5490 && max_take_default)
5492 /* Only the default case label reached.
5493 Return an empty range. */
5494 *min_idx = 1;
5495 *max_idx = 0;
5496 return false;
5498 else
5500 bool take_default = min_take_default || max_take_default;
5501 tree low, high;
5502 size_t k;
5504 if (max_take_default)
5505 j--;
5507 /* If the case label range is continuous, we do not need
5508 the default case label. Verify that. */
5509 high = CASE_LOW (gimple_switch_label (stmt, i));
5510 if (CASE_HIGH (gimple_switch_label (stmt, i)))
5511 high = CASE_HIGH (gimple_switch_label (stmt, i));
5512 for (k = i + 1; k <= j; ++k)
5514 low = CASE_LOW (gimple_switch_label (stmt, k));
5515 if (!integer_onep (int_const_binop (MINUS_EXPR, low, high)))
5517 take_default = true;
5518 break;
5520 high = low;
5521 if (CASE_HIGH (gimple_switch_label (stmt, k)))
5522 high = CASE_HIGH (gimple_switch_label (stmt, k));
5525 *min_idx = i;
5526 *max_idx = j;
5527 return !take_default;
5531 /* Evaluate statement STMT. If the statement produces a useful range,
5532 return SSA_PROP_INTERESTING and record the SSA name with the
5533 interesting range into *OUTPUT_P.
5535 If STMT is a conditional branch and we can determine its truth
5536 value, the taken edge is recorded in *TAKEN_EDGE_P.
5538 If STMT produces a varying value, return SSA_PROP_VARYING. */
5540 enum ssa_prop_result
5541 vrp_prop::visit_stmt (gimple *stmt, edge *taken_edge_p, tree *output_p)
5543 value_range vr = VR_INITIALIZER;
5544 tree lhs = gimple_get_lhs (stmt);
5545 extract_range_from_stmt (stmt, taken_edge_p, output_p, &vr);
5547 if (*output_p)
5549 if (update_value_range (*output_p, &vr))
5551 if (dump_file && (dump_flags & TDF_DETAILS))
5553 fprintf (dump_file, "Found new range for ");
5554 print_generic_expr (dump_file, *output_p);
5555 fprintf (dump_file, ": ");
5556 dump_value_range (dump_file, &vr);
5557 fprintf (dump_file, "\n");
5560 if (vr.type == VR_VARYING)
5561 return SSA_PROP_VARYING;
5563 return SSA_PROP_INTERESTING;
5565 return SSA_PROP_NOT_INTERESTING;
5568 if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
5569 switch (gimple_call_internal_fn (stmt))
5571 case IFN_ADD_OVERFLOW:
5572 case IFN_SUB_OVERFLOW:
5573 case IFN_MUL_OVERFLOW:
5574 case IFN_ATOMIC_COMPARE_EXCHANGE:
5575 /* These internal calls return _Complex integer type,
5576 which VRP does not track, but the immediate uses
5577 thereof might be interesting. */
5578 if (lhs && TREE_CODE (lhs) == SSA_NAME)
5580 imm_use_iterator iter;
5581 use_operand_p use_p;
5582 enum ssa_prop_result res = SSA_PROP_VARYING;
5584 set_value_range_to_varying (get_value_range (lhs));
5586 FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
5588 gimple *use_stmt = USE_STMT (use_p);
5589 if (!is_gimple_assign (use_stmt))
5590 continue;
5591 enum tree_code rhs_code = gimple_assign_rhs_code (use_stmt);
5592 if (rhs_code != REALPART_EXPR && rhs_code != IMAGPART_EXPR)
5593 continue;
5594 tree rhs1 = gimple_assign_rhs1 (use_stmt);
5595 tree use_lhs = gimple_assign_lhs (use_stmt);
5596 if (TREE_CODE (rhs1) != rhs_code
5597 || TREE_OPERAND (rhs1, 0) != lhs
5598 || TREE_CODE (use_lhs) != SSA_NAME
5599 || !stmt_interesting_for_vrp (use_stmt)
5600 || (!INTEGRAL_TYPE_P (TREE_TYPE (use_lhs))
5601 || !TYPE_MIN_VALUE (TREE_TYPE (use_lhs))
5602 || !TYPE_MAX_VALUE (TREE_TYPE (use_lhs))))
5603 continue;
5605 /* If there is a change in the value range for any of the
5606 REALPART_EXPR/IMAGPART_EXPR immediate uses, return
5607 SSA_PROP_INTERESTING. If there are any REALPART_EXPR
5608 or IMAGPART_EXPR immediate uses, but none of them have
5609 a change in their value ranges, return
5610 SSA_PROP_NOT_INTERESTING. If there are no
5611 {REAL,IMAG}PART_EXPR uses at all,
5612 return SSA_PROP_VARYING. */
5613 value_range new_vr = VR_INITIALIZER;
5614 extract_range_basic (&new_vr, use_stmt);
5615 value_range *old_vr = get_value_range (use_lhs);
5616 if (old_vr->type != new_vr.type
5617 || !vrp_operand_equal_p (old_vr->min, new_vr.min)
5618 || !vrp_operand_equal_p (old_vr->max, new_vr.max)
5619 || !vrp_bitmap_equal_p (old_vr->equiv, new_vr.equiv))
5620 res = SSA_PROP_INTERESTING;
5621 else
5622 res = SSA_PROP_NOT_INTERESTING;
5623 BITMAP_FREE (new_vr.equiv);
5624 if (res == SSA_PROP_INTERESTING)
5626 *output_p = lhs;
5627 return res;
5631 return res;
5633 break;
5634 default:
5635 break;
5638 /* All other statements produce nothing of interest for VRP, so mark
5639 their outputs varying and prevent further simulation. */
5640 set_defs_to_varying (stmt);
5642 return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
5645 /* Union the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
5646 { VR1TYPE, VR0MIN, VR0MAX } and store the result
5647 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
5648 possible such range. The resulting range is not canonicalized. */
5650 static void
5651 union_ranges (enum value_range_type *vr0type,
5652 tree *vr0min, tree *vr0max,
5653 enum value_range_type vr1type,
5654 tree vr1min, tree vr1max)
5656 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
5657 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
5659 /* [] is vr0, () is vr1 in the following classification comments. */
5660 if (mineq && maxeq)
5662 /* [( )] */
5663 if (*vr0type == vr1type)
5664 /* Nothing to do for equal ranges. */
5666 else if ((*vr0type == VR_RANGE
5667 && vr1type == VR_ANTI_RANGE)
5668 || (*vr0type == VR_ANTI_RANGE
5669 && vr1type == VR_RANGE))
5671 /* For anti-range with range union the result is varying. */
5672 goto give_up;
5674 else
5675 gcc_unreachable ();
5677 else if (operand_less_p (*vr0max, vr1min) == 1
5678 || operand_less_p (vr1max, *vr0min) == 1)
5680 /* [ ] ( ) or ( ) [ ]
5681 If the ranges have an empty intersection, result of the union
5682 operation is the anti-range or if both are anti-ranges
5683 it covers all. */
5684 if (*vr0type == VR_ANTI_RANGE
5685 && vr1type == VR_ANTI_RANGE)
5686 goto give_up;
5687 else if (*vr0type == VR_ANTI_RANGE
5688 && vr1type == VR_RANGE)
5690 else if (*vr0type == VR_RANGE
5691 && vr1type == VR_ANTI_RANGE)
5693 *vr0type = vr1type;
5694 *vr0min = vr1min;
5695 *vr0max = vr1max;
5697 else if (*vr0type == VR_RANGE
5698 && vr1type == VR_RANGE)
5700 /* The result is the convex hull of both ranges. */
5701 if (operand_less_p (*vr0max, vr1min) == 1)
5703 /* If the result can be an anti-range, create one. */
5704 if (TREE_CODE (*vr0max) == INTEGER_CST
5705 && TREE_CODE (vr1min) == INTEGER_CST
5706 && vrp_val_is_min (*vr0min)
5707 && vrp_val_is_max (vr1max))
5709 tree min = int_const_binop (PLUS_EXPR,
5710 *vr0max,
5711 build_int_cst (TREE_TYPE (*vr0max), 1));
5712 tree max = int_const_binop (MINUS_EXPR,
5713 vr1min,
5714 build_int_cst (TREE_TYPE (vr1min), 1));
5715 if (!operand_less_p (max, min))
5717 *vr0type = VR_ANTI_RANGE;
5718 *vr0min = min;
5719 *vr0max = max;
5721 else
5722 *vr0max = vr1max;
5724 else
5725 *vr0max = vr1max;
5727 else
5729 /* If the result can be an anti-range, create one. */
5730 if (TREE_CODE (vr1max) == INTEGER_CST
5731 && TREE_CODE (*vr0min) == INTEGER_CST
5732 && vrp_val_is_min (vr1min)
5733 && vrp_val_is_max (*vr0max))
5735 tree min = int_const_binop (PLUS_EXPR,
5736 vr1max,
5737 build_int_cst (TREE_TYPE (vr1max), 1));
5738 tree max = int_const_binop (MINUS_EXPR,
5739 *vr0min,
5740 build_int_cst (TREE_TYPE (*vr0min), 1));
5741 if (!operand_less_p (max, min))
5743 *vr0type = VR_ANTI_RANGE;
5744 *vr0min = min;
5745 *vr0max = max;
5747 else
5748 *vr0min = vr1min;
5750 else
5751 *vr0min = vr1min;
5754 else
5755 gcc_unreachable ();
5757 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
5758 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
5760 /* [ ( ) ] or [( ) ] or [ ( )] */
5761 if (*vr0type == VR_RANGE
5762 && vr1type == VR_RANGE)
5764 else if (*vr0type == VR_ANTI_RANGE
5765 && vr1type == VR_ANTI_RANGE)
5767 *vr0type = vr1type;
5768 *vr0min = vr1min;
5769 *vr0max = vr1max;
5771 else if (*vr0type == VR_ANTI_RANGE
5772 && vr1type == VR_RANGE)
5774 /* Arbitrarily choose the right or left gap. */
5775 if (!mineq && TREE_CODE (vr1min) == INTEGER_CST)
5776 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5777 build_int_cst (TREE_TYPE (vr1min), 1));
5778 else if (!maxeq && TREE_CODE (vr1max) == INTEGER_CST)
5779 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5780 build_int_cst (TREE_TYPE (vr1max), 1));
5781 else
5782 goto give_up;
5784 else if (*vr0type == VR_RANGE
5785 && vr1type == VR_ANTI_RANGE)
5786 /* The result covers everything. */
5787 goto give_up;
5788 else
5789 gcc_unreachable ();
5791 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
5792 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
5794 /* ( [ ] ) or ([ ] ) or ( [ ]) */
5795 if (*vr0type == VR_RANGE
5796 && vr1type == VR_RANGE)
5798 *vr0type = vr1type;
5799 *vr0min = vr1min;
5800 *vr0max = vr1max;
5802 else if (*vr0type == VR_ANTI_RANGE
5803 && vr1type == VR_ANTI_RANGE)
5805 else if (*vr0type == VR_RANGE
5806 && vr1type == VR_ANTI_RANGE)
5808 *vr0type = VR_ANTI_RANGE;
5809 if (!mineq && TREE_CODE (*vr0min) == INTEGER_CST)
5811 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5812 build_int_cst (TREE_TYPE (*vr0min), 1));
5813 *vr0min = vr1min;
5815 else if (!maxeq && TREE_CODE (*vr0max) == INTEGER_CST)
5817 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5818 build_int_cst (TREE_TYPE (*vr0max), 1));
5819 *vr0max = vr1max;
5821 else
5822 goto give_up;
5824 else if (*vr0type == VR_ANTI_RANGE
5825 && vr1type == VR_RANGE)
5826 /* The result covers everything. */
5827 goto give_up;
5828 else
5829 gcc_unreachable ();
5831 else if ((operand_less_p (vr1min, *vr0max) == 1
5832 || operand_equal_p (vr1min, *vr0max, 0))
5833 && operand_less_p (*vr0min, vr1min) == 1
5834 && operand_less_p (*vr0max, vr1max) == 1)
5836 /* [ ( ] ) or [ ]( ) */
5837 if (*vr0type == VR_RANGE
5838 && vr1type == VR_RANGE)
5839 *vr0max = vr1max;
5840 else if (*vr0type == VR_ANTI_RANGE
5841 && vr1type == VR_ANTI_RANGE)
5842 *vr0min = vr1min;
5843 else if (*vr0type == VR_ANTI_RANGE
5844 && vr1type == VR_RANGE)
5846 if (TREE_CODE (vr1min) == INTEGER_CST)
5847 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5848 build_int_cst (TREE_TYPE (vr1min), 1));
5849 else
5850 goto give_up;
5852 else if (*vr0type == VR_RANGE
5853 && vr1type == VR_ANTI_RANGE)
5855 if (TREE_CODE (*vr0max) == INTEGER_CST)
5857 *vr0type = vr1type;
5858 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5859 build_int_cst (TREE_TYPE (*vr0max), 1));
5860 *vr0max = vr1max;
5862 else
5863 goto give_up;
5865 else
5866 gcc_unreachable ();
5868 else if ((operand_less_p (*vr0min, vr1max) == 1
5869 || operand_equal_p (*vr0min, vr1max, 0))
5870 && operand_less_p (vr1min, *vr0min) == 1
5871 && operand_less_p (vr1max, *vr0max) == 1)
5873 /* ( [ ) ] or ( )[ ] */
5874 if (*vr0type == VR_RANGE
5875 && vr1type == VR_RANGE)
5876 *vr0min = vr1min;
5877 else if (*vr0type == VR_ANTI_RANGE
5878 && vr1type == VR_ANTI_RANGE)
5879 *vr0max = vr1max;
5880 else if (*vr0type == VR_ANTI_RANGE
5881 && vr1type == VR_RANGE)
5883 if (TREE_CODE (vr1max) == INTEGER_CST)
5884 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5885 build_int_cst (TREE_TYPE (vr1max), 1));
5886 else
5887 goto give_up;
5889 else if (*vr0type == VR_RANGE
5890 && vr1type == VR_ANTI_RANGE)
5892 if (TREE_CODE (*vr0min) == INTEGER_CST)
5894 *vr0type = vr1type;
5895 *vr0min = vr1min;
5896 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5897 build_int_cst (TREE_TYPE (*vr0min), 1));
5899 else
5900 goto give_up;
5902 else
5903 gcc_unreachable ();
5905 else
5906 goto give_up;
5908 return;
5910 give_up:
5911 *vr0type = VR_VARYING;
5912 *vr0min = NULL_TREE;
5913 *vr0max = NULL_TREE;
5916 /* Intersect the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
5917 { VR1TYPE, VR0MIN, VR0MAX } and store the result
5918 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
5919 possible such range. The resulting range is not canonicalized. */
5921 static void
5922 intersect_ranges (enum value_range_type *vr0type,
5923 tree *vr0min, tree *vr0max,
5924 enum value_range_type vr1type,
5925 tree vr1min, tree vr1max)
5927 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
5928 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
5930 /* [] is vr0, () is vr1 in the following classification comments. */
5931 if (mineq && maxeq)
5933 /* [( )] */
5934 if (*vr0type == vr1type)
5935 /* Nothing to do for equal ranges. */
5937 else if ((*vr0type == VR_RANGE
5938 && vr1type == VR_ANTI_RANGE)
5939 || (*vr0type == VR_ANTI_RANGE
5940 && vr1type == VR_RANGE))
5942 /* For anti-range with range intersection the result is empty. */
5943 *vr0type = VR_UNDEFINED;
5944 *vr0min = NULL_TREE;
5945 *vr0max = NULL_TREE;
5947 else
5948 gcc_unreachable ();
5950 else if (operand_less_p (*vr0max, vr1min) == 1
5951 || operand_less_p (vr1max, *vr0min) == 1)
5953 /* [ ] ( ) or ( ) [ ]
5954 If the ranges have an empty intersection, the result of the
5955 intersect operation is the range for intersecting an
5956 anti-range with a range or empty when intersecting two ranges. */
5957 if (*vr0type == VR_RANGE
5958 && vr1type == VR_ANTI_RANGE)
5960 else if (*vr0type == VR_ANTI_RANGE
5961 && vr1type == VR_RANGE)
5963 *vr0type = vr1type;
5964 *vr0min = vr1min;
5965 *vr0max = vr1max;
5967 else if (*vr0type == VR_RANGE
5968 && vr1type == VR_RANGE)
5970 *vr0type = VR_UNDEFINED;
5971 *vr0min = NULL_TREE;
5972 *vr0max = NULL_TREE;
5974 else if (*vr0type == VR_ANTI_RANGE
5975 && vr1type == VR_ANTI_RANGE)
5977 /* If the anti-ranges are adjacent to each other merge them. */
5978 if (TREE_CODE (*vr0max) == INTEGER_CST
5979 && TREE_CODE (vr1min) == INTEGER_CST
5980 && operand_less_p (*vr0max, vr1min) == 1
5981 && integer_onep (int_const_binop (MINUS_EXPR,
5982 vr1min, *vr0max)))
5983 *vr0max = vr1max;
5984 else if (TREE_CODE (vr1max) == INTEGER_CST
5985 && TREE_CODE (*vr0min) == INTEGER_CST
5986 && operand_less_p (vr1max, *vr0min) == 1
5987 && integer_onep (int_const_binop (MINUS_EXPR,
5988 *vr0min, vr1max)))
5989 *vr0min = vr1min;
5990 /* Else arbitrarily take VR0. */
5993 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
5994 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
5996 /* [ ( ) ] or [( ) ] or [ ( )] */
5997 if (*vr0type == VR_RANGE
5998 && vr1type == VR_RANGE)
6000 /* If both are ranges the result is the inner one. */
6001 *vr0type = vr1type;
6002 *vr0min = vr1min;
6003 *vr0max = vr1max;
6005 else if (*vr0type == VR_RANGE
6006 && vr1type == VR_ANTI_RANGE)
6008 /* Choose the right gap if the left one is empty. */
6009 if (mineq)
6011 if (TREE_CODE (vr1max) != INTEGER_CST)
6012 *vr0min = vr1max;
6013 else if (TYPE_PRECISION (TREE_TYPE (vr1max)) == 1
6014 && !TYPE_UNSIGNED (TREE_TYPE (vr1max)))
6015 *vr0min
6016 = int_const_binop (MINUS_EXPR, vr1max,
6017 build_int_cst (TREE_TYPE (vr1max), -1));
6018 else
6019 *vr0min
6020 = int_const_binop (PLUS_EXPR, vr1max,
6021 build_int_cst (TREE_TYPE (vr1max), 1));
6023 /* Choose the left gap if the right one is empty. */
6024 else if (maxeq)
6026 if (TREE_CODE (vr1min) != INTEGER_CST)
6027 *vr0max = vr1min;
6028 else if (TYPE_PRECISION (TREE_TYPE (vr1min)) == 1
6029 && !TYPE_UNSIGNED (TREE_TYPE (vr1min)))
6030 *vr0max
6031 = int_const_binop (PLUS_EXPR, vr1min,
6032 build_int_cst (TREE_TYPE (vr1min), -1));
6033 else
6034 *vr0max
6035 = int_const_binop (MINUS_EXPR, vr1min,
6036 build_int_cst (TREE_TYPE (vr1min), 1));
6038 /* Choose the anti-range if the range is effectively varying. */
6039 else if (vrp_val_is_min (*vr0min)
6040 && vrp_val_is_max (*vr0max))
6042 *vr0type = vr1type;
6043 *vr0min = vr1min;
6044 *vr0max = vr1max;
6046 /* Else choose the range. */
6048 else if (*vr0type == VR_ANTI_RANGE
6049 && vr1type == VR_ANTI_RANGE)
6050 /* If both are anti-ranges the result is the outer one. */
6052 else if (*vr0type == VR_ANTI_RANGE
6053 && vr1type == VR_RANGE)
6055 /* The intersection is empty. */
6056 *vr0type = VR_UNDEFINED;
6057 *vr0min = NULL_TREE;
6058 *vr0max = NULL_TREE;
6060 else
6061 gcc_unreachable ();
6063 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
6064 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
6066 /* ( [ ] ) or ([ ] ) or ( [ ]) */
6067 if (*vr0type == VR_RANGE
6068 && vr1type == VR_RANGE)
6069 /* Choose the inner range. */
6071 else if (*vr0type == VR_ANTI_RANGE
6072 && vr1type == VR_RANGE)
6074 /* Choose the right gap if the left is empty. */
6075 if (mineq)
6077 *vr0type = VR_RANGE;
6078 if (TREE_CODE (*vr0max) != INTEGER_CST)
6079 *vr0min = *vr0max;
6080 else if (TYPE_PRECISION (TREE_TYPE (*vr0max)) == 1
6081 && !TYPE_UNSIGNED (TREE_TYPE (*vr0max)))
6082 *vr0min
6083 = int_const_binop (MINUS_EXPR, *vr0max,
6084 build_int_cst (TREE_TYPE (*vr0max), -1));
6085 else
6086 *vr0min
6087 = int_const_binop (PLUS_EXPR, *vr0max,
6088 build_int_cst (TREE_TYPE (*vr0max), 1));
6089 *vr0max = vr1max;
6091 /* Choose the left gap if the right is empty. */
6092 else if (maxeq)
6094 *vr0type = VR_RANGE;
6095 if (TREE_CODE (*vr0min) != INTEGER_CST)
6096 *vr0max = *vr0min;
6097 else if (TYPE_PRECISION (TREE_TYPE (*vr0min)) == 1
6098 && !TYPE_UNSIGNED (TREE_TYPE (*vr0min)))
6099 *vr0max
6100 = int_const_binop (PLUS_EXPR, *vr0min,
6101 build_int_cst (TREE_TYPE (*vr0min), -1));
6102 else
6103 *vr0max
6104 = int_const_binop (MINUS_EXPR, *vr0min,
6105 build_int_cst (TREE_TYPE (*vr0min), 1));
6106 *vr0min = vr1min;
6108 /* Choose the anti-range if the range is effectively varying. */
6109 else if (vrp_val_is_min (vr1min)
6110 && vrp_val_is_max (vr1max))
6112 /* Choose the anti-range if it is ~[0,0], that range is special
6113 enough to special case when vr1's range is relatively wide.
6114 At least for types bigger than int - this covers pointers
6115 and arguments to functions like ctz. */
6116 else if (*vr0min == *vr0max
6117 && integer_zerop (*vr0min)
6118 && ((TYPE_PRECISION (TREE_TYPE (*vr0min))
6119 >= TYPE_PRECISION (integer_type_node))
6120 || POINTER_TYPE_P (TREE_TYPE (*vr0min)))
6121 && TREE_CODE (vr1max) == INTEGER_CST
6122 && TREE_CODE (vr1min) == INTEGER_CST
6123 && (wi::clz (wi::to_wide (vr1max) - wi::to_wide (vr1min))
6124 < TYPE_PRECISION (TREE_TYPE (*vr0min)) / 2))
6126 /* Else choose the range. */
6127 else
6129 *vr0type = vr1type;
6130 *vr0min = vr1min;
6131 *vr0max = vr1max;
6134 else if (*vr0type == VR_ANTI_RANGE
6135 && vr1type == VR_ANTI_RANGE)
6137 /* If both are anti-ranges the result is the outer one. */
6138 *vr0type = vr1type;
6139 *vr0min = vr1min;
6140 *vr0max = vr1max;
6142 else if (vr1type == VR_ANTI_RANGE
6143 && *vr0type == VR_RANGE)
6145 /* The intersection is empty. */
6146 *vr0type = VR_UNDEFINED;
6147 *vr0min = NULL_TREE;
6148 *vr0max = NULL_TREE;
6150 else
6151 gcc_unreachable ();
6153 else if ((operand_less_p (vr1min, *vr0max) == 1
6154 || operand_equal_p (vr1min, *vr0max, 0))
6155 && operand_less_p (*vr0min, vr1min) == 1)
6157 /* [ ( ] ) or [ ]( ) */
6158 if (*vr0type == VR_ANTI_RANGE
6159 && vr1type == VR_ANTI_RANGE)
6160 *vr0max = vr1max;
6161 else if (*vr0type == VR_RANGE
6162 && vr1type == VR_RANGE)
6163 *vr0min = vr1min;
6164 else if (*vr0type == VR_RANGE
6165 && vr1type == VR_ANTI_RANGE)
6167 if (TREE_CODE (vr1min) == INTEGER_CST)
6168 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
6169 build_int_cst (TREE_TYPE (vr1min), 1));
6170 else
6171 *vr0max = vr1min;
6173 else if (*vr0type == VR_ANTI_RANGE
6174 && vr1type == VR_RANGE)
6176 *vr0type = VR_RANGE;
6177 if (TREE_CODE (*vr0max) == INTEGER_CST)
6178 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
6179 build_int_cst (TREE_TYPE (*vr0max), 1));
6180 else
6181 *vr0min = *vr0max;
6182 *vr0max = vr1max;
6184 else
6185 gcc_unreachable ();
6187 else if ((operand_less_p (*vr0min, vr1max) == 1
6188 || operand_equal_p (*vr0min, vr1max, 0))
6189 && operand_less_p (vr1min, *vr0min) == 1)
6191 /* ( [ ) ] or ( )[ ] */
6192 if (*vr0type == VR_ANTI_RANGE
6193 && vr1type == VR_ANTI_RANGE)
6194 *vr0min = vr1min;
6195 else if (*vr0type == VR_RANGE
6196 && vr1type == VR_RANGE)
6197 *vr0max = vr1max;
6198 else if (*vr0type == VR_RANGE
6199 && vr1type == VR_ANTI_RANGE)
6201 if (TREE_CODE (vr1max) == INTEGER_CST)
6202 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
6203 build_int_cst (TREE_TYPE (vr1max), 1));
6204 else
6205 *vr0min = vr1max;
6207 else if (*vr0type == VR_ANTI_RANGE
6208 && vr1type == VR_RANGE)
6210 *vr0type = VR_RANGE;
6211 if (TREE_CODE (*vr0min) == INTEGER_CST)
6212 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
6213 build_int_cst (TREE_TYPE (*vr0min), 1));
6214 else
6215 *vr0max = *vr0min;
6216 *vr0min = vr1min;
6218 else
6219 gcc_unreachable ();
6222 /* As a fallback simply use { *VRTYPE, *VR0MIN, *VR0MAX } as
6223 result for the intersection. That's always a conservative
6224 correct estimate unless VR1 is a constant singleton range
6225 in which case we choose that. */
6226 if (vr1type == VR_RANGE
6227 && is_gimple_min_invariant (vr1min)
6228 && vrp_operand_equal_p (vr1min, vr1max))
6230 *vr0type = vr1type;
6231 *vr0min = vr1min;
6232 *vr0max = vr1max;
6235 return;
6239 /* Intersect the two value-ranges *VR0 and *VR1 and store the result
6240 in *VR0. This may not be the smallest possible such range. */
6242 static void
6243 vrp_intersect_ranges_1 (value_range *vr0, value_range *vr1)
6245 value_range saved;
6247 /* If either range is VR_VARYING the other one wins. */
6248 if (vr1->type == VR_VARYING)
6249 return;
6250 if (vr0->type == VR_VARYING)
6252 copy_value_range (vr0, vr1);
6253 return;
6256 /* When either range is VR_UNDEFINED the resulting range is
6257 VR_UNDEFINED, too. */
6258 if (vr0->type == VR_UNDEFINED)
6259 return;
6260 if (vr1->type == VR_UNDEFINED)
6262 set_value_range_to_undefined (vr0);
6263 return;
6266 /* Save the original vr0 so we can return it as conservative intersection
6267 result when our worker turns things to varying. */
6268 saved = *vr0;
6269 intersect_ranges (&vr0->type, &vr0->min, &vr0->max,
6270 vr1->type, vr1->min, vr1->max);
6271 /* Make sure to canonicalize the result though as the inversion of a
6272 VR_RANGE can still be a VR_RANGE. */
6273 set_and_canonicalize_value_range (vr0, vr0->type,
6274 vr0->min, vr0->max, vr0->equiv);
6275 /* If that failed, use the saved original VR0. */
6276 if (vr0->type == VR_VARYING)
6278 *vr0 = saved;
6279 return;
6281 /* If the result is VR_UNDEFINED there is no need to mess with
6282 the equivalencies. */
6283 if (vr0->type == VR_UNDEFINED)
6284 return;
6286 /* The resulting set of equivalences for range intersection is the union of
6287 the two sets. */
6288 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
6289 bitmap_ior_into (vr0->equiv, vr1->equiv);
6290 else if (vr1->equiv && !vr0->equiv)
6292 /* All equivalence bitmaps are allocated from the same obstack. So
6293 we can use the obstack associated with VR to allocate vr0->equiv. */
6294 vr0->equiv = BITMAP_ALLOC (vr1->equiv->obstack);
6295 bitmap_copy (vr0->equiv, vr1->equiv);
6299 void
6300 vrp_intersect_ranges (value_range *vr0, value_range *vr1)
6302 if (dump_file && (dump_flags & TDF_DETAILS))
6304 fprintf (dump_file, "Intersecting\n ");
6305 dump_value_range (dump_file, vr0);
6306 fprintf (dump_file, "\nand\n ");
6307 dump_value_range (dump_file, vr1);
6308 fprintf (dump_file, "\n");
6310 vrp_intersect_ranges_1 (vr0, vr1);
6311 if (dump_file && (dump_flags & TDF_DETAILS))
6313 fprintf (dump_file, "to\n ");
6314 dump_value_range (dump_file, vr0);
6315 fprintf (dump_file, "\n");
6319 /* Meet operation for value ranges. Given two value ranges VR0 and
6320 VR1, store in VR0 a range that contains both VR0 and VR1. This
6321 may not be the smallest possible such range. */
6323 static void
6324 vrp_meet_1 (value_range *vr0, const value_range *vr1)
6326 value_range saved;
6328 if (vr0->type == VR_UNDEFINED)
6330 set_value_range (vr0, vr1->type, vr1->min, vr1->max, vr1->equiv);
6331 return;
6334 if (vr1->type == VR_UNDEFINED)
6336 /* VR0 already has the resulting range. */
6337 return;
6340 if (vr0->type == VR_VARYING)
6342 /* Nothing to do. VR0 already has the resulting range. */
6343 return;
6346 if (vr1->type == VR_VARYING)
6348 set_value_range_to_varying (vr0);
6349 return;
6352 saved = *vr0;
6353 union_ranges (&vr0->type, &vr0->min, &vr0->max,
6354 vr1->type, vr1->min, vr1->max);
6355 if (vr0->type == VR_VARYING)
6357 /* Failed to find an efficient meet. Before giving up and setting
6358 the result to VARYING, see if we can at least derive a useful
6359 anti-range. FIXME, all this nonsense about distinguishing
6360 anti-ranges from ranges is necessary because of the odd
6361 semantics of range_includes_zero_p and friends. */
6362 if (((saved.type == VR_RANGE
6363 && range_includes_zero_p (saved.min, saved.max) == 0)
6364 || (saved.type == VR_ANTI_RANGE
6365 && range_includes_zero_p (saved.min, saved.max) == 1))
6366 && ((vr1->type == VR_RANGE
6367 && range_includes_zero_p (vr1->min, vr1->max) == 0)
6368 || (vr1->type == VR_ANTI_RANGE
6369 && range_includes_zero_p (vr1->min, vr1->max) == 1)))
6371 set_value_range_to_nonnull (vr0, TREE_TYPE (saved.min));
6373 /* Since this meet operation did not result from the meeting of
6374 two equivalent names, VR0 cannot have any equivalences. */
6375 if (vr0->equiv)
6376 bitmap_clear (vr0->equiv);
6377 return;
6380 set_value_range_to_varying (vr0);
6381 return;
6383 set_and_canonicalize_value_range (vr0, vr0->type, vr0->min, vr0->max,
6384 vr0->equiv);
6385 if (vr0->type == VR_VARYING)
6386 return;
6388 /* The resulting set of equivalences is always the intersection of
6389 the two sets. */
6390 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
6391 bitmap_and_into (vr0->equiv, vr1->equiv);
6392 else if (vr0->equiv && !vr1->equiv)
6393 bitmap_clear (vr0->equiv);
6396 void
6397 vrp_meet (value_range *vr0, const value_range *vr1)
6399 if (dump_file && (dump_flags & TDF_DETAILS))
6401 fprintf (dump_file, "Meeting\n ");
6402 dump_value_range (dump_file, vr0);
6403 fprintf (dump_file, "\nand\n ");
6404 dump_value_range (dump_file, vr1);
6405 fprintf (dump_file, "\n");
6407 vrp_meet_1 (vr0, vr1);
6408 if (dump_file && (dump_flags & TDF_DETAILS))
6410 fprintf (dump_file, "to\n ");
6411 dump_value_range (dump_file, vr0);
6412 fprintf (dump_file, "\n");
6417 /* Visit all arguments for PHI node PHI that flow through executable
6418 edges. If a valid value range can be derived from all the incoming
6419 value ranges, set a new range for the LHS of PHI. */
6421 enum ssa_prop_result
6422 vrp_prop::visit_phi (gphi *phi)
6424 tree lhs = PHI_RESULT (phi);
6425 value_range vr_result = VR_INITIALIZER;
6426 extract_range_from_phi_node (phi, &vr_result);
6427 if (update_value_range (lhs, &vr_result))
6429 if (dump_file && (dump_flags & TDF_DETAILS))
6431 fprintf (dump_file, "Found new range for ");
6432 print_generic_expr (dump_file, lhs);
6433 fprintf (dump_file, ": ");
6434 dump_value_range (dump_file, &vr_result);
6435 fprintf (dump_file, "\n");
6438 if (vr_result.type == VR_VARYING)
6439 return SSA_PROP_VARYING;
6441 return SSA_PROP_INTERESTING;
6444 /* Nothing changed, don't add outgoing edges. */
6445 return SSA_PROP_NOT_INTERESTING;
6448 class vrp_folder : public substitute_and_fold_engine
6450 public:
6451 tree get_value (tree) FINAL OVERRIDE;
6452 bool fold_stmt (gimple_stmt_iterator *) FINAL OVERRIDE;
6453 bool fold_predicate_in (gimple_stmt_iterator *);
6455 class vr_values *vr_values;
6457 /* Delegators. */
6458 tree vrp_evaluate_conditional (tree_code code, tree op0,
6459 tree op1, gimple *stmt)
6460 { return vr_values->vrp_evaluate_conditional (code, op0, op1, stmt); }
6461 bool simplify_stmt_using_ranges (gimple_stmt_iterator *gsi)
6462 { return vr_values->simplify_stmt_using_ranges (gsi); }
6463 tree op_with_constant_singleton_value_range (tree op)
6464 { return vr_values->op_with_constant_singleton_value_range (op); }
6467 /* If the statement pointed by SI has a predicate whose value can be
6468 computed using the value range information computed by VRP, compute
6469 its value and return true. Otherwise, return false. */
6471 bool
6472 vrp_folder::fold_predicate_in (gimple_stmt_iterator *si)
6474 bool assignment_p = false;
6475 tree val;
6476 gimple *stmt = gsi_stmt (*si);
6478 if (is_gimple_assign (stmt)
6479 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
6481 assignment_p = true;
6482 val = vrp_evaluate_conditional (gimple_assign_rhs_code (stmt),
6483 gimple_assign_rhs1 (stmt),
6484 gimple_assign_rhs2 (stmt),
6485 stmt);
6487 else if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
6488 val = vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
6489 gimple_cond_lhs (cond_stmt),
6490 gimple_cond_rhs (cond_stmt),
6491 stmt);
6492 else
6493 return false;
6495 if (val)
6497 if (assignment_p)
6498 val = fold_convert (gimple_expr_type (stmt), val);
6500 if (dump_file)
6502 fprintf (dump_file, "Folding predicate ");
6503 print_gimple_expr (dump_file, stmt, 0);
6504 fprintf (dump_file, " to ");
6505 print_generic_expr (dump_file, val);
6506 fprintf (dump_file, "\n");
6509 if (is_gimple_assign (stmt))
6510 gimple_assign_set_rhs_from_tree (si, val);
6511 else
6513 gcc_assert (gimple_code (stmt) == GIMPLE_COND);
6514 gcond *cond_stmt = as_a <gcond *> (stmt);
6515 if (integer_zerop (val))
6516 gimple_cond_make_false (cond_stmt);
6517 else if (integer_onep (val))
6518 gimple_cond_make_true (cond_stmt);
6519 else
6520 gcc_unreachable ();
6523 return true;
6526 return false;
6529 /* Callback for substitute_and_fold folding the stmt at *SI. */
6531 bool
6532 vrp_folder::fold_stmt (gimple_stmt_iterator *si)
6534 if (fold_predicate_in (si))
6535 return true;
6537 return simplify_stmt_using_ranges (si);
6540 /* If OP has a value range with a single constant value return that,
6541 otherwise return NULL_TREE. This returns OP itself if OP is a
6542 constant.
6544 Implemented as a pure wrapper right now, but this will change. */
6546 tree
6547 vrp_folder::get_value (tree op)
6549 return op_with_constant_singleton_value_range (op);
6552 /* Return the LHS of any ASSERT_EXPR where OP appears as the first
6553 argument to the ASSERT_EXPR and in which the ASSERT_EXPR dominates
6554 BB. If no such ASSERT_EXPR is found, return OP. */
6556 static tree
6557 lhs_of_dominating_assert (tree op, basic_block bb, gimple *stmt)
6559 imm_use_iterator imm_iter;
6560 gimple *use_stmt;
6561 use_operand_p use_p;
6563 if (TREE_CODE (op) == SSA_NAME)
6565 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, op)
6567 use_stmt = USE_STMT (use_p);
6568 if (use_stmt != stmt
6569 && gimple_assign_single_p (use_stmt)
6570 && TREE_CODE (gimple_assign_rhs1 (use_stmt)) == ASSERT_EXPR
6571 && TREE_OPERAND (gimple_assign_rhs1 (use_stmt), 0) == op
6572 && dominated_by_p (CDI_DOMINATORS, bb, gimple_bb (use_stmt)))
6573 return gimple_assign_lhs (use_stmt);
6576 return op;
6579 /* A hack. */
6580 static class vr_values *x_vr_values;
6582 /* A trivial wrapper so that we can present the generic jump threading
6583 code with a simple API for simplifying statements. STMT is the
6584 statement we want to simplify, WITHIN_STMT provides the location
6585 for any overflow warnings. */
6587 static tree
6588 simplify_stmt_for_jump_threading (gimple *stmt, gimple *within_stmt,
6589 class avail_exprs_stack *avail_exprs_stack ATTRIBUTE_UNUSED,
6590 basic_block bb)
6592 /* First see if the conditional is in the hash table. */
6593 tree cached_lhs = avail_exprs_stack->lookup_avail_expr (stmt, false, true);
6594 if (cached_lhs && is_gimple_min_invariant (cached_lhs))
6595 return cached_lhs;
6597 vr_values *vr_values = x_vr_values;
6598 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
6600 tree op0 = gimple_cond_lhs (cond_stmt);
6601 op0 = lhs_of_dominating_assert (op0, bb, stmt);
6603 tree op1 = gimple_cond_rhs (cond_stmt);
6604 op1 = lhs_of_dominating_assert (op1, bb, stmt);
6606 return vr_values->vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
6607 op0, op1, within_stmt);
6610 /* We simplify a switch statement by trying to determine which case label
6611 will be taken. If we are successful then we return the corresponding
6612 CASE_LABEL_EXPR. */
6613 if (gswitch *switch_stmt = dyn_cast <gswitch *> (stmt))
6615 tree op = gimple_switch_index (switch_stmt);
6616 if (TREE_CODE (op) != SSA_NAME)
6617 return NULL_TREE;
6619 op = lhs_of_dominating_assert (op, bb, stmt);
6621 value_range *vr = vr_values->get_value_range (op);
6622 if ((vr->type != VR_RANGE && vr->type != VR_ANTI_RANGE)
6623 || symbolic_range_p (vr))
6624 return NULL_TREE;
6626 if (vr->type == VR_RANGE)
6628 size_t i, j;
6629 /* Get the range of labels that contain a part of the operand's
6630 value range. */
6631 find_case_label_range (switch_stmt, vr->min, vr->max, &i, &j);
6633 /* Is there only one such label? */
6634 if (i == j)
6636 tree label = gimple_switch_label (switch_stmt, i);
6638 /* The i'th label will be taken only if the value range of the
6639 operand is entirely within the bounds of this label. */
6640 if (CASE_HIGH (label) != NULL_TREE
6641 ? (tree_int_cst_compare (CASE_LOW (label), vr->min) <= 0
6642 && tree_int_cst_compare (CASE_HIGH (label), vr->max) >= 0)
6643 : (tree_int_cst_equal (CASE_LOW (label), vr->min)
6644 && tree_int_cst_equal (vr->min, vr->max)))
6645 return label;
6648 /* If there are no such labels then the default label will be
6649 taken. */
6650 if (i > j)
6651 return gimple_switch_label (switch_stmt, 0);
6654 if (vr->type == VR_ANTI_RANGE)
6656 unsigned n = gimple_switch_num_labels (switch_stmt);
6657 tree min_label = gimple_switch_label (switch_stmt, 1);
6658 tree max_label = gimple_switch_label (switch_stmt, n - 1);
6660 /* The default label will be taken only if the anti-range of the
6661 operand is entirely outside the bounds of all the (non-default)
6662 case labels. */
6663 if (tree_int_cst_compare (vr->min, CASE_LOW (min_label)) <= 0
6664 && (CASE_HIGH (max_label) != NULL_TREE
6665 ? tree_int_cst_compare (vr->max, CASE_HIGH (max_label)) >= 0
6666 : tree_int_cst_compare (vr->max, CASE_LOW (max_label)) >= 0))
6667 return gimple_switch_label (switch_stmt, 0);
6670 return NULL_TREE;
6673 if (gassign *assign_stmt = dyn_cast <gassign *> (stmt))
6675 tree lhs = gimple_assign_lhs (assign_stmt);
6676 if (TREE_CODE (lhs) == SSA_NAME
6677 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
6678 || POINTER_TYPE_P (TREE_TYPE (lhs)))
6679 && stmt_interesting_for_vrp (stmt))
6681 edge dummy_e;
6682 tree dummy_tree;
6683 value_range new_vr = VR_INITIALIZER;
6684 vr_values->extract_range_from_stmt (stmt, &dummy_e,
6685 &dummy_tree, &new_vr);
6686 if (range_int_cst_singleton_p (&new_vr))
6687 return new_vr.min;
6691 return NULL_TREE;
6694 class vrp_dom_walker : public dom_walker
6696 public:
6697 vrp_dom_walker (cdi_direction direction,
6698 class const_and_copies *const_and_copies,
6699 class avail_exprs_stack *avail_exprs_stack)
6700 : dom_walker (direction, REACHABLE_BLOCKS),
6701 m_const_and_copies (const_and_copies),
6702 m_avail_exprs_stack (avail_exprs_stack),
6703 m_dummy_cond (NULL) {}
6705 virtual edge before_dom_children (basic_block);
6706 virtual void after_dom_children (basic_block);
6708 class vr_values *vr_values;
6710 private:
6711 class const_and_copies *m_const_and_copies;
6712 class avail_exprs_stack *m_avail_exprs_stack;
6714 gcond *m_dummy_cond;
6718 /* Called before processing dominator children of BB. We want to look
6719 at ASSERT_EXPRs and record information from them in the appropriate
6720 tables.
6722 We could look at other statements here. It's not seen as likely
6723 to significantly increase the jump threads we discover. */
6725 edge
6726 vrp_dom_walker::before_dom_children (basic_block bb)
6728 gimple_stmt_iterator gsi;
6730 m_avail_exprs_stack->push_marker ();
6731 m_const_and_copies->push_marker ();
6732 for (gsi = gsi_start_nondebug_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
6734 gimple *stmt = gsi_stmt (gsi);
6735 if (gimple_assign_single_p (stmt)
6736 && TREE_CODE (gimple_assign_rhs1 (stmt)) == ASSERT_EXPR)
6738 tree rhs1 = gimple_assign_rhs1 (stmt);
6739 tree cond = TREE_OPERAND (rhs1, 1);
6740 tree inverted = invert_truthvalue (cond);
6741 vec<cond_equivalence> p;
6742 p.create (3);
6743 record_conditions (&p, cond, inverted);
6744 for (unsigned int i = 0; i < p.length (); i++)
6745 m_avail_exprs_stack->record_cond (&p[i]);
6747 tree lhs = gimple_assign_lhs (stmt);
6748 m_const_and_copies->record_const_or_copy (lhs,
6749 TREE_OPERAND (rhs1, 0));
6750 p.release ();
6751 continue;
6753 break;
6755 return NULL;
6758 /* Called after processing dominator children of BB. This is where we
6759 actually call into the threader. */
6760 void
6761 vrp_dom_walker::after_dom_children (basic_block bb)
6763 if (!m_dummy_cond)
6764 m_dummy_cond = gimple_build_cond (NE_EXPR,
6765 integer_zero_node, integer_zero_node,
6766 NULL, NULL);
6768 x_vr_values = vr_values;
6769 thread_outgoing_edges (bb, m_dummy_cond, m_const_and_copies,
6770 m_avail_exprs_stack, NULL,
6771 simplify_stmt_for_jump_threading);
6772 x_vr_values = NULL;
6774 m_avail_exprs_stack->pop_to_marker ();
6775 m_const_and_copies->pop_to_marker ();
6778 /* Blocks which have more than one predecessor and more than
6779 one successor present jump threading opportunities, i.e.,
6780 when the block is reached from a specific predecessor, we
6781 may be able to determine which of the outgoing edges will
6782 be traversed. When this optimization applies, we are able
6783 to avoid conditionals at runtime and we may expose secondary
6784 optimization opportunities.
6786 This routine is effectively a driver for the generic jump
6787 threading code. It basically just presents the generic code
6788 with edges that may be suitable for jump threading.
6790 Unlike DOM, we do not iterate VRP if jump threading was successful.
6791 While iterating may expose new opportunities for VRP, it is expected
6792 those opportunities would be very limited and the compile time cost
6793 to expose those opportunities would be significant.
6795 As jump threading opportunities are discovered, they are registered
6796 for later realization. */
6798 static void
6799 identify_jump_threads (class vr_values *vr_values)
6801 int i;
6802 edge e;
6804 /* Ugh. When substituting values earlier in this pass we can
6805 wipe the dominance information. So rebuild the dominator
6806 information as we need it within the jump threading code. */
6807 calculate_dominance_info (CDI_DOMINATORS);
6809 /* We do not allow VRP information to be used for jump threading
6810 across a back edge in the CFG. Otherwise it becomes too
6811 difficult to avoid eliminating loop exit tests. Of course
6812 EDGE_DFS_BACK is not accurate at this time so we have to
6813 recompute it. */
6814 mark_dfs_back_edges ();
6816 /* Do not thread across edges we are about to remove. Just marking
6817 them as EDGE_IGNORE will do. */
6818 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
6819 e->flags |= EDGE_IGNORE;
6821 /* Allocate our unwinder stack to unwind any temporary equivalences
6822 that might be recorded. */
6823 const_and_copies *equiv_stack = new const_and_copies ();
6825 hash_table<expr_elt_hasher> *avail_exprs
6826 = new hash_table<expr_elt_hasher> (1024);
6827 avail_exprs_stack *avail_exprs_stack
6828 = new class avail_exprs_stack (avail_exprs);
6830 vrp_dom_walker walker (CDI_DOMINATORS, equiv_stack, avail_exprs_stack);
6831 walker.vr_values = vr_values;
6832 walker.walk (cfun->cfg->x_entry_block_ptr);
6834 /* Clear EDGE_IGNORE. */
6835 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
6836 e->flags &= ~EDGE_IGNORE;
6838 /* We do not actually update the CFG or SSA graphs at this point as
6839 ASSERT_EXPRs are still in the IL and cfg cleanup code does not yet
6840 handle ASSERT_EXPRs gracefully. */
6841 delete equiv_stack;
6842 delete avail_exprs;
6843 delete avail_exprs_stack;
6846 /* Traverse all the blocks folding conditionals with known ranges. */
6848 void
6849 vrp_prop::vrp_finalize (bool warn_array_bounds_p)
6851 size_t i;
6853 /* We have completed propagating through the lattice. */
6854 vr_values.set_lattice_propagation_complete ();
6856 if (dump_file)
6858 fprintf (dump_file, "\nValue ranges after VRP:\n\n");
6859 vr_values.dump_all_value_ranges (dump_file);
6860 fprintf (dump_file, "\n");
6863 /* Set value range to non pointer SSA_NAMEs. */
6864 for (i = 0; i < num_ssa_names; i++)
6866 tree name = ssa_name (i);
6867 if (!name)
6868 continue;
6870 value_range *vr = get_value_range (name);
6871 if (!name
6872 || (vr->type == VR_VARYING)
6873 || (vr->type == VR_UNDEFINED)
6874 || (TREE_CODE (vr->min) != INTEGER_CST)
6875 || (TREE_CODE (vr->max) != INTEGER_CST))
6876 continue;
6878 if (POINTER_TYPE_P (TREE_TYPE (name))
6879 && ((vr->type == VR_RANGE
6880 && range_includes_zero_p (vr->min, vr->max) == 0)
6881 || (vr->type == VR_ANTI_RANGE
6882 && range_includes_zero_p (vr->min, vr->max) == 1)))
6883 set_ptr_nonnull (name);
6884 else if (!POINTER_TYPE_P (TREE_TYPE (name)))
6885 set_range_info (name, vr->type,
6886 wi::to_wide (vr->min),
6887 wi::to_wide (vr->max));
6890 /* If we're checking array refs, we want to merge information on
6891 the executability of each edge between vrp_folder and the
6892 check_array_bounds_dom_walker: each can clear the
6893 EDGE_EXECUTABLE flag on edges, in different ways.
6895 Hence, if we're going to call check_all_array_refs, set
6896 the flag on every edge now, rather than in
6897 check_array_bounds_dom_walker's ctor; vrp_folder may clear
6898 it from some edges. */
6899 if (warn_array_bounds && warn_array_bounds_p)
6900 set_all_edges_as_executable (cfun);
6902 class vrp_folder vrp_folder;
6903 vrp_folder.vr_values = &vr_values;
6904 vrp_folder.substitute_and_fold ();
6906 if (warn_array_bounds && warn_array_bounds_p)
6907 check_all_array_refs ();
6910 /* Main entry point to VRP (Value Range Propagation). This pass is
6911 loosely based on J. R. C. Patterson, ``Accurate Static Branch
6912 Prediction by Value Range Propagation,'' in SIGPLAN Conference on
6913 Programming Language Design and Implementation, pp. 67-78, 1995.
6914 Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
6916 This is essentially an SSA-CCP pass modified to deal with ranges
6917 instead of constants.
6919 While propagating ranges, we may find that two or more SSA name
6920 have equivalent, though distinct ranges. For instance,
6922 1 x_9 = p_3->a;
6923 2 p_4 = ASSERT_EXPR <p_3, p_3 != 0>
6924 3 if (p_4 == q_2)
6925 4 p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
6926 5 endif
6927 6 if (q_2)
6929 In the code above, pointer p_5 has range [q_2, q_2], but from the
6930 code we can also determine that p_5 cannot be NULL and, if q_2 had
6931 a non-varying range, p_5's range should also be compatible with it.
6933 These equivalences are created by two expressions: ASSERT_EXPR and
6934 copy operations. Since p_5 is an assertion on p_4, and p_4 was the
6935 result of another assertion, then we can use the fact that p_5 and
6936 p_4 are equivalent when evaluating p_5's range.
6938 Together with value ranges, we also propagate these equivalences
6939 between names so that we can take advantage of information from
6940 multiple ranges when doing final replacement. Note that this
6941 equivalency relation is transitive but not symmetric.
6943 In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
6944 cannot assert that q_2 is equivalent to p_5 because q_2 may be used
6945 in contexts where that assertion does not hold (e.g., in line 6).
6947 TODO, the main difference between this pass and Patterson's is that
6948 we do not propagate edge probabilities. We only compute whether
6949 edges can be taken or not. That is, instead of having a spectrum
6950 of jump probabilities between 0 and 1, we only deal with 0, 1 and
6951 DON'T KNOW. In the future, it may be worthwhile to propagate
6952 probabilities to aid branch prediction. */
6954 static unsigned int
6955 execute_vrp (bool warn_array_bounds_p)
6957 int i;
6958 edge e;
6959 switch_update *su;
6961 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
6962 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
6963 scev_initialize ();
6965 /* ??? This ends up using stale EDGE_DFS_BACK for liveness computation.
6966 Inserting assertions may split edges which will invalidate
6967 EDGE_DFS_BACK. */
6968 insert_range_assertions ();
6970 to_remove_edges.create (10);
6971 to_update_switch_stmts.create (5);
6972 threadedge_initialize_values ();
6974 /* For visiting PHI nodes we need EDGE_DFS_BACK computed. */
6975 mark_dfs_back_edges ();
6977 class vrp_prop vrp_prop;
6978 vrp_prop.vrp_initialize ();
6979 vrp_prop.ssa_propagate ();
6980 vrp_prop.vrp_finalize (warn_array_bounds_p);
6982 /* We must identify jump threading opportunities before we release
6983 the datastructures built by VRP. */
6984 identify_jump_threads (&vrp_prop.vr_values);
6986 /* A comparison of an SSA_NAME against a constant where the SSA_NAME
6987 was set by a type conversion can often be rewritten to use the
6988 RHS of the type conversion.
6990 However, doing so inhibits jump threading through the comparison.
6991 So that transformation is not performed until after jump threading
6992 is complete. */
6993 basic_block bb;
6994 FOR_EACH_BB_FN (bb, cfun)
6996 gimple *last = last_stmt (bb);
6997 if (last && gimple_code (last) == GIMPLE_COND)
6998 vrp_prop.vr_values.simplify_cond_using_ranges_2 (as_a <gcond *> (last));
7001 free_numbers_of_iterations_estimates (cfun);
7003 /* ASSERT_EXPRs must be removed before finalizing jump threads
7004 as finalizing jump threads calls the CFG cleanup code which
7005 does not properly handle ASSERT_EXPRs. */
7006 remove_range_assertions ();
7008 /* If we exposed any new variables, go ahead and put them into
7009 SSA form now, before we handle jump threading. This simplifies
7010 interactions between rewriting of _DECL nodes into SSA form
7011 and rewriting SSA_NAME nodes into SSA form after block
7012 duplication and CFG manipulation. */
7013 update_ssa (TODO_update_ssa);
7015 /* We identified all the jump threading opportunities earlier, but could
7016 not transform the CFG at that time. This routine transforms the
7017 CFG and arranges for the dominator tree to be rebuilt if necessary.
7019 Note the SSA graph update will occur during the normal TODO
7020 processing by the pass manager. */
7021 thread_through_all_blocks (false);
7023 /* Remove dead edges from SWITCH_EXPR optimization. This leaves the
7024 CFG in a broken state and requires a cfg_cleanup run. */
7025 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
7026 remove_edge (e);
7027 /* Update SWITCH_EXPR case label vector. */
7028 FOR_EACH_VEC_ELT (to_update_switch_stmts, i, su)
7030 size_t j;
7031 size_t n = TREE_VEC_LENGTH (su->vec);
7032 tree label;
7033 gimple_switch_set_num_labels (su->stmt, n);
7034 for (j = 0; j < n; j++)
7035 gimple_switch_set_label (su->stmt, j, TREE_VEC_ELT (su->vec, j));
7036 /* As we may have replaced the default label with a regular one
7037 make sure to make it a real default label again. This ensures
7038 optimal expansion. */
7039 label = gimple_switch_label (su->stmt, 0);
7040 CASE_LOW (label) = NULL_TREE;
7041 CASE_HIGH (label) = NULL_TREE;
7044 if (to_remove_edges.length () > 0)
7046 free_dominance_info (CDI_DOMINATORS);
7047 loops_state_set (LOOPS_NEED_FIXUP);
7050 to_remove_edges.release ();
7051 to_update_switch_stmts.release ();
7052 threadedge_finalize_values ();
7054 scev_finalize ();
7055 loop_optimizer_finalize ();
7056 return 0;
7059 namespace {
7061 const pass_data pass_data_vrp =
7063 GIMPLE_PASS, /* type */
7064 "vrp", /* name */
7065 OPTGROUP_NONE, /* optinfo_flags */
7066 TV_TREE_VRP, /* tv_id */
7067 PROP_ssa, /* properties_required */
7068 0, /* properties_provided */
7069 0, /* properties_destroyed */
7070 0, /* todo_flags_start */
7071 ( TODO_cleanup_cfg | TODO_update_ssa ), /* todo_flags_finish */
7074 class pass_vrp : public gimple_opt_pass
7076 public:
7077 pass_vrp (gcc::context *ctxt)
7078 : gimple_opt_pass (pass_data_vrp, ctxt), warn_array_bounds_p (false)
7081 /* opt_pass methods: */
7082 opt_pass * clone () { return new pass_vrp (m_ctxt); }
7083 void set_pass_param (unsigned int n, bool param)
7085 gcc_assert (n == 0);
7086 warn_array_bounds_p = param;
7088 virtual bool gate (function *) { return flag_tree_vrp != 0; }
7089 virtual unsigned int execute (function *)
7090 { return execute_vrp (warn_array_bounds_p); }
7092 private:
7093 bool warn_array_bounds_p;
7094 }; // class pass_vrp
7096 } // anon namespace
7098 gimple_opt_pass *
7099 make_pass_vrp (gcc::context *ctxt)
7101 return new pass_vrp (ctxt);