* tree-ssa-dse.c (compute_trims): Avoid folding away undefined
[official-gcc.git] / gcc / tree-vrp.c
blobead19f159964cf6197f51726a74d11eb08c2f665
1 /* Support routines for Value Range Propagation (VRP).
2 Copyright (C) 2005-2018 Free Software Foundation, Inc.
3 Contributed by Diego Novillo <dnovillo@redhat.com>.
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "backend.h"
25 #include "insn-codes.h"
26 #include "rtl.h"
27 #include "tree.h"
28 #include "gimple.h"
29 #include "cfghooks.h"
30 #include "tree-pass.h"
31 #include "ssa.h"
32 #include "optabs-tree.h"
33 #include "gimple-pretty-print.h"
34 #include "diagnostic-core.h"
35 #include "flags.h"
36 #include "fold-const.h"
37 #include "stor-layout.h"
38 #include "calls.h"
39 #include "cfganal.h"
40 #include "gimple-fold.h"
41 #include "tree-eh.h"
42 #include "gimple-iterator.h"
43 #include "gimple-walk.h"
44 #include "tree-cfg.h"
45 #include "tree-dfa.h"
46 #include "tree-ssa-loop-manip.h"
47 #include "tree-ssa-loop-niter.h"
48 #include "tree-ssa-loop.h"
49 #include "tree-into-ssa.h"
50 #include "tree-ssa.h"
51 #include "intl.h"
52 #include "cfgloop.h"
53 #include "tree-scalar-evolution.h"
54 #include "tree-ssa-propagate.h"
55 #include "tree-chrec.h"
56 #include "tree-ssa-threadupdate.h"
57 #include "tree-ssa-scopedtables.h"
58 #include "tree-ssa-threadedge.h"
59 #include "omp-general.h"
60 #include "target.h"
61 #include "case-cfn-macros.h"
62 #include "params.h"
63 #include "alloc-pool.h"
64 #include "domwalk.h"
65 #include "tree-cfgcleanup.h"
66 #include "stringpool.h"
67 #include "attribs.h"
68 #include "vr-values.h"
69 #include "builtins.h"
70 #include "wide-int-range.h"
72 /* Set of SSA names found live during the RPO traversal of the function
73 for still active basic-blocks. */
74 static sbitmap *live;
76 /* Return true if the SSA name NAME is live on the edge E. */
78 static bool
79 live_on_edge (edge e, tree name)
81 return (live[e->dest->index]
82 && bitmap_bit_p (live[e->dest->index], SSA_NAME_VERSION (name)));
85 /* Location information for ASSERT_EXPRs. Each instance of this
86 structure describes an ASSERT_EXPR for an SSA name. Since a single
87 SSA name may have more than one assertion associated with it, these
88 locations are kept in a linked list attached to the corresponding
89 SSA name. */
90 struct assert_locus
92 /* Basic block where the assertion would be inserted. */
93 basic_block bb;
95 /* Some assertions need to be inserted on an edge (e.g., assertions
96 generated by COND_EXPRs). In those cases, BB will be NULL. */
97 edge e;
99 /* Pointer to the statement that generated this assertion. */
100 gimple_stmt_iterator si;
102 /* Predicate code for the ASSERT_EXPR. Must be COMPARISON_CLASS_P. */
103 enum tree_code comp_code;
105 /* Value being compared against. */
106 tree val;
108 /* Expression to compare. */
109 tree expr;
111 /* Next node in the linked list. */
112 assert_locus *next;
115 /* If bit I is present, it means that SSA name N_i has a list of
116 assertions that should be inserted in the IL. */
117 static bitmap need_assert_for;
119 /* Array of locations lists where to insert assertions. ASSERTS_FOR[I]
120 holds a list of ASSERT_LOCUS_T nodes that describe where
121 ASSERT_EXPRs for SSA name N_I should be inserted. */
122 static assert_locus **asserts_for;
124 vec<edge> to_remove_edges;
125 vec<switch_update> to_update_switch_stmts;
128 /* Return the maximum value for TYPE. */
130 tree
131 vrp_val_max (const_tree type)
133 if (!INTEGRAL_TYPE_P (type))
134 return NULL_TREE;
136 return TYPE_MAX_VALUE (type);
139 /* Return the minimum value for TYPE. */
141 tree
142 vrp_val_min (const_tree type)
144 if (!INTEGRAL_TYPE_P (type))
145 return NULL_TREE;
147 return TYPE_MIN_VALUE (type);
150 /* Return whether VAL is equal to the maximum value of its type.
151 We can't do a simple equality comparison with TYPE_MAX_VALUE because
152 C typedefs and Ada subtypes can produce types whose TYPE_MAX_VALUE
153 is not == to the integer constant with the same value in the type. */
155 bool
156 vrp_val_is_max (const_tree val)
158 tree type_max = vrp_val_max (TREE_TYPE (val));
159 return (val == type_max
160 || (type_max != NULL_TREE
161 && operand_equal_p (val, type_max, 0)));
164 /* Return whether VAL is equal to the minimum value of its type. */
166 bool
167 vrp_val_is_min (const_tree val)
169 tree type_min = vrp_val_min (TREE_TYPE (val));
170 return (val == type_min
171 || (type_min != NULL_TREE
172 && operand_equal_p (val, type_min, 0)));
175 /* VR_TYPE describes a range with mininum value *MIN and maximum
176 value *MAX. Restrict the range to the set of values that have
177 no bits set outside NONZERO_BITS. Update *MIN and *MAX and
178 return the new range type.
180 SGN gives the sign of the values described by the range. */
182 enum value_range_type
183 intersect_range_with_nonzero_bits (enum value_range_type vr_type,
184 wide_int *min, wide_int *max,
185 const wide_int &nonzero_bits,
186 signop sgn)
188 if (vr_type == VR_ANTI_RANGE)
190 /* The VR_ANTI_RANGE is equivalent to the union of the ranges
191 A: [-INF, *MIN) and B: (*MAX, +INF]. First use NONZERO_BITS
192 to create an inclusive upper bound for A and an inclusive lower
193 bound for B. */
194 wide_int a_max = wi::round_down_for_mask (*min - 1, nonzero_bits);
195 wide_int b_min = wi::round_up_for_mask (*max + 1, nonzero_bits);
197 /* If the calculation of A_MAX wrapped, A is effectively empty
198 and A_MAX is the highest value that satisfies NONZERO_BITS.
199 Likewise if the calculation of B_MIN wrapped, B is effectively
200 empty and B_MIN is the lowest value that satisfies NONZERO_BITS. */
201 bool a_empty = wi::ge_p (a_max, *min, sgn);
202 bool b_empty = wi::le_p (b_min, *max, sgn);
204 /* If both A and B are empty, there are no valid values. */
205 if (a_empty && b_empty)
206 return VR_UNDEFINED;
208 /* If exactly one of A or B is empty, return a VR_RANGE for the
209 other one. */
210 if (a_empty || b_empty)
212 *min = b_min;
213 *max = a_max;
214 gcc_checking_assert (wi::le_p (*min, *max, sgn));
215 return VR_RANGE;
218 /* Update the VR_ANTI_RANGE bounds. */
219 *min = a_max + 1;
220 *max = b_min - 1;
221 gcc_checking_assert (wi::le_p (*min, *max, sgn));
223 /* Now check whether the excluded range includes any values that
224 satisfy NONZERO_BITS. If not, switch to a full VR_RANGE. */
225 if (wi::round_up_for_mask (*min, nonzero_bits) == b_min)
227 unsigned int precision = min->get_precision ();
228 *min = wi::min_value (precision, sgn);
229 *max = wi::max_value (precision, sgn);
230 vr_type = VR_RANGE;
233 if (vr_type == VR_RANGE)
235 *max = wi::round_down_for_mask (*max, nonzero_bits);
237 /* Check that the range contains at least one valid value. */
238 if (wi::gt_p (*min, *max, sgn))
239 return VR_UNDEFINED;
241 *min = wi::round_up_for_mask (*min, nonzero_bits);
242 gcc_checking_assert (wi::le_p (*min, *max, sgn));
244 return vr_type;
247 /* Set value range VR to VR_UNDEFINED. */
249 static inline void
250 set_value_range_to_undefined (value_range *vr)
252 vr->type = VR_UNDEFINED;
253 vr->min = vr->max = NULL_TREE;
254 if (vr->equiv)
255 bitmap_clear (vr->equiv);
258 /* Set value range VR to VR_VARYING. */
260 void
261 set_value_range_to_varying (value_range *vr)
263 vr->type = VR_VARYING;
264 vr->min = vr->max = NULL_TREE;
265 if (vr->equiv)
266 bitmap_clear (vr->equiv);
269 /* Set value range VR to {T, MIN, MAX, EQUIV}. */
271 void
272 set_value_range (value_range *vr, enum value_range_type t, tree min,
273 tree max, bitmap equiv)
275 /* Check the validity of the range. */
276 if (flag_checking
277 && (t == VR_RANGE || t == VR_ANTI_RANGE))
279 int cmp;
281 gcc_assert (min && max);
283 gcc_assert (!TREE_OVERFLOW_P (min) && !TREE_OVERFLOW_P (max));
285 if (INTEGRAL_TYPE_P (TREE_TYPE (min)) && t == VR_ANTI_RANGE)
286 gcc_assert (!vrp_val_is_min (min) || !vrp_val_is_max (max));
288 cmp = compare_values (min, max);
289 gcc_assert (cmp == 0 || cmp == -1 || cmp == -2);
292 if (flag_checking
293 && (t == VR_UNDEFINED || t == VR_VARYING))
295 gcc_assert (min == NULL_TREE && max == NULL_TREE);
296 gcc_assert (equiv == NULL || bitmap_empty_p (equiv));
299 vr->type = t;
300 vr->min = min;
301 vr->max = max;
303 /* Since updating the equivalence set involves deep copying the
304 bitmaps, only do it if absolutely necessary.
306 All equivalence bitmaps are allocated from the same obstack. So
307 we can use the obstack associated with EQUIV to allocate vr->equiv. */
308 if (vr->equiv == NULL
309 && equiv != NULL)
310 vr->equiv = BITMAP_ALLOC (equiv->obstack);
312 if (equiv != vr->equiv)
314 if (equiv && !bitmap_empty_p (equiv))
315 bitmap_copy (vr->equiv, equiv);
316 else
317 bitmap_clear (vr->equiv);
322 /* Set value range VR to the canonical form of {T, MIN, MAX, EQUIV}.
323 This means adjusting T, MIN and MAX representing the case of a
324 wrapping range with MAX < MIN covering [MIN, type_max] U [type_min, MAX]
325 as anti-rage ~[MAX+1, MIN-1]. Likewise for wrapping anti-ranges.
326 In corner cases where MAX+1 or MIN-1 wraps this will fall back
327 to varying.
328 This routine exists to ease canonicalization in the case where we
329 extract ranges from var + CST op limit. */
331 void
332 set_and_canonicalize_value_range (value_range *vr, enum value_range_type t,
333 tree min, tree max, bitmap equiv)
335 /* Use the canonical setters for VR_UNDEFINED and VR_VARYING. */
336 if (t == VR_UNDEFINED)
338 set_value_range_to_undefined (vr);
339 return;
341 else if (t == VR_VARYING)
343 set_value_range_to_varying (vr);
344 return;
347 /* Nothing to canonicalize for symbolic ranges. */
348 if (TREE_CODE (min) != INTEGER_CST
349 || TREE_CODE (max) != INTEGER_CST)
351 set_value_range (vr, t, min, max, equiv);
352 return;
355 /* Wrong order for min and max, to swap them and the VR type we need
356 to adjust them. */
357 if (tree_int_cst_lt (max, min))
359 tree one, tmp;
361 /* For one bit precision if max < min, then the swapped
362 range covers all values, so for VR_RANGE it is varying and
363 for VR_ANTI_RANGE empty range, so drop to varying as well. */
364 if (TYPE_PRECISION (TREE_TYPE (min)) == 1)
366 set_value_range_to_varying (vr);
367 return;
370 one = build_int_cst (TREE_TYPE (min), 1);
371 tmp = int_const_binop (PLUS_EXPR, max, one);
372 max = int_const_binop (MINUS_EXPR, min, one);
373 min = tmp;
375 /* There's one corner case, if we had [C+1, C] before we now have
376 that again. But this represents an empty value range, so drop
377 to varying in this case. */
378 if (tree_int_cst_lt (max, min))
380 set_value_range_to_varying (vr);
381 return;
384 t = t == VR_RANGE ? VR_ANTI_RANGE : VR_RANGE;
387 /* Anti-ranges that can be represented as ranges should be so. */
388 if (t == VR_ANTI_RANGE)
390 /* For -fstrict-enums we may receive out-of-range ranges so consider
391 values < -INF and values > INF as -INF/INF as well. */
392 tree type = TREE_TYPE (min);
393 bool is_min = (INTEGRAL_TYPE_P (type)
394 && tree_int_cst_compare (min, TYPE_MIN_VALUE (type)) <= 0);
395 bool is_max = (INTEGRAL_TYPE_P (type)
396 && tree_int_cst_compare (max, TYPE_MAX_VALUE (type)) >= 0);
398 if (is_min && is_max)
400 /* We cannot deal with empty ranges, drop to varying.
401 ??? This could be VR_UNDEFINED instead. */
402 set_value_range_to_varying (vr);
403 return;
405 else if (TYPE_PRECISION (TREE_TYPE (min)) == 1
406 && (is_min || is_max))
408 /* Non-empty boolean ranges can always be represented
409 as a singleton range. */
410 if (is_min)
411 min = max = vrp_val_max (TREE_TYPE (min));
412 else
413 min = max = vrp_val_min (TREE_TYPE (min));
414 t = VR_RANGE;
416 else if (is_min
417 /* As a special exception preserve non-null ranges. */
418 && !(TYPE_UNSIGNED (TREE_TYPE (min))
419 && integer_zerop (max)))
421 tree one = build_int_cst (TREE_TYPE (max), 1);
422 min = int_const_binop (PLUS_EXPR, max, one);
423 max = vrp_val_max (TREE_TYPE (max));
424 t = VR_RANGE;
426 else if (is_max)
428 tree one = build_int_cst (TREE_TYPE (min), 1);
429 max = int_const_binop (MINUS_EXPR, min, one);
430 min = vrp_val_min (TREE_TYPE (min));
431 t = VR_RANGE;
435 /* Do not drop [-INF(OVF), +INF(OVF)] to varying. (OVF) has to be sticky
436 to make sure VRP iteration terminates, otherwise we can get into
437 oscillations. */
439 set_value_range (vr, t, min, max, equiv);
442 /* Copy value range FROM into value range TO. */
444 void
445 copy_value_range (value_range *to, value_range *from)
447 set_value_range (to, from->type, from->min, from->max, from->equiv);
450 /* Set value range VR to a single value. This function is only called
451 with values we get from statements, and exists to clear the
452 TREE_OVERFLOW flag. */
454 void
455 set_value_range_to_value (value_range *vr, tree val, bitmap equiv)
457 gcc_assert (is_gimple_min_invariant (val));
458 if (TREE_OVERFLOW_P (val))
459 val = drop_tree_overflow (val);
460 set_value_range (vr, VR_RANGE, val, val, equiv);
463 /* Set value range VR to a non-NULL range of type TYPE. */
465 void
466 set_value_range_to_nonnull (value_range *vr, tree type)
468 tree zero = build_int_cst (type, 0);
469 set_value_range (vr, VR_ANTI_RANGE, zero, zero, vr->equiv);
473 /* Set value range VR to a NULL range of type TYPE. */
475 void
476 set_value_range_to_null (value_range *vr, tree type)
478 set_value_range_to_value (vr, build_int_cst (type, 0), vr->equiv);
482 /* If abs (min) < abs (max), set VR to [-max, max], if
483 abs (min) >= abs (max), set VR to [-min, min]. */
485 static void
486 abs_extent_range (value_range *vr, tree min, tree max)
488 int cmp;
490 gcc_assert (TREE_CODE (min) == INTEGER_CST);
491 gcc_assert (TREE_CODE (max) == INTEGER_CST);
492 gcc_assert (INTEGRAL_TYPE_P (TREE_TYPE (min)));
493 gcc_assert (!TYPE_UNSIGNED (TREE_TYPE (min)));
494 min = fold_unary (ABS_EXPR, TREE_TYPE (min), min);
495 max = fold_unary (ABS_EXPR, TREE_TYPE (max), max);
496 if (TREE_OVERFLOW (min) || TREE_OVERFLOW (max))
498 set_value_range_to_varying (vr);
499 return;
501 cmp = compare_values (min, max);
502 if (cmp == -1)
503 min = fold_unary (NEGATE_EXPR, TREE_TYPE (min), max);
504 else if (cmp == 0 || cmp == 1)
506 max = min;
507 min = fold_unary (NEGATE_EXPR, TREE_TYPE (min), min);
509 else
511 set_value_range_to_varying (vr);
512 return;
514 set_and_canonicalize_value_range (vr, VR_RANGE, min, max, NULL);
517 /* Return true, if VAL1 and VAL2 are equal values for VRP purposes. */
519 bool
520 vrp_operand_equal_p (const_tree val1, const_tree val2)
522 if (val1 == val2)
523 return true;
524 if (!val1 || !val2 || !operand_equal_p (val1, val2, 0))
525 return false;
526 return true;
529 /* Return true, if the bitmaps B1 and B2 are equal. */
531 bool
532 vrp_bitmap_equal_p (const_bitmap b1, const_bitmap b2)
534 return (b1 == b2
535 || ((!b1 || bitmap_empty_p (b1))
536 && (!b2 || bitmap_empty_p (b2)))
537 || (b1 && b2
538 && bitmap_equal_p (b1, b2)));
541 /* Return true if VR is ~[0, 0]. */
543 bool
544 range_is_nonnull (value_range *vr)
546 return vr->type == VR_ANTI_RANGE
547 && integer_zerop (vr->min)
548 && integer_zerop (vr->max);
552 /* Return true if VR is [0, 0]. */
554 static inline bool
555 range_is_null (value_range *vr)
557 return vr->type == VR_RANGE
558 && integer_zerop (vr->min)
559 && integer_zerop (vr->max);
562 /* Return true if max and min of VR are INTEGER_CST. It's not necessary
563 a singleton. */
565 bool
566 range_int_cst_p (value_range *vr)
568 return (vr->type == VR_RANGE
569 && TREE_CODE (vr->max) == INTEGER_CST
570 && TREE_CODE (vr->min) == INTEGER_CST);
573 /* Return true if VR is a INTEGER_CST singleton. */
575 bool
576 range_int_cst_singleton_p (value_range *vr)
578 return (range_int_cst_p (vr)
579 && tree_int_cst_equal (vr->min, vr->max));
582 /* Return true if value range VR involves at least one symbol. */
584 bool
585 symbolic_range_p (value_range *vr)
587 return (!is_gimple_min_invariant (vr->min)
588 || !is_gimple_min_invariant (vr->max));
591 /* Return the single symbol (an SSA_NAME) contained in T if any, or NULL_TREE
592 otherwise. We only handle additive operations and set NEG to true if the
593 symbol is negated and INV to the invariant part, if any. */
595 tree
596 get_single_symbol (tree t, bool *neg, tree *inv)
598 bool neg_;
599 tree inv_;
601 *inv = NULL_TREE;
602 *neg = false;
604 if (TREE_CODE (t) == PLUS_EXPR
605 || TREE_CODE (t) == POINTER_PLUS_EXPR
606 || TREE_CODE (t) == MINUS_EXPR)
608 if (is_gimple_min_invariant (TREE_OPERAND (t, 0)))
610 neg_ = (TREE_CODE (t) == MINUS_EXPR);
611 inv_ = TREE_OPERAND (t, 0);
612 t = TREE_OPERAND (t, 1);
614 else if (is_gimple_min_invariant (TREE_OPERAND (t, 1)))
616 neg_ = false;
617 inv_ = TREE_OPERAND (t, 1);
618 t = TREE_OPERAND (t, 0);
620 else
621 return NULL_TREE;
623 else
625 neg_ = false;
626 inv_ = NULL_TREE;
629 if (TREE_CODE (t) == NEGATE_EXPR)
631 t = TREE_OPERAND (t, 0);
632 neg_ = !neg_;
635 if (TREE_CODE (t) != SSA_NAME)
636 return NULL_TREE;
638 if (inv_ && TREE_OVERFLOW_P (inv_))
639 inv_ = drop_tree_overflow (inv_);
641 *neg = neg_;
642 *inv = inv_;
643 return t;
646 /* The reverse operation: build a symbolic expression with TYPE
647 from symbol SYM, negated according to NEG, and invariant INV. */
649 static tree
650 build_symbolic_expr (tree type, tree sym, bool neg, tree inv)
652 const bool pointer_p = POINTER_TYPE_P (type);
653 tree t = sym;
655 if (neg)
656 t = build1 (NEGATE_EXPR, type, t);
658 if (integer_zerop (inv))
659 return t;
661 return build2 (pointer_p ? POINTER_PLUS_EXPR : PLUS_EXPR, type, t, inv);
664 /* Return
665 1 if VAL < VAL2
666 0 if !(VAL < VAL2)
667 -2 if those are incomparable. */
669 operand_less_p (tree val, tree val2)
671 /* LT is folded faster than GE and others. Inline the common case. */
672 if (TREE_CODE (val) == INTEGER_CST && TREE_CODE (val2) == INTEGER_CST)
673 return tree_int_cst_lt (val, val2);
674 else
676 tree tcmp;
678 fold_defer_overflow_warnings ();
680 tcmp = fold_binary_to_constant (LT_EXPR, boolean_type_node, val, val2);
682 fold_undefer_and_ignore_overflow_warnings ();
684 if (!tcmp
685 || TREE_CODE (tcmp) != INTEGER_CST)
686 return -2;
688 if (!integer_zerop (tcmp))
689 return 1;
692 return 0;
695 /* Compare two values VAL1 and VAL2. Return
697 -2 if VAL1 and VAL2 cannot be compared at compile-time,
698 -1 if VAL1 < VAL2,
699 0 if VAL1 == VAL2,
700 +1 if VAL1 > VAL2, and
701 +2 if VAL1 != VAL2
703 This is similar to tree_int_cst_compare but supports pointer values
704 and values that cannot be compared at compile time.
706 If STRICT_OVERFLOW_P is not NULL, then set *STRICT_OVERFLOW_P to
707 true if the return value is only valid if we assume that signed
708 overflow is undefined. */
711 compare_values_warnv (tree val1, tree val2, bool *strict_overflow_p)
713 if (val1 == val2)
714 return 0;
716 /* Below we rely on the fact that VAL1 and VAL2 are both pointers or
717 both integers. */
718 gcc_assert (POINTER_TYPE_P (TREE_TYPE (val1))
719 == POINTER_TYPE_P (TREE_TYPE (val2)));
721 /* Convert the two values into the same type. This is needed because
722 sizetype causes sign extension even for unsigned types. */
723 val2 = fold_convert (TREE_TYPE (val1), val2);
724 STRIP_USELESS_TYPE_CONVERSION (val2);
726 const bool overflow_undefined
727 = INTEGRAL_TYPE_P (TREE_TYPE (val1))
728 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1));
729 tree inv1, inv2;
730 bool neg1, neg2;
731 tree sym1 = get_single_symbol (val1, &neg1, &inv1);
732 tree sym2 = get_single_symbol (val2, &neg2, &inv2);
734 /* If VAL1 and VAL2 are of the form '[-]NAME [+ CST]', return -1 or +1
735 accordingly. If VAL1 and VAL2 don't use the same name, return -2. */
736 if (sym1 && sym2)
738 /* Both values must use the same name with the same sign. */
739 if (sym1 != sym2 || neg1 != neg2)
740 return -2;
742 /* [-]NAME + CST == [-]NAME + CST. */
743 if (inv1 == inv2)
744 return 0;
746 /* If overflow is defined we cannot simplify more. */
747 if (!overflow_undefined)
748 return -2;
750 if (strict_overflow_p != NULL
751 /* Symbolic range building sets TREE_NO_WARNING to declare
752 that overflow doesn't happen. */
753 && (!inv1 || !TREE_NO_WARNING (val1))
754 && (!inv2 || !TREE_NO_WARNING (val2)))
755 *strict_overflow_p = true;
757 if (!inv1)
758 inv1 = build_int_cst (TREE_TYPE (val1), 0);
759 if (!inv2)
760 inv2 = build_int_cst (TREE_TYPE (val2), 0);
762 return wi::cmp (wi::to_wide (inv1), wi::to_wide (inv2),
763 TYPE_SIGN (TREE_TYPE (val1)));
766 const bool cst1 = is_gimple_min_invariant (val1);
767 const bool cst2 = is_gimple_min_invariant (val2);
769 /* If one is of the form '[-]NAME + CST' and the other is constant, then
770 it might be possible to say something depending on the constants. */
771 if ((sym1 && inv1 && cst2) || (sym2 && inv2 && cst1))
773 if (!overflow_undefined)
774 return -2;
776 if (strict_overflow_p != NULL
777 /* Symbolic range building sets TREE_NO_WARNING to declare
778 that overflow doesn't happen. */
779 && (!sym1 || !TREE_NO_WARNING (val1))
780 && (!sym2 || !TREE_NO_WARNING (val2)))
781 *strict_overflow_p = true;
783 const signop sgn = TYPE_SIGN (TREE_TYPE (val1));
784 tree cst = cst1 ? val1 : val2;
785 tree inv = cst1 ? inv2 : inv1;
787 /* Compute the difference between the constants. If it overflows or
788 underflows, this means that we can trivially compare the NAME with
789 it and, consequently, the two values with each other. */
790 wide_int diff = wi::to_wide (cst) - wi::to_wide (inv);
791 if (wi::cmp (0, wi::to_wide (inv), sgn)
792 != wi::cmp (diff, wi::to_wide (cst), sgn))
794 const int res = wi::cmp (wi::to_wide (cst), wi::to_wide (inv), sgn);
795 return cst1 ? res : -res;
798 return -2;
801 /* We cannot say anything more for non-constants. */
802 if (!cst1 || !cst2)
803 return -2;
805 if (!POINTER_TYPE_P (TREE_TYPE (val1)))
807 /* We cannot compare overflowed values. */
808 if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
809 return -2;
811 if (TREE_CODE (val1) == INTEGER_CST
812 && TREE_CODE (val2) == INTEGER_CST)
813 return tree_int_cst_compare (val1, val2);
815 if (poly_int_tree_p (val1) && poly_int_tree_p (val2))
817 if (known_eq (wi::to_poly_widest (val1),
818 wi::to_poly_widest (val2)))
819 return 0;
820 if (known_lt (wi::to_poly_widest (val1),
821 wi::to_poly_widest (val2)))
822 return -1;
823 if (known_gt (wi::to_poly_widest (val1),
824 wi::to_poly_widest (val2)))
825 return 1;
828 return -2;
830 else
832 tree t;
834 /* First see if VAL1 and VAL2 are not the same. */
835 if (val1 == val2 || operand_equal_p (val1, val2, 0))
836 return 0;
838 /* If VAL1 is a lower address than VAL2, return -1. */
839 if (operand_less_p (val1, val2) == 1)
840 return -1;
842 /* If VAL1 is a higher address than VAL2, return +1. */
843 if (operand_less_p (val2, val1) == 1)
844 return 1;
846 /* If VAL1 is different than VAL2, return +2.
847 For integer constants we either have already returned -1 or 1
848 or they are equivalent. We still might succeed in proving
849 something about non-trivial operands. */
850 if (TREE_CODE (val1) != INTEGER_CST
851 || TREE_CODE (val2) != INTEGER_CST)
853 t = fold_binary_to_constant (NE_EXPR, boolean_type_node, val1, val2);
854 if (t && integer_onep (t))
855 return 2;
858 return -2;
862 /* Compare values like compare_values_warnv. */
865 compare_values (tree val1, tree val2)
867 bool sop;
868 return compare_values_warnv (val1, val2, &sop);
872 /* Return 1 if VAL is inside value range MIN <= VAL <= MAX,
873 0 if VAL is not inside [MIN, MAX],
874 -2 if we cannot tell either way.
876 Benchmark compile/20001226-1.c compilation time after changing this
877 function. */
880 value_inside_range (tree val, tree min, tree max)
882 int cmp1, cmp2;
884 cmp1 = operand_less_p (val, min);
885 if (cmp1 == -2)
886 return -2;
887 if (cmp1 == 1)
888 return 0;
890 cmp2 = operand_less_p (max, val);
891 if (cmp2 == -2)
892 return -2;
894 return !cmp2;
898 /* Return true if value ranges VR0 and VR1 have a non-empty
899 intersection.
901 Benchmark compile/20001226-1.c compilation time after changing this
902 function.
905 static inline bool
906 value_ranges_intersect_p (value_range *vr0, value_range *vr1)
908 /* The value ranges do not intersect if the maximum of the first range is
909 less than the minimum of the second range or vice versa.
910 When those relations are unknown, we can't do any better. */
911 if (operand_less_p (vr0->max, vr1->min) != 0)
912 return false;
913 if (operand_less_p (vr1->max, vr0->min) != 0)
914 return false;
915 return true;
919 /* Return 1 if [MIN, MAX] includes the value zero, 0 if it does not
920 include the value zero, -2 if we cannot tell. */
923 range_includes_zero_p (tree min, tree max)
925 tree zero = build_int_cst (TREE_TYPE (min), 0);
926 return value_inside_range (zero, min, max);
929 /* Return true if *VR is know to only contain nonnegative values. */
931 static inline bool
932 value_range_nonnegative_p (value_range *vr)
934 /* Testing for VR_ANTI_RANGE is not useful here as any anti-range
935 which would return a useful value should be encoded as a
936 VR_RANGE. */
937 if (vr->type == VR_RANGE)
939 int result = compare_values (vr->min, integer_zero_node);
940 return (result == 0 || result == 1);
943 return false;
946 /* If *VR has a value rante that is a single constant value return that,
947 otherwise return NULL_TREE. */
949 tree
950 value_range_constant_singleton (value_range *vr)
952 if (vr->type == VR_RANGE
953 && vrp_operand_equal_p (vr->min, vr->max)
954 && is_gimple_min_invariant (vr->min))
955 return vr->min;
957 return NULL_TREE;
960 /* Value range wrapper for wide_int_range_set_zero_nonzero_bits.
962 Compute MAY_BE_NONZERO and MUST_BE_NONZERO bit masks for range in VR.
964 Return TRUE if VR was a constant range and we were able to compute
965 the bit masks. */
967 bool
968 vrp_set_zero_nonzero_bits (const tree expr_type,
969 value_range *vr,
970 wide_int *may_be_nonzero,
971 wide_int *must_be_nonzero)
973 if (!range_int_cst_p (vr))
975 *may_be_nonzero = wi::minus_one (TYPE_PRECISION (expr_type));
976 *must_be_nonzero = wi::zero (TYPE_PRECISION (expr_type));
977 return false;
979 wide_int_range_set_zero_nonzero_bits (TYPE_SIGN (expr_type),
980 wi::to_wide (vr->min),
981 wi::to_wide (vr->max),
982 *may_be_nonzero, *must_be_nonzero);
983 return true;
986 /* Create two value-ranges in *VR0 and *VR1 from the anti-range *AR
987 so that *VR0 U *VR1 == *AR. Returns true if that is possible,
988 false otherwise. If *AR can be represented with a single range
989 *VR1 will be VR_UNDEFINED. */
991 static bool
992 ranges_from_anti_range (value_range *ar,
993 value_range *vr0, value_range *vr1)
995 tree type = TREE_TYPE (ar->min);
997 vr0->type = VR_UNDEFINED;
998 vr1->type = VR_UNDEFINED;
1000 if (ar->type != VR_ANTI_RANGE
1001 || TREE_CODE (ar->min) != INTEGER_CST
1002 || TREE_CODE (ar->max) != INTEGER_CST
1003 || !vrp_val_min (type)
1004 || !vrp_val_max (type))
1005 return false;
1007 if (!vrp_val_is_min (ar->min))
1009 vr0->type = VR_RANGE;
1010 vr0->min = vrp_val_min (type);
1011 vr0->max = wide_int_to_tree (type, wi::to_wide (ar->min) - 1);
1013 if (!vrp_val_is_max (ar->max))
1015 vr1->type = VR_RANGE;
1016 vr1->min = wide_int_to_tree (type, wi::to_wide (ar->max) + 1);
1017 vr1->max = vrp_val_max (type);
1019 if (vr0->type == VR_UNDEFINED)
1021 *vr0 = *vr1;
1022 vr1->type = VR_UNDEFINED;
1025 return vr0->type != VR_UNDEFINED;
1028 /* Extract the components of a value range into a pair of wide ints in
1029 [WMIN, WMAX].
1031 If the value range is anything but a VR_RANGE of constants, the
1032 resulting wide ints are set to [-MIN, +MAX] for the type. */
1034 static void inline
1035 extract_range_into_wide_ints (value_range *vr,
1036 signop sign, unsigned prec,
1037 wide_int *wmin, wide_int *wmax)
1039 if (range_int_cst_p (vr))
1041 *wmin = wi::to_wide (vr->min);
1042 *wmax = wi::to_wide (vr->max);
1044 else
1046 *wmin = wi::min_value (prec, sign);
1047 *wmax = wi::max_value (prec, sign);
1051 /* Value range wrapper for wide_int_range_shift_undefined_p. */
1053 static inline bool
1054 vrp_shift_undefined_p (const value_range &shifter, unsigned prec)
1056 tree type = TREE_TYPE (shifter.min);
1057 return wide_int_range_shift_undefined_p (TYPE_SIGN (type), prec,
1058 wi::to_wide (shifter.min),
1059 wi::to_wide (shifter.max));
1062 /* Value range wrapper for wide_int_range_multiplicative_op:
1064 *VR = *VR0 .CODE. *VR1. */
1066 static void
1067 extract_range_from_multiplicative_op (value_range *vr,
1068 enum tree_code code,
1069 value_range *vr0, value_range *vr1)
1071 gcc_assert (code == MULT_EXPR
1072 || code == TRUNC_DIV_EXPR
1073 || code == FLOOR_DIV_EXPR
1074 || code == CEIL_DIV_EXPR
1075 || code == EXACT_DIV_EXPR
1076 || code == ROUND_DIV_EXPR
1077 || code == RSHIFT_EXPR
1078 || code == LSHIFT_EXPR);
1079 gcc_assert (vr0->type == VR_RANGE && vr0->type == vr1->type);
1081 tree type = TREE_TYPE (vr0->min);
1082 wide_int res_lb, res_ub;
1083 wide_int vr0_lb = wi::to_wide (vr0->min);
1084 wide_int vr0_ub = wi::to_wide (vr0->max);
1085 wide_int vr1_lb = wi::to_wide (vr1->min);
1086 wide_int vr1_ub = wi::to_wide (vr1->max);
1087 bool overflow_undefined = TYPE_OVERFLOW_UNDEFINED (type);
1088 bool overflow_wraps = TYPE_OVERFLOW_WRAPS (type);
1089 unsigned prec = TYPE_PRECISION (type);
1091 if (wide_int_range_multiplicative_op (res_lb, res_ub,
1092 code, TYPE_SIGN (type), prec,
1093 vr0_lb, vr0_ub, vr1_lb, vr1_ub,
1094 overflow_undefined, overflow_wraps))
1095 set_and_canonicalize_value_range (vr, VR_RANGE,
1096 wide_int_to_tree (type, res_lb),
1097 wide_int_to_tree (type, res_ub), NULL);
1098 else
1099 set_value_range_to_varying (vr);
1102 /* Value range wrapper for wide_int_range_can_optimize_bit_op.
1104 If a bit operation on two ranges can be easily optimized in terms
1105 of a mask, store the optimized new range in VR and return TRUE. */
1107 static bool
1108 vrp_can_optimize_bit_op (value_range *vr, enum tree_code code,
1109 value_range *vr0, value_range *vr1)
1111 tree lower_bound, upper_bound, mask;
1112 if (code != BIT_AND_EXPR && code != BIT_IOR_EXPR)
1113 return false;
1114 if (range_int_cst_singleton_p (vr1))
1116 if (!range_int_cst_p (vr0))
1117 return false;
1118 mask = vr1->min;
1119 lower_bound = vr0->min;
1120 upper_bound = vr0->max;
1122 else if (range_int_cst_singleton_p (vr0))
1124 if (!range_int_cst_p (vr1))
1125 return false;
1126 mask = vr0->min;
1127 lower_bound = vr1->min;
1128 upper_bound = vr1->max;
1130 else
1131 return false;
1132 if (wide_int_range_can_optimize_bit_op (code,
1133 wi::to_wide (lower_bound),
1134 wi::to_wide (upper_bound),
1135 wi::to_wide (mask)))
1137 tree min = int_const_binop (code, lower_bound, mask);
1138 tree max = int_const_binop (code, upper_bound, mask);
1139 set_value_range (vr, VR_RANGE, min, max, NULL);
1140 return true;
1142 return false;
1145 /* If BOUND will include a symbolic bound, adjust it accordingly,
1146 otherwise leave it as is.
1148 CODE is the original operation that combined the bounds (PLUS_EXPR
1149 or MINUS_EXPR).
1151 TYPE is the type of the original operation.
1153 SYM_OPn is the symbolic for OPn if it has a symbolic.
1155 NEG_OPn is TRUE if the OPn was negated. */
1157 static void
1158 adjust_symbolic_bound (tree &bound, enum tree_code code, tree type,
1159 tree sym_op0, tree sym_op1,
1160 bool neg_op0, bool neg_op1)
1162 bool minus_p = (code == MINUS_EXPR);
1163 /* If the result bound is constant, we're done; otherwise, build the
1164 symbolic lower bound. */
1165 if (sym_op0 == sym_op1)
1167 else if (sym_op0)
1168 bound = build_symbolic_expr (type, sym_op0,
1169 neg_op0, bound);
1170 else if (sym_op1)
1172 /* We may not negate if that might introduce
1173 undefined overflow. */
1174 if (!minus_p
1175 || neg_op1
1176 || TYPE_OVERFLOW_WRAPS (type))
1177 bound = build_symbolic_expr (type, sym_op1,
1178 neg_op1 ^ minus_p, bound);
1179 else
1180 bound = NULL_TREE;
1184 /* Combine OP1 and OP1, which are two parts of a bound, into one wide
1185 int bound according to CODE. CODE is the operation combining the
1186 bound (either a PLUS_EXPR or a MINUS_EXPR).
1188 TYPE is the type of the combine operation.
1190 WI is the wide int to store the result.
1192 OVF is -1 if an underflow occurred, +1 if an overflow occurred or 0
1193 if over/underflow occurred. */
1195 static void
1196 combine_bound (enum tree_code code, wide_int &wi, wi::overflow_type &ovf,
1197 tree type, tree op0, tree op1)
1199 bool minus_p = (code == MINUS_EXPR);
1200 const signop sgn = TYPE_SIGN (type);
1201 const unsigned int prec = TYPE_PRECISION (type);
1203 /* Combine the bounds, if any. */
1204 if (op0 && op1)
1206 if (minus_p)
1207 wi = wi::sub (wi::to_wide (op0), wi::to_wide (op1), sgn, &ovf);
1208 else
1209 wi = wi::add (wi::to_wide (op0), wi::to_wide (op1), sgn, &ovf);
1211 else if (op0)
1212 wi = wi::to_wide (op0);
1213 else if (op1)
1215 if (minus_p)
1216 wi = wi::neg (wi::to_wide (op1), &ovf);
1217 else
1218 wi = wi::to_wide (op1);
1220 else
1221 wi = wi::shwi (0, prec);
1224 /* Given a range in [WMIN, WMAX], adjust it for possible overflow and
1225 put the result in VR.
1227 TYPE is the type of the range.
1229 MIN_OVF and MAX_OVF indicate what type of overflow, if any,
1230 occurred while originally calculating WMIN or WMAX. -1 indicates
1231 underflow. +1 indicates overflow. 0 indicates neither. */
1233 static void
1234 set_value_range_with_overflow (value_range &vr,
1235 tree type,
1236 const wide_int &wmin, const wide_int &wmax,
1237 wi::overflow_type min_ovf,
1238 wi::overflow_type max_ovf)
1240 const signop sgn = TYPE_SIGN (type);
1241 const unsigned int prec = TYPE_PRECISION (type);
1242 vr.type = VR_RANGE;
1243 vr.equiv = NULL;
1244 if (TYPE_OVERFLOW_WRAPS (type))
1246 /* If overflow wraps, truncate the values and adjust the
1247 range kind and bounds appropriately. */
1248 wide_int tmin = wide_int::from (wmin, prec, sgn);
1249 wide_int tmax = wide_int::from (wmax, prec, sgn);
1250 if ((min_ovf != wi::OVF_NONE) == (max_ovf != wi::OVF_NONE))
1252 /* No overflow or both overflow or underflow. The
1253 range kind stays VR_RANGE. */
1254 vr.min = wide_int_to_tree (type, tmin);
1255 vr.max = wide_int_to_tree (type, tmax);
1257 else if ((min_ovf == wi::OVF_UNDERFLOW && max_ovf == wi::OVF_NONE)
1258 || (max_ovf == wi::OVF_OVERFLOW && min_ovf == wi::OVF_NONE))
1260 /* Min underflow or max overflow. The range kind
1261 changes to VR_ANTI_RANGE. */
1262 bool covers = false;
1263 wide_int tem = tmin;
1264 vr.type = VR_ANTI_RANGE;
1265 tmin = tmax + 1;
1266 if (wi::cmp (tmin, tmax, sgn) < 0)
1267 covers = true;
1268 tmax = tem - 1;
1269 if (wi::cmp (tmax, tem, sgn) > 0)
1270 covers = true;
1271 /* If the anti-range would cover nothing, drop to varying.
1272 Likewise if the anti-range bounds are outside of the
1273 types values. */
1274 if (covers || wi::cmp (tmin, tmax, sgn) > 0)
1276 set_value_range_to_varying (&vr);
1277 return;
1279 vr.min = wide_int_to_tree (type, tmin);
1280 vr.max = wide_int_to_tree (type, tmax);
1282 else
1284 /* Other underflow and/or overflow, drop to VR_VARYING. */
1285 set_value_range_to_varying (&vr);
1286 return;
1289 else
1291 /* If overflow does not wrap, saturate to the types min/max
1292 value. */
1293 wide_int type_min = wi::min_value (prec, sgn);
1294 wide_int type_max = wi::max_value (prec, sgn);
1295 if (min_ovf == wi::OVF_UNDERFLOW)
1296 vr.min = wide_int_to_tree (type, type_min);
1297 else if (min_ovf == wi::OVF_OVERFLOW)
1298 vr.min = wide_int_to_tree (type, type_max);
1299 else
1300 vr.min = wide_int_to_tree (type, wmin);
1302 if (max_ovf == wi::OVF_UNDERFLOW)
1303 vr.max = wide_int_to_tree (type, type_min);
1304 else if (max_ovf == wi::OVF_OVERFLOW)
1305 vr.max = wide_int_to_tree (type, type_max);
1306 else
1307 vr.max = wide_int_to_tree (type, wmax);
1311 /* Extract range information from a binary operation CODE based on
1312 the ranges of each of its operands *VR0 and *VR1 with resulting
1313 type EXPR_TYPE. The resulting range is stored in *VR. */
1315 void
1316 extract_range_from_binary_expr_1 (value_range *vr,
1317 enum tree_code code, tree expr_type,
1318 value_range *vr0_, value_range *vr1_)
1320 signop sign = TYPE_SIGN (expr_type);
1321 unsigned int prec = TYPE_PRECISION (expr_type);
1322 value_range vr0 = *vr0_, vr1 = *vr1_;
1323 value_range vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
1324 enum value_range_type type;
1325 tree min = NULL_TREE, max = NULL_TREE;
1326 int cmp;
1328 if (!INTEGRAL_TYPE_P (expr_type)
1329 && !POINTER_TYPE_P (expr_type))
1331 set_value_range_to_varying (vr);
1332 return;
1335 /* Not all binary expressions can be applied to ranges in a
1336 meaningful way. Handle only arithmetic operations. */
1337 if (code != PLUS_EXPR
1338 && code != MINUS_EXPR
1339 && code != POINTER_PLUS_EXPR
1340 && code != MULT_EXPR
1341 && code != TRUNC_DIV_EXPR
1342 && code != FLOOR_DIV_EXPR
1343 && code != CEIL_DIV_EXPR
1344 && code != EXACT_DIV_EXPR
1345 && code != ROUND_DIV_EXPR
1346 && code != TRUNC_MOD_EXPR
1347 && code != RSHIFT_EXPR
1348 && code != LSHIFT_EXPR
1349 && code != MIN_EXPR
1350 && code != MAX_EXPR
1351 && code != BIT_AND_EXPR
1352 && code != BIT_IOR_EXPR
1353 && code != BIT_XOR_EXPR)
1355 set_value_range_to_varying (vr);
1356 return;
1359 /* If both ranges are UNDEFINED, so is the result. */
1360 if (vr0.type == VR_UNDEFINED && vr1.type == VR_UNDEFINED)
1362 set_value_range_to_undefined (vr);
1363 return;
1365 /* If one of the ranges is UNDEFINED drop it to VARYING for the following
1366 code. At some point we may want to special-case operations that
1367 have UNDEFINED result for all or some value-ranges of the not UNDEFINED
1368 operand. */
1369 else if (vr0.type == VR_UNDEFINED)
1370 set_value_range_to_varying (&vr0);
1371 else if (vr1.type == VR_UNDEFINED)
1372 set_value_range_to_varying (&vr1);
1374 /* We get imprecise results from ranges_from_anti_range when
1375 code is EXACT_DIV_EXPR. We could mask out bits in the resulting
1376 range, but then we also need to hack up vrp_meet. It's just
1377 easier to special case when vr0 is ~[0,0] for EXACT_DIV_EXPR. */
1378 if (code == EXACT_DIV_EXPR
1379 && vr0.type == VR_ANTI_RANGE
1380 && vr0.min == vr0.max
1381 && integer_zerop (vr0.min))
1383 set_value_range_to_nonnull (vr, expr_type);
1384 return;
1387 /* Now canonicalize anti-ranges to ranges when they are not symbolic
1388 and express ~[] op X as ([]' op X) U ([]'' op X). */
1389 if (vr0.type == VR_ANTI_RANGE
1390 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
1392 extract_range_from_binary_expr_1 (vr, code, expr_type, &vrtem0, vr1_);
1393 if (vrtem1.type != VR_UNDEFINED)
1395 value_range vrres = VR_INITIALIZER;
1396 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
1397 &vrtem1, vr1_);
1398 vrp_meet (vr, &vrres);
1400 return;
1402 /* Likewise for X op ~[]. */
1403 if (vr1.type == VR_ANTI_RANGE
1404 && ranges_from_anti_range (&vr1, &vrtem0, &vrtem1))
1406 extract_range_from_binary_expr_1 (vr, code, expr_type, vr0_, &vrtem0);
1407 if (vrtem1.type != VR_UNDEFINED)
1409 value_range vrres = VR_INITIALIZER;
1410 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
1411 vr0_, &vrtem1);
1412 vrp_meet (vr, &vrres);
1414 return;
1417 /* The type of the resulting value range defaults to VR0.TYPE. */
1418 type = vr0.type;
1420 /* Refuse to operate on VARYING ranges, ranges of different kinds
1421 and symbolic ranges. As an exception, we allow BIT_{AND,IOR}
1422 because we may be able to derive a useful range even if one of
1423 the operands is VR_VARYING or symbolic range. Similarly for
1424 divisions, MIN/MAX and PLUS/MINUS.
1426 TODO, we may be able to derive anti-ranges in some cases. */
1427 if (code != BIT_AND_EXPR
1428 && code != BIT_IOR_EXPR
1429 && code != TRUNC_DIV_EXPR
1430 && code != FLOOR_DIV_EXPR
1431 && code != CEIL_DIV_EXPR
1432 && code != EXACT_DIV_EXPR
1433 && code != ROUND_DIV_EXPR
1434 && code != TRUNC_MOD_EXPR
1435 && code != MIN_EXPR
1436 && code != MAX_EXPR
1437 && code != PLUS_EXPR
1438 && code != MINUS_EXPR
1439 && code != RSHIFT_EXPR
1440 && code != POINTER_PLUS_EXPR
1441 && (vr0.type == VR_VARYING
1442 || vr1.type == VR_VARYING
1443 || vr0.type != vr1.type
1444 || symbolic_range_p (&vr0)
1445 || symbolic_range_p (&vr1)))
1447 set_value_range_to_varying (vr);
1448 return;
1451 /* Now evaluate the expression to determine the new range. */
1452 if (POINTER_TYPE_P (expr_type))
1454 if (code == MIN_EXPR || code == MAX_EXPR)
1456 /* For MIN/MAX expressions with pointers, we only care about
1457 nullness, if both are non null, then the result is nonnull.
1458 If both are null, then the result is null. Otherwise they
1459 are varying. */
1460 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
1461 set_value_range_to_nonnull (vr, expr_type);
1462 else if (range_is_null (&vr0) && range_is_null (&vr1))
1463 set_value_range_to_null (vr, expr_type);
1464 else
1465 set_value_range_to_varying (vr);
1467 else if (code == POINTER_PLUS_EXPR)
1469 /* For pointer types, we are really only interested in asserting
1470 whether the expression evaluates to non-NULL. */
1471 if (range_is_nonnull (&vr0)
1472 || range_is_nonnull (&vr1)
1473 || (vr1.type == VR_RANGE
1474 && !symbolic_range_p (&vr1)
1475 && !range_includes_zero_p (vr1.min, vr1.max)))
1476 set_value_range_to_nonnull (vr, expr_type);
1477 else if (range_is_null (&vr0) && range_is_null (&vr1))
1478 set_value_range_to_null (vr, expr_type);
1479 else
1480 set_value_range_to_varying (vr);
1482 else if (code == BIT_AND_EXPR)
1484 /* For pointer types, we are really only interested in asserting
1485 whether the expression evaluates to non-NULL. */
1486 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
1487 set_value_range_to_nonnull (vr, expr_type);
1488 else if (range_is_null (&vr0) || range_is_null (&vr1))
1489 set_value_range_to_null (vr, expr_type);
1490 else
1491 set_value_range_to_varying (vr);
1493 else
1494 set_value_range_to_varying (vr);
1496 return;
1499 /* For integer ranges, apply the operation to each end of the
1500 range and see what we end up with. */
1501 if (code == PLUS_EXPR || code == MINUS_EXPR)
1503 const bool minus_p = (code == MINUS_EXPR);
1504 tree min_op0 = vr0.min;
1505 tree min_op1 = minus_p ? vr1.max : vr1.min;
1506 tree max_op0 = vr0.max;
1507 tree max_op1 = minus_p ? vr1.min : vr1.max;
1508 tree sym_min_op0 = NULL_TREE;
1509 tree sym_min_op1 = NULL_TREE;
1510 tree sym_max_op0 = NULL_TREE;
1511 tree sym_max_op1 = NULL_TREE;
1512 bool neg_min_op0, neg_min_op1, neg_max_op0, neg_max_op1;
1514 neg_min_op0 = neg_min_op1 = neg_max_op0 = neg_max_op1 = false;
1516 /* If we have a PLUS or MINUS with two VR_RANGEs, either constant or
1517 single-symbolic ranges, try to compute the precise resulting range,
1518 but only if we know that this resulting range will also be constant
1519 or single-symbolic. */
1520 if (vr0.type == VR_RANGE && vr1.type == VR_RANGE
1521 && (TREE_CODE (min_op0) == INTEGER_CST
1522 || (sym_min_op0
1523 = get_single_symbol (min_op0, &neg_min_op0, &min_op0)))
1524 && (TREE_CODE (min_op1) == INTEGER_CST
1525 || (sym_min_op1
1526 = get_single_symbol (min_op1, &neg_min_op1, &min_op1)))
1527 && (!(sym_min_op0 && sym_min_op1)
1528 || (sym_min_op0 == sym_min_op1
1529 && neg_min_op0 == (minus_p ? neg_min_op1 : !neg_min_op1)))
1530 && (TREE_CODE (max_op0) == INTEGER_CST
1531 || (sym_max_op0
1532 = get_single_symbol (max_op0, &neg_max_op0, &max_op0)))
1533 && (TREE_CODE (max_op1) == INTEGER_CST
1534 || (sym_max_op1
1535 = get_single_symbol (max_op1, &neg_max_op1, &max_op1)))
1536 && (!(sym_max_op0 && sym_max_op1)
1537 || (sym_max_op0 == sym_max_op1
1538 && neg_max_op0 == (minus_p ? neg_max_op1 : !neg_max_op1))))
1540 wide_int wmin, wmax;
1541 wi::overflow_type min_ovf = wi::OVF_NONE;
1542 wi::overflow_type max_ovf = wi::OVF_NONE;
1544 /* Build the bounds. */
1545 combine_bound (code, wmin, min_ovf, expr_type, min_op0, min_op1);
1546 combine_bound (code, wmax, max_ovf, expr_type, max_op0, max_op1);
1548 /* If we have overflow for the constant part and the resulting
1549 range will be symbolic, drop to VR_VARYING. */
1550 if (((bool)min_ovf && sym_min_op0 != sym_min_op1)
1551 || ((bool)max_ovf && sym_max_op0 != sym_max_op1))
1553 set_value_range_to_varying (vr);
1554 return;
1557 /* Adjust the range for possible overflow. */
1558 set_value_range_with_overflow (*vr, expr_type,
1559 wmin, wmax, min_ovf, max_ovf);
1560 if (vr->type == VR_VARYING)
1561 return;
1563 /* Build the symbolic bounds if needed. */
1564 adjust_symbolic_bound (vr->min, code, expr_type,
1565 sym_min_op0, sym_min_op1,
1566 neg_min_op0, neg_min_op1);
1567 adjust_symbolic_bound (vr->max, code, expr_type,
1568 sym_max_op0, sym_max_op1,
1569 neg_max_op0, neg_max_op1);
1570 /* ?? It would probably be cleaner to eliminate min/max/type
1571 entirely and hold these values in VR directly. */
1572 min = vr->min;
1573 max = vr->max;
1574 type = vr->type;
1576 else
1578 /* For other cases, for example if we have a PLUS_EXPR with two
1579 VR_ANTI_RANGEs, drop to VR_VARYING. It would take more effort
1580 to compute a precise range for such a case.
1581 ??? General even mixed range kind operations can be expressed
1582 by for example transforming ~[3, 5] + [1, 2] to range-only
1583 operations and a union primitive:
1584 [-INF, 2] + [1, 2] U [5, +INF] + [1, 2]
1585 [-INF+1, 4] U [6, +INF(OVF)]
1586 though usually the union is not exactly representable with
1587 a single range or anti-range as the above is
1588 [-INF+1, +INF(OVF)] intersected with ~[5, 5]
1589 but one could use a scheme similar to equivalences for this. */
1590 set_value_range_to_varying (vr);
1591 return;
1594 else if (code == MIN_EXPR
1595 || code == MAX_EXPR)
1597 wide_int wmin, wmax;
1598 wide_int vr0_min, vr0_max;
1599 wide_int vr1_min, vr1_max;
1600 extract_range_into_wide_ints (&vr0, sign, prec, &vr0_min, &vr0_max);
1601 extract_range_into_wide_ints (&vr1, sign, prec, &vr1_min, &vr1_max);
1602 if (wide_int_range_min_max (wmin, wmax, code, sign, prec,
1603 vr0_min, vr0_max, vr1_min, vr1_max))
1604 set_value_range (vr, VR_RANGE,
1605 wide_int_to_tree (expr_type, wmin),
1606 wide_int_to_tree (expr_type, wmax), NULL);
1607 else
1608 set_value_range_to_varying (vr);
1609 return;
1611 else if (code == MULT_EXPR)
1613 if (!range_int_cst_p (&vr0)
1614 || !range_int_cst_p (&vr1))
1616 set_value_range_to_varying (vr);
1617 return;
1619 extract_range_from_multiplicative_op (vr, code, &vr0, &vr1);
1620 return;
1622 else if (code == RSHIFT_EXPR
1623 || code == LSHIFT_EXPR)
1625 if (range_int_cst_p (&vr1)
1626 && !vrp_shift_undefined_p (vr1, prec))
1628 if (code == RSHIFT_EXPR)
1630 /* Even if vr0 is VARYING or otherwise not usable, we can derive
1631 useful ranges just from the shift count. E.g.
1632 x >> 63 for signed 64-bit x is always [-1, 0]. */
1633 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
1635 vr0.type = type = VR_RANGE;
1636 vr0.min = vrp_val_min (expr_type);
1637 vr0.max = vrp_val_max (expr_type);
1639 extract_range_from_multiplicative_op (vr, code, &vr0, &vr1);
1640 return;
1642 else if (code == LSHIFT_EXPR
1643 && range_int_cst_p (&vr0))
1645 wide_int res_lb, res_ub;
1646 if (wide_int_range_lshift (res_lb, res_ub, sign, prec,
1647 wi::to_wide (vr0.min),
1648 wi::to_wide (vr0.max),
1649 wi::to_wide (vr1.min),
1650 wi::to_wide (vr1.max),
1651 TYPE_OVERFLOW_UNDEFINED (expr_type),
1652 TYPE_OVERFLOW_WRAPS (expr_type)))
1654 min = wide_int_to_tree (expr_type, res_lb);
1655 max = wide_int_to_tree (expr_type, res_ub);
1656 set_and_canonicalize_value_range (vr, VR_RANGE,
1657 min, max, NULL);
1658 return;
1662 set_value_range_to_varying (vr);
1663 return;
1665 else if (code == TRUNC_DIV_EXPR
1666 || code == FLOOR_DIV_EXPR
1667 || code == CEIL_DIV_EXPR
1668 || code == EXACT_DIV_EXPR
1669 || code == ROUND_DIV_EXPR)
1671 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
1673 /* For division, if op1 has VR_RANGE but op0 does not, something
1674 can be deduced just from that range. Say [min, max] / [4, max]
1675 gives [min / 4, max / 4] range. */
1676 if (vr1.type == VR_RANGE
1677 && !symbolic_range_p (&vr1)
1678 && range_includes_zero_p (vr1.min, vr1.max) == 0)
1680 vr0.type = type = VR_RANGE;
1681 vr0.min = vrp_val_min (expr_type);
1682 vr0.max = vrp_val_max (expr_type);
1684 else
1686 set_value_range_to_varying (vr);
1687 return;
1691 /* For divisions, if flag_non_call_exceptions is true, we must
1692 not eliminate a division by zero. */
1693 if (cfun->can_throw_non_call_exceptions
1694 && (vr1.type != VR_RANGE
1695 || range_includes_zero_p (vr1.min, vr1.max) != 0))
1697 set_value_range_to_varying (vr);
1698 return;
1701 /* For divisions, if op0 is VR_RANGE, we can deduce a range
1702 even if op1 is VR_VARYING, VR_ANTI_RANGE, symbolic or can
1703 include 0. */
1704 if (vr0.type == VR_RANGE
1705 && (vr1.type != VR_RANGE
1706 || range_includes_zero_p (vr1.min, vr1.max) != 0))
1708 tree zero = build_int_cst (TREE_TYPE (vr0.min), 0);
1709 int cmp;
1711 min = NULL_TREE;
1712 max = NULL_TREE;
1713 if (TYPE_UNSIGNED (expr_type)
1714 || value_range_nonnegative_p (&vr1))
1716 /* For unsigned division or when divisor is known
1717 to be non-negative, the range has to cover
1718 all numbers from 0 to max for positive max
1719 and all numbers from min to 0 for negative min. */
1720 cmp = compare_values (vr0.max, zero);
1721 if (cmp == -1)
1723 /* When vr0.max < 0, vr1.min != 0 and value
1724 ranges for dividend and divisor are available. */
1725 if (vr1.type == VR_RANGE
1726 && !symbolic_range_p (&vr0)
1727 && !symbolic_range_p (&vr1)
1728 && compare_values (vr1.min, zero) != 0)
1729 max = int_const_binop (code, vr0.max, vr1.min);
1730 else
1731 max = zero;
1733 else if (cmp == 0 || cmp == 1)
1734 max = vr0.max;
1735 else
1736 type = VR_VARYING;
1737 cmp = compare_values (vr0.min, zero);
1738 if (cmp == 1)
1740 /* For unsigned division when value ranges for dividend
1741 and divisor are available. */
1742 if (vr1.type == VR_RANGE
1743 && !symbolic_range_p (&vr0)
1744 && !symbolic_range_p (&vr1)
1745 && compare_values (vr1.max, zero) != 0)
1746 min = int_const_binop (code, vr0.min, vr1.max);
1747 else
1748 min = zero;
1750 else if (cmp == 0 || cmp == -1)
1751 min = vr0.min;
1752 else
1753 type = VR_VARYING;
1755 else
1757 /* Otherwise the range is -max .. max or min .. -min
1758 depending on which bound is bigger in absolute value,
1759 as the division can change the sign. */
1760 abs_extent_range (vr, vr0.min, vr0.max);
1761 return;
1763 if (type == VR_VARYING)
1765 set_value_range_to_varying (vr);
1766 return;
1769 else if (range_int_cst_p (&vr0) && range_int_cst_p (&vr1))
1771 extract_range_from_multiplicative_op (vr, code, &vr0, &vr1);
1772 return;
1775 else if (code == TRUNC_MOD_EXPR)
1777 if (range_is_null (&vr1))
1779 set_value_range_to_undefined (vr);
1780 return;
1782 wide_int wmin, wmax, tmp;
1783 wide_int vr0_min, vr0_max, vr1_min, vr1_max;
1784 extract_range_into_wide_ints (&vr0, sign, prec, &vr0_min, &vr0_max);
1785 extract_range_into_wide_ints (&vr1, sign, prec, &vr1_min, &vr1_max);
1786 wide_int_range_trunc_mod (wmin, wmax, sign, prec,
1787 vr0_min, vr0_max, vr1_min, vr1_max);
1788 min = wide_int_to_tree (expr_type, wmin);
1789 max = wide_int_to_tree (expr_type, wmax);
1790 set_value_range (vr, VR_RANGE, min, max, NULL);
1791 return;
1793 else if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR || code == BIT_XOR_EXPR)
1795 if (vrp_can_optimize_bit_op (vr, code, &vr0, &vr1))
1796 return;
1798 wide_int may_be_nonzero0, may_be_nonzero1;
1799 wide_int must_be_nonzero0, must_be_nonzero1;
1800 wide_int wmin, wmax;
1801 wide_int vr0_min, vr0_max, vr1_min, vr1_max;
1802 vrp_set_zero_nonzero_bits (expr_type, &vr0,
1803 &may_be_nonzero0, &must_be_nonzero0);
1804 vrp_set_zero_nonzero_bits (expr_type, &vr1,
1805 &may_be_nonzero1, &must_be_nonzero1);
1806 extract_range_into_wide_ints (&vr0, sign, prec, &vr0_min, &vr0_max);
1807 extract_range_into_wide_ints (&vr1, sign, prec, &vr1_min, &vr1_max);
1808 if (code == BIT_AND_EXPR)
1810 if (wide_int_range_bit_and (wmin, wmax, sign, prec,
1811 vr0_min, vr0_max,
1812 vr1_min, vr1_max,
1813 must_be_nonzero0,
1814 may_be_nonzero0,
1815 must_be_nonzero1,
1816 may_be_nonzero1))
1818 min = wide_int_to_tree (expr_type, wmin);
1819 max = wide_int_to_tree (expr_type, wmax);
1820 set_value_range (vr, VR_RANGE, min, max, NULL);
1822 else
1823 set_value_range_to_varying (vr);
1824 return;
1826 else if (code == BIT_IOR_EXPR)
1828 if (wide_int_range_bit_ior (wmin, wmax, sign,
1829 vr0_min, vr0_max,
1830 vr1_min, vr1_max,
1831 must_be_nonzero0,
1832 may_be_nonzero0,
1833 must_be_nonzero1,
1834 may_be_nonzero1))
1836 min = wide_int_to_tree (expr_type, wmin);
1837 max = wide_int_to_tree (expr_type, wmax);
1838 set_value_range (vr, VR_RANGE, min, max, NULL);
1840 else
1841 set_value_range_to_varying (vr);
1842 return;
1844 else if (code == BIT_XOR_EXPR)
1846 if (wide_int_range_bit_xor (wmin, wmax, sign, prec,
1847 must_be_nonzero0,
1848 may_be_nonzero0,
1849 must_be_nonzero1,
1850 may_be_nonzero1))
1852 min = wide_int_to_tree (expr_type, wmin);
1853 max = wide_int_to_tree (expr_type, wmax);
1854 set_value_range (vr, VR_RANGE, min, max, NULL);
1856 else
1857 set_value_range_to_varying (vr);
1858 return;
1861 else
1862 gcc_unreachable ();
1864 /* If either MIN or MAX overflowed, then set the resulting range to
1865 VARYING. */
1866 if (min == NULL_TREE
1867 || TREE_OVERFLOW_P (min)
1868 || max == NULL_TREE
1869 || TREE_OVERFLOW_P (max))
1871 set_value_range_to_varying (vr);
1872 return;
1875 /* We punt for [-INF, +INF].
1876 We learn nothing when we have INF on both sides.
1877 Note that we do accept [-INF, -INF] and [+INF, +INF]. */
1878 if (vrp_val_is_min (min) && vrp_val_is_max (max))
1880 set_value_range_to_varying (vr);
1881 return;
1884 cmp = compare_values (min, max);
1885 if (cmp == -2 || cmp == 1)
1887 /* If the new range has its limits swapped around (MIN > MAX),
1888 then the operation caused one of them to wrap around, mark
1889 the new range VARYING. */
1890 set_value_range_to_varying (vr);
1892 else
1893 set_value_range (vr, type, min, max, NULL);
1896 /* Extract range information from a unary operation CODE based on
1897 the range of its operand *VR0 with type OP0_TYPE with resulting type TYPE.
1898 The resulting range is stored in *VR. */
1900 void
1901 extract_range_from_unary_expr (value_range *vr,
1902 enum tree_code code, tree type,
1903 value_range *vr0_, tree op0_type)
1905 signop sign = TYPE_SIGN (type);
1906 unsigned int prec = TYPE_PRECISION (type);
1907 value_range vr0 = *vr0_, vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
1909 /* VRP only operates on integral and pointer types. */
1910 if (!(INTEGRAL_TYPE_P (op0_type)
1911 || POINTER_TYPE_P (op0_type))
1912 || !(INTEGRAL_TYPE_P (type)
1913 || POINTER_TYPE_P (type)))
1915 set_value_range_to_varying (vr);
1916 return;
1919 /* If VR0 is UNDEFINED, so is the result. */
1920 if (vr0.type == VR_UNDEFINED)
1922 set_value_range_to_undefined (vr);
1923 return;
1926 /* Handle operations that we express in terms of others. */
1927 if (code == PAREN_EXPR || code == OBJ_TYPE_REF)
1929 /* PAREN_EXPR and OBJ_TYPE_REF are simple copies. */
1930 copy_value_range (vr, &vr0);
1931 return;
1933 else if (code == NEGATE_EXPR)
1935 /* -X is simply 0 - X, so re-use existing code that also handles
1936 anti-ranges fine. */
1937 value_range zero = VR_INITIALIZER;
1938 set_value_range_to_value (&zero, build_int_cst (type, 0), NULL);
1939 extract_range_from_binary_expr_1 (vr, MINUS_EXPR, type, &zero, &vr0);
1940 return;
1942 else if (code == BIT_NOT_EXPR)
1944 /* ~X is simply -1 - X, so re-use existing code that also handles
1945 anti-ranges fine. */
1946 value_range minusone = VR_INITIALIZER;
1947 set_value_range_to_value (&minusone, build_int_cst (type, -1), NULL);
1948 extract_range_from_binary_expr_1 (vr, MINUS_EXPR,
1949 type, &minusone, &vr0);
1950 return;
1953 /* Now canonicalize anti-ranges to ranges when they are not symbolic
1954 and express op ~[] as (op []') U (op []''). */
1955 if (vr0.type == VR_ANTI_RANGE
1956 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
1958 extract_range_from_unary_expr (vr, code, type, &vrtem0, op0_type);
1959 if (vrtem1.type != VR_UNDEFINED)
1961 value_range vrres = VR_INITIALIZER;
1962 extract_range_from_unary_expr (&vrres, code, type,
1963 &vrtem1, op0_type);
1964 vrp_meet (vr, &vrres);
1966 return;
1969 if (CONVERT_EXPR_CODE_P (code))
1971 tree inner_type = op0_type;
1972 tree outer_type = type;
1974 /* If the expression evaluates to a pointer, we are only interested in
1975 determining if it evaluates to NULL [0, 0] or non-NULL (~[0, 0]). */
1976 if (POINTER_TYPE_P (type))
1978 if (range_is_nonnull (&vr0))
1979 set_value_range_to_nonnull (vr, type);
1980 else if (range_is_null (&vr0))
1981 set_value_range_to_null (vr, type);
1982 else
1983 set_value_range_to_varying (vr);
1984 return;
1987 /* If VR0 is varying and we increase the type precision, assume
1988 a full range for the following transformation. */
1989 if (vr0.type == VR_VARYING
1990 && INTEGRAL_TYPE_P (inner_type)
1991 && TYPE_PRECISION (inner_type) < TYPE_PRECISION (outer_type))
1993 vr0.type = VR_RANGE;
1994 vr0.min = TYPE_MIN_VALUE (inner_type);
1995 vr0.max = TYPE_MAX_VALUE (inner_type);
1998 /* If VR0 is a constant range or anti-range and the conversion is
1999 not truncating we can convert the min and max values and
2000 canonicalize the resulting range. Otherwise we can do the
2001 conversion if the size of the range is less than what the
2002 precision of the target type can represent and the range is
2003 not an anti-range. */
2004 if ((vr0.type == VR_RANGE
2005 || vr0.type == VR_ANTI_RANGE)
2006 && TREE_CODE (vr0.min) == INTEGER_CST
2007 && TREE_CODE (vr0.max) == INTEGER_CST
2008 && (TYPE_PRECISION (outer_type) >= TYPE_PRECISION (inner_type)
2009 || (vr0.type == VR_RANGE
2010 && integer_zerop (int_const_binop (RSHIFT_EXPR,
2011 int_const_binop (MINUS_EXPR, vr0.max, vr0.min),
2012 size_int (TYPE_PRECISION (outer_type)))))))
2014 tree new_min, new_max;
2015 new_min = force_fit_type (outer_type, wi::to_widest (vr0.min),
2016 0, false);
2017 new_max = force_fit_type (outer_type, wi::to_widest (vr0.max),
2018 0, false);
2019 set_and_canonicalize_value_range (vr, vr0.type,
2020 new_min, new_max, NULL);
2021 return;
2024 set_value_range_to_varying (vr);
2025 return;
2027 else if (code == ABS_EXPR)
2029 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
2031 set_value_range_to_varying (vr);
2032 return;
2034 wide_int wmin, wmax;
2035 wide_int vr0_min, vr0_max;
2036 extract_range_into_wide_ints (&vr0, sign, prec, &vr0_min, &vr0_max);
2037 if (wide_int_range_abs (wmin, wmax, sign, prec, vr0_min, vr0_max,
2038 TYPE_OVERFLOW_UNDEFINED (type)))
2039 set_value_range (vr, VR_RANGE,
2040 wide_int_to_tree (type, wmin),
2041 wide_int_to_tree (type, wmax), NULL);
2042 else
2043 set_value_range_to_varying (vr);
2044 return;
2047 /* For unhandled operations fall back to varying. */
2048 set_value_range_to_varying (vr);
2049 return;
2052 /* Debugging dumps. */
2054 void dump_value_range (FILE *, const value_range *);
2055 void debug_value_range (value_range *);
2056 void dump_all_value_ranges (FILE *);
2057 void dump_vr_equiv (FILE *, bitmap);
2058 void debug_vr_equiv (bitmap);
2061 /* Dump value range VR to FILE. */
2063 void
2064 dump_value_range (FILE *file, const value_range *vr)
2066 if (vr == NULL)
2067 fprintf (file, "[]");
2068 else if (vr->type == VR_UNDEFINED)
2069 fprintf (file, "UNDEFINED");
2070 else if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
2072 tree type = TREE_TYPE (vr->min);
2074 fprintf (file, "%s[", (vr->type == VR_ANTI_RANGE) ? "~" : "");
2076 if (INTEGRAL_TYPE_P (type)
2077 && !TYPE_UNSIGNED (type)
2078 && vrp_val_is_min (vr->min))
2079 fprintf (file, "-INF");
2080 else
2081 print_generic_expr (file, vr->min);
2083 fprintf (file, ", ");
2085 if (INTEGRAL_TYPE_P (type)
2086 && vrp_val_is_max (vr->max))
2087 fprintf (file, "+INF");
2088 else
2089 print_generic_expr (file, vr->max);
2091 fprintf (file, "]");
2093 if (vr->equiv)
2095 bitmap_iterator bi;
2096 unsigned i, c = 0;
2098 fprintf (file, " EQUIVALENCES: { ");
2100 EXECUTE_IF_SET_IN_BITMAP (vr->equiv, 0, i, bi)
2102 print_generic_expr (file, ssa_name (i));
2103 fprintf (file, " ");
2104 c++;
2107 fprintf (file, "} (%u elements)", c);
2110 else if (vr->type == VR_VARYING)
2111 fprintf (file, "VARYING");
2112 else
2113 fprintf (file, "INVALID RANGE");
2117 /* Dump value range VR to stderr. */
2119 DEBUG_FUNCTION void
2120 debug_value_range (value_range *vr)
2122 dump_value_range (stderr, vr);
2123 fprintf (stderr, "\n");
2126 void
2127 value_range::dump ()
2129 debug_value_range (this);
2133 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
2134 create a new SSA name N and return the assertion assignment
2135 'N = ASSERT_EXPR <V, V OP W>'. */
2137 static gimple *
2138 build_assert_expr_for (tree cond, tree v)
2140 tree a;
2141 gassign *assertion;
2143 gcc_assert (TREE_CODE (v) == SSA_NAME
2144 && COMPARISON_CLASS_P (cond));
2146 a = build2 (ASSERT_EXPR, TREE_TYPE (v), v, cond);
2147 assertion = gimple_build_assign (NULL_TREE, a);
2149 /* The new ASSERT_EXPR, creates a new SSA name that replaces the
2150 operand of the ASSERT_EXPR. Create it so the new name and the old one
2151 are registered in the replacement table so that we can fix the SSA web
2152 after adding all the ASSERT_EXPRs. */
2153 tree new_def = create_new_def_for (v, assertion, NULL);
2154 /* Make sure we preserve abnormalness throughout an ASSERT_EXPR chain
2155 given we have to be able to fully propagate those out to re-create
2156 valid SSA when removing the asserts. */
2157 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (v))
2158 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_def) = 1;
2160 return assertion;
2164 /* Return false if EXPR is a predicate expression involving floating
2165 point values. */
2167 static inline bool
2168 fp_predicate (gimple *stmt)
2170 GIMPLE_CHECK (stmt, GIMPLE_COND);
2172 return FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)));
2175 /* If the range of values taken by OP can be inferred after STMT executes,
2176 return the comparison code (COMP_CODE_P) and value (VAL_P) that
2177 describes the inferred range. Return true if a range could be
2178 inferred. */
2180 bool
2181 infer_value_range (gimple *stmt, tree op, tree_code *comp_code_p, tree *val_p)
2183 *val_p = NULL_TREE;
2184 *comp_code_p = ERROR_MARK;
2186 /* Do not attempt to infer anything in names that flow through
2187 abnormal edges. */
2188 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
2189 return false;
2191 /* If STMT is the last statement of a basic block with no normal
2192 successors, there is no point inferring anything about any of its
2193 operands. We would not be able to find a proper insertion point
2194 for the assertion, anyway. */
2195 if (stmt_ends_bb_p (stmt))
2197 edge_iterator ei;
2198 edge e;
2200 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
2201 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
2202 break;
2203 if (e == NULL)
2204 return false;
2207 if (infer_nonnull_range (stmt, op))
2209 *val_p = build_int_cst (TREE_TYPE (op), 0);
2210 *comp_code_p = NE_EXPR;
2211 return true;
2214 return false;
2218 void dump_asserts_for (FILE *, tree);
2219 void debug_asserts_for (tree);
2220 void dump_all_asserts (FILE *);
2221 void debug_all_asserts (void);
2223 /* Dump all the registered assertions for NAME to FILE. */
2225 void
2226 dump_asserts_for (FILE *file, tree name)
2228 assert_locus *loc;
2230 fprintf (file, "Assertions to be inserted for ");
2231 print_generic_expr (file, name);
2232 fprintf (file, "\n");
2234 loc = asserts_for[SSA_NAME_VERSION (name)];
2235 while (loc)
2237 fprintf (file, "\t");
2238 print_gimple_stmt (file, gsi_stmt (loc->si), 0);
2239 fprintf (file, "\n\tBB #%d", loc->bb->index);
2240 if (loc->e)
2242 fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
2243 loc->e->dest->index);
2244 dump_edge_info (file, loc->e, dump_flags, 0);
2246 fprintf (file, "\n\tPREDICATE: ");
2247 print_generic_expr (file, loc->expr);
2248 fprintf (file, " %s ", get_tree_code_name (loc->comp_code));
2249 print_generic_expr (file, loc->val);
2250 fprintf (file, "\n\n");
2251 loc = loc->next;
2254 fprintf (file, "\n");
2258 /* Dump all the registered assertions for NAME to stderr. */
2260 DEBUG_FUNCTION void
2261 debug_asserts_for (tree name)
2263 dump_asserts_for (stderr, name);
2267 /* Dump all the registered assertions for all the names to FILE. */
2269 void
2270 dump_all_asserts (FILE *file)
2272 unsigned i;
2273 bitmap_iterator bi;
2275 fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
2276 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
2277 dump_asserts_for (file, ssa_name (i));
2278 fprintf (file, "\n");
2282 /* Dump all the registered assertions for all the names to stderr. */
2284 DEBUG_FUNCTION void
2285 debug_all_asserts (void)
2287 dump_all_asserts (stderr);
2290 /* Push the assert info for NAME, EXPR, COMP_CODE and VAL to ASSERTS. */
2292 static void
2293 add_assert_info (vec<assert_info> &asserts,
2294 tree name, tree expr, enum tree_code comp_code, tree val)
2296 assert_info info;
2297 info.comp_code = comp_code;
2298 info.name = name;
2299 if (TREE_OVERFLOW_P (val))
2300 val = drop_tree_overflow (val);
2301 info.val = val;
2302 info.expr = expr;
2303 asserts.safe_push (info);
2306 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
2307 'EXPR COMP_CODE VAL' at a location that dominates block BB or
2308 E->DEST, then register this location as a possible insertion point
2309 for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
2311 BB, E and SI provide the exact insertion point for the new
2312 ASSERT_EXPR. If BB is NULL, then the ASSERT_EXPR is to be inserted
2313 on edge E. Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
2314 BB. If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
2315 must not be NULL. */
2317 static void
2318 register_new_assert_for (tree name, tree expr,
2319 enum tree_code comp_code,
2320 tree val,
2321 basic_block bb,
2322 edge e,
2323 gimple_stmt_iterator si)
2325 assert_locus *n, *loc, *last_loc;
2326 basic_block dest_bb;
2328 gcc_checking_assert (bb == NULL || e == NULL);
2330 if (e == NULL)
2331 gcc_checking_assert (gimple_code (gsi_stmt (si)) != GIMPLE_COND
2332 && gimple_code (gsi_stmt (si)) != GIMPLE_SWITCH);
2334 /* Never build an assert comparing against an integer constant with
2335 TREE_OVERFLOW set. This confuses our undefined overflow warning
2336 machinery. */
2337 if (TREE_OVERFLOW_P (val))
2338 val = drop_tree_overflow (val);
2340 /* The new assertion A will be inserted at BB or E. We need to
2341 determine if the new location is dominated by a previously
2342 registered location for A. If we are doing an edge insertion,
2343 assume that A will be inserted at E->DEST. Note that this is not
2344 necessarily true.
2346 If E is a critical edge, it will be split. But even if E is
2347 split, the new block will dominate the same set of blocks that
2348 E->DEST dominates.
2350 The reverse, however, is not true, blocks dominated by E->DEST
2351 will not be dominated by the new block created to split E. So,
2352 if the insertion location is on a critical edge, we will not use
2353 the new location to move another assertion previously registered
2354 at a block dominated by E->DEST. */
2355 dest_bb = (bb) ? bb : e->dest;
2357 /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
2358 VAL at a block dominating DEST_BB, then we don't need to insert a new
2359 one. Similarly, if the same assertion already exists at a block
2360 dominated by DEST_BB and the new location is not on a critical
2361 edge, then update the existing location for the assertion (i.e.,
2362 move the assertion up in the dominance tree).
2364 Note, this is implemented as a simple linked list because there
2365 should not be more than a handful of assertions registered per
2366 name. If this becomes a performance problem, a table hashed by
2367 COMP_CODE and VAL could be implemented. */
2368 loc = asserts_for[SSA_NAME_VERSION (name)];
2369 last_loc = loc;
2370 while (loc)
2372 if (loc->comp_code == comp_code
2373 && (loc->val == val
2374 || operand_equal_p (loc->val, val, 0))
2375 && (loc->expr == expr
2376 || operand_equal_p (loc->expr, expr, 0)))
2378 /* If E is not a critical edge and DEST_BB
2379 dominates the existing location for the assertion, move
2380 the assertion up in the dominance tree by updating its
2381 location information. */
2382 if ((e == NULL || !EDGE_CRITICAL_P (e))
2383 && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
2385 loc->bb = dest_bb;
2386 loc->e = e;
2387 loc->si = si;
2388 return;
2392 /* Update the last node of the list and move to the next one. */
2393 last_loc = loc;
2394 loc = loc->next;
2397 /* If we didn't find an assertion already registered for
2398 NAME COMP_CODE VAL, add a new one at the end of the list of
2399 assertions associated with NAME. */
2400 n = XNEW (struct assert_locus);
2401 n->bb = dest_bb;
2402 n->e = e;
2403 n->si = si;
2404 n->comp_code = comp_code;
2405 n->val = val;
2406 n->expr = expr;
2407 n->next = NULL;
2409 if (last_loc)
2410 last_loc->next = n;
2411 else
2412 asserts_for[SSA_NAME_VERSION (name)] = n;
2414 bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
2417 /* (COND_OP0 COND_CODE COND_OP1) is a predicate which uses NAME.
2418 Extract a suitable test code and value and store them into *CODE_P and
2419 *VAL_P so the predicate is normalized to NAME *CODE_P *VAL_P.
2421 If no extraction was possible, return FALSE, otherwise return TRUE.
2423 If INVERT is true, then we invert the result stored into *CODE_P. */
2425 static bool
2426 extract_code_and_val_from_cond_with_ops (tree name, enum tree_code cond_code,
2427 tree cond_op0, tree cond_op1,
2428 bool invert, enum tree_code *code_p,
2429 tree *val_p)
2431 enum tree_code comp_code;
2432 tree val;
2434 /* Otherwise, we have a comparison of the form NAME COMP VAL
2435 or VAL COMP NAME. */
2436 if (name == cond_op1)
2438 /* If the predicate is of the form VAL COMP NAME, flip
2439 COMP around because we need to register NAME as the
2440 first operand in the predicate. */
2441 comp_code = swap_tree_comparison (cond_code);
2442 val = cond_op0;
2444 else if (name == cond_op0)
2446 /* The comparison is of the form NAME COMP VAL, so the
2447 comparison code remains unchanged. */
2448 comp_code = cond_code;
2449 val = cond_op1;
2451 else
2452 gcc_unreachable ();
2454 /* Invert the comparison code as necessary. */
2455 if (invert)
2456 comp_code = invert_tree_comparison (comp_code, 0);
2458 /* VRP only handles integral and pointer types. */
2459 if (! INTEGRAL_TYPE_P (TREE_TYPE (val))
2460 && ! POINTER_TYPE_P (TREE_TYPE (val)))
2461 return false;
2463 /* Do not register always-false predicates.
2464 FIXME: this works around a limitation in fold() when dealing with
2465 enumerations. Given 'enum { N1, N2 } x;', fold will not
2466 fold 'if (x > N2)' to 'if (0)'. */
2467 if ((comp_code == GT_EXPR || comp_code == LT_EXPR)
2468 && INTEGRAL_TYPE_P (TREE_TYPE (val)))
2470 tree min = TYPE_MIN_VALUE (TREE_TYPE (val));
2471 tree max = TYPE_MAX_VALUE (TREE_TYPE (val));
2473 if (comp_code == GT_EXPR
2474 && (!max
2475 || compare_values (val, max) == 0))
2476 return false;
2478 if (comp_code == LT_EXPR
2479 && (!min
2480 || compare_values (val, min) == 0))
2481 return false;
2483 *code_p = comp_code;
2484 *val_p = val;
2485 return true;
2488 /* Find out smallest RES where RES > VAL && (RES & MASK) == RES, if any
2489 (otherwise return VAL). VAL and MASK must be zero-extended for
2490 precision PREC. If SGNBIT is non-zero, first xor VAL with SGNBIT
2491 (to transform signed values into unsigned) and at the end xor
2492 SGNBIT back. */
2494 static wide_int
2495 masked_increment (const wide_int &val_in, const wide_int &mask,
2496 const wide_int &sgnbit, unsigned int prec)
2498 wide_int bit = wi::one (prec), res;
2499 unsigned int i;
2501 wide_int val = val_in ^ sgnbit;
2502 for (i = 0; i < prec; i++, bit += bit)
2504 res = mask;
2505 if ((res & bit) == 0)
2506 continue;
2507 res = bit - 1;
2508 res = wi::bit_and_not (val + bit, res);
2509 res &= mask;
2510 if (wi::gtu_p (res, val))
2511 return res ^ sgnbit;
2513 return val ^ sgnbit;
2516 /* Helper for overflow_comparison_p
2518 OP0 CODE OP1 is a comparison. Examine the comparison and potentially
2519 OP1's defining statement to see if it ultimately has the form
2520 OP0 CODE (OP0 PLUS INTEGER_CST)
2522 If so, return TRUE indicating this is an overflow test and store into
2523 *NEW_CST an updated constant that can be used in a narrowed range test.
2525 REVERSED indicates if the comparison was originally:
2527 OP1 CODE' OP0.
2529 This affects how we build the updated constant. */
2531 static bool
2532 overflow_comparison_p_1 (enum tree_code code, tree op0, tree op1,
2533 bool follow_assert_exprs, bool reversed, tree *new_cst)
2535 /* See if this is a relational operation between two SSA_NAMES with
2536 unsigned, overflow wrapping values. If so, check it more deeply. */
2537 if ((code == LT_EXPR || code == LE_EXPR
2538 || code == GE_EXPR || code == GT_EXPR)
2539 && TREE_CODE (op0) == SSA_NAME
2540 && TREE_CODE (op1) == SSA_NAME
2541 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
2542 && TYPE_UNSIGNED (TREE_TYPE (op0))
2543 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0)))
2545 gimple *op1_def = SSA_NAME_DEF_STMT (op1);
2547 /* If requested, follow any ASSERT_EXPRs backwards for OP1. */
2548 if (follow_assert_exprs)
2550 while (gimple_assign_single_p (op1_def)
2551 && TREE_CODE (gimple_assign_rhs1 (op1_def)) == ASSERT_EXPR)
2553 op1 = TREE_OPERAND (gimple_assign_rhs1 (op1_def), 0);
2554 if (TREE_CODE (op1) != SSA_NAME)
2555 break;
2556 op1_def = SSA_NAME_DEF_STMT (op1);
2560 /* Now look at the defining statement of OP1 to see if it adds
2561 or subtracts a nonzero constant from another operand. */
2562 if (op1_def
2563 && is_gimple_assign (op1_def)
2564 && gimple_assign_rhs_code (op1_def) == PLUS_EXPR
2565 && TREE_CODE (gimple_assign_rhs2 (op1_def)) == INTEGER_CST
2566 && !integer_zerop (gimple_assign_rhs2 (op1_def)))
2568 tree target = gimple_assign_rhs1 (op1_def);
2570 /* If requested, follow ASSERT_EXPRs backwards for op0 looking
2571 for one where TARGET appears on the RHS. */
2572 if (follow_assert_exprs)
2574 /* Now see if that "other operand" is op0, following the chain
2575 of ASSERT_EXPRs if necessary. */
2576 gimple *op0_def = SSA_NAME_DEF_STMT (op0);
2577 while (op0 != target
2578 && gimple_assign_single_p (op0_def)
2579 && TREE_CODE (gimple_assign_rhs1 (op0_def)) == ASSERT_EXPR)
2581 op0 = TREE_OPERAND (gimple_assign_rhs1 (op0_def), 0);
2582 if (TREE_CODE (op0) != SSA_NAME)
2583 break;
2584 op0_def = SSA_NAME_DEF_STMT (op0);
2588 /* If we did not find our target SSA_NAME, then this is not
2589 an overflow test. */
2590 if (op0 != target)
2591 return false;
2593 tree type = TREE_TYPE (op0);
2594 wide_int max = wi::max_value (TYPE_PRECISION (type), UNSIGNED);
2595 tree inc = gimple_assign_rhs2 (op1_def);
2596 if (reversed)
2597 *new_cst = wide_int_to_tree (type, max + wi::to_wide (inc));
2598 else
2599 *new_cst = wide_int_to_tree (type, max - wi::to_wide (inc));
2600 return true;
2603 return false;
2606 /* OP0 CODE OP1 is a comparison. Examine the comparison and potentially
2607 OP1's defining statement to see if it ultimately has the form
2608 OP0 CODE (OP0 PLUS INTEGER_CST)
2610 If so, return TRUE indicating this is an overflow test and store into
2611 *NEW_CST an updated constant that can be used in a narrowed range test.
2613 These statements are left as-is in the IL to facilitate discovery of
2614 {ADD,SUB}_OVERFLOW sequences later in the optimizer pipeline. But
2615 the alternate range representation is often useful within VRP. */
2617 bool
2618 overflow_comparison_p (tree_code code, tree name, tree val,
2619 bool use_equiv_p, tree *new_cst)
2621 if (overflow_comparison_p_1 (code, name, val, use_equiv_p, false, new_cst))
2622 return true;
2623 return overflow_comparison_p_1 (swap_tree_comparison (code), val, name,
2624 use_equiv_p, true, new_cst);
2628 /* Try to register an edge assertion for SSA name NAME on edge E for
2629 the condition COND contributing to the conditional jump pointed to by BSI.
2630 Invert the condition COND if INVERT is true. */
2632 static void
2633 register_edge_assert_for_2 (tree name, edge e,
2634 enum tree_code cond_code,
2635 tree cond_op0, tree cond_op1, bool invert,
2636 vec<assert_info> &asserts)
2638 tree val;
2639 enum tree_code comp_code;
2641 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
2642 cond_op0,
2643 cond_op1,
2644 invert, &comp_code, &val))
2645 return;
2647 /* Queue the assert. */
2648 tree x;
2649 if (overflow_comparison_p (comp_code, name, val, false, &x))
2651 enum tree_code new_code = ((comp_code == GT_EXPR || comp_code == GE_EXPR)
2652 ? GT_EXPR : LE_EXPR);
2653 add_assert_info (asserts, name, name, new_code, x);
2655 add_assert_info (asserts, name, name, comp_code, val);
2657 /* In the case of NAME <= CST and NAME being defined as
2658 NAME = (unsigned) NAME2 + CST2 we can assert NAME2 >= -CST2
2659 and NAME2 <= CST - CST2. We can do the same for NAME > CST.
2660 This catches range and anti-range tests. */
2661 if ((comp_code == LE_EXPR
2662 || comp_code == GT_EXPR)
2663 && TREE_CODE (val) == INTEGER_CST
2664 && TYPE_UNSIGNED (TREE_TYPE (val)))
2666 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
2667 tree cst2 = NULL_TREE, name2 = NULL_TREE, name3 = NULL_TREE;
2669 /* Extract CST2 from the (optional) addition. */
2670 if (is_gimple_assign (def_stmt)
2671 && gimple_assign_rhs_code (def_stmt) == PLUS_EXPR)
2673 name2 = gimple_assign_rhs1 (def_stmt);
2674 cst2 = gimple_assign_rhs2 (def_stmt);
2675 if (TREE_CODE (name2) == SSA_NAME
2676 && TREE_CODE (cst2) == INTEGER_CST)
2677 def_stmt = SSA_NAME_DEF_STMT (name2);
2680 /* Extract NAME2 from the (optional) sign-changing cast. */
2681 if (gimple_assign_cast_p (def_stmt))
2683 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt))
2684 && ! TYPE_UNSIGNED (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
2685 && (TYPE_PRECISION (gimple_expr_type (def_stmt))
2686 == TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))))
2687 name3 = gimple_assign_rhs1 (def_stmt);
2690 /* If name3 is used later, create an ASSERT_EXPR for it. */
2691 if (name3 != NULL_TREE
2692 && TREE_CODE (name3) == SSA_NAME
2693 && (cst2 == NULL_TREE
2694 || TREE_CODE (cst2) == INTEGER_CST)
2695 && INTEGRAL_TYPE_P (TREE_TYPE (name3)))
2697 tree tmp;
2699 /* Build an expression for the range test. */
2700 tmp = build1 (NOP_EXPR, TREE_TYPE (name), name3);
2701 if (cst2 != NULL_TREE)
2702 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
2704 if (dump_file)
2706 fprintf (dump_file, "Adding assert for ");
2707 print_generic_expr (dump_file, name3);
2708 fprintf (dump_file, " from ");
2709 print_generic_expr (dump_file, tmp);
2710 fprintf (dump_file, "\n");
2713 add_assert_info (asserts, name3, tmp, comp_code, val);
2716 /* If name2 is used later, create an ASSERT_EXPR for it. */
2717 if (name2 != NULL_TREE
2718 && TREE_CODE (name2) == SSA_NAME
2719 && TREE_CODE (cst2) == INTEGER_CST
2720 && INTEGRAL_TYPE_P (TREE_TYPE (name2)))
2722 tree tmp;
2724 /* Build an expression for the range test. */
2725 tmp = name2;
2726 if (TREE_TYPE (name) != TREE_TYPE (name2))
2727 tmp = build1 (NOP_EXPR, TREE_TYPE (name), tmp);
2728 if (cst2 != NULL_TREE)
2729 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
2731 if (dump_file)
2733 fprintf (dump_file, "Adding assert for ");
2734 print_generic_expr (dump_file, name2);
2735 fprintf (dump_file, " from ");
2736 print_generic_expr (dump_file, tmp);
2737 fprintf (dump_file, "\n");
2740 add_assert_info (asserts, name2, tmp, comp_code, val);
2744 /* In the case of post-in/decrement tests like if (i++) ... and uses
2745 of the in/decremented value on the edge the extra name we want to
2746 assert for is not on the def chain of the name compared. Instead
2747 it is in the set of use stmts.
2748 Similar cases happen for conversions that were simplified through
2749 fold_{sign_changed,widened}_comparison. */
2750 if ((comp_code == NE_EXPR
2751 || comp_code == EQ_EXPR)
2752 && TREE_CODE (val) == INTEGER_CST)
2754 imm_use_iterator ui;
2755 gimple *use_stmt;
2756 FOR_EACH_IMM_USE_STMT (use_stmt, ui, name)
2758 if (!is_gimple_assign (use_stmt))
2759 continue;
2761 /* Cut off to use-stmts that are dominating the predecessor. */
2762 if (!dominated_by_p (CDI_DOMINATORS, e->src, gimple_bb (use_stmt)))
2763 continue;
2765 tree name2 = gimple_assign_lhs (use_stmt);
2766 if (TREE_CODE (name2) != SSA_NAME)
2767 continue;
2769 enum tree_code code = gimple_assign_rhs_code (use_stmt);
2770 tree cst;
2771 if (code == PLUS_EXPR
2772 || code == MINUS_EXPR)
2774 cst = gimple_assign_rhs2 (use_stmt);
2775 if (TREE_CODE (cst) != INTEGER_CST)
2776 continue;
2777 cst = int_const_binop (code, val, cst);
2779 else if (CONVERT_EXPR_CODE_P (code))
2781 /* For truncating conversions we cannot record
2782 an inequality. */
2783 if (comp_code == NE_EXPR
2784 && (TYPE_PRECISION (TREE_TYPE (name2))
2785 < TYPE_PRECISION (TREE_TYPE (name))))
2786 continue;
2787 cst = fold_convert (TREE_TYPE (name2), val);
2789 else
2790 continue;
2792 if (TREE_OVERFLOW_P (cst))
2793 cst = drop_tree_overflow (cst);
2794 add_assert_info (asserts, name2, name2, comp_code, cst);
2798 if (TREE_CODE_CLASS (comp_code) == tcc_comparison
2799 && TREE_CODE (val) == INTEGER_CST)
2801 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
2802 tree name2 = NULL_TREE, names[2], cst2 = NULL_TREE;
2803 tree val2 = NULL_TREE;
2804 unsigned int prec = TYPE_PRECISION (TREE_TYPE (val));
2805 wide_int mask = wi::zero (prec);
2806 unsigned int nprec = prec;
2807 enum tree_code rhs_code = ERROR_MARK;
2809 if (is_gimple_assign (def_stmt))
2810 rhs_code = gimple_assign_rhs_code (def_stmt);
2812 /* In the case of NAME != CST1 where NAME = A +- CST2 we can
2813 assert that A != CST1 -+ CST2. */
2814 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
2815 && (rhs_code == PLUS_EXPR || rhs_code == MINUS_EXPR))
2817 tree op0 = gimple_assign_rhs1 (def_stmt);
2818 tree op1 = gimple_assign_rhs2 (def_stmt);
2819 if (TREE_CODE (op0) == SSA_NAME
2820 && TREE_CODE (op1) == INTEGER_CST)
2822 enum tree_code reverse_op = (rhs_code == PLUS_EXPR
2823 ? MINUS_EXPR : PLUS_EXPR);
2824 op1 = int_const_binop (reverse_op, val, op1);
2825 if (TREE_OVERFLOW (op1))
2826 op1 = drop_tree_overflow (op1);
2827 add_assert_info (asserts, op0, op0, comp_code, op1);
2831 /* Add asserts for NAME cmp CST and NAME being defined
2832 as NAME = (int) NAME2. */
2833 if (!TYPE_UNSIGNED (TREE_TYPE (val))
2834 && (comp_code == LE_EXPR || comp_code == LT_EXPR
2835 || comp_code == GT_EXPR || comp_code == GE_EXPR)
2836 && gimple_assign_cast_p (def_stmt))
2838 name2 = gimple_assign_rhs1 (def_stmt);
2839 if (CONVERT_EXPR_CODE_P (rhs_code)
2840 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
2841 && TYPE_UNSIGNED (TREE_TYPE (name2))
2842 && prec == TYPE_PRECISION (TREE_TYPE (name2))
2843 && (comp_code == LE_EXPR || comp_code == GT_EXPR
2844 || !tree_int_cst_equal (val,
2845 TYPE_MIN_VALUE (TREE_TYPE (val)))))
2847 tree tmp, cst;
2848 enum tree_code new_comp_code = comp_code;
2850 cst = fold_convert (TREE_TYPE (name2),
2851 TYPE_MIN_VALUE (TREE_TYPE (val)));
2852 /* Build an expression for the range test. */
2853 tmp = build2 (PLUS_EXPR, TREE_TYPE (name2), name2, cst);
2854 cst = fold_build2 (PLUS_EXPR, TREE_TYPE (name2), cst,
2855 fold_convert (TREE_TYPE (name2), val));
2856 if (comp_code == LT_EXPR || comp_code == GE_EXPR)
2858 new_comp_code = comp_code == LT_EXPR ? LE_EXPR : GT_EXPR;
2859 cst = fold_build2 (MINUS_EXPR, TREE_TYPE (name2), cst,
2860 build_int_cst (TREE_TYPE (name2), 1));
2863 if (dump_file)
2865 fprintf (dump_file, "Adding assert for ");
2866 print_generic_expr (dump_file, name2);
2867 fprintf (dump_file, " from ");
2868 print_generic_expr (dump_file, tmp);
2869 fprintf (dump_file, "\n");
2872 add_assert_info (asserts, name2, tmp, new_comp_code, cst);
2876 /* Add asserts for NAME cmp CST and NAME being defined as
2877 NAME = NAME2 >> CST2.
2879 Extract CST2 from the right shift. */
2880 if (rhs_code == RSHIFT_EXPR)
2882 name2 = gimple_assign_rhs1 (def_stmt);
2883 cst2 = gimple_assign_rhs2 (def_stmt);
2884 if (TREE_CODE (name2) == SSA_NAME
2885 && tree_fits_uhwi_p (cst2)
2886 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
2887 && IN_RANGE (tree_to_uhwi (cst2), 1, prec - 1)
2888 && type_has_mode_precision_p (TREE_TYPE (val)))
2890 mask = wi::mask (tree_to_uhwi (cst2), false, prec);
2891 val2 = fold_binary (LSHIFT_EXPR, TREE_TYPE (val), val, cst2);
2894 if (val2 != NULL_TREE
2895 && TREE_CODE (val2) == INTEGER_CST
2896 && simple_cst_equal (fold_build2 (RSHIFT_EXPR,
2897 TREE_TYPE (val),
2898 val2, cst2), val))
2900 enum tree_code new_comp_code = comp_code;
2901 tree tmp, new_val;
2903 tmp = name2;
2904 if (comp_code == EQ_EXPR || comp_code == NE_EXPR)
2906 if (!TYPE_UNSIGNED (TREE_TYPE (val)))
2908 tree type = build_nonstandard_integer_type (prec, 1);
2909 tmp = build1 (NOP_EXPR, type, name2);
2910 val2 = fold_convert (type, val2);
2912 tmp = fold_build2 (MINUS_EXPR, TREE_TYPE (tmp), tmp, val2);
2913 new_val = wide_int_to_tree (TREE_TYPE (tmp), mask);
2914 new_comp_code = comp_code == EQ_EXPR ? LE_EXPR : GT_EXPR;
2916 else if (comp_code == LT_EXPR || comp_code == GE_EXPR)
2918 wide_int minval
2919 = wi::min_value (prec, TYPE_SIGN (TREE_TYPE (val)));
2920 new_val = val2;
2921 if (minval == wi::to_wide (new_val))
2922 new_val = NULL_TREE;
2924 else
2926 wide_int maxval
2927 = wi::max_value (prec, TYPE_SIGN (TREE_TYPE (val)));
2928 mask |= wi::to_wide (val2);
2929 if (wi::eq_p (mask, maxval))
2930 new_val = NULL_TREE;
2931 else
2932 new_val = wide_int_to_tree (TREE_TYPE (val2), mask);
2935 if (new_val)
2937 if (dump_file)
2939 fprintf (dump_file, "Adding assert for ");
2940 print_generic_expr (dump_file, name2);
2941 fprintf (dump_file, " from ");
2942 print_generic_expr (dump_file, tmp);
2943 fprintf (dump_file, "\n");
2946 add_assert_info (asserts, name2, tmp, new_comp_code, new_val);
2950 /* Add asserts for NAME cmp CST and NAME being defined as
2951 NAME = NAME2 & CST2.
2953 Extract CST2 from the and.
2955 Also handle
2956 NAME = (unsigned) NAME2;
2957 casts where NAME's type is unsigned and has smaller precision
2958 than NAME2's type as if it was NAME = NAME2 & MASK. */
2959 names[0] = NULL_TREE;
2960 names[1] = NULL_TREE;
2961 cst2 = NULL_TREE;
2962 if (rhs_code == BIT_AND_EXPR
2963 || (CONVERT_EXPR_CODE_P (rhs_code)
2964 && INTEGRAL_TYPE_P (TREE_TYPE (val))
2965 && TYPE_UNSIGNED (TREE_TYPE (val))
2966 && TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
2967 > prec))
2969 name2 = gimple_assign_rhs1 (def_stmt);
2970 if (rhs_code == BIT_AND_EXPR)
2971 cst2 = gimple_assign_rhs2 (def_stmt);
2972 else
2974 cst2 = TYPE_MAX_VALUE (TREE_TYPE (val));
2975 nprec = TYPE_PRECISION (TREE_TYPE (name2));
2977 if (TREE_CODE (name2) == SSA_NAME
2978 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
2979 && TREE_CODE (cst2) == INTEGER_CST
2980 && !integer_zerop (cst2)
2981 && (nprec > 1
2982 || TYPE_UNSIGNED (TREE_TYPE (val))))
2984 gimple *def_stmt2 = SSA_NAME_DEF_STMT (name2);
2985 if (gimple_assign_cast_p (def_stmt2))
2987 names[1] = gimple_assign_rhs1 (def_stmt2);
2988 if (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt2))
2989 || !INTEGRAL_TYPE_P (TREE_TYPE (names[1]))
2990 || (TYPE_PRECISION (TREE_TYPE (name2))
2991 != TYPE_PRECISION (TREE_TYPE (names[1]))))
2992 names[1] = NULL_TREE;
2994 names[0] = name2;
2997 if (names[0] || names[1])
2999 wide_int minv, maxv, valv, cst2v;
3000 wide_int tem, sgnbit;
3001 bool valid_p = false, valn, cst2n;
3002 enum tree_code ccode = comp_code;
3004 valv = wide_int::from (wi::to_wide (val), nprec, UNSIGNED);
3005 cst2v = wide_int::from (wi::to_wide (cst2), nprec, UNSIGNED);
3006 valn = wi::neg_p (valv, TYPE_SIGN (TREE_TYPE (val)));
3007 cst2n = wi::neg_p (cst2v, TYPE_SIGN (TREE_TYPE (val)));
3008 /* If CST2 doesn't have most significant bit set,
3009 but VAL is negative, we have comparison like
3010 if ((x & 0x123) > -4) (always true). Just give up. */
3011 if (!cst2n && valn)
3012 ccode = ERROR_MARK;
3013 if (cst2n)
3014 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
3015 else
3016 sgnbit = wi::zero (nprec);
3017 minv = valv & cst2v;
3018 switch (ccode)
3020 case EQ_EXPR:
3021 /* Minimum unsigned value for equality is VAL & CST2
3022 (should be equal to VAL, otherwise we probably should
3023 have folded the comparison into false) and
3024 maximum unsigned value is VAL | ~CST2. */
3025 maxv = valv | ~cst2v;
3026 valid_p = true;
3027 break;
3029 case NE_EXPR:
3030 tem = valv | ~cst2v;
3031 /* If VAL is 0, handle (X & CST2) != 0 as (X & CST2) > 0U. */
3032 if (valv == 0)
3034 cst2n = false;
3035 sgnbit = wi::zero (nprec);
3036 goto gt_expr;
3038 /* If (VAL | ~CST2) is all ones, handle it as
3039 (X & CST2) < VAL. */
3040 if (tem == -1)
3042 cst2n = false;
3043 valn = false;
3044 sgnbit = wi::zero (nprec);
3045 goto lt_expr;
3047 if (!cst2n && wi::neg_p (cst2v))
3048 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
3049 if (sgnbit != 0)
3051 if (valv == sgnbit)
3053 cst2n = true;
3054 valn = true;
3055 goto gt_expr;
3057 if (tem == wi::mask (nprec - 1, false, nprec))
3059 cst2n = true;
3060 goto lt_expr;
3062 if (!cst2n)
3063 sgnbit = wi::zero (nprec);
3065 break;
3067 case GE_EXPR:
3068 /* Minimum unsigned value for >= if (VAL & CST2) == VAL
3069 is VAL and maximum unsigned value is ~0. For signed
3070 comparison, if CST2 doesn't have most significant bit
3071 set, handle it similarly. If CST2 has MSB set,
3072 the minimum is the same, and maximum is ~0U/2. */
3073 if (minv != valv)
3075 /* If (VAL & CST2) != VAL, X & CST2 can't be equal to
3076 VAL. */
3077 minv = masked_increment (valv, cst2v, sgnbit, nprec);
3078 if (minv == valv)
3079 break;
3081 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
3082 valid_p = true;
3083 break;
3085 case GT_EXPR:
3086 gt_expr:
3087 /* Find out smallest MINV where MINV > VAL
3088 && (MINV & CST2) == MINV, if any. If VAL is signed and
3089 CST2 has MSB set, compute it biased by 1 << (nprec - 1). */
3090 minv = masked_increment (valv, cst2v, sgnbit, nprec);
3091 if (minv == valv)
3092 break;
3093 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
3094 valid_p = true;
3095 break;
3097 case LE_EXPR:
3098 /* Minimum unsigned value for <= is 0 and maximum
3099 unsigned value is VAL | ~CST2 if (VAL & CST2) == VAL.
3100 Otherwise, find smallest VAL2 where VAL2 > VAL
3101 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
3102 as maximum.
3103 For signed comparison, if CST2 doesn't have most
3104 significant bit set, handle it similarly. If CST2 has
3105 MSB set, the maximum is the same and minimum is INT_MIN. */
3106 if (minv == valv)
3107 maxv = valv;
3108 else
3110 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
3111 if (maxv == valv)
3112 break;
3113 maxv -= 1;
3115 maxv |= ~cst2v;
3116 minv = sgnbit;
3117 valid_p = true;
3118 break;
3120 case LT_EXPR:
3121 lt_expr:
3122 /* Minimum unsigned value for < is 0 and maximum
3123 unsigned value is (VAL-1) | ~CST2 if (VAL & CST2) == VAL.
3124 Otherwise, find smallest VAL2 where VAL2 > VAL
3125 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
3126 as maximum.
3127 For signed comparison, if CST2 doesn't have most
3128 significant bit set, handle it similarly. If CST2 has
3129 MSB set, the maximum is the same and minimum is INT_MIN. */
3130 if (minv == valv)
3132 if (valv == sgnbit)
3133 break;
3134 maxv = valv;
3136 else
3138 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
3139 if (maxv == valv)
3140 break;
3142 maxv -= 1;
3143 maxv |= ~cst2v;
3144 minv = sgnbit;
3145 valid_p = true;
3146 break;
3148 default:
3149 break;
3151 if (valid_p
3152 && (maxv - minv) != -1)
3154 tree tmp, new_val, type;
3155 int i;
3157 for (i = 0; i < 2; i++)
3158 if (names[i])
3160 wide_int maxv2 = maxv;
3161 tmp = names[i];
3162 type = TREE_TYPE (names[i]);
3163 if (!TYPE_UNSIGNED (type))
3165 type = build_nonstandard_integer_type (nprec, 1);
3166 tmp = build1 (NOP_EXPR, type, names[i]);
3168 if (minv != 0)
3170 tmp = build2 (PLUS_EXPR, type, tmp,
3171 wide_int_to_tree (type, -minv));
3172 maxv2 = maxv - minv;
3174 new_val = wide_int_to_tree (type, maxv2);
3176 if (dump_file)
3178 fprintf (dump_file, "Adding assert for ");
3179 print_generic_expr (dump_file, names[i]);
3180 fprintf (dump_file, " from ");
3181 print_generic_expr (dump_file, tmp);
3182 fprintf (dump_file, "\n");
3185 add_assert_info (asserts, names[i], tmp, LE_EXPR, new_val);
3192 /* OP is an operand of a truth value expression which is known to have
3193 a particular value. Register any asserts for OP and for any
3194 operands in OP's defining statement.
3196 If CODE is EQ_EXPR, then we want to register OP is zero (false),
3197 if CODE is NE_EXPR, then we want to register OP is nonzero (true). */
3199 static void
3200 register_edge_assert_for_1 (tree op, enum tree_code code,
3201 edge e, vec<assert_info> &asserts)
3203 gimple *op_def;
3204 tree val;
3205 enum tree_code rhs_code;
3207 /* We only care about SSA_NAMEs. */
3208 if (TREE_CODE (op) != SSA_NAME)
3209 return;
3211 /* We know that OP will have a zero or nonzero value. */
3212 val = build_int_cst (TREE_TYPE (op), 0);
3213 add_assert_info (asserts, op, op, code, val);
3215 /* Now look at how OP is set. If it's set from a comparison,
3216 a truth operation or some bit operations, then we may be able
3217 to register information about the operands of that assignment. */
3218 op_def = SSA_NAME_DEF_STMT (op);
3219 if (gimple_code (op_def) != GIMPLE_ASSIGN)
3220 return;
3222 rhs_code = gimple_assign_rhs_code (op_def);
3224 if (TREE_CODE_CLASS (rhs_code) == tcc_comparison)
3226 bool invert = (code == EQ_EXPR ? true : false);
3227 tree op0 = gimple_assign_rhs1 (op_def);
3228 tree op1 = gimple_assign_rhs2 (op_def);
3230 if (TREE_CODE (op0) == SSA_NAME)
3231 register_edge_assert_for_2 (op0, e, rhs_code, op0, op1, invert, asserts);
3232 if (TREE_CODE (op1) == SSA_NAME)
3233 register_edge_assert_for_2 (op1, e, rhs_code, op0, op1, invert, asserts);
3235 else if ((code == NE_EXPR
3236 && gimple_assign_rhs_code (op_def) == BIT_AND_EXPR)
3237 || (code == EQ_EXPR
3238 && gimple_assign_rhs_code (op_def) == BIT_IOR_EXPR))
3240 /* Recurse on each operand. */
3241 tree op0 = gimple_assign_rhs1 (op_def);
3242 tree op1 = gimple_assign_rhs2 (op_def);
3243 if (TREE_CODE (op0) == SSA_NAME
3244 && has_single_use (op0))
3245 register_edge_assert_for_1 (op0, code, e, asserts);
3246 if (TREE_CODE (op1) == SSA_NAME
3247 && has_single_use (op1))
3248 register_edge_assert_for_1 (op1, code, e, asserts);
3250 else if (gimple_assign_rhs_code (op_def) == BIT_NOT_EXPR
3251 && TYPE_PRECISION (TREE_TYPE (gimple_assign_lhs (op_def))) == 1)
3253 /* Recurse, flipping CODE. */
3254 code = invert_tree_comparison (code, false);
3255 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
3257 else if (gimple_assign_rhs_code (op_def) == SSA_NAME)
3259 /* Recurse through the copy. */
3260 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
3262 else if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (op_def)))
3264 /* Recurse through the type conversion, unless it is a narrowing
3265 conversion or conversion from non-integral type. */
3266 tree rhs = gimple_assign_rhs1 (op_def);
3267 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs))
3268 && (TYPE_PRECISION (TREE_TYPE (rhs))
3269 <= TYPE_PRECISION (TREE_TYPE (op))))
3270 register_edge_assert_for_1 (rhs, code, e, asserts);
3274 /* Check if comparison
3275 NAME COND_OP INTEGER_CST
3276 has a form of
3277 (X & 11...100..0) COND_OP XX...X00...0
3278 Such comparison can yield assertions like
3279 X >= XX...X00...0
3280 X <= XX...X11...1
3281 in case of COND_OP being EQ_EXPR or
3282 X < XX...X00...0
3283 X > XX...X11...1
3284 in case of NE_EXPR. */
3286 static bool
3287 is_masked_range_test (tree name, tree valt, enum tree_code cond_code,
3288 tree *new_name, tree *low, enum tree_code *low_code,
3289 tree *high, enum tree_code *high_code)
3291 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3293 if (!is_gimple_assign (def_stmt)
3294 || gimple_assign_rhs_code (def_stmt) != BIT_AND_EXPR)
3295 return false;
3297 tree t = gimple_assign_rhs1 (def_stmt);
3298 tree maskt = gimple_assign_rhs2 (def_stmt);
3299 if (TREE_CODE (t) != SSA_NAME || TREE_CODE (maskt) != INTEGER_CST)
3300 return false;
3302 wi::tree_to_wide_ref mask = wi::to_wide (maskt);
3303 wide_int inv_mask = ~mask;
3304 /* Must have been removed by now so don't bother optimizing. */
3305 if (mask == 0 || inv_mask == 0)
3306 return false;
3308 /* Assume VALT is INTEGER_CST. */
3309 wi::tree_to_wide_ref val = wi::to_wide (valt);
3311 if ((inv_mask & (inv_mask + 1)) != 0
3312 || (val & mask) != val)
3313 return false;
3315 bool is_range = cond_code == EQ_EXPR;
3317 tree type = TREE_TYPE (t);
3318 wide_int min = wi::min_value (type),
3319 max = wi::max_value (type);
3321 if (is_range)
3323 *low_code = val == min ? ERROR_MARK : GE_EXPR;
3324 *high_code = val == max ? ERROR_MARK : LE_EXPR;
3326 else
3328 /* We can still generate assertion if one of alternatives
3329 is known to always be false. */
3330 if (val == min)
3332 *low_code = (enum tree_code) 0;
3333 *high_code = GT_EXPR;
3335 else if ((val | inv_mask) == max)
3337 *low_code = LT_EXPR;
3338 *high_code = (enum tree_code) 0;
3340 else
3341 return false;
3344 *new_name = t;
3345 *low = wide_int_to_tree (type, val);
3346 *high = wide_int_to_tree (type, val | inv_mask);
3348 return true;
3351 /* Try to register an edge assertion for SSA name NAME on edge E for
3352 the condition COND contributing to the conditional jump pointed to by
3353 SI. */
3355 void
3356 register_edge_assert_for (tree name, edge e,
3357 enum tree_code cond_code, tree cond_op0,
3358 tree cond_op1, vec<assert_info> &asserts)
3360 tree val;
3361 enum tree_code comp_code;
3362 bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
3364 /* Do not attempt to infer anything in names that flow through
3365 abnormal edges. */
3366 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
3367 return;
3369 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
3370 cond_op0, cond_op1,
3371 is_else_edge,
3372 &comp_code, &val))
3373 return;
3375 /* Register ASSERT_EXPRs for name. */
3376 register_edge_assert_for_2 (name, e, cond_code, cond_op0,
3377 cond_op1, is_else_edge, asserts);
3380 /* If COND is effectively an equality test of an SSA_NAME against
3381 the value zero or one, then we may be able to assert values
3382 for SSA_NAMEs which flow into COND. */
3384 /* In the case of NAME == 1 or NAME != 0, for BIT_AND_EXPR defining
3385 statement of NAME we can assert both operands of the BIT_AND_EXPR
3386 have nonzero value. */
3387 if (((comp_code == EQ_EXPR && integer_onep (val))
3388 || (comp_code == NE_EXPR && integer_zerop (val))))
3390 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3392 if (is_gimple_assign (def_stmt)
3393 && gimple_assign_rhs_code (def_stmt) == BIT_AND_EXPR)
3395 tree op0 = gimple_assign_rhs1 (def_stmt);
3396 tree op1 = gimple_assign_rhs2 (def_stmt);
3397 register_edge_assert_for_1 (op0, NE_EXPR, e, asserts);
3398 register_edge_assert_for_1 (op1, NE_EXPR, e, asserts);
3402 /* In the case of NAME == 0 or NAME != 1, for BIT_IOR_EXPR defining
3403 statement of NAME we can assert both operands of the BIT_IOR_EXPR
3404 have zero value. */
3405 if (((comp_code == EQ_EXPR && integer_zerop (val))
3406 || (comp_code == NE_EXPR && integer_onep (val))))
3408 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3410 /* For BIT_IOR_EXPR only if NAME == 0 both operands have
3411 necessarily zero value, or if type-precision is one. */
3412 if (is_gimple_assign (def_stmt)
3413 && (gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR
3414 && (TYPE_PRECISION (TREE_TYPE (name)) == 1
3415 || comp_code == EQ_EXPR)))
3417 tree op0 = gimple_assign_rhs1 (def_stmt);
3418 tree op1 = gimple_assign_rhs2 (def_stmt);
3419 register_edge_assert_for_1 (op0, EQ_EXPR, e, asserts);
3420 register_edge_assert_for_1 (op1, EQ_EXPR, e, asserts);
3424 /* Sometimes we can infer ranges from (NAME & MASK) == VALUE. */
3425 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
3426 && TREE_CODE (val) == INTEGER_CST)
3428 enum tree_code low_code, high_code;
3429 tree low, high;
3430 if (is_masked_range_test (name, val, comp_code, &name, &low,
3431 &low_code, &high, &high_code))
3433 if (low_code != ERROR_MARK)
3434 register_edge_assert_for_2 (name, e, low_code, name,
3435 low, /*invert*/false, asserts);
3436 if (high_code != ERROR_MARK)
3437 register_edge_assert_for_2 (name, e, high_code, name,
3438 high, /*invert*/false, asserts);
3443 /* Finish found ASSERTS for E and register them at GSI. */
3445 static void
3446 finish_register_edge_assert_for (edge e, gimple_stmt_iterator gsi,
3447 vec<assert_info> &asserts)
3449 for (unsigned i = 0; i < asserts.length (); ++i)
3450 /* Only register an ASSERT_EXPR if NAME was found in the sub-graph
3451 reachable from E. */
3452 if (live_on_edge (e, asserts[i].name))
3453 register_new_assert_for (asserts[i].name, asserts[i].expr,
3454 asserts[i].comp_code, asserts[i].val,
3455 NULL, e, gsi);
3460 /* Determine whether the outgoing edges of BB should receive an
3461 ASSERT_EXPR for each of the operands of BB's LAST statement.
3462 The last statement of BB must be a COND_EXPR.
3464 If any of the sub-graphs rooted at BB have an interesting use of
3465 the predicate operands, an assert location node is added to the
3466 list of assertions for the corresponding operands. */
3468 static void
3469 find_conditional_asserts (basic_block bb, gcond *last)
3471 gimple_stmt_iterator bsi;
3472 tree op;
3473 edge_iterator ei;
3474 edge e;
3475 ssa_op_iter iter;
3477 bsi = gsi_for_stmt (last);
3479 /* Look for uses of the operands in each of the sub-graphs
3480 rooted at BB. We need to check each of the outgoing edges
3481 separately, so that we know what kind of ASSERT_EXPR to
3482 insert. */
3483 FOR_EACH_EDGE (e, ei, bb->succs)
3485 if (e->dest == bb)
3486 continue;
3488 /* Register the necessary assertions for each operand in the
3489 conditional predicate. */
3490 auto_vec<assert_info, 8> asserts;
3491 FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
3492 register_edge_assert_for (op, e,
3493 gimple_cond_code (last),
3494 gimple_cond_lhs (last),
3495 gimple_cond_rhs (last), asserts);
3496 finish_register_edge_assert_for (e, bsi, asserts);
3500 struct case_info
3502 tree expr;
3503 basic_block bb;
3506 /* Compare two case labels sorting first by the destination bb index
3507 and then by the case value. */
3509 static int
3510 compare_case_labels (const void *p1, const void *p2)
3512 const struct case_info *ci1 = (const struct case_info *) p1;
3513 const struct case_info *ci2 = (const struct case_info *) p2;
3514 int idx1 = ci1->bb->index;
3515 int idx2 = ci2->bb->index;
3517 if (idx1 < idx2)
3518 return -1;
3519 else if (idx1 == idx2)
3521 /* Make sure the default label is first in a group. */
3522 if (!CASE_LOW (ci1->expr))
3523 return -1;
3524 else if (!CASE_LOW (ci2->expr))
3525 return 1;
3526 else
3527 return tree_int_cst_compare (CASE_LOW (ci1->expr),
3528 CASE_LOW (ci2->expr));
3530 else
3531 return 1;
3534 /* Determine whether the outgoing edges of BB should receive an
3535 ASSERT_EXPR for each of the operands of BB's LAST statement.
3536 The last statement of BB must be a SWITCH_EXPR.
3538 If any of the sub-graphs rooted at BB have an interesting use of
3539 the predicate operands, an assert location node is added to the
3540 list of assertions for the corresponding operands. */
3542 static void
3543 find_switch_asserts (basic_block bb, gswitch *last)
3545 gimple_stmt_iterator bsi;
3546 tree op;
3547 edge e;
3548 struct case_info *ci;
3549 size_t n = gimple_switch_num_labels (last);
3550 #if GCC_VERSION >= 4000
3551 unsigned int idx;
3552 #else
3553 /* Work around GCC 3.4 bug (PR 37086). */
3554 volatile unsigned int idx;
3555 #endif
3557 bsi = gsi_for_stmt (last);
3558 op = gimple_switch_index (last);
3559 if (TREE_CODE (op) != SSA_NAME)
3560 return;
3562 /* Build a vector of case labels sorted by destination label. */
3563 ci = XNEWVEC (struct case_info, n);
3564 for (idx = 0; idx < n; ++idx)
3566 ci[idx].expr = gimple_switch_label (last, idx);
3567 ci[idx].bb = label_to_block (CASE_LABEL (ci[idx].expr));
3569 edge default_edge = find_edge (bb, ci[0].bb);
3570 qsort (ci, n, sizeof (struct case_info), compare_case_labels);
3572 for (idx = 0; idx < n; ++idx)
3574 tree min, max;
3575 tree cl = ci[idx].expr;
3576 basic_block cbb = ci[idx].bb;
3578 min = CASE_LOW (cl);
3579 max = CASE_HIGH (cl);
3581 /* If there are multiple case labels with the same destination
3582 we need to combine them to a single value range for the edge. */
3583 if (idx + 1 < n && cbb == ci[idx + 1].bb)
3585 /* Skip labels until the last of the group. */
3586 do {
3587 ++idx;
3588 } while (idx < n && cbb == ci[idx].bb);
3589 --idx;
3591 /* Pick up the maximum of the case label range. */
3592 if (CASE_HIGH (ci[idx].expr))
3593 max = CASE_HIGH (ci[idx].expr);
3594 else
3595 max = CASE_LOW (ci[idx].expr);
3598 /* Can't extract a useful assertion out of a range that includes the
3599 default label. */
3600 if (min == NULL_TREE)
3601 continue;
3603 /* Find the edge to register the assert expr on. */
3604 e = find_edge (bb, cbb);
3606 /* Register the necessary assertions for the operand in the
3607 SWITCH_EXPR. */
3608 auto_vec<assert_info, 8> asserts;
3609 register_edge_assert_for (op, e,
3610 max ? GE_EXPR : EQ_EXPR,
3611 op, fold_convert (TREE_TYPE (op), min),
3612 asserts);
3613 if (max)
3614 register_edge_assert_for (op, e, LE_EXPR, op,
3615 fold_convert (TREE_TYPE (op), max),
3616 asserts);
3617 finish_register_edge_assert_for (e, bsi, asserts);
3620 XDELETEVEC (ci);
3622 if (!live_on_edge (default_edge, op))
3623 return;
3625 /* Now register along the default label assertions that correspond to the
3626 anti-range of each label. */
3627 int insertion_limit = PARAM_VALUE (PARAM_MAX_VRP_SWITCH_ASSERTIONS);
3628 if (insertion_limit == 0)
3629 return;
3631 /* We can't do this if the default case shares a label with another case. */
3632 tree default_cl = gimple_switch_default_label (last);
3633 for (idx = 1; idx < n; idx++)
3635 tree min, max;
3636 tree cl = gimple_switch_label (last, idx);
3637 if (CASE_LABEL (cl) == CASE_LABEL (default_cl))
3638 continue;
3640 min = CASE_LOW (cl);
3641 max = CASE_HIGH (cl);
3643 /* Combine contiguous case ranges to reduce the number of assertions
3644 to insert. */
3645 for (idx = idx + 1; idx < n; idx++)
3647 tree next_min, next_max;
3648 tree next_cl = gimple_switch_label (last, idx);
3649 if (CASE_LABEL (next_cl) == CASE_LABEL (default_cl))
3650 break;
3652 next_min = CASE_LOW (next_cl);
3653 next_max = CASE_HIGH (next_cl);
3655 wide_int difference = (wi::to_wide (next_min)
3656 - wi::to_wide (max ? max : min));
3657 if (wi::eq_p (difference, 1))
3658 max = next_max ? next_max : next_min;
3659 else
3660 break;
3662 idx--;
3664 if (max == NULL_TREE)
3666 /* Register the assertion OP != MIN. */
3667 auto_vec<assert_info, 8> asserts;
3668 min = fold_convert (TREE_TYPE (op), min);
3669 register_edge_assert_for (op, default_edge, NE_EXPR, op, min,
3670 asserts);
3671 finish_register_edge_assert_for (default_edge, bsi, asserts);
3673 else
3675 /* Register the assertion (unsigned)OP - MIN > (MAX - MIN),
3676 which will give OP the anti-range ~[MIN,MAX]. */
3677 tree uop = fold_convert (unsigned_type_for (TREE_TYPE (op)), op);
3678 min = fold_convert (TREE_TYPE (uop), min);
3679 max = fold_convert (TREE_TYPE (uop), max);
3681 tree lhs = fold_build2 (MINUS_EXPR, TREE_TYPE (uop), uop, min);
3682 tree rhs = int_const_binop (MINUS_EXPR, max, min);
3683 register_new_assert_for (op, lhs, GT_EXPR, rhs,
3684 NULL, default_edge, bsi);
3687 if (--insertion_limit == 0)
3688 break;
3693 /* Traverse all the statements in block BB looking for statements that
3694 may generate useful assertions for the SSA names in their operand.
3695 If a statement produces a useful assertion A for name N_i, then the
3696 list of assertions already generated for N_i is scanned to
3697 determine if A is actually needed.
3699 If N_i already had the assertion A at a location dominating the
3700 current location, then nothing needs to be done. Otherwise, the
3701 new location for A is recorded instead.
3703 1- For every statement S in BB, all the variables used by S are
3704 added to bitmap FOUND_IN_SUBGRAPH.
3706 2- If statement S uses an operand N in a way that exposes a known
3707 value range for N, then if N was not already generated by an
3708 ASSERT_EXPR, create a new assert location for N. For instance,
3709 if N is a pointer and the statement dereferences it, we can
3710 assume that N is not NULL.
3712 3- COND_EXPRs are a special case of #2. We can derive range
3713 information from the predicate but need to insert different
3714 ASSERT_EXPRs for each of the sub-graphs rooted at the
3715 conditional block. If the last statement of BB is a conditional
3716 expression of the form 'X op Y', then
3718 a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
3720 b) If the conditional is the only entry point to the sub-graph
3721 corresponding to the THEN_CLAUSE, recurse into it. On
3722 return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
3723 an ASSERT_EXPR is added for the corresponding variable.
3725 c) Repeat step (b) on the ELSE_CLAUSE.
3727 d) Mark X and Y in FOUND_IN_SUBGRAPH.
3729 For instance,
3731 if (a == 9)
3732 b = a;
3733 else
3734 b = c + 1;
3736 In this case, an assertion on the THEN clause is useful to
3737 determine that 'a' is always 9 on that edge. However, an assertion
3738 on the ELSE clause would be unnecessary.
3740 4- If BB does not end in a conditional expression, then we recurse
3741 into BB's dominator children.
3743 At the end of the recursive traversal, every SSA name will have a
3744 list of locations where ASSERT_EXPRs should be added. When a new
3745 location for name N is found, it is registered by calling
3746 register_new_assert_for. That function keeps track of all the
3747 registered assertions to prevent adding unnecessary assertions.
3748 For instance, if a pointer P_4 is dereferenced more than once in a
3749 dominator tree, only the location dominating all the dereference of
3750 P_4 will receive an ASSERT_EXPR. */
3752 static void
3753 find_assert_locations_1 (basic_block bb, sbitmap live)
3755 gimple *last;
3757 last = last_stmt (bb);
3759 /* If BB's last statement is a conditional statement involving integer
3760 operands, determine if we need to add ASSERT_EXPRs. */
3761 if (last
3762 && gimple_code (last) == GIMPLE_COND
3763 && !fp_predicate (last)
3764 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
3765 find_conditional_asserts (bb, as_a <gcond *> (last));
3767 /* If BB's last statement is a switch statement involving integer
3768 operands, determine if we need to add ASSERT_EXPRs. */
3769 if (last
3770 && gimple_code (last) == GIMPLE_SWITCH
3771 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
3772 find_switch_asserts (bb, as_a <gswitch *> (last));
3774 /* Traverse all the statements in BB marking used names and looking
3775 for statements that may infer assertions for their used operands. */
3776 for (gimple_stmt_iterator si = gsi_last_bb (bb); !gsi_end_p (si);
3777 gsi_prev (&si))
3779 gimple *stmt;
3780 tree op;
3781 ssa_op_iter i;
3783 stmt = gsi_stmt (si);
3785 if (is_gimple_debug (stmt))
3786 continue;
3788 /* See if we can derive an assertion for any of STMT's operands. */
3789 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
3791 tree value;
3792 enum tree_code comp_code;
3794 /* If op is not live beyond this stmt, do not bother to insert
3795 asserts for it. */
3796 if (!bitmap_bit_p (live, SSA_NAME_VERSION (op)))
3797 continue;
3799 /* If OP is used in such a way that we can infer a value
3800 range for it, and we don't find a previous assertion for
3801 it, create a new assertion location node for OP. */
3802 if (infer_value_range (stmt, op, &comp_code, &value))
3804 /* If we are able to infer a nonzero value range for OP,
3805 then walk backwards through the use-def chain to see if OP
3806 was set via a typecast.
3808 If so, then we can also infer a nonzero value range
3809 for the operand of the NOP_EXPR. */
3810 if (comp_code == NE_EXPR && integer_zerop (value))
3812 tree t = op;
3813 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
3815 while (is_gimple_assign (def_stmt)
3816 && CONVERT_EXPR_CODE_P
3817 (gimple_assign_rhs_code (def_stmt))
3818 && TREE_CODE
3819 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
3820 && POINTER_TYPE_P
3821 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
3823 t = gimple_assign_rhs1 (def_stmt);
3824 def_stmt = SSA_NAME_DEF_STMT (t);
3826 /* Note we want to register the assert for the
3827 operand of the NOP_EXPR after SI, not after the
3828 conversion. */
3829 if (bitmap_bit_p (live, SSA_NAME_VERSION (t)))
3830 register_new_assert_for (t, t, comp_code, value,
3831 bb, NULL, si);
3835 register_new_assert_for (op, op, comp_code, value, bb, NULL, si);
3839 /* Update live. */
3840 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
3841 bitmap_set_bit (live, SSA_NAME_VERSION (op));
3842 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_DEF)
3843 bitmap_clear_bit (live, SSA_NAME_VERSION (op));
3846 /* Traverse all PHI nodes in BB, updating live. */
3847 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
3848 gsi_next (&si))
3850 use_operand_p arg_p;
3851 ssa_op_iter i;
3852 gphi *phi = si.phi ();
3853 tree res = gimple_phi_result (phi);
3855 if (virtual_operand_p (res))
3856 continue;
3858 FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
3860 tree arg = USE_FROM_PTR (arg_p);
3861 if (TREE_CODE (arg) == SSA_NAME)
3862 bitmap_set_bit (live, SSA_NAME_VERSION (arg));
3865 bitmap_clear_bit (live, SSA_NAME_VERSION (res));
3869 /* Do an RPO walk over the function computing SSA name liveness
3870 on-the-fly and deciding on assert expressions to insert. */
3872 static void
3873 find_assert_locations (void)
3875 int *rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
3876 int *bb_rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
3877 int *last_rpo = XCNEWVEC (int, last_basic_block_for_fn (cfun));
3878 int rpo_cnt, i;
3880 live = XCNEWVEC (sbitmap, last_basic_block_for_fn (cfun));
3881 rpo_cnt = pre_and_rev_post_order_compute (NULL, rpo, false);
3882 for (i = 0; i < rpo_cnt; ++i)
3883 bb_rpo[rpo[i]] = i;
3885 /* Pre-seed loop latch liveness from loop header PHI nodes. Due to
3886 the order we compute liveness and insert asserts we otherwise
3887 fail to insert asserts into the loop latch. */
3888 loop_p loop;
3889 FOR_EACH_LOOP (loop, 0)
3891 i = loop->latch->index;
3892 unsigned int j = single_succ_edge (loop->latch)->dest_idx;
3893 for (gphi_iterator gsi = gsi_start_phis (loop->header);
3894 !gsi_end_p (gsi); gsi_next (&gsi))
3896 gphi *phi = gsi.phi ();
3897 if (virtual_operand_p (gimple_phi_result (phi)))
3898 continue;
3899 tree arg = gimple_phi_arg_def (phi, j);
3900 if (TREE_CODE (arg) == SSA_NAME)
3902 if (live[i] == NULL)
3904 live[i] = sbitmap_alloc (num_ssa_names);
3905 bitmap_clear (live[i]);
3907 bitmap_set_bit (live[i], SSA_NAME_VERSION (arg));
3912 for (i = rpo_cnt - 1; i >= 0; --i)
3914 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, rpo[i]);
3915 edge e;
3916 edge_iterator ei;
3918 if (!live[rpo[i]])
3920 live[rpo[i]] = sbitmap_alloc (num_ssa_names);
3921 bitmap_clear (live[rpo[i]]);
3924 /* Process BB and update the live information with uses in
3925 this block. */
3926 find_assert_locations_1 (bb, live[rpo[i]]);
3928 /* Merge liveness into the predecessor blocks and free it. */
3929 if (!bitmap_empty_p (live[rpo[i]]))
3931 int pred_rpo = i;
3932 FOR_EACH_EDGE (e, ei, bb->preds)
3934 int pred = e->src->index;
3935 if ((e->flags & EDGE_DFS_BACK) || pred == ENTRY_BLOCK)
3936 continue;
3938 if (!live[pred])
3940 live[pred] = sbitmap_alloc (num_ssa_names);
3941 bitmap_clear (live[pred]);
3943 bitmap_ior (live[pred], live[pred], live[rpo[i]]);
3945 if (bb_rpo[pred] < pred_rpo)
3946 pred_rpo = bb_rpo[pred];
3949 /* Record the RPO number of the last visited block that needs
3950 live information from this block. */
3951 last_rpo[rpo[i]] = pred_rpo;
3953 else
3955 sbitmap_free (live[rpo[i]]);
3956 live[rpo[i]] = NULL;
3959 /* We can free all successors live bitmaps if all their
3960 predecessors have been visited already. */
3961 FOR_EACH_EDGE (e, ei, bb->succs)
3962 if (last_rpo[e->dest->index] == i
3963 && live[e->dest->index])
3965 sbitmap_free (live[e->dest->index]);
3966 live[e->dest->index] = NULL;
3970 XDELETEVEC (rpo);
3971 XDELETEVEC (bb_rpo);
3972 XDELETEVEC (last_rpo);
3973 for (i = 0; i < last_basic_block_for_fn (cfun); ++i)
3974 if (live[i])
3975 sbitmap_free (live[i]);
3976 XDELETEVEC (live);
3979 /* Create an ASSERT_EXPR for NAME and insert it in the location
3980 indicated by LOC. Return true if we made any edge insertions. */
3982 static bool
3983 process_assert_insertions_for (tree name, assert_locus *loc)
3985 /* Build the comparison expression NAME_i COMP_CODE VAL. */
3986 gimple *stmt;
3987 tree cond;
3988 gimple *assert_stmt;
3989 edge_iterator ei;
3990 edge e;
3992 /* If we have X <=> X do not insert an assert expr for that. */
3993 if (loc->expr == loc->val)
3994 return false;
3996 cond = build2 (loc->comp_code, boolean_type_node, loc->expr, loc->val);
3997 assert_stmt = build_assert_expr_for (cond, name);
3998 if (loc->e)
4000 /* We have been asked to insert the assertion on an edge. This
4001 is used only by COND_EXPR and SWITCH_EXPR assertions. */
4002 gcc_checking_assert (gimple_code (gsi_stmt (loc->si)) == GIMPLE_COND
4003 || (gimple_code (gsi_stmt (loc->si))
4004 == GIMPLE_SWITCH));
4006 gsi_insert_on_edge (loc->e, assert_stmt);
4007 return true;
4010 /* If the stmt iterator points at the end then this is an insertion
4011 at the beginning of a block. */
4012 if (gsi_end_p (loc->si))
4014 gimple_stmt_iterator si = gsi_after_labels (loc->bb);
4015 gsi_insert_before (&si, assert_stmt, GSI_SAME_STMT);
4016 return false;
4019 /* Otherwise, we can insert right after LOC->SI iff the
4020 statement must not be the last statement in the block. */
4021 stmt = gsi_stmt (loc->si);
4022 if (!stmt_ends_bb_p (stmt))
4024 gsi_insert_after (&loc->si, assert_stmt, GSI_SAME_STMT);
4025 return false;
4028 /* If STMT must be the last statement in BB, we can only insert new
4029 assertions on the non-abnormal edge out of BB. Note that since
4030 STMT is not control flow, there may only be one non-abnormal/eh edge
4031 out of BB. */
4032 FOR_EACH_EDGE (e, ei, loc->bb->succs)
4033 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
4035 gsi_insert_on_edge (e, assert_stmt);
4036 return true;
4039 gcc_unreachable ();
4042 /* Qsort helper for sorting assert locations. If stable is true, don't
4043 use iterative_hash_expr because it can be unstable for -fcompare-debug,
4044 on the other side some pointers might be NULL. */
4046 template <bool stable>
4047 static int
4048 compare_assert_loc (const void *pa, const void *pb)
4050 assert_locus * const a = *(assert_locus * const *)pa;
4051 assert_locus * const b = *(assert_locus * const *)pb;
4053 /* If stable, some asserts might be optimized away already, sort
4054 them last. */
4055 if (stable)
4057 if (a == NULL)
4058 return b != NULL;
4059 else if (b == NULL)
4060 return -1;
4063 if (a->e == NULL && b->e != NULL)
4064 return 1;
4065 else if (a->e != NULL && b->e == NULL)
4066 return -1;
4068 /* After the above checks, we know that (a->e == NULL) == (b->e == NULL),
4069 no need to test both a->e and b->e. */
4071 /* Sort after destination index. */
4072 if (a->e == NULL)
4074 else if (a->e->dest->index > b->e->dest->index)
4075 return 1;
4076 else if (a->e->dest->index < b->e->dest->index)
4077 return -1;
4079 /* Sort after comp_code. */
4080 if (a->comp_code > b->comp_code)
4081 return 1;
4082 else if (a->comp_code < b->comp_code)
4083 return -1;
4085 hashval_t ha, hb;
4087 /* E.g. if a->val is ADDR_EXPR of a VAR_DECL, iterative_hash_expr
4088 uses DECL_UID of the VAR_DECL, so sorting might differ between
4089 -g and -g0. When doing the removal of redundant assert exprs
4090 and commonization to successors, this does not matter, but for
4091 the final sort needs to be stable. */
4092 if (stable)
4094 ha = 0;
4095 hb = 0;
4097 else
4099 ha = iterative_hash_expr (a->expr, iterative_hash_expr (a->val, 0));
4100 hb = iterative_hash_expr (b->expr, iterative_hash_expr (b->val, 0));
4103 /* Break the tie using hashing and source/bb index. */
4104 if (ha == hb)
4105 return (a->e != NULL
4106 ? a->e->src->index - b->e->src->index
4107 : a->bb->index - b->bb->index);
4108 return ha > hb ? 1 : -1;
4111 /* Process all the insertions registered for every name N_i registered
4112 in NEED_ASSERT_FOR. The list of assertions to be inserted are
4113 found in ASSERTS_FOR[i]. */
4115 static void
4116 process_assert_insertions (void)
4118 unsigned i;
4119 bitmap_iterator bi;
4120 bool update_edges_p = false;
4121 int num_asserts = 0;
4123 if (dump_file && (dump_flags & TDF_DETAILS))
4124 dump_all_asserts (dump_file);
4126 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
4128 assert_locus *loc = asserts_for[i];
4129 gcc_assert (loc);
4131 auto_vec<assert_locus *, 16> asserts;
4132 for (; loc; loc = loc->next)
4133 asserts.safe_push (loc);
4134 asserts.qsort (compare_assert_loc<false>);
4136 /* Push down common asserts to successors and remove redundant ones. */
4137 unsigned ecnt = 0;
4138 assert_locus *common = NULL;
4139 unsigned commonj = 0;
4140 for (unsigned j = 0; j < asserts.length (); ++j)
4142 loc = asserts[j];
4143 if (! loc->e)
4144 common = NULL;
4145 else if (! common
4146 || loc->e->dest != common->e->dest
4147 || loc->comp_code != common->comp_code
4148 || ! operand_equal_p (loc->val, common->val, 0)
4149 || ! operand_equal_p (loc->expr, common->expr, 0))
4151 commonj = j;
4152 common = loc;
4153 ecnt = 1;
4155 else if (loc->e == asserts[j-1]->e)
4157 /* Remove duplicate asserts. */
4158 if (commonj == j - 1)
4160 commonj = j;
4161 common = loc;
4163 free (asserts[j-1]);
4164 asserts[j-1] = NULL;
4166 else
4168 ecnt++;
4169 if (EDGE_COUNT (common->e->dest->preds) == ecnt)
4171 /* We have the same assertion on all incoming edges of a BB.
4172 Insert it at the beginning of that block. */
4173 loc->bb = loc->e->dest;
4174 loc->e = NULL;
4175 loc->si = gsi_none ();
4176 common = NULL;
4177 /* Clear asserts commoned. */
4178 for (; commonj != j; ++commonj)
4179 if (asserts[commonj])
4181 free (asserts[commonj]);
4182 asserts[commonj] = NULL;
4188 /* The asserts vector sorting above might be unstable for
4189 -fcompare-debug, sort again to ensure a stable sort. */
4190 asserts.qsort (compare_assert_loc<true>);
4191 for (unsigned j = 0; j < asserts.length (); ++j)
4193 loc = asserts[j];
4194 if (! loc)
4195 break;
4196 update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
4197 num_asserts++;
4198 free (loc);
4202 if (update_edges_p)
4203 gsi_commit_edge_inserts ();
4205 statistics_counter_event (cfun, "Number of ASSERT_EXPR expressions inserted",
4206 num_asserts);
4210 /* Traverse the flowgraph looking for conditional jumps to insert range
4211 expressions. These range expressions are meant to provide information
4212 to optimizations that need to reason in terms of value ranges. They
4213 will not be expanded into RTL. For instance, given:
4215 x = ...
4216 y = ...
4217 if (x < y)
4218 y = x - 2;
4219 else
4220 x = y + 3;
4222 this pass will transform the code into:
4224 x = ...
4225 y = ...
4226 if (x < y)
4228 x = ASSERT_EXPR <x, x < y>
4229 y = x - 2
4231 else
4233 y = ASSERT_EXPR <y, x >= y>
4234 x = y + 3
4237 The idea is that once copy and constant propagation have run, other
4238 optimizations will be able to determine what ranges of values can 'x'
4239 take in different paths of the code, simply by checking the reaching
4240 definition of 'x'. */
4242 static void
4243 insert_range_assertions (void)
4245 need_assert_for = BITMAP_ALLOC (NULL);
4246 asserts_for = XCNEWVEC (assert_locus *, num_ssa_names);
4248 calculate_dominance_info (CDI_DOMINATORS);
4250 find_assert_locations ();
4251 if (!bitmap_empty_p (need_assert_for))
4253 process_assert_insertions ();
4254 update_ssa (TODO_update_ssa_no_phi);
4257 if (dump_file && (dump_flags & TDF_DETAILS))
4259 fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
4260 dump_function_to_file (current_function_decl, dump_file, dump_flags);
4263 free (asserts_for);
4264 BITMAP_FREE (need_assert_for);
4267 class vrp_prop : public ssa_propagation_engine
4269 public:
4270 enum ssa_prop_result visit_stmt (gimple *, edge *, tree *) FINAL OVERRIDE;
4271 enum ssa_prop_result visit_phi (gphi *) FINAL OVERRIDE;
4273 void vrp_initialize (void);
4274 void vrp_finalize (bool);
4275 void check_all_array_refs (void);
4276 void check_array_ref (location_t, tree, bool);
4277 void check_mem_ref (location_t, tree, bool);
4278 void search_for_addr_array (tree, location_t);
4280 class vr_values vr_values;
4281 /* Temporary delegator to minimize code churn. */
4282 value_range *get_value_range (const_tree op)
4283 { return vr_values.get_value_range (op); }
4284 void set_defs_to_varying (gimple *stmt)
4285 { return vr_values.set_defs_to_varying (stmt); }
4286 void extract_range_from_stmt (gimple *stmt, edge *taken_edge_p,
4287 tree *output_p, value_range *vr)
4288 { vr_values.extract_range_from_stmt (stmt, taken_edge_p, output_p, vr); }
4289 bool update_value_range (const_tree op, value_range *vr)
4290 { return vr_values.update_value_range (op, vr); }
4291 void extract_range_basic (value_range *vr, gimple *stmt)
4292 { vr_values.extract_range_basic (vr, stmt); }
4293 void extract_range_from_phi_node (gphi *phi, value_range *vr)
4294 { vr_values.extract_range_from_phi_node (phi, vr); }
4296 /* Checks one ARRAY_REF in REF, located at LOCUS. Ignores flexible arrays
4297 and "struct" hacks. If VRP can determine that the
4298 array subscript is a constant, check if it is outside valid
4299 range. If the array subscript is a RANGE, warn if it is
4300 non-overlapping with valid range.
4301 IGNORE_OFF_BY_ONE is true if the ARRAY_REF is inside a ADDR_EXPR. */
4303 void
4304 vrp_prop::check_array_ref (location_t location, tree ref,
4305 bool ignore_off_by_one)
4307 value_range *vr = NULL;
4308 tree low_sub, up_sub;
4309 tree low_bound, up_bound, up_bound_p1;
4311 if (TREE_NO_WARNING (ref))
4312 return;
4314 low_sub = up_sub = TREE_OPERAND (ref, 1);
4315 up_bound = array_ref_up_bound (ref);
4317 if (!up_bound
4318 || TREE_CODE (up_bound) != INTEGER_CST
4319 || (warn_array_bounds < 2
4320 && array_at_struct_end_p (ref)))
4322 /* Accesses to trailing arrays via pointers may access storage
4323 beyond the types array bounds. For such arrays, or for flexible
4324 array members, as well as for other arrays of an unknown size,
4325 replace the upper bound with a more permissive one that assumes
4326 the size of the largest object is PTRDIFF_MAX. */
4327 tree eltsize = array_ref_element_size (ref);
4329 if (TREE_CODE (eltsize) != INTEGER_CST
4330 || integer_zerop (eltsize))
4332 up_bound = NULL_TREE;
4333 up_bound_p1 = NULL_TREE;
4335 else
4337 tree maxbound = TYPE_MAX_VALUE (ptrdiff_type_node);
4338 tree arg = TREE_OPERAND (ref, 0);
4339 poly_int64 off;
4341 if (get_addr_base_and_unit_offset (arg, &off) && known_gt (off, 0))
4342 maxbound = wide_int_to_tree (sizetype,
4343 wi::sub (wi::to_wide (maxbound),
4344 off));
4345 else
4346 maxbound = fold_convert (sizetype, maxbound);
4348 up_bound_p1 = int_const_binop (TRUNC_DIV_EXPR, maxbound, eltsize);
4350 up_bound = int_const_binop (MINUS_EXPR, up_bound_p1,
4351 build_int_cst (ptrdiff_type_node, 1));
4354 else
4355 up_bound_p1 = int_const_binop (PLUS_EXPR, up_bound,
4356 build_int_cst (TREE_TYPE (up_bound), 1));
4358 low_bound = array_ref_low_bound (ref);
4360 tree artype = TREE_TYPE (TREE_OPERAND (ref, 0));
4362 bool warned = false;
4364 /* Empty array. */
4365 if (up_bound && tree_int_cst_equal (low_bound, up_bound_p1))
4366 warned = warning_at (location, OPT_Warray_bounds,
4367 "array subscript %E is above array bounds of %qT",
4368 low_bound, artype);
4370 if (TREE_CODE (low_sub) == SSA_NAME)
4372 vr = get_value_range (low_sub);
4373 if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
4375 low_sub = vr->type == VR_RANGE ? vr->max : vr->min;
4376 up_sub = vr->type == VR_RANGE ? vr->min : vr->max;
4380 if (vr && vr->type == VR_ANTI_RANGE)
4382 if (up_bound
4383 && TREE_CODE (up_sub) == INTEGER_CST
4384 && (ignore_off_by_one
4385 ? tree_int_cst_lt (up_bound, up_sub)
4386 : tree_int_cst_le (up_bound, up_sub))
4387 && TREE_CODE (low_sub) == INTEGER_CST
4388 && tree_int_cst_le (low_sub, low_bound))
4389 warned = warning_at (location, OPT_Warray_bounds,
4390 "array subscript [%E, %E] is outside "
4391 "array bounds of %qT",
4392 low_sub, up_sub, artype);
4394 else if (up_bound
4395 && TREE_CODE (up_sub) == INTEGER_CST
4396 && (ignore_off_by_one
4397 ? !tree_int_cst_le (up_sub, up_bound_p1)
4398 : !tree_int_cst_le (up_sub, up_bound)))
4400 if (dump_file && (dump_flags & TDF_DETAILS))
4402 fprintf (dump_file, "Array bound warning for ");
4403 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
4404 fprintf (dump_file, "\n");
4406 warned = warning_at (location, OPT_Warray_bounds,
4407 "array subscript %E is above array bounds of %qT",
4408 up_sub, artype);
4410 else if (TREE_CODE (low_sub) == INTEGER_CST
4411 && tree_int_cst_lt (low_sub, low_bound))
4413 if (dump_file && (dump_flags & TDF_DETAILS))
4415 fprintf (dump_file, "Array bound warning for ");
4416 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
4417 fprintf (dump_file, "\n");
4419 warned = warning_at (location, OPT_Warray_bounds,
4420 "array subscript %E is below array bounds of %qT",
4421 low_sub, artype);
4424 if (warned)
4426 ref = TREE_OPERAND (ref, 0);
4428 if (DECL_P (ref))
4429 inform (DECL_SOURCE_LOCATION (ref), "while referencing %qD", ref);
4431 TREE_NO_WARNING (ref) = 1;
4435 /* Checks one MEM_REF in REF, located at LOCATION, for out-of-bounds
4436 references to string constants. If VRP can determine that the array
4437 subscript is a constant, check if it is outside valid range.
4438 If the array subscript is a RANGE, warn if it is non-overlapping
4439 with valid range.
4440 IGNORE_OFF_BY_ONE is true if the MEM_REF is inside an ADDR_EXPR
4441 (used to allow one-past-the-end indices for code that takes
4442 the address of the just-past-the-end element of an array). */
4444 void
4445 vrp_prop::check_mem_ref (location_t location, tree ref,
4446 bool ignore_off_by_one)
4448 if (TREE_NO_WARNING (ref))
4449 return;
4451 tree arg = TREE_OPERAND (ref, 0);
4452 /* The constant and variable offset of the reference. */
4453 tree cstoff = TREE_OPERAND (ref, 1);
4454 tree varoff = NULL_TREE;
4456 const offset_int maxobjsize = tree_to_shwi (max_object_size ());
4458 /* The array or string constant bounds in bytes. Initially set
4459 to [-MAXOBJSIZE - 1, MAXOBJSIZE] until a tighter bound is
4460 determined. */
4461 offset_int arrbounds[2] = { -maxobjsize - 1, maxobjsize };
4463 /* The minimum and maximum intermediate offset. For a reference
4464 to be valid, not only does the final offset/subscript must be
4465 in bounds but all intermediate offsets should be as well.
4466 GCC may be able to deal gracefully with such out-of-bounds
4467 offsets so the checking is only enbaled at -Warray-bounds=2
4468 where it may help detect bugs in uses of the intermediate
4469 offsets that could otherwise not be detectable. */
4470 offset_int ioff = wi::to_offset (fold_convert (ptrdiff_type_node, cstoff));
4471 offset_int extrema[2] = { 0, wi::abs (ioff) };
4473 /* The range of the byte offset into the reference. */
4474 offset_int offrange[2] = { 0, 0 };
4476 value_range *vr = NULL;
4478 /* Determine the offsets and increment OFFRANGE for the bounds of each.
4479 The loop computes the the range of the final offset for expressions
4480 such as (A + i0 + ... + iN)[CSTOFF] where i0 through iN are SSA_NAMEs
4481 in some range. */
4482 while (TREE_CODE (arg) == SSA_NAME)
4484 gimple *def = SSA_NAME_DEF_STMT (arg);
4485 if (!is_gimple_assign (def))
4486 break;
4488 tree_code code = gimple_assign_rhs_code (def);
4489 if (code == POINTER_PLUS_EXPR)
4491 arg = gimple_assign_rhs1 (def);
4492 varoff = gimple_assign_rhs2 (def);
4494 else if (code == ASSERT_EXPR)
4496 arg = TREE_OPERAND (gimple_assign_rhs1 (def), 0);
4497 continue;
4499 else
4500 return;
4502 /* VAROFF should always be a SSA_NAME here (and not even
4503 INTEGER_CST) but there's no point in taking chances. */
4504 if (TREE_CODE (varoff) != SSA_NAME)
4505 break;
4507 vr = get_value_range (varoff);
4508 if (!vr || vr->type == VR_UNDEFINED || !vr->min || !vr->max)
4509 break;
4511 if (TREE_CODE (vr->min) != INTEGER_CST
4512 || TREE_CODE (vr->max) != INTEGER_CST)
4513 break;
4515 if (vr->type == VR_RANGE)
4517 if (tree_int_cst_lt (vr->min, vr->max))
4519 offset_int min
4520 = wi::to_offset (fold_convert (ptrdiff_type_node, vr->min));
4521 offset_int max
4522 = wi::to_offset (fold_convert (ptrdiff_type_node, vr->max));
4523 if (min < max)
4525 offrange[0] += min;
4526 offrange[1] += max;
4528 else
4530 offrange[0] += max;
4531 offrange[1] += min;
4534 else
4536 /* Conservatively add [-MAXOBJSIZE -1, MAXOBJSIZE]
4537 to OFFRANGE. */
4538 offrange[0] += arrbounds[0];
4539 offrange[1] += arrbounds[1];
4542 else
4544 /* For an anti-range, analogously to the above, conservatively
4545 add [-MAXOBJSIZE -1, MAXOBJSIZE] to OFFRANGE. */
4546 offrange[0] += arrbounds[0];
4547 offrange[1] += arrbounds[1];
4550 /* Keep track of the minimum and maximum offset. */
4551 if (offrange[1] < 0 && offrange[1] < extrema[0])
4552 extrema[0] = offrange[1];
4553 if (offrange[0] > 0 && offrange[0] > extrema[1])
4554 extrema[1] = offrange[0];
4556 if (offrange[0] < arrbounds[0])
4557 offrange[0] = arrbounds[0];
4559 if (offrange[1] > arrbounds[1])
4560 offrange[1] = arrbounds[1];
4563 if (TREE_CODE (arg) == ADDR_EXPR)
4565 arg = TREE_OPERAND (arg, 0);
4566 if (TREE_CODE (arg) != STRING_CST
4567 && TREE_CODE (arg) != VAR_DECL)
4568 return;
4570 else
4571 return;
4573 /* The type of the object being referred to. It can be an array,
4574 string literal, or a non-array type when the MEM_REF represents
4575 a reference/subscript via a pointer to an object that is not
4576 an element of an array. References to members of structs and
4577 unions are excluded because MEM_REF doesn't make it possible
4578 to identify the member where the reference originated.
4579 Incomplete types are excluded as well because their size is
4580 not known. */
4581 tree reftype = TREE_TYPE (arg);
4582 if (POINTER_TYPE_P (reftype)
4583 || !COMPLETE_TYPE_P (reftype)
4584 || TREE_CODE (TYPE_SIZE_UNIT (reftype)) != INTEGER_CST
4585 || RECORD_OR_UNION_TYPE_P (reftype))
4586 return;
4588 offset_int eltsize;
4589 if (TREE_CODE (reftype) == ARRAY_TYPE)
4591 eltsize = wi::to_offset (TYPE_SIZE_UNIT (TREE_TYPE (reftype)));
4593 if (tree dom = TYPE_DOMAIN (reftype))
4595 tree bnds[] = { TYPE_MIN_VALUE (dom), TYPE_MAX_VALUE (dom) };
4596 if (array_at_struct_end_p (arg)
4597 || !bnds[0] || !bnds[1])
4599 arrbounds[0] = 0;
4600 arrbounds[1] = wi::lrshift (maxobjsize, wi::floor_log2 (eltsize));
4602 else
4604 arrbounds[0] = wi::to_offset (bnds[0]) * eltsize;
4605 arrbounds[1] = (wi::to_offset (bnds[1]) + 1) * eltsize;
4608 else
4610 arrbounds[0] = 0;
4611 arrbounds[1] = wi::lrshift (maxobjsize, wi::floor_log2 (eltsize));
4614 if (TREE_CODE (ref) == MEM_REF)
4616 /* For MEM_REF determine a tighter bound of the non-array
4617 element type. */
4618 tree eltype = TREE_TYPE (reftype);
4619 while (TREE_CODE (eltype) == ARRAY_TYPE)
4620 eltype = TREE_TYPE (eltype);
4621 eltsize = wi::to_offset (TYPE_SIZE_UNIT (eltype));
4624 else
4626 eltsize = 1;
4627 arrbounds[0] = 0;
4628 arrbounds[1] = wi::to_offset (TYPE_SIZE_UNIT (reftype));
4631 offrange[0] += ioff;
4632 offrange[1] += ioff;
4634 /* Compute the more permissive upper bound when IGNORE_OFF_BY_ONE
4635 is set (when taking the address of the one-past-last element
4636 of an array) but always use the stricter bound in diagnostics. */
4637 offset_int ubound = arrbounds[1];
4638 if (ignore_off_by_one)
4639 ubound += 1;
4641 if (offrange[0] >= ubound || offrange[1] < arrbounds[0])
4643 /* Treat a reference to a non-array object as one to an array
4644 of a single element. */
4645 if (TREE_CODE (reftype) != ARRAY_TYPE)
4646 reftype = build_array_type_nelts (reftype, 1);
4648 if (TREE_CODE (ref) == MEM_REF)
4650 /* Extract the element type out of MEM_REF and use its size
4651 to compute the index to print in the diagnostic; arrays
4652 in MEM_REF don't mean anything. */
4653 tree type = TREE_TYPE (ref);
4654 while (TREE_CODE (type) == ARRAY_TYPE)
4655 type = TREE_TYPE (type);
4656 tree size = TYPE_SIZE_UNIT (type);
4657 offrange[0] = offrange[0] / wi::to_offset (size);
4658 offrange[1] = offrange[1] / wi::to_offset (size);
4660 else
4662 /* For anything other than MEM_REF, compute the index to
4663 print in the diagnostic as the offset over element size. */
4664 offrange[0] = offrange[0] / eltsize;
4665 offrange[1] = offrange[1] / eltsize;
4668 bool warned;
4669 if (offrange[0] == offrange[1])
4670 warned = warning_at (location, OPT_Warray_bounds,
4671 "array subscript %wi is outside array bounds "
4672 "of %qT",
4673 offrange[0].to_shwi (), reftype);
4674 else
4675 warned = warning_at (location, OPT_Warray_bounds,
4676 "array subscript [%wi, %wi] is outside "
4677 "array bounds of %qT",
4678 offrange[0].to_shwi (),
4679 offrange[1].to_shwi (), reftype);
4680 if (warned && DECL_P (arg))
4681 inform (DECL_SOURCE_LOCATION (arg), "while referencing %qD", arg);
4683 TREE_NO_WARNING (ref) = 1;
4684 return;
4687 if (warn_array_bounds < 2)
4688 return;
4690 /* At level 2 check also intermediate offsets. */
4691 int i = 0;
4692 if (extrema[i] < -arrbounds[1] || extrema[i = 1] > ubound)
4694 HOST_WIDE_INT tmpidx = extrema[i].to_shwi () / eltsize.to_shwi ();
4696 warning_at (location, OPT_Warray_bounds,
4697 "intermediate array offset %wi is outside array bounds "
4698 "of %qT",
4699 tmpidx, reftype);
4700 TREE_NO_WARNING (ref) = 1;
4704 /* Searches if the expr T, located at LOCATION computes
4705 address of an ARRAY_REF, and call check_array_ref on it. */
4707 void
4708 vrp_prop::search_for_addr_array (tree t, location_t location)
4710 /* Check each ARRAY_REF and MEM_REF in the reference chain. */
4713 if (TREE_CODE (t) == ARRAY_REF)
4714 check_array_ref (location, t, true /*ignore_off_by_one*/);
4715 else if (TREE_CODE (t) == MEM_REF)
4716 check_mem_ref (location, t, true /*ignore_off_by_one*/);
4718 t = TREE_OPERAND (t, 0);
4720 while (handled_component_p (t) || TREE_CODE (t) == MEM_REF);
4722 if (TREE_CODE (t) != MEM_REF
4723 || TREE_CODE (TREE_OPERAND (t, 0)) != ADDR_EXPR
4724 || TREE_NO_WARNING (t))
4725 return;
4727 tree tem = TREE_OPERAND (TREE_OPERAND (t, 0), 0);
4728 tree low_bound, up_bound, el_sz;
4729 if (TREE_CODE (TREE_TYPE (tem)) != ARRAY_TYPE
4730 || TREE_CODE (TREE_TYPE (TREE_TYPE (tem))) == ARRAY_TYPE
4731 || !TYPE_DOMAIN (TREE_TYPE (tem)))
4732 return;
4734 low_bound = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
4735 up_bound = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
4736 el_sz = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (tem)));
4737 if (!low_bound
4738 || TREE_CODE (low_bound) != INTEGER_CST
4739 || !up_bound
4740 || TREE_CODE (up_bound) != INTEGER_CST
4741 || !el_sz
4742 || TREE_CODE (el_sz) != INTEGER_CST)
4743 return;
4745 offset_int idx;
4746 if (!mem_ref_offset (t).is_constant (&idx))
4747 return;
4749 bool warned = false;
4750 idx = wi::sdiv_trunc (idx, wi::to_offset (el_sz));
4751 if (idx < 0)
4753 if (dump_file && (dump_flags & TDF_DETAILS))
4755 fprintf (dump_file, "Array bound warning for ");
4756 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
4757 fprintf (dump_file, "\n");
4759 warned = warning_at (location, OPT_Warray_bounds,
4760 "array subscript %wi is below "
4761 "array bounds of %qT",
4762 idx.to_shwi (), TREE_TYPE (tem));
4764 else if (idx > (wi::to_offset (up_bound)
4765 - wi::to_offset (low_bound) + 1))
4767 if (dump_file && (dump_flags & TDF_DETAILS))
4769 fprintf (dump_file, "Array bound warning for ");
4770 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
4771 fprintf (dump_file, "\n");
4773 warned = warning_at (location, OPT_Warray_bounds,
4774 "array subscript %wu is above "
4775 "array bounds of %qT",
4776 idx.to_uhwi (), TREE_TYPE (tem));
4779 if (warned)
4781 if (DECL_P (t))
4782 inform (DECL_SOURCE_LOCATION (t), "while referencing %qD", t);
4784 TREE_NO_WARNING (t) = 1;
4788 /* walk_tree() callback that checks if *TP is
4789 an ARRAY_REF inside an ADDR_EXPR (in which an array
4790 subscript one outside the valid range is allowed). Call
4791 check_array_ref for each ARRAY_REF found. The location is
4792 passed in DATA. */
4794 static tree
4795 check_array_bounds (tree *tp, int *walk_subtree, void *data)
4797 tree t = *tp;
4798 struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
4799 location_t location;
4801 if (EXPR_HAS_LOCATION (t))
4802 location = EXPR_LOCATION (t);
4803 else
4804 location = gimple_location (wi->stmt);
4806 *walk_subtree = TRUE;
4808 vrp_prop *vrp_prop = (class vrp_prop *)wi->info;
4809 if (TREE_CODE (t) == ARRAY_REF)
4810 vrp_prop->check_array_ref (location, t, false /*ignore_off_by_one*/);
4811 else if (TREE_CODE (t) == MEM_REF)
4812 vrp_prop->check_mem_ref (location, t, false /*ignore_off_by_one*/);
4813 else if (TREE_CODE (t) == ADDR_EXPR)
4815 vrp_prop->search_for_addr_array (t, location);
4816 *walk_subtree = FALSE;
4819 return NULL_TREE;
4822 /* A dom_walker subclass for use by vrp_prop::check_all_array_refs,
4823 to walk over all statements of all reachable BBs and call
4824 check_array_bounds on them. */
4826 class check_array_bounds_dom_walker : public dom_walker
4828 public:
4829 check_array_bounds_dom_walker (vrp_prop *prop)
4830 : dom_walker (CDI_DOMINATORS,
4831 /* Discover non-executable edges, preserving EDGE_EXECUTABLE
4832 flags, so that we can merge in information on
4833 non-executable edges from vrp_folder . */
4834 REACHABLE_BLOCKS_PRESERVING_FLAGS),
4835 m_prop (prop) {}
4836 ~check_array_bounds_dom_walker () {}
4838 edge before_dom_children (basic_block) FINAL OVERRIDE;
4840 private:
4841 vrp_prop *m_prop;
4844 /* Implementation of dom_walker::before_dom_children.
4846 Walk over all statements of BB and call check_array_bounds on them,
4847 and determine if there's a unique successor edge. */
4849 edge
4850 check_array_bounds_dom_walker::before_dom_children (basic_block bb)
4852 gimple_stmt_iterator si;
4853 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
4855 gimple *stmt = gsi_stmt (si);
4856 struct walk_stmt_info wi;
4857 if (!gimple_has_location (stmt)
4858 || is_gimple_debug (stmt))
4859 continue;
4861 memset (&wi, 0, sizeof (wi));
4863 wi.info = m_prop;
4865 walk_gimple_op (stmt, check_array_bounds, &wi);
4868 /* Determine if there's a unique successor edge, and if so, return
4869 that back to dom_walker, ensuring that we don't visit blocks that
4870 became unreachable during the VRP propagation
4871 (PR tree-optimization/83312). */
4872 return find_taken_edge (bb, NULL_TREE);
4875 /* Walk over all statements of all reachable BBs and call check_array_bounds
4876 on them. */
4878 void
4879 vrp_prop::check_all_array_refs ()
4881 check_array_bounds_dom_walker w (this);
4882 w.walk (ENTRY_BLOCK_PTR_FOR_FN (cfun));
4885 /* Return true if all imm uses of VAR are either in STMT, or
4886 feed (optionally through a chain of single imm uses) GIMPLE_COND
4887 in basic block COND_BB. */
4889 static bool
4890 all_imm_uses_in_stmt_or_feed_cond (tree var, gimple *stmt, basic_block cond_bb)
4892 use_operand_p use_p, use2_p;
4893 imm_use_iterator iter;
4895 FOR_EACH_IMM_USE_FAST (use_p, iter, var)
4896 if (USE_STMT (use_p) != stmt)
4898 gimple *use_stmt = USE_STMT (use_p), *use_stmt2;
4899 if (is_gimple_debug (use_stmt))
4900 continue;
4901 while (is_gimple_assign (use_stmt)
4902 && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
4903 && single_imm_use (gimple_assign_lhs (use_stmt),
4904 &use2_p, &use_stmt2))
4905 use_stmt = use_stmt2;
4906 if (gimple_code (use_stmt) != GIMPLE_COND
4907 || gimple_bb (use_stmt) != cond_bb)
4908 return false;
4910 return true;
4913 /* Handle
4914 _4 = x_3 & 31;
4915 if (_4 != 0)
4916 goto <bb 6>;
4917 else
4918 goto <bb 7>;
4919 <bb 6>:
4920 __builtin_unreachable ();
4921 <bb 7>:
4922 x_5 = ASSERT_EXPR <x_3, ...>;
4923 If x_3 has no other immediate uses (checked by caller),
4924 var is the x_3 var from ASSERT_EXPR, we can clear low 5 bits
4925 from the non-zero bitmask. */
4927 void
4928 maybe_set_nonzero_bits (edge e, tree var)
4930 basic_block cond_bb = e->src;
4931 gimple *stmt = last_stmt (cond_bb);
4932 tree cst;
4934 if (stmt == NULL
4935 || gimple_code (stmt) != GIMPLE_COND
4936 || gimple_cond_code (stmt) != ((e->flags & EDGE_TRUE_VALUE)
4937 ? EQ_EXPR : NE_EXPR)
4938 || TREE_CODE (gimple_cond_lhs (stmt)) != SSA_NAME
4939 || !integer_zerop (gimple_cond_rhs (stmt)))
4940 return;
4942 stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt));
4943 if (!is_gimple_assign (stmt)
4944 || gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
4945 || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
4946 return;
4947 if (gimple_assign_rhs1 (stmt) != var)
4949 gimple *stmt2;
4951 if (TREE_CODE (gimple_assign_rhs1 (stmt)) != SSA_NAME)
4952 return;
4953 stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
4954 if (!gimple_assign_cast_p (stmt2)
4955 || gimple_assign_rhs1 (stmt2) != var
4956 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt2))
4957 || (TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (stmt)))
4958 != TYPE_PRECISION (TREE_TYPE (var))))
4959 return;
4961 cst = gimple_assign_rhs2 (stmt);
4962 set_nonzero_bits (var, wi::bit_and_not (get_nonzero_bits (var),
4963 wi::to_wide (cst)));
4966 /* Convert range assertion expressions into the implied copies and
4967 copy propagate away the copies. Doing the trivial copy propagation
4968 here avoids the need to run the full copy propagation pass after
4969 VRP.
4971 FIXME, this will eventually lead to copy propagation removing the
4972 names that had useful range information attached to them. For
4973 instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
4974 then N_i will have the range [3, +INF].
4976 However, by converting the assertion into the implied copy
4977 operation N_i = N_j, we will then copy-propagate N_j into the uses
4978 of N_i and lose the range information. We may want to hold on to
4979 ASSERT_EXPRs a little while longer as the ranges could be used in
4980 things like jump threading.
4982 The problem with keeping ASSERT_EXPRs around is that passes after
4983 VRP need to handle them appropriately.
4985 Another approach would be to make the range information a first
4986 class property of the SSA_NAME so that it can be queried from
4987 any pass. This is made somewhat more complex by the need for
4988 multiple ranges to be associated with one SSA_NAME. */
4990 static void
4991 remove_range_assertions (void)
4993 basic_block bb;
4994 gimple_stmt_iterator si;
4995 /* 1 if looking at ASSERT_EXPRs immediately at the beginning of
4996 a basic block preceeded by GIMPLE_COND branching to it and
4997 __builtin_trap, -1 if not yet checked, 0 otherwise. */
4998 int is_unreachable;
5000 /* Note that the BSI iterator bump happens at the bottom of the
5001 loop and no bump is necessary if we're removing the statement
5002 referenced by the current BSI. */
5003 FOR_EACH_BB_FN (bb, cfun)
5004 for (si = gsi_after_labels (bb), is_unreachable = -1; !gsi_end_p (si);)
5006 gimple *stmt = gsi_stmt (si);
5008 if (is_gimple_assign (stmt)
5009 && gimple_assign_rhs_code (stmt) == ASSERT_EXPR)
5011 tree lhs = gimple_assign_lhs (stmt);
5012 tree rhs = gimple_assign_rhs1 (stmt);
5013 tree var;
5015 var = ASSERT_EXPR_VAR (rhs);
5017 if (TREE_CODE (var) == SSA_NAME
5018 && !POINTER_TYPE_P (TREE_TYPE (lhs))
5019 && SSA_NAME_RANGE_INFO (lhs))
5021 if (is_unreachable == -1)
5023 is_unreachable = 0;
5024 if (single_pred_p (bb)
5025 && assert_unreachable_fallthru_edge_p
5026 (single_pred_edge (bb)))
5027 is_unreachable = 1;
5029 /* Handle
5030 if (x_7 >= 10 && x_7 < 20)
5031 __builtin_unreachable ();
5032 x_8 = ASSERT_EXPR <x_7, ...>;
5033 if the only uses of x_7 are in the ASSERT_EXPR and
5034 in the condition. In that case, we can copy the
5035 range info from x_8 computed in this pass also
5036 for x_7. */
5037 if (is_unreachable
5038 && all_imm_uses_in_stmt_or_feed_cond (var, stmt,
5039 single_pred (bb)))
5041 set_range_info (var, SSA_NAME_RANGE_TYPE (lhs),
5042 SSA_NAME_RANGE_INFO (lhs)->get_min (),
5043 SSA_NAME_RANGE_INFO (lhs)->get_max ());
5044 maybe_set_nonzero_bits (single_pred_edge (bb), var);
5048 /* Propagate the RHS into every use of the LHS. For SSA names
5049 also propagate abnormals as it merely restores the original
5050 IL in this case (an replace_uses_by would assert). */
5051 if (TREE_CODE (var) == SSA_NAME)
5053 imm_use_iterator iter;
5054 use_operand_p use_p;
5055 gimple *use_stmt;
5056 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
5057 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
5058 SET_USE (use_p, var);
5060 else
5061 replace_uses_by (lhs, var);
5063 /* And finally, remove the copy, it is not needed. */
5064 gsi_remove (&si, true);
5065 release_defs (stmt);
5067 else
5069 if (!is_gimple_debug (gsi_stmt (si)))
5070 is_unreachable = 0;
5071 gsi_next (&si);
5076 /* Return true if STMT is interesting for VRP. */
5078 bool
5079 stmt_interesting_for_vrp (gimple *stmt)
5081 if (gimple_code (stmt) == GIMPLE_PHI)
5083 tree res = gimple_phi_result (stmt);
5084 return (!virtual_operand_p (res)
5085 && (INTEGRAL_TYPE_P (TREE_TYPE (res))
5086 || POINTER_TYPE_P (TREE_TYPE (res))));
5088 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
5090 tree lhs = gimple_get_lhs (stmt);
5092 /* In general, assignments with virtual operands are not useful
5093 for deriving ranges, with the obvious exception of calls to
5094 builtin functions. */
5095 if (lhs && TREE_CODE (lhs) == SSA_NAME
5096 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
5097 || POINTER_TYPE_P (TREE_TYPE (lhs)))
5098 && (is_gimple_call (stmt)
5099 || !gimple_vuse (stmt)))
5100 return true;
5101 else if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
5102 switch (gimple_call_internal_fn (stmt))
5104 case IFN_ADD_OVERFLOW:
5105 case IFN_SUB_OVERFLOW:
5106 case IFN_MUL_OVERFLOW:
5107 case IFN_ATOMIC_COMPARE_EXCHANGE:
5108 /* These internal calls return _Complex integer type,
5109 but are interesting to VRP nevertheless. */
5110 if (lhs && TREE_CODE (lhs) == SSA_NAME)
5111 return true;
5112 break;
5113 default:
5114 break;
5117 else if (gimple_code (stmt) == GIMPLE_COND
5118 || gimple_code (stmt) == GIMPLE_SWITCH)
5119 return true;
5121 return false;
5124 /* Initialization required by ssa_propagate engine. */
5126 void
5127 vrp_prop::vrp_initialize ()
5129 basic_block bb;
5131 FOR_EACH_BB_FN (bb, cfun)
5133 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
5134 gsi_next (&si))
5136 gphi *phi = si.phi ();
5137 if (!stmt_interesting_for_vrp (phi))
5139 tree lhs = PHI_RESULT (phi);
5140 set_value_range_to_varying (get_value_range (lhs));
5141 prop_set_simulate_again (phi, false);
5143 else
5144 prop_set_simulate_again (phi, true);
5147 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
5148 gsi_next (&si))
5150 gimple *stmt = gsi_stmt (si);
5152 /* If the statement is a control insn, then we do not
5153 want to avoid simulating the statement once. Failure
5154 to do so means that those edges will never get added. */
5155 if (stmt_ends_bb_p (stmt))
5156 prop_set_simulate_again (stmt, true);
5157 else if (!stmt_interesting_for_vrp (stmt))
5159 set_defs_to_varying (stmt);
5160 prop_set_simulate_again (stmt, false);
5162 else
5163 prop_set_simulate_again (stmt, true);
5168 /* Searches the case label vector VEC for the index *IDX of the CASE_LABEL
5169 that includes the value VAL. The search is restricted to the range
5170 [START_IDX, n - 1] where n is the size of VEC.
5172 If there is a CASE_LABEL for VAL, its index is placed in IDX and true is
5173 returned.
5175 If there is no CASE_LABEL for VAL and there is one that is larger than VAL,
5176 it is placed in IDX and false is returned.
5178 If VAL is larger than any CASE_LABEL, n is placed on IDX and false is
5179 returned. */
5181 bool
5182 find_case_label_index (gswitch *stmt, size_t start_idx, tree val, size_t *idx)
5184 size_t n = gimple_switch_num_labels (stmt);
5185 size_t low, high;
5187 /* Find case label for minimum of the value range or the next one.
5188 At each iteration we are searching in [low, high - 1]. */
5190 for (low = start_idx, high = n; high != low; )
5192 tree t;
5193 int cmp;
5194 /* Note that i != high, so we never ask for n. */
5195 size_t i = (high + low) / 2;
5196 t = gimple_switch_label (stmt, i);
5198 /* Cache the result of comparing CASE_LOW and val. */
5199 cmp = tree_int_cst_compare (CASE_LOW (t), val);
5201 if (cmp == 0)
5203 /* Ranges cannot be empty. */
5204 *idx = i;
5205 return true;
5207 else if (cmp > 0)
5208 high = i;
5209 else
5211 low = i + 1;
5212 if (CASE_HIGH (t) != NULL
5213 && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
5215 *idx = i;
5216 return true;
5221 *idx = high;
5222 return false;
5225 /* Searches the case label vector VEC for the range of CASE_LABELs that is used
5226 for values between MIN and MAX. The first index is placed in MIN_IDX. The
5227 last index is placed in MAX_IDX. If the range of CASE_LABELs is empty
5228 then MAX_IDX < MIN_IDX.
5229 Returns true if the default label is not needed. */
5231 bool
5232 find_case_label_range (gswitch *stmt, tree min, tree max, size_t *min_idx,
5233 size_t *max_idx)
5235 size_t i, j;
5236 bool min_take_default = !find_case_label_index (stmt, 1, min, &i);
5237 bool max_take_default = !find_case_label_index (stmt, i, max, &j);
5239 if (i == j
5240 && min_take_default
5241 && max_take_default)
5243 /* Only the default case label reached.
5244 Return an empty range. */
5245 *min_idx = 1;
5246 *max_idx = 0;
5247 return false;
5249 else
5251 bool take_default = min_take_default || max_take_default;
5252 tree low, high;
5253 size_t k;
5255 if (max_take_default)
5256 j--;
5258 /* If the case label range is continuous, we do not need
5259 the default case label. Verify that. */
5260 high = CASE_LOW (gimple_switch_label (stmt, i));
5261 if (CASE_HIGH (gimple_switch_label (stmt, i)))
5262 high = CASE_HIGH (gimple_switch_label (stmt, i));
5263 for (k = i + 1; k <= j; ++k)
5265 low = CASE_LOW (gimple_switch_label (stmt, k));
5266 if (!integer_onep (int_const_binop (MINUS_EXPR, low, high)))
5268 take_default = true;
5269 break;
5271 high = low;
5272 if (CASE_HIGH (gimple_switch_label (stmt, k)))
5273 high = CASE_HIGH (gimple_switch_label (stmt, k));
5276 *min_idx = i;
5277 *max_idx = j;
5278 return !take_default;
5282 /* Evaluate statement STMT. If the statement produces a useful range,
5283 return SSA_PROP_INTERESTING and record the SSA name with the
5284 interesting range into *OUTPUT_P.
5286 If STMT is a conditional branch and we can determine its truth
5287 value, the taken edge is recorded in *TAKEN_EDGE_P.
5289 If STMT produces a varying value, return SSA_PROP_VARYING. */
5291 enum ssa_prop_result
5292 vrp_prop::visit_stmt (gimple *stmt, edge *taken_edge_p, tree *output_p)
5294 value_range vr = VR_INITIALIZER;
5295 tree lhs = gimple_get_lhs (stmt);
5296 extract_range_from_stmt (stmt, taken_edge_p, output_p, &vr);
5298 if (*output_p)
5300 if (update_value_range (*output_p, &vr))
5302 if (dump_file && (dump_flags & TDF_DETAILS))
5304 fprintf (dump_file, "Found new range for ");
5305 print_generic_expr (dump_file, *output_p);
5306 fprintf (dump_file, ": ");
5307 dump_value_range (dump_file, &vr);
5308 fprintf (dump_file, "\n");
5311 if (vr.type == VR_VARYING)
5312 return SSA_PROP_VARYING;
5314 return SSA_PROP_INTERESTING;
5316 return SSA_PROP_NOT_INTERESTING;
5319 if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
5320 switch (gimple_call_internal_fn (stmt))
5322 case IFN_ADD_OVERFLOW:
5323 case IFN_SUB_OVERFLOW:
5324 case IFN_MUL_OVERFLOW:
5325 case IFN_ATOMIC_COMPARE_EXCHANGE:
5326 /* These internal calls return _Complex integer type,
5327 which VRP does not track, but the immediate uses
5328 thereof might be interesting. */
5329 if (lhs && TREE_CODE (lhs) == SSA_NAME)
5331 imm_use_iterator iter;
5332 use_operand_p use_p;
5333 enum ssa_prop_result res = SSA_PROP_VARYING;
5335 set_value_range_to_varying (get_value_range (lhs));
5337 FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
5339 gimple *use_stmt = USE_STMT (use_p);
5340 if (!is_gimple_assign (use_stmt))
5341 continue;
5342 enum tree_code rhs_code = gimple_assign_rhs_code (use_stmt);
5343 if (rhs_code != REALPART_EXPR && rhs_code != IMAGPART_EXPR)
5344 continue;
5345 tree rhs1 = gimple_assign_rhs1 (use_stmt);
5346 tree use_lhs = gimple_assign_lhs (use_stmt);
5347 if (TREE_CODE (rhs1) != rhs_code
5348 || TREE_OPERAND (rhs1, 0) != lhs
5349 || TREE_CODE (use_lhs) != SSA_NAME
5350 || !stmt_interesting_for_vrp (use_stmt)
5351 || (!INTEGRAL_TYPE_P (TREE_TYPE (use_lhs))
5352 || !TYPE_MIN_VALUE (TREE_TYPE (use_lhs))
5353 || !TYPE_MAX_VALUE (TREE_TYPE (use_lhs))))
5354 continue;
5356 /* If there is a change in the value range for any of the
5357 REALPART_EXPR/IMAGPART_EXPR immediate uses, return
5358 SSA_PROP_INTERESTING. If there are any REALPART_EXPR
5359 or IMAGPART_EXPR immediate uses, but none of them have
5360 a change in their value ranges, return
5361 SSA_PROP_NOT_INTERESTING. If there are no
5362 {REAL,IMAG}PART_EXPR uses at all,
5363 return SSA_PROP_VARYING. */
5364 value_range new_vr = VR_INITIALIZER;
5365 extract_range_basic (&new_vr, use_stmt);
5366 value_range *old_vr = get_value_range (use_lhs);
5367 if (old_vr->type != new_vr.type
5368 || !vrp_operand_equal_p (old_vr->min, new_vr.min)
5369 || !vrp_operand_equal_p (old_vr->max, new_vr.max)
5370 || !vrp_bitmap_equal_p (old_vr->equiv, new_vr.equiv))
5371 res = SSA_PROP_INTERESTING;
5372 else
5373 res = SSA_PROP_NOT_INTERESTING;
5374 BITMAP_FREE (new_vr.equiv);
5375 if (res == SSA_PROP_INTERESTING)
5377 *output_p = lhs;
5378 return res;
5382 return res;
5384 break;
5385 default:
5386 break;
5389 /* All other statements produce nothing of interest for VRP, so mark
5390 their outputs varying and prevent further simulation. */
5391 set_defs_to_varying (stmt);
5393 return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
5396 /* Union the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
5397 { VR1TYPE, VR0MIN, VR0MAX } and store the result
5398 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
5399 possible such range. The resulting range is not canonicalized. */
5401 static void
5402 union_ranges (enum value_range_type *vr0type,
5403 tree *vr0min, tree *vr0max,
5404 enum value_range_type vr1type,
5405 tree vr1min, tree vr1max)
5407 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
5408 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
5410 /* [] is vr0, () is vr1 in the following classification comments. */
5411 if (mineq && maxeq)
5413 /* [( )] */
5414 if (*vr0type == vr1type)
5415 /* Nothing to do for equal ranges. */
5417 else if ((*vr0type == VR_RANGE
5418 && vr1type == VR_ANTI_RANGE)
5419 || (*vr0type == VR_ANTI_RANGE
5420 && vr1type == VR_RANGE))
5422 /* For anti-range with range union the result is varying. */
5423 goto give_up;
5425 else
5426 gcc_unreachable ();
5428 else if (operand_less_p (*vr0max, vr1min) == 1
5429 || operand_less_p (vr1max, *vr0min) == 1)
5431 /* [ ] ( ) or ( ) [ ]
5432 If the ranges have an empty intersection, result of the union
5433 operation is the anti-range or if both are anti-ranges
5434 it covers all. */
5435 if (*vr0type == VR_ANTI_RANGE
5436 && vr1type == VR_ANTI_RANGE)
5437 goto give_up;
5438 else if (*vr0type == VR_ANTI_RANGE
5439 && vr1type == VR_RANGE)
5441 else if (*vr0type == VR_RANGE
5442 && vr1type == VR_ANTI_RANGE)
5444 *vr0type = vr1type;
5445 *vr0min = vr1min;
5446 *vr0max = vr1max;
5448 else if (*vr0type == VR_RANGE
5449 && vr1type == VR_RANGE)
5451 /* The result is the convex hull of both ranges. */
5452 if (operand_less_p (*vr0max, vr1min) == 1)
5454 /* If the result can be an anti-range, create one. */
5455 if (TREE_CODE (*vr0max) == INTEGER_CST
5456 && TREE_CODE (vr1min) == INTEGER_CST
5457 && vrp_val_is_min (*vr0min)
5458 && vrp_val_is_max (vr1max))
5460 tree min = int_const_binop (PLUS_EXPR,
5461 *vr0max,
5462 build_int_cst (TREE_TYPE (*vr0max), 1));
5463 tree max = int_const_binop (MINUS_EXPR,
5464 vr1min,
5465 build_int_cst (TREE_TYPE (vr1min), 1));
5466 if (!operand_less_p (max, min))
5468 *vr0type = VR_ANTI_RANGE;
5469 *vr0min = min;
5470 *vr0max = max;
5472 else
5473 *vr0max = vr1max;
5475 else
5476 *vr0max = vr1max;
5478 else
5480 /* If the result can be an anti-range, create one. */
5481 if (TREE_CODE (vr1max) == INTEGER_CST
5482 && TREE_CODE (*vr0min) == INTEGER_CST
5483 && vrp_val_is_min (vr1min)
5484 && vrp_val_is_max (*vr0max))
5486 tree min = int_const_binop (PLUS_EXPR,
5487 vr1max,
5488 build_int_cst (TREE_TYPE (vr1max), 1));
5489 tree max = int_const_binop (MINUS_EXPR,
5490 *vr0min,
5491 build_int_cst (TREE_TYPE (*vr0min), 1));
5492 if (!operand_less_p (max, min))
5494 *vr0type = VR_ANTI_RANGE;
5495 *vr0min = min;
5496 *vr0max = max;
5498 else
5499 *vr0min = vr1min;
5501 else
5502 *vr0min = vr1min;
5505 else
5506 gcc_unreachable ();
5508 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
5509 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
5511 /* [ ( ) ] or [( ) ] or [ ( )] */
5512 if (*vr0type == VR_RANGE
5513 && vr1type == VR_RANGE)
5515 else if (*vr0type == VR_ANTI_RANGE
5516 && vr1type == VR_ANTI_RANGE)
5518 *vr0type = vr1type;
5519 *vr0min = vr1min;
5520 *vr0max = vr1max;
5522 else if (*vr0type == VR_ANTI_RANGE
5523 && vr1type == VR_RANGE)
5525 /* Arbitrarily choose the right or left gap. */
5526 if (!mineq && TREE_CODE (vr1min) == INTEGER_CST)
5527 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5528 build_int_cst (TREE_TYPE (vr1min), 1));
5529 else if (!maxeq && TREE_CODE (vr1max) == INTEGER_CST)
5530 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5531 build_int_cst (TREE_TYPE (vr1max), 1));
5532 else
5533 goto give_up;
5535 else if (*vr0type == VR_RANGE
5536 && vr1type == VR_ANTI_RANGE)
5537 /* The result covers everything. */
5538 goto give_up;
5539 else
5540 gcc_unreachable ();
5542 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
5543 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
5545 /* ( [ ] ) or ([ ] ) or ( [ ]) */
5546 if (*vr0type == VR_RANGE
5547 && vr1type == VR_RANGE)
5549 *vr0type = vr1type;
5550 *vr0min = vr1min;
5551 *vr0max = vr1max;
5553 else if (*vr0type == VR_ANTI_RANGE
5554 && vr1type == VR_ANTI_RANGE)
5556 else if (*vr0type == VR_RANGE
5557 && vr1type == VR_ANTI_RANGE)
5559 *vr0type = VR_ANTI_RANGE;
5560 if (!mineq && TREE_CODE (*vr0min) == INTEGER_CST)
5562 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5563 build_int_cst (TREE_TYPE (*vr0min), 1));
5564 *vr0min = vr1min;
5566 else if (!maxeq && TREE_CODE (*vr0max) == INTEGER_CST)
5568 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5569 build_int_cst (TREE_TYPE (*vr0max), 1));
5570 *vr0max = vr1max;
5572 else
5573 goto give_up;
5575 else if (*vr0type == VR_ANTI_RANGE
5576 && vr1type == VR_RANGE)
5577 /* The result covers everything. */
5578 goto give_up;
5579 else
5580 gcc_unreachable ();
5582 else if ((operand_less_p (vr1min, *vr0max) == 1
5583 || operand_equal_p (vr1min, *vr0max, 0))
5584 && operand_less_p (*vr0min, vr1min) == 1
5585 && operand_less_p (*vr0max, vr1max) == 1)
5587 /* [ ( ] ) or [ ]( ) */
5588 if (*vr0type == VR_RANGE
5589 && vr1type == VR_RANGE)
5590 *vr0max = vr1max;
5591 else if (*vr0type == VR_ANTI_RANGE
5592 && vr1type == VR_ANTI_RANGE)
5593 *vr0min = vr1min;
5594 else if (*vr0type == VR_ANTI_RANGE
5595 && vr1type == VR_RANGE)
5597 if (TREE_CODE (vr1min) == INTEGER_CST)
5598 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5599 build_int_cst (TREE_TYPE (vr1min), 1));
5600 else
5601 goto give_up;
5603 else if (*vr0type == VR_RANGE
5604 && vr1type == VR_ANTI_RANGE)
5606 if (TREE_CODE (*vr0max) == INTEGER_CST)
5608 *vr0type = vr1type;
5609 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5610 build_int_cst (TREE_TYPE (*vr0max), 1));
5611 *vr0max = vr1max;
5613 else
5614 goto give_up;
5616 else
5617 gcc_unreachable ();
5619 else if ((operand_less_p (*vr0min, vr1max) == 1
5620 || operand_equal_p (*vr0min, vr1max, 0))
5621 && operand_less_p (vr1min, *vr0min) == 1
5622 && operand_less_p (vr1max, *vr0max) == 1)
5624 /* ( [ ) ] or ( )[ ] */
5625 if (*vr0type == VR_RANGE
5626 && vr1type == VR_RANGE)
5627 *vr0min = vr1min;
5628 else if (*vr0type == VR_ANTI_RANGE
5629 && vr1type == VR_ANTI_RANGE)
5630 *vr0max = vr1max;
5631 else if (*vr0type == VR_ANTI_RANGE
5632 && vr1type == VR_RANGE)
5634 if (TREE_CODE (vr1max) == INTEGER_CST)
5635 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5636 build_int_cst (TREE_TYPE (vr1max), 1));
5637 else
5638 goto give_up;
5640 else if (*vr0type == VR_RANGE
5641 && vr1type == VR_ANTI_RANGE)
5643 if (TREE_CODE (*vr0min) == INTEGER_CST)
5645 *vr0type = vr1type;
5646 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5647 build_int_cst (TREE_TYPE (*vr0min), 1));
5648 *vr0min = vr1min;
5650 else
5651 goto give_up;
5653 else
5654 gcc_unreachable ();
5656 else
5657 goto give_up;
5659 return;
5661 give_up:
5662 *vr0type = VR_VARYING;
5663 *vr0min = NULL_TREE;
5664 *vr0max = NULL_TREE;
5667 /* Intersect the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
5668 { VR1TYPE, VR0MIN, VR0MAX } and store the result
5669 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
5670 possible such range. The resulting range is not canonicalized. */
5672 static void
5673 intersect_ranges (enum value_range_type *vr0type,
5674 tree *vr0min, tree *vr0max,
5675 enum value_range_type vr1type,
5676 tree vr1min, tree vr1max)
5678 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
5679 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
5681 /* [] is vr0, () is vr1 in the following classification comments. */
5682 if (mineq && maxeq)
5684 /* [( )] */
5685 if (*vr0type == vr1type)
5686 /* Nothing to do for equal ranges. */
5688 else if ((*vr0type == VR_RANGE
5689 && vr1type == VR_ANTI_RANGE)
5690 || (*vr0type == VR_ANTI_RANGE
5691 && vr1type == VR_RANGE))
5693 /* For anti-range with range intersection the result is empty. */
5694 *vr0type = VR_UNDEFINED;
5695 *vr0min = NULL_TREE;
5696 *vr0max = NULL_TREE;
5698 else
5699 gcc_unreachable ();
5701 else if (operand_less_p (*vr0max, vr1min) == 1
5702 || operand_less_p (vr1max, *vr0min) == 1)
5704 /* [ ] ( ) or ( ) [ ]
5705 If the ranges have an empty intersection, the result of the
5706 intersect operation is the range for intersecting an
5707 anti-range with a range or empty when intersecting two ranges. */
5708 if (*vr0type == VR_RANGE
5709 && vr1type == VR_ANTI_RANGE)
5711 else if (*vr0type == VR_ANTI_RANGE
5712 && vr1type == VR_RANGE)
5714 *vr0type = vr1type;
5715 *vr0min = vr1min;
5716 *vr0max = vr1max;
5718 else if (*vr0type == VR_RANGE
5719 && vr1type == VR_RANGE)
5721 *vr0type = VR_UNDEFINED;
5722 *vr0min = NULL_TREE;
5723 *vr0max = NULL_TREE;
5725 else if (*vr0type == VR_ANTI_RANGE
5726 && vr1type == VR_ANTI_RANGE)
5728 /* If the anti-ranges are adjacent to each other merge them. */
5729 if (TREE_CODE (*vr0max) == INTEGER_CST
5730 && TREE_CODE (vr1min) == INTEGER_CST
5731 && operand_less_p (*vr0max, vr1min) == 1
5732 && integer_onep (int_const_binop (MINUS_EXPR,
5733 vr1min, *vr0max)))
5734 *vr0max = vr1max;
5735 else if (TREE_CODE (vr1max) == INTEGER_CST
5736 && TREE_CODE (*vr0min) == INTEGER_CST
5737 && operand_less_p (vr1max, *vr0min) == 1
5738 && integer_onep (int_const_binop (MINUS_EXPR,
5739 *vr0min, vr1max)))
5740 *vr0min = vr1min;
5741 /* Else arbitrarily take VR0. */
5744 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
5745 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
5747 /* [ ( ) ] or [( ) ] or [ ( )] */
5748 if (*vr0type == VR_RANGE
5749 && vr1type == VR_RANGE)
5751 /* If both are ranges the result is the inner one. */
5752 *vr0type = vr1type;
5753 *vr0min = vr1min;
5754 *vr0max = vr1max;
5756 else if (*vr0type == VR_RANGE
5757 && vr1type == VR_ANTI_RANGE)
5759 /* Choose the right gap if the left one is empty. */
5760 if (mineq)
5762 if (TREE_CODE (vr1max) != INTEGER_CST)
5763 *vr0min = vr1max;
5764 else if (TYPE_PRECISION (TREE_TYPE (vr1max)) == 1
5765 && !TYPE_UNSIGNED (TREE_TYPE (vr1max)))
5766 *vr0min
5767 = int_const_binop (MINUS_EXPR, vr1max,
5768 build_int_cst (TREE_TYPE (vr1max), -1));
5769 else
5770 *vr0min
5771 = int_const_binop (PLUS_EXPR, vr1max,
5772 build_int_cst (TREE_TYPE (vr1max), 1));
5774 /* Choose the left gap if the right one is empty. */
5775 else if (maxeq)
5777 if (TREE_CODE (vr1min) != INTEGER_CST)
5778 *vr0max = vr1min;
5779 else if (TYPE_PRECISION (TREE_TYPE (vr1min)) == 1
5780 && !TYPE_UNSIGNED (TREE_TYPE (vr1min)))
5781 *vr0max
5782 = int_const_binop (PLUS_EXPR, vr1min,
5783 build_int_cst (TREE_TYPE (vr1min), -1));
5784 else
5785 *vr0max
5786 = int_const_binop (MINUS_EXPR, vr1min,
5787 build_int_cst (TREE_TYPE (vr1min), 1));
5789 /* Choose the anti-range if the range is effectively varying. */
5790 else if (vrp_val_is_min (*vr0min)
5791 && vrp_val_is_max (*vr0max))
5793 *vr0type = vr1type;
5794 *vr0min = vr1min;
5795 *vr0max = vr1max;
5797 /* Else choose the range. */
5799 else if (*vr0type == VR_ANTI_RANGE
5800 && vr1type == VR_ANTI_RANGE)
5801 /* If both are anti-ranges the result is the outer one. */
5803 else if (*vr0type == VR_ANTI_RANGE
5804 && vr1type == VR_RANGE)
5806 /* The intersection is empty. */
5807 *vr0type = VR_UNDEFINED;
5808 *vr0min = NULL_TREE;
5809 *vr0max = NULL_TREE;
5811 else
5812 gcc_unreachable ();
5814 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
5815 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
5817 /* ( [ ] ) or ([ ] ) or ( [ ]) */
5818 if (*vr0type == VR_RANGE
5819 && vr1type == VR_RANGE)
5820 /* Choose the inner range. */
5822 else if (*vr0type == VR_ANTI_RANGE
5823 && vr1type == VR_RANGE)
5825 /* Choose the right gap if the left is empty. */
5826 if (mineq)
5828 *vr0type = VR_RANGE;
5829 if (TREE_CODE (*vr0max) != INTEGER_CST)
5830 *vr0min = *vr0max;
5831 else if (TYPE_PRECISION (TREE_TYPE (*vr0max)) == 1
5832 && !TYPE_UNSIGNED (TREE_TYPE (*vr0max)))
5833 *vr0min
5834 = int_const_binop (MINUS_EXPR, *vr0max,
5835 build_int_cst (TREE_TYPE (*vr0max), -1));
5836 else
5837 *vr0min
5838 = int_const_binop (PLUS_EXPR, *vr0max,
5839 build_int_cst (TREE_TYPE (*vr0max), 1));
5840 *vr0max = vr1max;
5842 /* Choose the left gap if the right is empty. */
5843 else if (maxeq)
5845 *vr0type = VR_RANGE;
5846 if (TREE_CODE (*vr0min) != INTEGER_CST)
5847 *vr0max = *vr0min;
5848 else if (TYPE_PRECISION (TREE_TYPE (*vr0min)) == 1
5849 && !TYPE_UNSIGNED (TREE_TYPE (*vr0min)))
5850 *vr0max
5851 = int_const_binop (PLUS_EXPR, *vr0min,
5852 build_int_cst (TREE_TYPE (*vr0min), -1));
5853 else
5854 *vr0max
5855 = int_const_binop (MINUS_EXPR, *vr0min,
5856 build_int_cst (TREE_TYPE (*vr0min), 1));
5857 *vr0min = vr1min;
5859 /* Choose the anti-range if the range is effectively varying. */
5860 else if (vrp_val_is_min (vr1min)
5861 && vrp_val_is_max (vr1max))
5863 /* Choose the anti-range if it is ~[0,0], that range is special
5864 enough to special case when vr1's range is relatively wide.
5865 At least for types bigger than int - this covers pointers
5866 and arguments to functions like ctz. */
5867 else if (*vr0min == *vr0max
5868 && integer_zerop (*vr0min)
5869 && ((TYPE_PRECISION (TREE_TYPE (*vr0min))
5870 >= TYPE_PRECISION (integer_type_node))
5871 || POINTER_TYPE_P (TREE_TYPE (*vr0min)))
5872 && TREE_CODE (vr1max) == INTEGER_CST
5873 && TREE_CODE (vr1min) == INTEGER_CST
5874 && (wi::clz (wi::to_wide (vr1max) - wi::to_wide (vr1min))
5875 < TYPE_PRECISION (TREE_TYPE (*vr0min)) / 2))
5877 /* Else choose the range. */
5878 else
5880 *vr0type = vr1type;
5881 *vr0min = vr1min;
5882 *vr0max = vr1max;
5885 else if (*vr0type == VR_ANTI_RANGE
5886 && vr1type == VR_ANTI_RANGE)
5888 /* If both are anti-ranges the result is the outer one. */
5889 *vr0type = vr1type;
5890 *vr0min = vr1min;
5891 *vr0max = vr1max;
5893 else if (vr1type == VR_ANTI_RANGE
5894 && *vr0type == VR_RANGE)
5896 /* The intersection is empty. */
5897 *vr0type = VR_UNDEFINED;
5898 *vr0min = NULL_TREE;
5899 *vr0max = NULL_TREE;
5901 else
5902 gcc_unreachable ();
5904 else if ((operand_less_p (vr1min, *vr0max) == 1
5905 || operand_equal_p (vr1min, *vr0max, 0))
5906 && operand_less_p (*vr0min, vr1min) == 1)
5908 /* [ ( ] ) or [ ]( ) */
5909 if (*vr0type == VR_ANTI_RANGE
5910 && vr1type == VR_ANTI_RANGE)
5911 *vr0max = vr1max;
5912 else if (*vr0type == VR_RANGE
5913 && vr1type == VR_RANGE)
5914 *vr0min = vr1min;
5915 else if (*vr0type == VR_RANGE
5916 && vr1type == VR_ANTI_RANGE)
5918 if (TREE_CODE (vr1min) == INTEGER_CST)
5919 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5920 build_int_cst (TREE_TYPE (vr1min), 1));
5921 else
5922 *vr0max = vr1min;
5924 else if (*vr0type == VR_ANTI_RANGE
5925 && vr1type == VR_RANGE)
5927 *vr0type = VR_RANGE;
5928 if (TREE_CODE (*vr0max) == INTEGER_CST)
5929 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5930 build_int_cst (TREE_TYPE (*vr0max), 1));
5931 else
5932 *vr0min = *vr0max;
5933 *vr0max = vr1max;
5935 else
5936 gcc_unreachable ();
5938 else if ((operand_less_p (*vr0min, vr1max) == 1
5939 || operand_equal_p (*vr0min, vr1max, 0))
5940 && operand_less_p (vr1min, *vr0min) == 1)
5942 /* ( [ ) ] or ( )[ ] */
5943 if (*vr0type == VR_ANTI_RANGE
5944 && vr1type == VR_ANTI_RANGE)
5945 *vr0min = vr1min;
5946 else if (*vr0type == VR_RANGE
5947 && vr1type == VR_RANGE)
5948 *vr0max = vr1max;
5949 else if (*vr0type == VR_RANGE
5950 && vr1type == VR_ANTI_RANGE)
5952 if (TREE_CODE (vr1max) == INTEGER_CST)
5953 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5954 build_int_cst (TREE_TYPE (vr1max), 1));
5955 else
5956 *vr0min = vr1max;
5958 else if (*vr0type == VR_ANTI_RANGE
5959 && vr1type == VR_RANGE)
5961 *vr0type = VR_RANGE;
5962 if (TREE_CODE (*vr0min) == INTEGER_CST)
5963 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5964 build_int_cst (TREE_TYPE (*vr0min), 1));
5965 else
5966 *vr0max = *vr0min;
5967 *vr0min = vr1min;
5969 else
5970 gcc_unreachable ();
5973 /* As a fallback simply use { *VRTYPE, *VR0MIN, *VR0MAX } as
5974 result for the intersection. That's always a conservative
5975 correct estimate unless VR1 is a constant singleton range
5976 in which case we choose that. */
5977 if (vr1type == VR_RANGE
5978 && is_gimple_min_invariant (vr1min)
5979 && vrp_operand_equal_p (vr1min, vr1max))
5981 *vr0type = vr1type;
5982 *vr0min = vr1min;
5983 *vr0max = vr1max;
5986 return;
5990 /* Intersect the two value-ranges *VR0 and *VR1 and store the result
5991 in *VR0. This may not be the smallest possible such range. */
5993 static void
5994 vrp_intersect_ranges_1 (value_range *vr0, value_range *vr1)
5996 value_range saved;
5998 /* If either range is VR_VARYING the other one wins. */
5999 if (vr1->type == VR_VARYING)
6000 return;
6001 if (vr0->type == VR_VARYING)
6003 copy_value_range (vr0, vr1);
6004 return;
6007 /* When either range is VR_UNDEFINED the resulting range is
6008 VR_UNDEFINED, too. */
6009 if (vr0->type == VR_UNDEFINED)
6010 return;
6011 if (vr1->type == VR_UNDEFINED)
6013 set_value_range_to_undefined (vr0);
6014 return;
6017 /* Save the original vr0 so we can return it as conservative intersection
6018 result when our worker turns things to varying. */
6019 saved = *vr0;
6020 intersect_ranges (&vr0->type, &vr0->min, &vr0->max,
6021 vr1->type, vr1->min, vr1->max);
6022 /* Make sure to canonicalize the result though as the inversion of a
6023 VR_RANGE can still be a VR_RANGE. */
6024 set_and_canonicalize_value_range (vr0, vr0->type,
6025 vr0->min, vr0->max, vr0->equiv);
6026 /* If that failed, use the saved original VR0. */
6027 if (vr0->type == VR_VARYING)
6029 *vr0 = saved;
6030 return;
6032 /* If the result is VR_UNDEFINED there is no need to mess with
6033 the equivalencies. */
6034 if (vr0->type == VR_UNDEFINED)
6035 return;
6037 /* The resulting set of equivalences for range intersection is the union of
6038 the two sets. */
6039 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
6040 bitmap_ior_into (vr0->equiv, vr1->equiv);
6041 else if (vr1->equiv && !vr0->equiv)
6043 /* All equivalence bitmaps are allocated from the same obstack. So
6044 we can use the obstack associated with VR to allocate vr0->equiv. */
6045 vr0->equiv = BITMAP_ALLOC (vr1->equiv->obstack);
6046 bitmap_copy (vr0->equiv, vr1->equiv);
6050 void
6051 vrp_intersect_ranges (value_range *vr0, value_range *vr1)
6053 if (dump_file && (dump_flags & TDF_DETAILS))
6055 fprintf (dump_file, "Intersecting\n ");
6056 dump_value_range (dump_file, vr0);
6057 fprintf (dump_file, "\nand\n ");
6058 dump_value_range (dump_file, vr1);
6059 fprintf (dump_file, "\n");
6061 vrp_intersect_ranges_1 (vr0, vr1);
6062 if (dump_file && (dump_flags & TDF_DETAILS))
6064 fprintf (dump_file, "to\n ");
6065 dump_value_range (dump_file, vr0);
6066 fprintf (dump_file, "\n");
6070 /* Meet operation for value ranges. Given two value ranges VR0 and
6071 VR1, store in VR0 a range that contains both VR0 and VR1. This
6072 may not be the smallest possible such range. */
6074 static void
6075 vrp_meet_1 (value_range *vr0, const value_range *vr1)
6077 value_range saved;
6079 if (vr0->type == VR_UNDEFINED)
6081 set_value_range (vr0, vr1->type, vr1->min, vr1->max, vr1->equiv);
6082 return;
6085 if (vr1->type == VR_UNDEFINED)
6087 /* VR0 already has the resulting range. */
6088 return;
6091 if (vr0->type == VR_VARYING)
6093 /* Nothing to do. VR0 already has the resulting range. */
6094 return;
6097 if (vr1->type == VR_VARYING)
6099 set_value_range_to_varying (vr0);
6100 return;
6103 saved = *vr0;
6104 union_ranges (&vr0->type, &vr0->min, &vr0->max,
6105 vr1->type, vr1->min, vr1->max);
6106 if (vr0->type == VR_VARYING)
6108 /* Failed to find an efficient meet. Before giving up and setting
6109 the result to VARYING, see if we can at least derive a useful
6110 anti-range. FIXME, all this nonsense about distinguishing
6111 anti-ranges from ranges is necessary because of the odd
6112 semantics of range_includes_zero_p and friends. */
6113 if (((saved.type == VR_RANGE
6114 && range_includes_zero_p (saved.min, saved.max) == 0)
6115 || (saved.type == VR_ANTI_RANGE
6116 && range_includes_zero_p (saved.min, saved.max) == 1))
6117 && ((vr1->type == VR_RANGE
6118 && range_includes_zero_p (vr1->min, vr1->max) == 0)
6119 || (vr1->type == VR_ANTI_RANGE
6120 && range_includes_zero_p (vr1->min, vr1->max) == 1)))
6122 set_value_range_to_nonnull (vr0, TREE_TYPE (saved.min));
6124 /* Since this meet operation did not result from the meeting of
6125 two equivalent names, VR0 cannot have any equivalences. */
6126 if (vr0->equiv)
6127 bitmap_clear (vr0->equiv);
6128 return;
6131 set_value_range_to_varying (vr0);
6132 return;
6134 set_and_canonicalize_value_range (vr0, vr0->type, vr0->min, vr0->max,
6135 vr0->equiv);
6136 if (vr0->type == VR_VARYING)
6137 return;
6139 /* The resulting set of equivalences is always the intersection of
6140 the two sets. */
6141 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
6142 bitmap_and_into (vr0->equiv, vr1->equiv);
6143 else if (vr0->equiv && !vr1->equiv)
6144 bitmap_clear (vr0->equiv);
6147 void
6148 vrp_meet (value_range *vr0, const value_range *vr1)
6150 if (dump_file && (dump_flags & TDF_DETAILS))
6152 fprintf (dump_file, "Meeting\n ");
6153 dump_value_range (dump_file, vr0);
6154 fprintf (dump_file, "\nand\n ");
6155 dump_value_range (dump_file, vr1);
6156 fprintf (dump_file, "\n");
6158 vrp_meet_1 (vr0, vr1);
6159 if (dump_file && (dump_flags & TDF_DETAILS))
6161 fprintf (dump_file, "to\n ");
6162 dump_value_range (dump_file, vr0);
6163 fprintf (dump_file, "\n");
6168 /* Visit all arguments for PHI node PHI that flow through executable
6169 edges. If a valid value range can be derived from all the incoming
6170 value ranges, set a new range for the LHS of PHI. */
6172 enum ssa_prop_result
6173 vrp_prop::visit_phi (gphi *phi)
6175 tree lhs = PHI_RESULT (phi);
6176 value_range vr_result = VR_INITIALIZER;
6177 extract_range_from_phi_node (phi, &vr_result);
6178 if (update_value_range (lhs, &vr_result))
6180 if (dump_file && (dump_flags & TDF_DETAILS))
6182 fprintf (dump_file, "Found new range for ");
6183 print_generic_expr (dump_file, lhs);
6184 fprintf (dump_file, ": ");
6185 dump_value_range (dump_file, &vr_result);
6186 fprintf (dump_file, "\n");
6189 if (vr_result.type == VR_VARYING)
6190 return SSA_PROP_VARYING;
6192 return SSA_PROP_INTERESTING;
6195 /* Nothing changed, don't add outgoing edges. */
6196 return SSA_PROP_NOT_INTERESTING;
6199 class vrp_folder : public substitute_and_fold_engine
6201 public:
6202 tree get_value (tree) FINAL OVERRIDE;
6203 bool fold_stmt (gimple_stmt_iterator *) FINAL OVERRIDE;
6204 bool fold_predicate_in (gimple_stmt_iterator *);
6206 class vr_values *vr_values;
6208 /* Delegators. */
6209 tree vrp_evaluate_conditional (tree_code code, tree op0,
6210 tree op1, gimple *stmt)
6211 { return vr_values->vrp_evaluate_conditional (code, op0, op1, stmt); }
6212 bool simplify_stmt_using_ranges (gimple_stmt_iterator *gsi)
6213 { return vr_values->simplify_stmt_using_ranges (gsi); }
6214 tree op_with_constant_singleton_value_range (tree op)
6215 { return vr_values->op_with_constant_singleton_value_range (op); }
6218 /* If the statement pointed by SI has a predicate whose value can be
6219 computed using the value range information computed by VRP, compute
6220 its value and return true. Otherwise, return false. */
6222 bool
6223 vrp_folder::fold_predicate_in (gimple_stmt_iterator *si)
6225 bool assignment_p = false;
6226 tree val;
6227 gimple *stmt = gsi_stmt (*si);
6229 if (is_gimple_assign (stmt)
6230 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
6232 assignment_p = true;
6233 val = vrp_evaluate_conditional (gimple_assign_rhs_code (stmt),
6234 gimple_assign_rhs1 (stmt),
6235 gimple_assign_rhs2 (stmt),
6236 stmt);
6238 else if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
6239 val = vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
6240 gimple_cond_lhs (cond_stmt),
6241 gimple_cond_rhs (cond_stmt),
6242 stmt);
6243 else
6244 return false;
6246 if (val)
6248 if (assignment_p)
6249 val = fold_convert (gimple_expr_type (stmt), val);
6251 if (dump_file)
6253 fprintf (dump_file, "Folding predicate ");
6254 print_gimple_expr (dump_file, stmt, 0);
6255 fprintf (dump_file, " to ");
6256 print_generic_expr (dump_file, val);
6257 fprintf (dump_file, "\n");
6260 if (is_gimple_assign (stmt))
6261 gimple_assign_set_rhs_from_tree (si, val);
6262 else
6264 gcc_assert (gimple_code (stmt) == GIMPLE_COND);
6265 gcond *cond_stmt = as_a <gcond *> (stmt);
6266 if (integer_zerop (val))
6267 gimple_cond_make_false (cond_stmt);
6268 else if (integer_onep (val))
6269 gimple_cond_make_true (cond_stmt);
6270 else
6271 gcc_unreachable ();
6274 return true;
6277 return false;
6280 /* Callback for substitute_and_fold folding the stmt at *SI. */
6282 bool
6283 vrp_folder::fold_stmt (gimple_stmt_iterator *si)
6285 if (fold_predicate_in (si))
6286 return true;
6288 return simplify_stmt_using_ranges (si);
6291 /* If OP has a value range with a single constant value return that,
6292 otherwise return NULL_TREE. This returns OP itself if OP is a
6293 constant.
6295 Implemented as a pure wrapper right now, but this will change. */
6297 tree
6298 vrp_folder::get_value (tree op)
6300 return op_with_constant_singleton_value_range (op);
6303 /* Return the LHS of any ASSERT_EXPR where OP appears as the first
6304 argument to the ASSERT_EXPR and in which the ASSERT_EXPR dominates
6305 BB. If no such ASSERT_EXPR is found, return OP. */
6307 static tree
6308 lhs_of_dominating_assert (tree op, basic_block bb, gimple *stmt)
6310 imm_use_iterator imm_iter;
6311 gimple *use_stmt;
6312 use_operand_p use_p;
6314 if (TREE_CODE (op) == SSA_NAME)
6316 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, op)
6318 use_stmt = USE_STMT (use_p);
6319 if (use_stmt != stmt
6320 && gimple_assign_single_p (use_stmt)
6321 && TREE_CODE (gimple_assign_rhs1 (use_stmt)) == ASSERT_EXPR
6322 && TREE_OPERAND (gimple_assign_rhs1 (use_stmt), 0) == op
6323 && dominated_by_p (CDI_DOMINATORS, bb, gimple_bb (use_stmt)))
6324 return gimple_assign_lhs (use_stmt);
6327 return op;
6330 /* A hack. */
6331 static class vr_values *x_vr_values;
6333 /* A trivial wrapper so that we can present the generic jump threading
6334 code with a simple API for simplifying statements. STMT is the
6335 statement we want to simplify, WITHIN_STMT provides the location
6336 for any overflow warnings. */
6338 static tree
6339 simplify_stmt_for_jump_threading (gimple *stmt, gimple *within_stmt,
6340 class avail_exprs_stack *avail_exprs_stack ATTRIBUTE_UNUSED,
6341 basic_block bb)
6343 /* First see if the conditional is in the hash table. */
6344 tree cached_lhs = avail_exprs_stack->lookup_avail_expr (stmt, false, true);
6345 if (cached_lhs && is_gimple_min_invariant (cached_lhs))
6346 return cached_lhs;
6348 vr_values *vr_values = x_vr_values;
6349 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
6351 tree op0 = gimple_cond_lhs (cond_stmt);
6352 op0 = lhs_of_dominating_assert (op0, bb, stmt);
6354 tree op1 = gimple_cond_rhs (cond_stmt);
6355 op1 = lhs_of_dominating_assert (op1, bb, stmt);
6357 return vr_values->vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
6358 op0, op1, within_stmt);
6361 /* We simplify a switch statement by trying to determine which case label
6362 will be taken. If we are successful then we return the corresponding
6363 CASE_LABEL_EXPR. */
6364 if (gswitch *switch_stmt = dyn_cast <gswitch *> (stmt))
6366 tree op = gimple_switch_index (switch_stmt);
6367 if (TREE_CODE (op) != SSA_NAME)
6368 return NULL_TREE;
6370 op = lhs_of_dominating_assert (op, bb, stmt);
6372 value_range *vr = vr_values->get_value_range (op);
6373 if ((vr->type != VR_RANGE && vr->type != VR_ANTI_RANGE)
6374 || symbolic_range_p (vr))
6375 return NULL_TREE;
6377 if (vr->type == VR_RANGE)
6379 size_t i, j;
6380 /* Get the range of labels that contain a part of the operand's
6381 value range. */
6382 find_case_label_range (switch_stmt, vr->min, vr->max, &i, &j);
6384 /* Is there only one such label? */
6385 if (i == j)
6387 tree label = gimple_switch_label (switch_stmt, i);
6389 /* The i'th label will be taken only if the value range of the
6390 operand is entirely within the bounds of this label. */
6391 if (CASE_HIGH (label) != NULL_TREE
6392 ? (tree_int_cst_compare (CASE_LOW (label), vr->min) <= 0
6393 && tree_int_cst_compare (CASE_HIGH (label), vr->max) >= 0)
6394 : (tree_int_cst_equal (CASE_LOW (label), vr->min)
6395 && tree_int_cst_equal (vr->min, vr->max)))
6396 return label;
6399 /* If there are no such labels then the default label will be
6400 taken. */
6401 if (i > j)
6402 return gimple_switch_label (switch_stmt, 0);
6405 if (vr->type == VR_ANTI_RANGE)
6407 unsigned n = gimple_switch_num_labels (switch_stmt);
6408 tree min_label = gimple_switch_label (switch_stmt, 1);
6409 tree max_label = gimple_switch_label (switch_stmt, n - 1);
6411 /* The default label will be taken only if the anti-range of the
6412 operand is entirely outside the bounds of all the (non-default)
6413 case labels. */
6414 if (tree_int_cst_compare (vr->min, CASE_LOW (min_label)) <= 0
6415 && (CASE_HIGH (max_label) != NULL_TREE
6416 ? tree_int_cst_compare (vr->max, CASE_HIGH (max_label)) >= 0
6417 : tree_int_cst_compare (vr->max, CASE_LOW (max_label)) >= 0))
6418 return gimple_switch_label (switch_stmt, 0);
6421 return NULL_TREE;
6424 if (gassign *assign_stmt = dyn_cast <gassign *> (stmt))
6426 tree lhs = gimple_assign_lhs (assign_stmt);
6427 if (TREE_CODE (lhs) == SSA_NAME
6428 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
6429 || POINTER_TYPE_P (TREE_TYPE (lhs)))
6430 && stmt_interesting_for_vrp (stmt))
6432 edge dummy_e;
6433 tree dummy_tree;
6434 value_range new_vr = VR_INITIALIZER;
6435 vr_values->extract_range_from_stmt (stmt, &dummy_e,
6436 &dummy_tree, &new_vr);
6437 if (range_int_cst_singleton_p (&new_vr))
6438 return new_vr.min;
6442 return NULL_TREE;
6445 class vrp_dom_walker : public dom_walker
6447 public:
6448 vrp_dom_walker (cdi_direction direction,
6449 class const_and_copies *const_and_copies,
6450 class avail_exprs_stack *avail_exprs_stack)
6451 : dom_walker (direction, REACHABLE_BLOCKS),
6452 m_const_and_copies (const_and_copies),
6453 m_avail_exprs_stack (avail_exprs_stack),
6454 m_dummy_cond (NULL) {}
6456 virtual edge before_dom_children (basic_block);
6457 virtual void after_dom_children (basic_block);
6459 class vr_values *vr_values;
6461 private:
6462 class const_and_copies *m_const_and_copies;
6463 class avail_exprs_stack *m_avail_exprs_stack;
6465 gcond *m_dummy_cond;
6469 /* Called before processing dominator children of BB. We want to look
6470 at ASSERT_EXPRs and record information from them in the appropriate
6471 tables.
6473 We could look at other statements here. It's not seen as likely
6474 to significantly increase the jump threads we discover. */
6476 edge
6477 vrp_dom_walker::before_dom_children (basic_block bb)
6479 gimple_stmt_iterator gsi;
6481 m_avail_exprs_stack->push_marker ();
6482 m_const_and_copies->push_marker ();
6483 for (gsi = gsi_start_nondebug_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
6485 gimple *stmt = gsi_stmt (gsi);
6486 if (gimple_assign_single_p (stmt)
6487 && TREE_CODE (gimple_assign_rhs1 (stmt)) == ASSERT_EXPR)
6489 tree rhs1 = gimple_assign_rhs1 (stmt);
6490 tree cond = TREE_OPERAND (rhs1, 1);
6491 tree inverted = invert_truthvalue (cond);
6492 vec<cond_equivalence> p;
6493 p.create (3);
6494 record_conditions (&p, cond, inverted);
6495 for (unsigned int i = 0; i < p.length (); i++)
6496 m_avail_exprs_stack->record_cond (&p[i]);
6498 tree lhs = gimple_assign_lhs (stmt);
6499 m_const_and_copies->record_const_or_copy (lhs,
6500 TREE_OPERAND (rhs1, 0));
6501 p.release ();
6502 continue;
6504 break;
6506 return NULL;
6509 /* Called after processing dominator children of BB. This is where we
6510 actually call into the threader. */
6511 void
6512 vrp_dom_walker::after_dom_children (basic_block bb)
6514 if (!m_dummy_cond)
6515 m_dummy_cond = gimple_build_cond (NE_EXPR,
6516 integer_zero_node, integer_zero_node,
6517 NULL, NULL);
6519 x_vr_values = vr_values;
6520 thread_outgoing_edges (bb, m_dummy_cond, m_const_and_copies,
6521 m_avail_exprs_stack, NULL,
6522 simplify_stmt_for_jump_threading);
6523 x_vr_values = NULL;
6525 m_avail_exprs_stack->pop_to_marker ();
6526 m_const_and_copies->pop_to_marker ();
6529 /* Blocks which have more than one predecessor and more than
6530 one successor present jump threading opportunities, i.e.,
6531 when the block is reached from a specific predecessor, we
6532 may be able to determine which of the outgoing edges will
6533 be traversed. When this optimization applies, we are able
6534 to avoid conditionals at runtime and we may expose secondary
6535 optimization opportunities.
6537 This routine is effectively a driver for the generic jump
6538 threading code. It basically just presents the generic code
6539 with edges that may be suitable for jump threading.
6541 Unlike DOM, we do not iterate VRP if jump threading was successful.
6542 While iterating may expose new opportunities for VRP, it is expected
6543 those opportunities would be very limited and the compile time cost
6544 to expose those opportunities would be significant.
6546 As jump threading opportunities are discovered, they are registered
6547 for later realization. */
6549 static void
6550 identify_jump_threads (class vr_values *vr_values)
6552 int i;
6553 edge e;
6555 /* Ugh. When substituting values earlier in this pass we can
6556 wipe the dominance information. So rebuild the dominator
6557 information as we need it within the jump threading code. */
6558 calculate_dominance_info (CDI_DOMINATORS);
6560 /* We do not allow VRP information to be used for jump threading
6561 across a back edge in the CFG. Otherwise it becomes too
6562 difficult to avoid eliminating loop exit tests. Of course
6563 EDGE_DFS_BACK is not accurate at this time so we have to
6564 recompute it. */
6565 mark_dfs_back_edges ();
6567 /* Do not thread across edges we are about to remove. Just marking
6568 them as EDGE_IGNORE will do. */
6569 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
6570 e->flags |= EDGE_IGNORE;
6572 /* Allocate our unwinder stack to unwind any temporary equivalences
6573 that might be recorded. */
6574 const_and_copies *equiv_stack = new const_and_copies ();
6576 hash_table<expr_elt_hasher> *avail_exprs
6577 = new hash_table<expr_elt_hasher> (1024);
6578 avail_exprs_stack *avail_exprs_stack
6579 = new class avail_exprs_stack (avail_exprs);
6581 vrp_dom_walker walker (CDI_DOMINATORS, equiv_stack, avail_exprs_stack);
6582 walker.vr_values = vr_values;
6583 walker.walk (cfun->cfg->x_entry_block_ptr);
6585 /* Clear EDGE_IGNORE. */
6586 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
6587 e->flags &= ~EDGE_IGNORE;
6589 /* We do not actually update the CFG or SSA graphs at this point as
6590 ASSERT_EXPRs are still in the IL and cfg cleanup code does not yet
6591 handle ASSERT_EXPRs gracefully. */
6592 delete equiv_stack;
6593 delete avail_exprs;
6594 delete avail_exprs_stack;
6597 /* Traverse all the blocks folding conditionals with known ranges. */
6599 void
6600 vrp_prop::vrp_finalize (bool warn_array_bounds_p)
6602 size_t i;
6604 /* We have completed propagating through the lattice. */
6605 vr_values.set_lattice_propagation_complete ();
6607 if (dump_file)
6609 fprintf (dump_file, "\nValue ranges after VRP:\n\n");
6610 vr_values.dump_all_value_ranges (dump_file);
6611 fprintf (dump_file, "\n");
6614 /* Set value range to non pointer SSA_NAMEs. */
6615 for (i = 0; i < num_ssa_names; i++)
6617 tree name = ssa_name (i);
6618 if (!name)
6619 continue;
6621 value_range *vr = get_value_range (name);
6622 if (!name
6623 || (vr->type == VR_VARYING)
6624 || (vr->type == VR_UNDEFINED)
6625 || (TREE_CODE (vr->min) != INTEGER_CST)
6626 || (TREE_CODE (vr->max) != INTEGER_CST))
6627 continue;
6629 if (POINTER_TYPE_P (TREE_TYPE (name))
6630 && ((vr->type == VR_RANGE
6631 && range_includes_zero_p (vr->min, vr->max) == 0)
6632 || (vr->type == VR_ANTI_RANGE
6633 && range_includes_zero_p (vr->min, vr->max) == 1)))
6634 set_ptr_nonnull (name);
6635 else if (!POINTER_TYPE_P (TREE_TYPE (name)))
6636 set_range_info (name, vr->type,
6637 wi::to_wide (vr->min),
6638 wi::to_wide (vr->max));
6641 /* If we're checking array refs, we want to merge information on
6642 the executability of each edge between vrp_folder and the
6643 check_array_bounds_dom_walker: each can clear the
6644 EDGE_EXECUTABLE flag on edges, in different ways.
6646 Hence, if we're going to call check_all_array_refs, set
6647 the flag on every edge now, rather than in
6648 check_array_bounds_dom_walker's ctor; vrp_folder may clear
6649 it from some edges. */
6650 if (warn_array_bounds && warn_array_bounds_p)
6651 set_all_edges_as_executable (cfun);
6653 class vrp_folder vrp_folder;
6654 vrp_folder.vr_values = &vr_values;
6655 vrp_folder.substitute_and_fold ();
6657 if (warn_array_bounds && warn_array_bounds_p)
6658 check_all_array_refs ();
6661 /* Main entry point to VRP (Value Range Propagation). This pass is
6662 loosely based on J. R. C. Patterson, ``Accurate Static Branch
6663 Prediction by Value Range Propagation,'' in SIGPLAN Conference on
6664 Programming Language Design and Implementation, pp. 67-78, 1995.
6665 Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
6667 This is essentially an SSA-CCP pass modified to deal with ranges
6668 instead of constants.
6670 While propagating ranges, we may find that two or more SSA name
6671 have equivalent, though distinct ranges. For instance,
6673 1 x_9 = p_3->a;
6674 2 p_4 = ASSERT_EXPR <p_3, p_3 != 0>
6675 3 if (p_4 == q_2)
6676 4 p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
6677 5 endif
6678 6 if (q_2)
6680 In the code above, pointer p_5 has range [q_2, q_2], but from the
6681 code we can also determine that p_5 cannot be NULL and, if q_2 had
6682 a non-varying range, p_5's range should also be compatible with it.
6684 These equivalences are created by two expressions: ASSERT_EXPR and
6685 copy operations. Since p_5 is an assertion on p_4, and p_4 was the
6686 result of another assertion, then we can use the fact that p_5 and
6687 p_4 are equivalent when evaluating p_5's range.
6689 Together with value ranges, we also propagate these equivalences
6690 between names so that we can take advantage of information from
6691 multiple ranges when doing final replacement. Note that this
6692 equivalency relation is transitive but not symmetric.
6694 In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
6695 cannot assert that q_2 is equivalent to p_5 because q_2 may be used
6696 in contexts where that assertion does not hold (e.g., in line 6).
6698 TODO, the main difference between this pass and Patterson's is that
6699 we do not propagate edge probabilities. We only compute whether
6700 edges can be taken or not. That is, instead of having a spectrum
6701 of jump probabilities between 0 and 1, we only deal with 0, 1 and
6702 DON'T KNOW. In the future, it may be worthwhile to propagate
6703 probabilities to aid branch prediction. */
6705 static unsigned int
6706 execute_vrp (bool warn_array_bounds_p)
6708 int i;
6709 edge e;
6710 switch_update *su;
6712 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
6713 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
6714 scev_initialize ();
6716 /* ??? This ends up using stale EDGE_DFS_BACK for liveness computation.
6717 Inserting assertions may split edges which will invalidate
6718 EDGE_DFS_BACK. */
6719 insert_range_assertions ();
6721 to_remove_edges.create (10);
6722 to_update_switch_stmts.create (5);
6723 threadedge_initialize_values ();
6725 /* For visiting PHI nodes we need EDGE_DFS_BACK computed. */
6726 mark_dfs_back_edges ();
6728 class vrp_prop vrp_prop;
6729 vrp_prop.vrp_initialize ();
6730 vrp_prop.ssa_propagate ();
6731 vrp_prop.vrp_finalize (warn_array_bounds_p);
6733 /* We must identify jump threading opportunities before we release
6734 the datastructures built by VRP. */
6735 identify_jump_threads (&vrp_prop.vr_values);
6737 /* A comparison of an SSA_NAME against a constant where the SSA_NAME
6738 was set by a type conversion can often be rewritten to use the
6739 RHS of the type conversion.
6741 However, doing so inhibits jump threading through the comparison.
6742 So that transformation is not performed until after jump threading
6743 is complete. */
6744 basic_block bb;
6745 FOR_EACH_BB_FN (bb, cfun)
6747 gimple *last = last_stmt (bb);
6748 if (last && gimple_code (last) == GIMPLE_COND)
6749 vrp_prop.vr_values.simplify_cond_using_ranges_2 (as_a <gcond *> (last));
6752 free_numbers_of_iterations_estimates (cfun);
6754 /* ASSERT_EXPRs must be removed before finalizing jump threads
6755 as finalizing jump threads calls the CFG cleanup code which
6756 does not properly handle ASSERT_EXPRs. */
6757 remove_range_assertions ();
6759 /* If we exposed any new variables, go ahead and put them into
6760 SSA form now, before we handle jump threading. This simplifies
6761 interactions between rewriting of _DECL nodes into SSA form
6762 and rewriting SSA_NAME nodes into SSA form after block
6763 duplication and CFG manipulation. */
6764 update_ssa (TODO_update_ssa);
6766 /* We identified all the jump threading opportunities earlier, but could
6767 not transform the CFG at that time. This routine transforms the
6768 CFG and arranges for the dominator tree to be rebuilt if necessary.
6770 Note the SSA graph update will occur during the normal TODO
6771 processing by the pass manager. */
6772 thread_through_all_blocks (false);
6774 /* Remove dead edges from SWITCH_EXPR optimization. This leaves the
6775 CFG in a broken state and requires a cfg_cleanup run. */
6776 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
6777 remove_edge (e);
6778 /* Update SWITCH_EXPR case label vector. */
6779 FOR_EACH_VEC_ELT (to_update_switch_stmts, i, su)
6781 size_t j;
6782 size_t n = TREE_VEC_LENGTH (su->vec);
6783 tree label;
6784 gimple_switch_set_num_labels (su->stmt, n);
6785 for (j = 0; j < n; j++)
6786 gimple_switch_set_label (su->stmt, j, TREE_VEC_ELT (su->vec, j));
6787 /* As we may have replaced the default label with a regular one
6788 make sure to make it a real default label again. This ensures
6789 optimal expansion. */
6790 label = gimple_switch_label (su->stmt, 0);
6791 CASE_LOW (label) = NULL_TREE;
6792 CASE_HIGH (label) = NULL_TREE;
6795 if (to_remove_edges.length () > 0)
6797 free_dominance_info (CDI_DOMINATORS);
6798 loops_state_set (LOOPS_NEED_FIXUP);
6801 to_remove_edges.release ();
6802 to_update_switch_stmts.release ();
6803 threadedge_finalize_values ();
6805 scev_finalize ();
6806 loop_optimizer_finalize ();
6807 return 0;
6810 namespace {
6812 const pass_data pass_data_vrp =
6814 GIMPLE_PASS, /* type */
6815 "vrp", /* name */
6816 OPTGROUP_NONE, /* optinfo_flags */
6817 TV_TREE_VRP, /* tv_id */
6818 PROP_ssa, /* properties_required */
6819 0, /* properties_provided */
6820 0, /* properties_destroyed */
6821 0, /* todo_flags_start */
6822 ( TODO_cleanup_cfg | TODO_update_ssa ), /* todo_flags_finish */
6825 class pass_vrp : public gimple_opt_pass
6827 public:
6828 pass_vrp (gcc::context *ctxt)
6829 : gimple_opt_pass (pass_data_vrp, ctxt), warn_array_bounds_p (false)
6832 /* opt_pass methods: */
6833 opt_pass * clone () { return new pass_vrp (m_ctxt); }
6834 void set_pass_param (unsigned int n, bool param)
6836 gcc_assert (n == 0);
6837 warn_array_bounds_p = param;
6839 virtual bool gate (function *) { return flag_tree_vrp != 0; }
6840 virtual unsigned int execute (function *)
6841 { return execute_vrp (warn_array_bounds_p); }
6843 private:
6844 bool warn_array_bounds_p;
6845 }; // class pass_vrp
6847 } // anon namespace
6849 gimple_opt_pass *
6850 make_pass_vrp (gcc::context *ctxt)
6852 return new pass_vrp (ctxt);
6856 /* Worker for determine_value_range. */
6858 static void
6859 determine_value_range_1 (value_range *vr, tree expr)
6861 if (BINARY_CLASS_P (expr))
6863 value_range vr0 = VR_INITIALIZER, vr1 = VR_INITIALIZER;
6864 determine_value_range_1 (&vr0, TREE_OPERAND (expr, 0));
6865 determine_value_range_1 (&vr1, TREE_OPERAND (expr, 1));
6866 extract_range_from_binary_expr_1 (vr, TREE_CODE (expr), TREE_TYPE (expr),
6867 &vr0, &vr1);
6869 else if (UNARY_CLASS_P (expr))
6871 value_range vr0 = VR_INITIALIZER;
6872 determine_value_range_1 (&vr0, TREE_OPERAND (expr, 0));
6873 extract_range_from_unary_expr (vr, TREE_CODE (expr), TREE_TYPE (expr),
6874 &vr0, TREE_TYPE (TREE_OPERAND (expr, 0)));
6876 else if (TREE_CODE (expr) == INTEGER_CST)
6877 set_value_range_to_value (vr, expr, NULL);
6878 else
6880 value_range_type kind;
6881 wide_int min, max;
6882 /* For SSA names try to extract range info computed by VRP. Otherwise
6883 fall back to varying. */
6884 if (TREE_CODE (expr) == SSA_NAME
6885 && INTEGRAL_TYPE_P (TREE_TYPE (expr))
6886 && (kind = get_range_info (expr, &min, &max)) != VR_VARYING)
6887 set_value_range (vr, kind, wide_int_to_tree (TREE_TYPE (expr), min),
6888 wide_int_to_tree (TREE_TYPE (expr), max), NULL);
6889 else
6890 set_value_range_to_varying (vr);
6894 /* Compute a value-range for EXPR and set it in *MIN and *MAX. Return
6895 the determined range type. */
6897 value_range_type
6898 determine_value_range (tree expr, wide_int *min, wide_int *max)
6900 value_range vr = VR_INITIALIZER;
6901 determine_value_range_1 (&vr, expr);
6902 if ((vr.type == VR_RANGE
6903 || vr.type == VR_ANTI_RANGE)
6904 && !symbolic_range_p (&vr))
6906 *min = wi::to_wide (vr.min);
6907 *max = wi::to_wide (vr.max);
6908 return vr.type;
6911 return VR_VARYING;