introduce --enable-large-address-aware
[official-gcc.git] / gcc / tree-vrp.c
blobcbc2ea2f26b911117667e8f769e3dcd33638fe9e
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 /* Return the maximum value for TYPE. */
126 tree
127 vrp_val_max (const_tree type)
129 if (!INTEGRAL_TYPE_P (type))
130 return NULL_TREE;
132 return TYPE_MAX_VALUE (type);
135 /* Return the minimum value for TYPE. */
137 tree
138 vrp_val_min (const_tree type)
140 if (!INTEGRAL_TYPE_P (type))
141 return NULL_TREE;
143 return TYPE_MIN_VALUE (type);
146 /* Return whether VAL is equal to the maximum value of its type.
147 We can't do a simple equality comparison with TYPE_MAX_VALUE because
148 C typedefs and Ada subtypes can produce types whose TYPE_MAX_VALUE
149 is not == to the integer constant with the same value in the type. */
151 bool
152 vrp_val_is_max (const_tree val)
154 tree type_max = vrp_val_max (TREE_TYPE (val));
155 return (val == type_max
156 || (type_max != NULL_TREE
157 && operand_equal_p (val, type_max, 0)));
160 /* Return whether VAL is equal to the minimum value of its type. */
162 bool
163 vrp_val_is_min (const_tree val)
165 tree type_min = vrp_val_min (TREE_TYPE (val));
166 return (val == type_min
167 || (type_min != NULL_TREE
168 && operand_equal_p (val, type_min, 0)));
171 /* VR_TYPE describes a range with mininum value *MIN and maximum
172 value *MAX. Restrict the range to the set of values that have
173 no bits set outside NONZERO_BITS. Update *MIN and *MAX and
174 return the new range type.
176 SGN gives the sign of the values described by the range. */
178 enum value_range_type
179 intersect_range_with_nonzero_bits (enum value_range_type vr_type,
180 wide_int *min, wide_int *max,
181 const wide_int &nonzero_bits,
182 signop sgn)
184 if (vr_type == VR_ANTI_RANGE)
186 /* The VR_ANTI_RANGE is equivalent to the union of the ranges
187 A: [-INF, *MIN) and B: (*MAX, +INF]. First use NONZERO_BITS
188 to create an inclusive upper bound for A and an inclusive lower
189 bound for B. */
190 wide_int a_max = wi::round_down_for_mask (*min - 1, nonzero_bits);
191 wide_int b_min = wi::round_up_for_mask (*max + 1, nonzero_bits);
193 /* If the calculation of A_MAX wrapped, A is effectively empty
194 and A_MAX is the highest value that satisfies NONZERO_BITS.
195 Likewise if the calculation of B_MIN wrapped, B is effectively
196 empty and B_MIN is the lowest value that satisfies NONZERO_BITS. */
197 bool a_empty = wi::ge_p (a_max, *min, sgn);
198 bool b_empty = wi::le_p (b_min, *max, sgn);
200 /* If both A and B are empty, there are no valid values. */
201 if (a_empty && b_empty)
202 return VR_UNDEFINED;
204 /* If exactly one of A or B is empty, return a VR_RANGE for the
205 other one. */
206 if (a_empty || b_empty)
208 *min = b_min;
209 *max = a_max;
210 gcc_checking_assert (wi::le_p (*min, *max, sgn));
211 return VR_RANGE;
214 /* Update the VR_ANTI_RANGE bounds. */
215 *min = a_max + 1;
216 *max = b_min - 1;
217 gcc_checking_assert (wi::le_p (*min, *max, sgn));
219 /* Now check whether the excluded range includes any values that
220 satisfy NONZERO_BITS. If not, switch to a full VR_RANGE. */
221 if (wi::round_up_for_mask (*min, nonzero_bits) == b_min)
223 unsigned int precision = min->get_precision ();
224 *min = wi::min_value (precision, sgn);
225 *max = wi::max_value (precision, sgn);
226 vr_type = VR_RANGE;
229 if (vr_type == VR_RANGE)
231 *max = wi::round_down_for_mask (*max, nonzero_bits);
233 /* Check that the range contains at least one valid value. */
234 if (wi::gt_p (*min, *max, sgn))
235 return VR_UNDEFINED;
237 *min = wi::round_up_for_mask (*min, nonzero_bits);
238 gcc_checking_assert (wi::le_p (*min, *max, sgn));
240 return vr_type;
243 /* Set value range VR to VR_UNDEFINED. */
245 static inline void
246 set_value_range_to_undefined (value_range *vr)
248 vr->type = VR_UNDEFINED;
249 vr->min = vr->max = NULL_TREE;
250 if (vr->equiv)
251 bitmap_clear (vr->equiv);
254 /* Set value range VR to VR_VARYING. */
256 void
257 set_value_range_to_varying (value_range *vr)
259 vr->type = VR_VARYING;
260 vr->min = vr->max = NULL_TREE;
261 if (vr->equiv)
262 bitmap_clear (vr->equiv);
265 /* Set value range VR to {T, MIN, MAX, EQUIV}. */
267 void
268 set_value_range (value_range *vr, enum value_range_type t, tree min,
269 tree max, bitmap equiv)
271 /* Check the validity of the range. */
272 if (flag_checking
273 && (t == VR_RANGE || t == VR_ANTI_RANGE))
275 int cmp;
277 gcc_assert (min && max);
279 gcc_assert (!TREE_OVERFLOW_P (min) && !TREE_OVERFLOW_P (max));
281 if (INTEGRAL_TYPE_P (TREE_TYPE (min)) && t == VR_ANTI_RANGE)
282 gcc_assert (!vrp_val_is_min (min) || !vrp_val_is_max (max));
284 cmp = compare_values (min, max);
285 gcc_assert (cmp == 0 || cmp == -1 || cmp == -2);
288 if (flag_checking
289 && (t == VR_UNDEFINED || t == VR_VARYING))
291 gcc_assert (min == NULL_TREE && max == NULL_TREE);
292 gcc_assert (equiv == NULL || bitmap_empty_p (equiv));
295 vr->type = t;
296 vr->min = min;
297 vr->max = max;
299 /* Since updating the equivalence set involves deep copying the
300 bitmaps, only do it if absolutely necessary.
302 All equivalence bitmaps are allocated from the same obstack. So
303 we can use the obstack associated with EQUIV to allocate vr->equiv. */
304 if (vr->equiv == NULL
305 && equiv != NULL)
306 vr->equiv = BITMAP_ALLOC (equiv->obstack);
308 if (equiv != vr->equiv)
310 if (equiv && !bitmap_empty_p (equiv))
311 bitmap_copy (vr->equiv, equiv);
312 else
313 bitmap_clear (vr->equiv);
318 /* Set value range VR to the canonical form of {T, MIN, MAX, EQUIV}.
319 This means adjusting T, MIN and MAX representing the case of a
320 wrapping range with MAX < MIN covering [MIN, type_max] U [type_min, MAX]
321 as anti-rage ~[MAX+1, MIN-1]. Likewise for wrapping anti-ranges.
322 In corner cases where MAX+1 or MIN-1 wraps this will fall back
323 to varying.
324 This routine exists to ease canonicalization in the case where we
325 extract ranges from var + CST op limit. */
327 void
328 set_and_canonicalize_value_range (value_range *vr, enum value_range_type t,
329 tree min, tree max, bitmap equiv)
331 /* Use the canonical setters for VR_UNDEFINED and VR_VARYING. */
332 if (t == VR_UNDEFINED)
334 set_value_range_to_undefined (vr);
335 return;
337 else if (t == VR_VARYING)
339 set_value_range_to_varying (vr);
340 return;
343 /* Nothing to canonicalize for symbolic ranges. */
344 if (TREE_CODE (min) != INTEGER_CST
345 || TREE_CODE (max) != INTEGER_CST)
347 set_value_range (vr, t, min, max, equiv);
348 return;
351 /* Wrong order for min and max, to swap them and the VR type we need
352 to adjust them. */
353 if (tree_int_cst_lt (max, min))
355 tree one, tmp;
357 /* For one bit precision if max < min, then the swapped
358 range covers all values, so for VR_RANGE it is varying and
359 for VR_ANTI_RANGE empty range, so drop to varying as well. */
360 if (TYPE_PRECISION (TREE_TYPE (min)) == 1)
362 set_value_range_to_varying (vr);
363 return;
366 one = build_int_cst (TREE_TYPE (min), 1);
367 tmp = int_const_binop (PLUS_EXPR, max, one);
368 max = int_const_binop (MINUS_EXPR, min, one);
369 min = tmp;
371 /* There's one corner case, if we had [C+1, C] before we now have
372 that again. But this represents an empty value range, so drop
373 to varying in this case. */
374 if (tree_int_cst_lt (max, min))
376 set_value_range_to_varying (vr);
377 return;
380 t = t == VR_RANGE ? VR_ANTI_RANGE : VR_RANGE;
383 /* Anti-ranges that can be represented as ranges should be so. */
384 if (t == VR_ANTI_RANGE)
386 /* For -fstrict-enums we may receive out-of-range ranges so consider
387 values < -INF and values > INF as -INF/INF as well. */
388 tree type = TREE_TYPE (min);
389 bool is_min = (INTEGRAL_TYPE_P (type)
390 && tree_int_cst_compare (min, TYPE_MIN_VALUE (type)) <= 0);
391 bool is_max = (INTEGRAL_TYPE_P (type)
392 && tree_int_cst_compare (max, TYPE_MAX_VALUE (type)) >= 0);
394 if (is_min && is_max)
396 /* We cannot deal with empty ranges, drop to varying.
397 ??? This could be VR_UNDEFINED instead. */
398 set_value_range_to_varying (vr);
399 return;
401 else if (TYPE_PRECISION (TREE_TYPE (min)) == 1
402 && (is_min || is_max))
404 /* Non-empty boolean ranges can always be represented
405 as a singleton range. */
406 if (is_min)
407 min = max = vrp_val_max (TREE_TYPE (min));
408 else
409 min = max = vrp_val_min (TREE_TYPE (min));
410 t = VR_RANGE;
412 else if (is_min
413 /* As a special exception preserve non-null ranges. */
414 && !(TYPE_UNSIGNED (TREE_TYPE (min))
415 && integer_zerop (max)))
417 tree one = build_int_cst (TREE_TYPE (max), 1);
418 min = int_const_binop (PLUS_EXPR, max, one);
419 max = vrp_val_max (TREE_TYPE (max));
420 t = VR_RANGE;
422 else if (is_max)
424 tree one = build_int_cst (TREE_TYPE (min), 1);
425 max = int_const_binop (MINUS_EXPR, min, one);
426 min = vrp_val_min (TREE_TYPE (min));
427 t = VR_RANGE;
431 /* Do not drop [-INF(OVF), +INF(OVF)] to varying. (OVF) has to be sticky
432 to make sure VRP iteration terminates, otherwise we can get into
433 oscillations. */
435 set_value_range (vr, t, min, max, equiv);
438 /* Copy value range FROM into value range TO. */
440 void
441 copy_value_range (value_range *to, const value_range *from)
443 set_value_range (to, from->type, from->min, from->max, from->equiv);
446 /* Set value range VR to a single value. This function is only called
447 with values we get from statements, and exists to clear the
448 TREE_OVERFLOW flag. */
450 void
451 set_value_range_to_value (value_range *vr, tree val, bitmap equiv)
453 gcc_assert (is_gimple_min_invariant (val));
454 if (TREE_OVERFLOW_P (val))
455 val = drop_tree_overflow (val);
456 set_value_range (vr, VR_RANGE, val, val, equiv);
459 /* Set value range VR to a non-NULL range of type TYPE. */
461 void
462 set_value_range_to_nonnull (value_range *vr, tree type)
464 tree zero = build_int_cst (type, 0);
465 set_value_range (vr, VR_ANTI_RANGE, zero, zero, vr->equiv);
469 /* Set value range VR to a NULL range of type TYPE. */
471 void
472 set_value_range_to_null (value_range *vr, tree type)
474 set_value_range_to_value (vr, build_int_cst (type, 0), vr->equiv);
477 /* Return true, if VAL1 and VAL2 are equal values for VRP purposes. */
479 bool
480 vrp_operand_equal_p (const_tree val1, const_tree val2)
482 if (val1 == val2)
483 return true;
484 if (!val1 || !val2 || !operand_equal_p (val1, val2, 0))
485 return false;
486 return true;
489 /* Return true, if the bitmaps B1 and B2 are equal. */
491 bool
492 vrp_bitmap_equal_p (const_bitmap b1, const_bitmap b2)
494 return (b1 == b2
495 || ((!b1 || bitmap_empty_p (b1))
496 && (!b2 || bitmap_empty_p (b2)))
497 || (b1 && b2
498 && bitmap_equal_p (b1, b2)));
501 /* Return true if VR is [0, 0]. */
503 static inline bool
504 range_is_null (const value_range *vr)
506 return vr->type == VR_RANGE
507 && integer_zerop (vr->min)
508 && integer_zerop (vr->max);
511 /* Return true if max and min of VR are INTEGER_CST. It's not necessary
512 a singleton. */
514 bool
515 range_int_cst_p (const value_range *vr)
517 return (vr->type == VR_RANGE
518 && TREE_CODE (vr->max) == INTEGER_CST
519 && TREE_CODE (vr->min) == INTEGER_CST);
522 /* Return true if VR is a INTEGER_CST singleton. */
524 bool
525 range_int_cst_singleton_p (const value_range *vr)
527 return (range_int_cst_p (vr)
528 && tree_int_cst_equal (vr->min, vr->max));
531 /* Return true if value range VR involves at least one symbol. */
533 bool
534 symbolic_range_p (const value_range *vr)
536 return (!is_gimple_min_invariant (vr->min)
537 || !is_gimple_min_invariant (vr->max));
540 /* Return the single symbol (an SSA_NAME) contained in T if any, or NULL_TREE
541 otherwise. We only handle additive operations and set NEG to true if the
542 symbol is negated and INV to the invariant part, if any. */
544 tree
545 get_single_symbol (tree t, bool *neg, tree *inv)
547 bool neg_;
548 tree inv_;
550 *inv = NULL_TREE;
551 *neg = false;
553 if (TREE_CODE (t) == PLUS_EXPR
554 || TREE_CODE (t) == POINTER_PLUS_EXPR
555 || TREE_CODE (t) == MINUS_EXPR)
557 if (is_gimple_min_invariant (TREE_OPERAND (t, 0)))
559 neg_ = (TREE_CODE (t) == MINUS_EXPR);
560 inv_ = TREE_OPERAND (t, 0);
561 t = TREE_OPERAND (t, 1);
563 else if (is_gimple_min_invariant (TREE_OPERAND (t, 1)))
565 neg_ = false;
566 inv_ = TREE_OPERAND (t, 1);
567 t = TREE_OPERAND (t, 0);
569 else
570 return NULL_TREE;
572 else
574 neg_ = false;
575 inv_ = NULL_TREE;
578 if (TREE_CODE (t) == NEGATE_EXPR)
580 t = TREE_OPERAND (t, 0);
581 neg_ = !neg_;
584 if (TREE_CODE (t) != SSA_NAME)
585 return NULL_TREE;
587 if (inv_ && TREE_OVERFLOW_P (inv_))
588 inv_ = drop_tree_overflow (inv_);
590 *neg = neg_;
591 *inv = inv_;
592 return t;
595 /* The reverse operation: build a symbolic expression with TYPE
596 from symbol SYM, negated according to NEG, and invariant INV. */
598 static tree
599 build_symbolic_expr (tree type, tree sym, bool neg, tree inv)
601 const bool pointer_p = POINTER_TYPE_P (type);
602 tree t = sym;
604 if (neg)
605 t = build1 (NEGATE_EXPR, type, t);
607 if (integer_zerop (inv))
608 return t;
610 return build2 (pointer_p ? POINTER_PLUS_EXPR : PLUS_EXPR, type, t, inv);
613 /* Return
614 1 if VAL < VAL2
615 0 if !(VAL < VAL2)
616 -2 if those are incomparable. */
618 operand_less_p (tree val, tree val2)
620 /* LT is folded faster than GE and others. Inline the common case. */
621 if (TREE_CODE (val) == INTEGER_CST && TREE_CODE (val2) == INTEGER_CST)
622 return tree_int_cst_lt (val, val2);
623 else
625 tree tcmp;
627 fold_defer_overflow_warnings ();
629 tcmp = fold_binary_to_constant (LT_EXPR, boolean_type_node, val, val2);
631 fold_undefer_and_ignore_overflow_warnings ();
633 if (!tcmp
634 || TREE_CODE (tcmp) != INTEGER_CST)
635 return -2;
637 if (!integer_zerop (tcmp))
638 return 1;
641 return 0;
644 /* Compare two values VAL1 and VAL2. Return
646 -2 if VAL1 and VAL2 cannot be compared at compile-time,
647 -1 if VAL1 < VAL2,
648 0 if VAL1 == VAL2,
649 +1 if VAL1 > VAL2, and
650 +2 if VAL1 != VAL2
652 This is similar to tree_int_cst_compare but supports pointer values
653 and values that cannot be compared at compile time.
655 If STRICT_OVERFLOW_P is not NULL, then set *STRICT_OVERFLOW_P to
656 true if the return value is only valid if we assume that signed
657 overflow is undefined. */
660 compare_values_warnv (tree val1, tree val2, bool *strict_overflow_p)
662 if (val1 == val2)
663 return 0;
665 /* Below we rely on the fact that VAL1 and VAL2 are both pointers or
666 both integers. */
667 gcc_assert (POINTER_TYPE_P (TREE_TYPE (val1))
668 == POINTER_TYPE_P (TREE_TYPE (val2)));
670 /* Convert the two values into the same type. This is needed because
671 sizetype causes sign extension even for unsigned types. */
672 val2 = fold_convert (TREE_TYPE (val1), val2);
673 STRIP_USELESS_TYPE_CONVERSION (val2);
675 const bool overflow_undefined
676 = INTEGRAL_TYPE_P (TREE_TYPE (val1))
677 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1));
678 tree inv1, inv2;
679 bool neg1, neg2;
680 tree sym1 = get_single_symbol (val1, &neg1, &inv1);
681 tree sym2 = get_single_symbol (val2, &neg2, &inv2);
683 /* If VAL1 and VAL2 are of the form '[-]NAME [+ CST]', return -1 or +1
684 accordingly. If VAL1 and VAL2 don't use the same name, return -2. */
685 if (sym1 && sym2)
687 /* Both values must use the same name with the same sign. */
688 if (sym1 != sym2 || neg1 != neg2)
689 return -2;
691 /* [-]NAME + CST == [-]NAME + CST. */
692 if (inv1 == inv2)
693 return 0;
695 /* If overflow is defined we cannot simplify more. */
696 if (!overflow_undefined)
697 return -2;
699 if (strict_overflow_p != NULL
700 /* Symbolic range building sets TREE_NO_WARNING to declare
701 that overflow doesn't happen. */
702 && (!inv1 || !TREE_NO_WARNING (val1))
703 && (!inv2 || !TREE_NO_WARNING (val2)))
704 *strict_overflow_p = true;
706 if (!inv1)
707 inv1 = build_int_cst (TREE_TYPE (val1), 0);
708 if (!inv2)
709 inv2 = build_int_cst (TREE_TYPE (val2), 0);
711 return wi::cmp (wi::to_wide (inv1), wi::to_wide (inv2),
712 TYPE_SIGN (TREE_TYPE (val1)));
715 const bool cst1 = is_gimple_min_invariant (val1);
716 const bool cst2 = is_gimple_min_invariant (val2);
718 /* If one is of the form '[-]NAME + CST' and the other is constant, then
719 it might be possible to say something depending on the constants. */
720 if ((sym1 && inv1 && cst2) || (sym2 && inv2 && cst1))
722 if (!overflow_undefined)
723 return -2;
725 if (strict_overflow_p != NULL
726 /* Symbolic range building sets TREE_NO_WARNING to declare
727 that overflow doesn't happen. */
728 && (!sym1 || !TREE_NO_WARNING (val1))
729 && (!sym2 || !TREE_NO_WARNING (val2)))
730 *strict_overflow_p = true;
732 const signop sgn = TYPE_SIGN (TREE_TYPE (val1));
733 tree cst = cst1 ? val1 : val2;
734 tree inv = cst1 ? inv2 : inv1;
736 /* Compute the difference between the constants. If it overflows or
737 underflows, this means that we can trivially compare the NAME with
738 it and, consequently, the two values with each other. */
739 wide_int diff = wi::to_wide (cst) - wi::to_wide (inv);
740 if (wi::cmp (0, wi::to_wide (inv), sgn)
741 != wi::cmp (diff, wi::to_wide (cst), sgn))
743 const int res = wi::cmp (wi::to_wide (cst), wi::to_wide (inv), sgn);
744 return cst1 ? res : -res;
747 return -2;
750 /* We cannot say anything more for non-constants. */
751 if (!cst1 || !cst2)
752 return -2;
754 if (!POINTER_TYPE_P (TREE_TYPE (val1)))
756 /* We cannot compare overflowed values. */
757 if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
758 return -2;
760 if (TREE_CODE (val1) == INTEGER_CST
761 && TREE_CODE (val2) == INTEGER_CST)
762 return tree_int_cst_compare (val1, val2);
764 if (poly_int_tree_p (val1) && poly_int_tree_p (val2))
766 if (known_eq (wi::to_poly_widest (val1),
767 wi::to_poly_widest (val2)))
768 return 0;
769 if (known_lt (wi::to_poly_widest (val1),
770 wi::to_poly_widest (val2)))
771 return -1;
772 if (known_gt (wi::to_poly_widest (val1),
773 wi::to_poly_widest (val2)))
774 return 1;
777 return -2;
779 else
781 tree t;
783 /* First see if VAL1 and VAL2 are not the same. */
784 if (val1 == val2 || operand_equal_p (val1, val2, 0))
785 return 0;
787 /* If VAL1 is a lower address than VAL2, return -1. */
788 if (operand_less_p (val1, val2) == 1)
789 return -1;
791 /* If VAL1 is a higher address than VAL2, return +1. */
792 if (operand_less_p (val2, val1) == 1)
793 return 1;
795 /* If VAL1 is different than VAL2, return +2.
796 For integer constants we either have already returned -1 or 1
797 or they are equivalent. We still might succeed in proving
798 something about non-trivial operands. */
799 if (TREE_CODE (val1) != INTEGER_CST
800 || TREE_CODE (val2) != INTEGER_CST)
802 t = fold_binary_to_constant (NE_EXPR, boolean_type_node, val1, val2);
803 if (t && integer_onep (t))
804 return 2;
807 return -2;
811 /* Compare values like compare_values_warnv. */
814 compare_values (tree val1, tree val2)
816 bool sop;
817 return compare_values_warnv (val1, val2, &sop);
821 /* Return 1 if VAL is inside value range MIN <= VAL <= MAX,
822 0 if VAL is not inside [MIN, MAX],
823 -2 if we cannot tell either way.
825 Benchmark compile/20001226-1.c compilation time after changing this
826 function. */
829 value_inside_range (tree val, tree min, tree max)
831 int cmp1, cmp2;
833 cmp1 = operand_less_p (val, min);
834 if (cmp1 == -2)
835 return -2;
836 if (cmp1 == 1)
837 return 0;
839 cmp2 = operand_less_p (max, val);
840 if (cmp2 == -2)
841 return -2;
843 return !cmp2;
847 /* Return TRUE if *VR includes the value zero. */
849 bool
850 range_includes_zero_p (const value_range *vr)
852 if (vr->type == VR_VARYING)
853 return true;
855 /* Ughh, we don't know. We choose not to optimize. */
856 if (vr->type == VR_UNDEFINED)
857 return true;
859 tree zero = build_int_cst (TREE_TYPE (vr->min), 0);
860 if (vr->type == VR_ANTI_RANGE)
862 int res = value_inside_range (zero, vr->min, vr->max);
863 return res == 0 || res == -2;
865 return value_inside_range (zero, vr->min, vr->max) != 0;
868 /* If *VR has a value rante that is a single constant value return that,
869 otherwise return NULL_TREE. */
871 tree
872 value_range_constant_singleton (const value_range *vr)
874 if (vr->type == VR_RANGE
875 && vrp_operand_equal_p (vr->min, vr->max)
876 && is_gimple_min_invariant (vr->min))
877 return vr->min;
879 return NULL_TREE;
882 /* Value range wrapper for wide_int_range_set_zero_nonzero_bits.
884 Compute MAY_BE_NONZERO and MUST_BE_NONZERO bit masks for range in VR.
886 Return TRUE if VR was a constant range and we were able to compute
887 the bit masks. */
889 bool
890 vrp_set_zero_nonzero_bits (const tree expr_type,
891 const value_range *vr,
892 wide_int *may_be_nonzero,
893 wide_int *must_be_nonzero)
895 if (!range_int_cst_p (vr))
897 *may_be_nonzero = wi::minus_one (TYPE_PRECISION (expr_type));
898 *must_be_nonzero = wi::zero (TYPE_PRECISION (expr_type));
899 return false;
901 wide_int_range_set_zero_nonzero_bits (TYPE_SIGN (expr_type),
902 wi::to_wide (vr->min),
903 wi::to_wide (vr->max),
904 *may_be_nonzero, *must_be_nonzero);
905 return true;
908 /* Create two value-ranges in *VR0 and *VR1 from the anti-range *AR
909 so that *VR0 U *VR1 == *AR. Returns true if that is possible,
910 false otherwise. If *AR can be represented with a single range
911 *VR1 will be VR_UNDEFINED. */
913 static bool
914 ranges_from_anti_range (const value_range *ar,
915 value_range *vr0, value_range *vr1)
917 tree type = TREE_TYPE (ar->min);
919 vr0->type = VR_UNDEFINED;
920 vr1->type = VR_UNDEFINED;
922 /* As a future improvement, we could handle ~[0, A] as: [-INF, -1] U
923 [A+1, +INF]. Not sure if this helps in practice, though. */
925 if (ar->type != VR_ANTI_RANGE
926 || TREE_CODE (ar->min) != INTEGER_CST
927 || TREE_CODE (ar->max) != INTEGER_CST
928 || !vrp_val_min (type)
929 || !vrp_val_max (type))
930 return false;
932 if (!vrp_val_is_min (ar->min))
934 vr0->type = VR_RANGE;
935 vr0->min = vrp_val_min (type);
936 vr0->max = wide_int_to_tree (type, wi::to_wide (ar->min) - 1);
938 if (!vrp_val_is_max (ar->max))
940 vr1->type = VR_RANGE;
941 vr1->min = wide_int_to_tree (type, wi::to_wide (ar->max) + 1);
942 vr1->max = vrp_val_max (type);
944 if (vr0->type == VR_UNDEFINED)
946 *vr0 = *vr1;
947 vr1->type = VR_UNDEFINED;
950 return vr0->type != VR_UNDEFINED;
953 /* Extract the components of a value range into a pair of wide ints in
954 [WMIN, WMAX].
956 If the value range is anything but a VR_*RANGE of constants, the
957 resulting wide ints are set to [-MIN, +MAX] for the type. */
959 static void inline
960 extract_range_into_wide_ints (const value_range *vr,
961 signop sign, unsigned prec,
962 wide_int &wmin, wide_int &wmax)
964 if ((vr->type == VR_RANGE
965 || vr->type == VR_ANTI_RANGE)
966 && TREE_CODE (vr->min) == INTEGER_CST
967 && TREE_CODE (vr->max) == INTEGER_CST)
969 wmin = wi::to_wide (vr->min);
970 wmax = wi::to_wide (vr->max);
972 else
974 wmin = wi::min_value (prec, sign);
975 wmax = wi::max_value (prec, sign);
979 /* Value range wrapper for wide_int_range_multiplicative_op:
981 *VR = *VR0 .CODE. *VR1. */
983 static void
984 extract_range_from_multiplicative_op (value_range *vr,
985 enum tree_code code,
986 const value_range *vr0,
987 const value_range *vr1)
989 gcc_assert (code == MULT_EXPR
990 || code == TRUNC_DIV_EXPR
991 || code == FLOOR_DIV_EXPR
992 || code == CEIL_DIV_EXPR
993 || code == EXACT_DIV_EXPR
994 || code == ROUND_DIV_EXPR
995 || code == RSHIFT_EXPR
996 || code == LSHIFT_EXPR);
997 gcc_assert (vr0->type == VR_RANGE && vr0->type == vr1->type);
999 tree type = TREE_TYPE (vr0->min);
1000 wide_int res_lb, res_ub;
1001 wide_int vr0_lb = wi::to_wide (vr0->min);
1002 wide_int vr0_ub = wi::to_wide (vr0->max);
1003 wide_int vr1_lb = wi::to_wide (vr1->min);
1004 wide_int vr1_ub = wi::to_wide (vr1->max);
1005 bool overflow_undefined = TYPE_OVERFLOW_UNDEFINED (type);
1006 bool overflow_wraps = TYPE_OVERFLOW_WRAPS (type);
1007 unsigned prec = TYPE_PRECISION (type);
1009 if (wide_int_range_multiplicative_op (res_lb, res_ub,
1010 code, TYPE_SIGN (type), prec,
1011 vr0_lb, vr0_ub, vr1_lb, vr1_ub,
1012 overflow_undefined, overflow_wraps))
1013 set_and_canonicalize_value_range (vr, VR_RANGE,
1014 wide_int_to_tree (type, res_lb),
1015 wide_int_to_tree (type, res_ub), NULL);
1016 else
1017 set_value_range_to_varying (vr);
1020 /* If BOUND will include a symbolic bound, adjust it accordingly,
1021 otherwise leave it as is.
1023 CODE is the original operation that combined the bounds (PLUS_EXPR
1024 or MINUS_EXPR).
1026 TYPE is the type of the original operation.
1028 SYM_OPn is the symbolic for OPn if it has a symbolic.
1030 NEG_OPn is TRUE if the OPn was negated. */
1032 static void
1033 adjust_symbolic_bound (tree &bound, enum tree_code code, tree type,
1034 tree sym_op0, tree sym_op1,
1035 bool neg_op0, bool neg_op1)
1037 bool minus_p = (code == MINUS_EXPR);
1038 /* If the result bound is constant, we're done; otherwise, build the
1039 symbolic lower bound. */
1040 if (sym_op0 == sym_op1)
1042 else if (sym_op0)
1043 bound = build_symbolic_expr (type, sym_op0,
1044 neg_op0, bound);
1045 else if (sym_op1)
1047 /* We may not negate if that might introduce
1048 undefined overflow. */
1049 if (!minus_p
1050 || neg_op1
1051 || TYPE_OVERFLOW_WRAPS (type))
1052 bound = build_symbolic_expr (type, sym_op1,
1053 neg_op1 ^ minus_p, bound);
1054 else
1055 bound = NULL_TREE;
1059 /* Combine OP1 and OP1, which are two parts of a bound, into one wide
1060 int bound according to CODE. CODE is the operation combining the
1061 bound (either a PLUS_EXPR or a MINUS_EXPR).
1063 TYPE is the type of the combine operation.
1065 WI is the wide int to store the result.
1067 OVF is -1 if an underflow occurred, +1 if an overflow occurred or 0
1068 if over/underflow occurred. */
1070 static void
1071 combine_bound (enum tree_code code, wide_int &wi, wi::overflow_type &ovf,
1072 tree type, tree op0, tree op1)
1074 bool minus_p = (code == MINUS_EXPR);
1075 const signop sgn = TYPE_SIGN (type);
1076 const unsigned int prec = TYPE_PRECISION (type);
1078 /* Combine the bounds, if any. */
1079 if (op0 && op1)
1081 if (minus_p)
1082 wi = wi::sub (wi::to_wide (op0), wi::to_wide (op1), sgn, &ovf);
1083 else
1084 wi = wi::add (wi::to_wide (op0), wi::to_wide (op1), sgn, &ovf);
1086 else if (op0)
1087 wi = wi::to_wide (op0);
1088 else if (op1)
1090 if (minus_p)
1091 wi = wi::neg (wi::to_wide (op1), &ovf);
1092 else
1093 wi = wi::to_wide (op1);
1095 else
1096 wi = wi::shwi (0, prec);
1099 /* Given a range in [WMIN, WMAX], adjust it for possible overflow and
1100 put the result in VR.
1102 TYPE is the type of the range.
1104 MIN_OVF and MAX_OVF indicate what type of overflow, if any,
1105 occurred while originally calculating WMIN or WMAX. -1 indicates
1106 underflow. +1 indicates overflow. 0 indicates neither. */
1108 static void
1109 set_value_range_with_overflow (value_range &vr,
1110 tree type,
1111 const wide_int &wmin, const wide_int &wmax,
1112 wi::overflow_type min_ovf,
1113 wi::overflow_type max_ovf)
1115 const signop sgn = TYPE_SIGN (type);
1116 const unsigned int prec = TYPE_PRECISION (type);
1117 vr.type = VR_RANGE;
1118 vr.equiv = NULL;
1120 /* For one bit precision if max < min, then the swapped
1121 range covers all values. */
1122 if (prec == 1 && wi::lt_p (wmax, wmin, sgn))
1124 set_value_range_to_varying (&vr);
1125 return;
1128 if (TYPE_OVERFLOW_WRAPS (type))
1130 /* If overflow wraps, truncate the values and adjust the
1131 range kind and bounds appropriately. */
1132 wide_int tmin = wide_int::from (wmin, prec, sgn);
1133 wide_int tmax = wide_int::from (wmax, prec, sgn);
1134 if ((min_ovf != wi::OVF_NONE) == (max_ovf != wi::OVF_NONE))
1136 /* No overflow or both overflow or underflow. The
1137 range kind stays VR_RANGE. */
1138 vr.min = wide_int_to_tree (type, tmin);
1139 vr.max = wide_int_to_tree (type, tmax);
1141 else if ((min_ovf == wi::OVF_UNDERFLOW && max_ovf == wi::OVF_NONE)
1142 || (max_ovf == wi::OVF_OVERFLOW && min_ovf == wi::OVF_NONE))
1144 /* Min underflow or max overflow. The range kind
1145 changes to VR_ANTI_RANGE. */
1146 bool covers = false;
1147 wide_int tem = tmin;
1148 vr.type = VR_ANTI_RANGE;
1149 tmin = tmax + 1;
1150 if (wi::cmp (tmin, tmax, sgn) < 0)
1151 covers = true;
1152 tmax = tem - 1;
1153 if (wi::cmp (tmax, tem, sgn) > 0)
1154 covers = true;
1155 /* If the anti-range would cover nothing, drop to varying.
1156 Likewise if the anti-range bounds are outside of the
1157 types values. */
1158 if (covers || wi::cmp (tmin, tmax, sgn) > 0)
1160 set_value_range_to_varying (&vr);
1161 return;
1163 vr.min = wide_int_to_tree (type, tmin);
1164 vr.max = wide_int_to_tree (type, tmax);
1166 else
1168 /* Other underflow and/or overflow, drop to VR_VARYING. */
1169 set_value_range_to_varying (&vr);
1170 return;
1173 else
1175 /* If overflow does not wrap, saturate to the types min/max
1176 value. */
1177 wide_int type_min = wi::min_value (prec, sgn);
1178 wide_int type_max = wi::max_value (prec, sgn);
1179 if (min_ovf == wi::OVF_UNDERFLOW)
1180 vr.min = wide_int_to_tree (type, type_min);
1181 else if (min_ovf == wi::OVF_OVERFLOW)
1182 vr.min = wide_int_to_tree (type, type_max);
1183 else
1184 vr.min = wide_int_to_tree (type, wmin);
1186 if (max_ovf == wi::OVF_UNDERFLOW)
1187 vr.max = wide_int_to_tree (type, type_min);
1188 else if (max_ovf == wi::OVF_OVERFLOW)
1189 vr.max = wide_int_to_tree (type, type_max);
1190 else
1191 vr.max = wide_int_to_tree (type, wmax);
1195 /* Extract range information from a binary operation CODE based on
1196 the ranges of each of its operands *VR0 and *VR1 with resulting
1197 type EXPR_TYPE. The resulting range is stored in *VR. */
1199 void
1200 extract_range_from_binary_expr_1 (value_range *vr,
1201 enum tree_code code, tree expr_type,
1202 const value_range *vr0_,
1203 const value_range *vr1_)
1205 signop sign = TYPE_SIGN (expr_type);
1206 unsigned int prec = TYPE_PRECISION (expr_type);
1207 value_range vr0 = *vr0_, vr1 = *vr1_;
1208 value_range vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
1209 enum value_range_type type;
1210 tree min = NULL_TREE, max = NULL_TREE;
1211 int cmp;
1213 if (!INTEGRAL_TYPE_P (expr_type)
1214 && !POINTER_TYPE_P (expr_type))
1216 set_value_range_to_varying (vr);
1217 return;
1220 /* Not all binary expressions can be applied to ranges in a
1221 meaningful way. Handle only arithmetic operations. */
1222 if (code != PLUS_EXPR
1223 && code != MINUS_EXPR
1224 && code != POINTER_PLUS_EXPR
1225 && code != MULT_EXPR
1226 && code != TRUNC_DIV_EXPR
1227 && code != FLOOR_DIV_EXPR
1228 && code != CEIL_DIV_EXPR
1229 && code != EXACT_DIV_EXPR
1230 && code != ROUND_DIV_EXPR
1231 && code != TRUNC_MOD_EXPR
1232 && code != RSHIFT_EXPR
1233 && code != LSHIFT_EXPR
1234 && code != MIN_EXPR
1235 && code != MAX_EXPR
1236 && code != BIT_AND_EXPR
1237 && code != BIT_IOR_EXPR
1238 && code != BIT_XOR_EXPR)
1240 set_value_range_to_varying (vr);
1241 return;
1244 /* If both ranges are UNDEFINED, so is the result. */
1245 if (vr0.type == VR_UNDEFINED && vr1.type == VR_UNDEFINED)
1247 set_value_range_to_undefined (vr);
1248 return;
1250 /* If one of the ranges is UNDEFINED drop it to VARYING for the following
1251 code. At some point we may want to special-case operations that
1252 have UNDEFINED result for all or some value-ranges of the not UNDEFINED
1253 operand. */
1254 else if (vr0.type == VR_UNDEFINED)
1255 set_value_range_to_varying (&vr0);
1256 else if (vr1.type == VR_UNDEFINED)
1257 set_value_range_to_varying (&vr1);
1259 /* We get imprecise results from ranges_from_anti_range when
1260 code is EXACT_DIV_EXPR. We could mask out bits in the resulting
1261 range, but then we also need to hack up vrp_meet. It's just
1262 easier to special case when vr0 is ~[0,0] for EXACT_DIV_EXPR. */
1263 if (code == EXACT_DIV_EXPR
1264 && vr0.type == VR_ANTI_RANGE
1265 && vr0.min == vr0.max
1266 && integer_zerop (vr0.min))
1268 set_value_range_to_nonnull (vr, expr_type);
1269 return;
1272 /* Now canonicalize anti-ranges to ranges when they are not symbolic
1273 and express ~[] op X as ([]' op X) U ([]'' op X). */
1274 if (vr0.type == VR_ANTI_RANGE
1275 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
1277 extract_range_from_binary_expr_1 (vr, code, expr_type, &vrtem0, vr1_);
1278 if (vrtem1.type != VR_UNDEFINED)
1280 value_range vrres = VR_INITIALIZER;
1281 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
1282 &vrtem1, vr1_);
1283 vrp_meet (vr, &vrres);
1285 return;
1287 /* Likewise for X op ~[]. */
1288 if (vr1.type == VR_ANTI_RANGE
1289 && ranges_from_anti_range (&vr1, &vrtem0, &vrtem1))
1291 extract_range_from_binary_expr_1 (vr, code, expr_type, vr0_, &vrtem0);
1292 if (vrtem1.type != VR_UNDEFINED)
1294 value_range vrres = VR_INITIALIZER;
1295 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
1296 vr0_, &vrtem1);
1297 vrp_meet (vr, &vrres);
1299 return;
1302 /* The type of the resulting value range defaults to VR0.TYPE. */
1303 type = vr0.type;
1305 /* Refuse to operate on VARYING ranges, ranges of different kinds
1306 and symbolic ranges. As an exception, we allow BIT_{AND,IOR}
1307 because we may be able to derive a useful range even if one of
1308 the operands is VR_VARYING or symbolic range. Similarly for
1309 divisions, MIN/MAX and PLUS/MINUS.
1311 TODO, we may be able to derive anti-ranges in some cases. */
1312 if (code != BIT_AND_EXPR
1313 && code != BIT_IOR_EXPR
1314 && code != TRUNC_DIV_EXPR
1315 && code != FLOOR_DIV_EXPR
1316 && code != CEIL_DIV_EXPR
1317 && code != EXACT_DIV_EXPR
1318 && code != ROUND_DIV_EXPR
1319 && code != TRUNC_MOD_EXPR
1320 && code != MIN_EXPR
1321 && code != MAX_EXPR
1322 && code != PLUS_EXPR
1323 && code != MINUS_EXPR
1324 && code != RSHIFT_EXPR
1325 && code != POINTER_PLUS_EXPR
1326 && (vr0.type == VR_VARYING
1327 || vr1.type == VR_VARYING
1328 || vr0.type != vr1.type
1329 || symbolic_range_p (&vr0)
1330 || symbolic_range_p (&vr1)))
1332 set_value_range_to_varying (vr);
1333 return;
1336 /* Now evaluate the expression to determine the new range. */
1337 if (POINTER_TYPE_P (expr_type))
1339 if (code == MIN_EXPR || code == MAX_EXPR)
1341 /* For MIN/MAX expressions with pointers, we only care about
1342 nullness, if both are non null, then the result is nonnull.
1343 If both are null, then the result is null. Otherwise they
1344 are varying. */
1345 if (!range_includes_zero_p (&vr0) && !range_includes_zero_p (&vr1))
1346 set_value_range_to_nonnull (vr, expr_type);
1347 else if (range_is_null (&vr0) && range_is_null (&vr1))
1348 set_value_range_to_null (vr, expr_type);
1349 else
1350 set_value_range_to_varying (vr);
1352 else if (code == POINTER_PLUS_EXPR)
1354 /* For pointer types, we are really only interested in asserting
1355 whether the expression evaluates to non-NULL. */
1356 if (!range_includes_zero_p (&vr0)
1357 || !range_includes_zero_p (&vr1))
1358 set_value_range_to_nonnull (vr, expr_type);
1359 else if (range_is_null (&vr0) && range_is_null (&vr1))
1360 set_value_range_to_null (vr, expr_type);
1361 else
1362 set_value_range_to_varying (vr);
1364 else if (code == BIT_AND_EXPR)
1366 /* For pointer types, we are really only interested in asserting
1367 whether the expression evaluates to non-NULL. */
1368 if (!range_includes_zero_p (&vr0) && !range_includes_zero_p (&vr1))
1369 set_value_range_to_nonnull (vr, expr_type);
1370 else if (range_is_null (&vr0) || range_is_null (&vr1))
1371 set_value_range_to_null (vr, expr_type);
1372 else
1373 set_value_range_to_varying (vr);
1375 else
1376 set_value_range_to_varying (vr);
1378 return;
1381 /* For integer ranges, apply the operation to each end of the
1382 range and see what we end up with. */
1383 if (code == PLUS_EXPR || code == MINUS_EXPR)
1385 /* This will normalize things such that calculating
1386 [0,0] - VR_VARYING is not dropped to varying, but is
1387 calculated as [MIN+1, MAX]. */
1388 if (vr0.type == VR_VARYING)
1390 vr0.type = VR_RANGE;
1391 vr0.min = vrp_val_min (expr_type);
1392 vr0.max = vrp_val_max (expr_type);
1394 if (vr1.type == VR_VARYING)
1396 vr1.type = VR_RANGE;
1397 vr1.min = vrp_val_min (expr_type);
1398 vr1.max = vrp_val_max (expr_type);
1401 const bool minus_p = (code == MINUS_EXPR);
1402 tree min_op0 = vr0.min;
1403 tree min_op1 = minus_p ? vr1.max : vr1.min;
1404 tree max_op0 = vr0.max;
1405 tree max_op1 = minus_p ? vr1.min : vr1.max;
1406 tree sym_min_op0 = NULL_TREE;
1407 tree sym_min_op1 = NULL_TREE;
1408 tree sym_max_op0 = NULL_TREE;
1409 tree sym_max_op1 = NULL_TREE;
1410 bool neg_min_op0, neg_min_op1, neg_max_op0, neg_max_op1;
1412 neg_min_op0 = neg_min_op1 = neg_max_op0 = neg_max_op1 = false;
1414 /* If we have a PLUS or MINUS with two VR_RANGEs, either constant or
1415 single-symbolic ranges, try to compute the precise resulting range,
1416 but only if we know that this resulting range will also be constant
1417 or single-symbolic. */
1418 if (vr0.type == VR_RANGE && vr1.type == VR_RANGE
1419 && (TREE_CODE (min_op0) == INTEGER_CST
1420 || (sym_min_op0
1421 = get_single_symbol (min_op0, &neg_min_op0, &min_op0)))
1422 && (TREE_CODE (min_op1) == INTEGER_CST
1423 || (sym_min_op1
1424 = get_single_symbol (min_op1, &neg_min_op1, &min_op1)))
1425 && (!(sym_min_op0 && sym_min_op1)
1426 || (sym_min_op0 == sym_min_op1
1427 && neg_min_op0 == (minus_p ? neg_min_op1 : !neg_min_op1)))
1428 && (TREE_CODE (max_op0) == INTEGER_CST
1429 || (sym_max_op0
1430 = get_single_symbol (max_op0, &neg_max_op0, &max_op0)))
1431 && (TREE_CODE (max_op1) == INTEGER_CST
1432 || (sym_max_op1
1433 = get_single_symbol (max_op1, &neg_max_op1, &max_op1)))
1434 && (!(sym_max_op0 && sym_max_op1)
1435 || (sym_max_op0 == sym_max_op1
1436 && neg_max_op0 == (minus_p ? neg_max_op1 : !neg_max_op1))))
1438 wide_int wmin, wmax;
1439 wi::overflow_type min_ovf = wi::OVF_NONE;
1440 wi::overflow_type max_ovf = wi::OVF_NONE;
1442 /* Build the bounds. */
1443 combine_bound (code, wmin, min_ovf, expr_type, min_op0, min_op1);
1444 combine_bound (code, wmax, max_ovf, expr_type, max_op0, max_op1);
1446 /* If we have overflow for the constant part and the resulting
1447 range will be symbolic, drop to VR_VARYING. */
1448 if (((bool)min_ovf && sym_min_op0 != sym_min_op1)
1449 || ((bool)max_ovf && sym_max_op0 != sym_max_op1))
1451 set_value_range_to_varying (vr);
1452 return;
1455 /* Adjust the range for possible overflow. */
1456 set_value_range_with_overflow (*vr, expr_type,
1457 wmin, wmax, min_ovf, max_ovf);
1458 if (vr->type == VR_VARYING)
1459 return;
1461 /* Build the symbolic bounds if needed. */
1462 adjust_symbolic_bound (vr->min, code, expr_type,
1463 sym_min_op0, sym_min_op1,
1464 neg_min_op0, neg_min_op1);
1465 adjust_symbolic_bound (vr->max, code, expr_type,
1466 sym_max_op0, sym_max_op1,
1467 neg_max_op0, neg_max_op1);
1468 /* ?? It would probably be cleaner to eliminate min/max/type
1469 entirely and hold these values in VR directly. */
1470 min = vr->min;
1471 max = vr->max;
1472 type = vr->type;
1474 else
1476 /* For other cases, for example if we have a PLUS_EXPR with two
1477 VR_ANTI_RANGEs, drop to VR_VARYING. It would take more effort
1478 to compute a precise range for such a case.
1479 ??? General even mixed range kind operations can be expressed
1480 by for example transforming ~[3, 5] + [1, 2] to range-only
1481 operations and a union primitive:
1482 [-INF, 2] + [1, 2] U [5, +INF] + [1, 2]
1483 [-INF+1, 4] U [6, +INF(OVF)]
1484 though usually the union is not exactly representable with
1485 a single range or anti-range as the above is
1486 [-INF+1, +INF(OVF)] intersected with ~[5, 5]
1487 but one could use a scheme similar to equivalences for this. */
1488 set_value_range_to_varying (vr);
1489 return;
1492 else if (code == MIN_EXPR
1493 || code == MAX_EXPR)
1495 wide_int wmin, wmax;
1496 wide_int vr0_min, vr0_max;
1497 wide_int vr1_min, vr1_max;
1498 extract_range_into_wide_ints (&vr0, sign, prec, vr0_min, vr0_max);
1499 extract_range_into_wide_ints (&vr1, sign, prec, vr1_min, vr1_max);
1500 if (wide_int_range_min_max (wmin, wmax, code, sign, prec,
1501 vr0_min, vr0_max, vr1_min, vr1_max))
1502 set_value_range (vr, VR_RANGE,
1503 wide_int_to_tree (expr_type, wmin),
1504 wide_int_to_tree (expr_type, wmax), NULL);
1505 else
1506 set_value_range_to_varying (vr);
1507 return;
1509 else if (code == MULT_EXPR)
1511 if (!range_int_cst_p (&vr0)
1512 || !range_int_cst_p (&vr1))
1514 set_value_range_to_varying (vr);
1515 return;
1517 extract_range_from_multiplicative_op (vr, code, &vr0, &vr1);
1518 return;
1520 else if (code == RSHIFT_EXPR
1521 || code == LSHIFT_EXPR)
1523 if (range_int_cst_p (&vr1)
1524 && !wide_int_range_shift_undefined_p (prec,
1525 wi::to_wide (vr1.min),
1526 wi::to_wide (vr1.max)))
1528 if (code == RSHIFT_EXPR)
1530 /* Even if vr0 is VARYING or otherwise not usable, we can derive
1531 useful ranges just from the shift count. E.g.
1532 x >> 63 for signed 64-bit x is always [-1, 0]. */
1533 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
1535 vr0.type = type = VR_RANGE;
1536 vr0.min = vrp_val_min (expr_type);
1537 vr0.max = vrp_val_max (expr_type);
1539 extract_range_from_multiplicative_op (vr, code, &vr0, &vr1);
1540 return;
1542 else if (code == LSHIFT_EXPR
1543 && range_int_cst_p (&vr0))
1545 wide_int res_lb, res_ub;
1546 if (wide_int_range_lshift (res_lb, res_ub, sign, prec,
1547 wi::to_wide (vr0.min),
1548 wi::to_wide (vr0.max),
1549 wi::to_wide (vr1.min),
1550 wi::to_wide (vr1.max),
1551 TYPE_OVERFLOW_UNDEFINED (expr_type),
1552 TYPE_OVERFLOW_WRAPS (expr_type)))
1554 min = wide_int_to_tree (expr_type, res_lb);
1555 max = wide_int_to_tree (expr_type, res_ub);
1556 set_and_canonicalize_value_range (vr, VR_RANGE,
1557 min, max, NULL);
1558 return;
1562 set_value_range_to_varying (vr);
1563 return;
1565 else if (code == TRUNC_DIV_EXPR
1566 || code == FLOOR_DIV_EXPR
1567 || code == CEIL_DIV_EXPR
1568 || code == EXACT_DIV_EXPR
1569 || code == ROUND_DIV_EXPR)
1571 wide_int dividend_min, dividend_max, divisor_min, divisor_max;
1572 wide_int wmin, wmax, extra_min, extra_max;
1573 bool extra_range_p;
1575 /* Special case explicit division by zero as undefined. */
1576 if (range_is_null (&vr1))
1578 set_value_range_to_undefined (vr);
1579 return;
1582 /* First, normalize ranges into constants we can handle. Note
1583 that VR_ANTI_RANGE's of constants were already normalized
1584 before arriving here.
1586 NOTE: As a future improvement, we may be able to do better
1587 with mixed symbolic (anti-)ranges like [0, A]. See note in
1588 ranges_from_anti_range. */
1589 extract_range_into_wide_ints (&vr0, sign, prec,
1590 dividend_min, dividend_max);
1591 extract_range_into_wide_ints (&vr1, sign, prec,
1592 divisor_min, divisor_max);
1593 if (!wide_int_range_div (wmin, wmax, code, sign, prec,
1594 dividend_min, dividend_max,
1595 divisor_min, divisor_max,
1596 TYPE_OVERFLOW_UNDEFINED (expr_type),
1597 TYPE_OVERFLOW_WRAPS (expr_type),
1598 extra_range_p, extra_min, extra_max))
1600 set_value_range_to_varying (vr);
1601 return;
1603 set_value_range (vr, VR_RANGE,
1604 wide_int_to_tree (expr_type, wmin),
1605 wide_int_to_tree (expr_type, wmax), NULL);
1606 if (extra_range_p)
1608 value_range extra_range = VR_INITIALIZER;
1609 set_value_range (&extra_range, VR_RANGE,
1610 wide_int_to_tree (expr_type, extra_min),
1611 wide_int_to_tree (expr_type, extra_max), NULL);
1612 vrp_meet (vr, &extra_range);
1614 return;
1616 else if (code == TRUNC_MOD_EXPR)
1618 if (range_is_null (&vr1))
1620 set_value_range_to_undefined (vr);
1621 return;
1623 wide_int wmin, wmax, tmp;
1624 wide_int vr0_min, vr0_max, vr1_min, vr1_max;
1625 extract_range_into_wide_ints (&vr0, sign, prec, vr0_min, vr0_max);
1626 extract_range_into_wide_ints (&vr1, sign, prec, vr1_min, vr1_max);
1627 wide_int_range_trunc_mod (wmin, wmax, sign, prec,
1628 vr0_min, vr0_max, vr1_min, vr1_max);
1629 min = wide_int_to_tree (expr_type, wmin);
1630 max = wide_int_to_tree (expr_type, wmax);
1631 set_value_range (vr, VR_RANGE, min, max, NULL);
1632 return;
1634 else if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR || code == BIT_XOR_EXPR)
1636 wide_int may_be_nonzero0, may_be_nonzero1;
1637 wide_int must_be_nonzero0, must_be_nonzero1;
1638 wide_int wmin, wmax;
1639 wide_int vr0_min, vr0_max, vr1_min, vr1_max;
1640 vrp_set_zero_nonzero_bits (expr_type, &vr0,
1641 &may_be_nonzero0, &must_be_nonzero0);
1642 vrp_set_zero_nonzero_bits (expr_type, &vr1,
1643 &may_be_nonzero1, &must_be_nonzero1);
1644 extract_range_into_wide_ints (&vr0, sign, prec, vr0_min, vr0_max);
1645 extract_range_into_wide_ints (&vr1, sign, prec, vr1_min, vr1_max);
1646 if (code == BIT_AND_EXPR)
1648 if (wide_int_range_bit_and (wmin, wmax, sign, prec,
1649 vr0_min, vr0_max,
1650 vr1_min, vr1_max,
1651 must_be_nonzero0,
1652 may_be_nonzero0,
1653 must_be_nonzero1,
1654 may_be_nonzero1))
1656 min = wide_int_to_tree (expr_type, wmin);
1657 max = wide_int_to_tree (expr_type, wmax);
1658 set_value_range (vr, VR_RANGE, min, max, NULL);
1660 else
1661 set_value_range_to_varying (vr);
1662 return;
1664 else if (code == BIT_IOR_EXPR)
1666 if (wide_int_range_bit_ior (wmin, wmax, sign,
1667 vr0_min, vr0_max,
1668 vr1_min, vr1_max,
1669 must_be_nonzero0,
1670 may_be_nonzero0,
1671 must_be_nonzero1,
1672 may_be_nonzero1))
1674 min = wide_int_to_tree (expr_type, wmin);
1675 max = wide_int_to_tree (expr_type, wmax);
1676 set_value_range (vr, VR_RANGE, min, max, NULL);
1678 else
1679 set_value_range_to_varying (vr);
1680 return;
1682 else if (code == BIT_XOR_EXPR)
1684 if (wide_int_range_bit_xor (wmin, wmax, sign, prec,
1685 must_be_nonzero0,
1686 may_be_nonzero0,
1687 must_be_nonzero1,
1688 may_be_nonzero1))
1690 min = wide_int_to_tree (expr_type, wmin);
1691 max = wide_int_to_tree (expr_type, wmax);
1692 set_value_range (vr, VR_RANGE, min, max, NULL);
1694 else
1695 set_value_range_to_varying (vr);
1696 return;
1699 else
1700 gcc_unreachable ();
1702 /* If either MIN or MAX overflowed, then set the resulting range to
1703 VARYING. */
1704 if (min == NULL_TREE
1705 || TREE_OVERFLOW_P (min)
1706 || max == NULL_TREE
1707 || TREE_OVERFLOW_P (max))
1709 set_value_range_to_varying (vr);
1710 return;
1713 /* We punt for [-INF, +INF].
1714 We learn nothing when we have INF on both sides.
1715 Note that we do accept [-INF, -INF] and [+INF, +INF]. */
1716 if (vrp_val_is_min (min) && vrp_val_is_max (max))
1718 set_value_range_to_varying (vr);
1719 return;
1722 cmp = compare_values (min, max);
1723 if (cmp == -2 || cmp == 1)
1725 /* If the new range has its limits swapped around (MIN > MAX),
1726 then the operation caused one of them to wrap around, mark
1727 the new range VARYING. */
1728 set_value_range_to_varying (vr);
1730 else
1731 set_value_range (vr, type, min, max, NULL);
1734 /* Extract range information from a unary operation CODE based on
1735 the range of its operand *VR0 with type OP0_TYPE with resulting type TYPE.
1736 The resulting range is stored in *VR. */
1738 void
1739 extract_range_from_unary_expr (value_range *vr,
1740 enum tree_code code, tree type,
1741 const value_range *vr0_, tree op0_type)
1743 signop sign = TYPE_SIGN (type);
1744 unsigned int prec = TYPE_PRECISION (type);
1745 value_range vr0 = *vr0_, vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
1747 /* VRP only operates on integral and pointer types. */
1748 if (!(INTEGRAL_TYPE_P (op0_type)
1749 || POINTER_TYPE_P (op0_type))
1750 || !(INTEGRAL_TYPE_P (type)
1751 || POINTER_TYPE_P (type)))
1753 set_value_range_to_varying (vr);
1754 return;
1757 /* If VR0 is UNDEFINED, so is the result. */
1758 if (vr0.type == VR_UNDEFINED)
1760 set_value_range_to_undefined (vr);
1761 return;
1764 /* Handle operations that we express in terms of others. */
1765 if (code == PAREN_EXPR || code == OBJ_TYPE_REF)
1767 /* PAREN_EXPR and OBJ_TYPE_REF are simple copies. */
1768 copy_value_range (vr, &vr0);
1769 return;
1771 else if (code == NEGATE_EXPR)
1773 /* -X is simply 0 - X, so re-use existing code that also handles
1774 anti-ranges fine. */
1775 value_range zero = VR_INITIALIZER;
1776 set_value_range_to_value (&zero, build_int_cst (type, 0), NULL);
1777 extract_range_from_binary_expr_1 (vr, MINUS_EXPR, type, &zero, &vr0);
1778 return;
1780 else if (code == BIT_NOT_EXPR)
1782 /* ~X is simply -1 - X, so re-use existing code that also handles
1783 anti-ranges fine. */
1784 value_range minusone = VR_INITIALIZER;
1785 set_value_range_to_value (&minusone, build_int_cst (type, -1), NULL);
1786 extract_range_from_binary_expr_1 (vr, MINUS_EXPR,
1787 type, &minusone, &vr0);
1788 return;
1791 /* Now canonicalize anti-ranges to ranges when they are not symbolic
1792 and express op ~[] as (op []') U (op []''). */
1793 if (vr0.type == VR_ANTI_RANGE
1794 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
1796 extract_range_from_unary_expr (vr, code, type, &vrtem0, op0_type);
1797 if (vrtem1.type != VR_UNDEFINED)
1799 value_range vrres = VR_INITIALIZER;
1800 extract_range_from_unary_expr (&vrres, code, type,
1801 &vrtem1, op0_type);
1802 vrp_meet (vr, &vrres);
1804 return;
1807 if (CONVERT_EXPR_CODE_P (code))
1809 tree inner_type = op0_type;
1810 tree outer_type = type;
1812 /* If the expression involves a pointer, we are only interested in
1813 determining if it evaluates to NULL [0, 0] or non-NULL (~[0, 0]).
1815 This may lose precision when converting (char *)~[0,2] to
1816 int, because we'll forget that the pointer can also not be 1
1817 or 2. In practice we don't care, as this is some idiot
1818 storing a magic constant to a pointer. */
1819 if (POINTER_TYPE_P (type) || POINTER_TYPE_P (op0_type))
1821 if (!range_includes_zero_p (&vr0))
1822 set_value_range_to_nonnull (vr, type);
1823 else if (range_is_null (&vr0))
1824 set_value_range_to_null (vr, type);
1825 else
1826 set_value_range_to_varying (vr);
1827 return;
1830 /* The POINTER_TYPE_P code above will have dealt with all
1831 pointer anti-ranges. Any remaining anti-ranges at this point
1832 will be integer conversions from SSA names that will be
1833 normalized into VARYING. For instance: ~[x_55, x_55]. */
1834 gcc_assert (vr0.type != VR_ANTI_RANGE
1835 || TREE_CODE (vr0.min) != INTEGER_CST);
1837 /* NOTES: Previously we were returning VARYING for all symbolics, but
1838 we can do better by treating them as [-MIN, +MAX]. For
1839 example, converting [SYM, SYM] from INT to LONG UNSIGNED,
1840 we can return: ~[0x8000000, 0xffffffff7fffffff].
1842 We were also failing to convert ~[0,0] from char* to unsigned,
1843 instead choosing to return VR_VARYING. Now we return ~[0,0]. */
1844 wide_int vr0_min, vr0_max, wmin, wmax;
1845 signop inner_sign = TYPE_SIGN (inner_type);
1846 signop outer_sign = TYPE_SIGN (outer_type);
1847 unsigned inner_prec = TYPE_PRECISION (inner_type);
1848 unsigned outer_prec = TYPE_PRECISION (outer_type);
1849 extract_range_into_wide_ints (&vr0, inner_sign, inner_prec,
1850 vr0_min, vr0_max);
1851 if (wide_int_range_convert (wmin, wmax,
1852 inner_sign, inner_prec,
1853 outer_sign, outer_prec,
1854 vr0_min, vr0_max))
1856 tree min = wide_int_to_tree (outer_type, wmin);
1857 tree max = wide_int_to_tree (outer_type, wmax);
1858 set_and_canonicalize_value_range (vr, VR_RANGE, min, max, NULL);
1860 else
1861 set_value_range_to_varying (vr);
1862 return;
1864 else if (code == ABS_EXPR)
1866 wide_int wmin, wmax;
1867 wide_int vr0_min, vr0_max;
1868 extract_range_into_wide_ints (&vr0, sign, prec, vr0_min, vr0_max);
1869 if (wide_int_range_abs (wmin, wmax, sign, prec, vr0_min, vr0_max,
1870 TYPE_OVERFLOW_UNDEFINED (type)))
1871 set_value_range (vr, VR_RANGE,
1872 wide_int_to_tree (type, wmin),
1873 wide_int_to_tree (type, wmax), NULL);
1874 else
1875 set_value_range_to_varying (vr);
1876 return;
1879 /* For unhandled operations fall back to varying. */
1880 set_value_range_to_varying (vr);
1881 return;
1884 /* Debugging dumps. */
1886 void dump_value_range (FILE *, const value_range *);
1887 void debug_value_range (const value_range *);
1888 void dump_all_value_ranges (FILE *);
1889 void dump_vr_equiv (FILE *, bitmap);
1890 void debug_vr_equiv (bitmap);
1893 /* Dump value range VR to FILE. */
1895 void
1896 dump_value_range (FILE *file, const value_range *vr)
1898 if (vr == NULL)
1899 fprintf (file, "[]");
1900 else if (vr->type == VR_UNDEFINED)
1901 fprintf (file, "UNDEFINED");
1902 else if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
1904 tree type = TREE_TYPE (vr->min);
1906 fprintf (file, "%s[", (vr->type == VR_ANTI_RANGE) ? "~" : "");
1908 if (INTEGRAL_TYPE_P (type)
1909 && !TYPE_UNSIGNED (type)
1910 && vrp_val_is_min (vr->min))
1911 fprintf (file, "-INF");
1912 else
1913 print_generic_expr (file, vr->min);
1915 fprintf (file, ", ");
1917 if (INTEGRAL_TYPE_P (type)
1918 && vrp_val_is_max (vr->max))
1919 fprintf (file, "+INF");
1920 else
1921 print_generic_expr (file, vr->max);
1923 fprintf (file, "]");
1925 if (vr->equiv)
1927 bitmap_iterator bi;
1928 unsigned i, c = 0;
1930 fprintf (file, " EQUIVALENCES: { ");
1932 EXECUTE_IF_SET_IN_BITMAP (vr->equiv, 0, i, bi)
1934 print_generic_expr (file, ssa_name (i));
1935 fprintf (file, " ");
1936 c++;
1939 fprintf (file, "} (%u elements)", c);
1942 else if (vr->type == VR_VARYING)
1943 fprintf (file, "VARYING");
1944 else
1945 fprintf (file, "INVALID RANGE");
1949 /* Dump value range VR to stderr. */
1951 DEBUG_FUNCTION void
1952 debug_value_range (const value_range *vr)
1954 dump_value_range (stderr, vr);
1955 fprintf (stderr, "\n");
1958 void
1959 value_range::dump () const
1961 debug_value_range (this);
1965 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
1966 create a new SSA name N and return the assertion assignment
1967 'N = ASSERT_EXPR <V, V OP W>'. */
1969 static gimple *
1970 build_assert_expr_for (tree cond, tree v)
1972 tree a;
1973 gassign *assertion;
1975 gcc_assert (TREE_CODE (v) == SSA_NAME
1976 && COMPARISON_CLASS_P (cond));
1978 a = build2 (ASSERT_EXPR, TREE_TYPE (v), v, cond);
1979 assertion = gimple_build_assign (NULL_TREE, a);
1981 /* The new ASSERT_EXPR, creates a new SSA name that replaces the
1982 operand of the ASSERT_EXPR. Create it so the new name and the old one
1983 are registered in the replacement table so that we can fix the SSA web
1984 after adding all the ASSERT_EXPRs. */
1985 tree new_def = create_new_def_for (v, assertion, NULL);
1986 /* Make sure we preserve abnormalness throughout an ASSERT_EXPR chain
1987 given we have to be able to fully propagate those out to re-create
1988 valid SSA when removing the asserts. */
1989 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (v))
1990 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_def) = 1;
1992 return assertion;
1996 /* Return false if EXPR is a predicate expression involving floating
1997 point values. */
1999 static inline bool
2000 fp_predicate (gimple *stmt)
2002 GIMPLE_CHECK (stmt, GIMPLE_COND);
2004 return FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)));
2007 /* If the range of values taken by OP can be inferred after STMT executes,
2008 return the comparison code (COMP_CODE_P) and value (VAL_P) that
2009 describes the inferred range. Return true if a range could be
2010 inferred. */
2012 bool
2013 infer_value_range (gimple *stmt, tree op, tree_code *comp_code_p, tree *val_p)
2015 *val_p = NULL_TREE;
2016 *comp_code_p = ERROR_MARK;
2018 /* Do not attempt to infer anything in names that flow through
2019 abnormal edges. */
2020 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
2021 return false;
2023 /* If STMT is the last statement of a basic block with no normal
2024 successors, there is no point inferring anything about any of its
2025 operands. We would not be able to find a proper insertion point
2026 for the assertion, anyway. */
2027 if (stmt_ends_bb_p (stmt))
2029 edge_iterator ei;
2030 edge e;
2032 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
2033 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
2034 break;
2035 if (e == NULL)
2036 return false;
2039 if (infer_nonnull_range (stmt, op))
2041 *val_p = build_int_cst (TREE_TYPE (op), 0);
2042 *comp_code_p = NE_EXPR;
2043 return true;
2046 return false;
2050 void dump_asserts_for (FILE *, tree);
2051 void debug_asserts_for (tree);
2052 void dump_all_asserts (FILE *);
2053 void debug_all_asserts (void);
2055 /* Dump all the registered assertions for NAME to FILE. */
2057 void
2058 dump_asserts_for (FILE *file, tree name)
2060 assert_locus *loc;
2062 fprintf (file, "Assertions to be inserted for ");
2063 print_generic_expr (file, name);
2064 fprintf (file, "\n");
2066 loc = asserts_for[SSA_NAME_VERSION (name)];
2067 while (loc)
2069 fprintf (file, "\t");
2070 print_gimple_stmt (file, gsi_stmt (loc->si), 0);
2071 fprintf (file, "\n\tBB #%d", loc->bb->index);
2072 if (loc->e)
2074 fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
2075 loc->e->dest->index);
2076 dump_edge_info (file, loc->e, dump_flags, 0);
2078 fprintf (file, "\n\tPREDICATE: ");
2079 print_generic_expr (file, loc->expr);
2080 fprintf (file, " %s ", get_tree_code_name (loc->comp_code));
2081 print_generic_expr (file, loc->val);
2082 fprintf (file, "\n\n");
2083 loc = loc->next;
2086 fprintf (file, "\n");
2090 /* Dump all the registered assertions for NAME to stderr. */
2092 DEBUG_FUNCTION void
2093 debug_asserts_for (tree name)
2095 dump_asserts_for (stderr, name);
2099 /* Dump all the registered assertions for all the names to FILE. */
2101 void
2102 dump_all_asserts (FILE *file)
2104 unsigned i;
2105 bitmap_iterator bi;
2107 fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
2108 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
2109 dump_asserts_for (file, ssa_name (i));
2110 fprintf (file, "\n");
2114 /* Dump all the registered assertions for all the names to stderr. */
2116 DEBUG_FUNCTION void
2117 debug_all_asserts (void)
2119 dump_all_asserts (stderr);
2122 /* Push the assert info for NAME, EXPR, COMP_CODE and VAL to ASSERTS. */
2124 static void
2125 add_assert_info (vec<assert_info> &asserts,
2126 tree name, tree expr, enum tree_code comp_code, tree val)
2128 assert_info info;
2129 info.comp_code = comp_code;
2130 info.name = name;
2131 if (TREE_OVERFLOW_P (val))
2132 val = drop_tree_overflow (val);
2133 info.val = val;
2134 info.expr = expr;
2135 asserts.safe_push (info);
2138 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
2139 'EXPR COMP_CODE VAL' at a location that dominates block BB or
2140 E->DEST, then register this location as a possible insertion point
2141 for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
2143 BB, E and SI provide the exact insertion point for the new
2144 ASSERT_EXPR. If BB is NULL, then the ASSERT_EXPR is to be inserted
2145 on edge E. Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
2146 BB. If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
2147 must not be NULL. */
2149 static void
2150 register_new_assert_for (tree name, tree expr,
2151 enum tree_code comp_code,
2152 tree val,
2153 basic_block bb,
2154 edge e,
2155 gimple_stmt_iterator si)
2157 assert_locus *n, *loc, *last_loc;
2158 basic_block dest_bb;
2160 gcc_checking_assert (bb == NULL || e == NULL);
2162 if (e == NULL)
2163 gcc_checking_assert (gimple_code (gsi_stmt (si)) != GIMPLE_COND
2164 && gimple_code (gsi_stmt (si)) != GIMPLE_SWITCH);
2166 /* Never build an assert comparing against an integer constant with
2167 TREE_OVERFLOW set. This confuses our undefined overflow warning
2168 machinery. */
2169 if (TREE_OVERFLOW_P (val))
2170 val = drop_tree_overflow (val);
2172 /* The new assertion A will be inserted at BB or E. We need to
2173 determine if the new location is dominated by a previously
2174 registered location for A. If we are doing an edge insertion,
2175 assume that A will be inserted at E->DEST. Note that this is not
2176 necessarily true.
2178 If E is a critical edge, it will be split. But even if E is
2179 split, the new block will dominate the same set of blocks that
2180 E->DEST dominates.
2182 The reverse, however, is not true, blocks dominated by E->DEST
2183 will not be dominated by the new block created to split E. So,
2184 if the insertion location is on a critical edge, we will not use
2185 the new location to move another assertion previously registered
2186 at a block dominated by E->DEST. */
2187 dest_bb = (bb) ? bb : e->dest;
2189 /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
2190 VAL at a block dominating DEST_BB, then we don't need to insert a new
2191 one. Similarly, if the same assertion already exists at a block
2192 dominated by DEST_BB and the new location is not on a critical
2193 edge, then update the existing location for the assertion (i.e.,
2194 move the assertion up in the dominance tree).
2196 Note, this is implemented as a simple linked list because there
2197 should not be more than a handful of assertions registered per
2198 name. If this becomes a performance problem, a table hashed by
2199 COMP_CODE and VAL could be implemented. */
2200 loc = asserts_for[SSA_NAME_VERSION (name)];
2201 last_loc = loc;
2202 while (loc)
2204 if (loc->comp_code == comp_code
2205 && (loc->val == val
2206 || operand_equal_p (loc->val, val, 0))
2207 && (loc->expr == expr
2208 || operand_equal_p (loc->expr, expr, 0)))
2210 /* If E is not a critical edge and DEST_BB
2211 dominates the existing location for the assertion, move
2212 the assertion up in the dominance tree by updating its
2213 location information. */
2214 if ((e == NULL || !EDGE_CRITICAL_P (e))
2215 && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
2217 loc->bb = dest_bb;
2218 loc->e = e;
2219 loc->si = si;
2220 return;
2224 /* Update the last node of the list and move to the next one. */
2225 last_loc = loc;
2226 loc = loc->next;
2229 /* If we didn't find an assertion already registered for
2230 NAME COMP_CODE VAL, add a new one at the end of the list of
2231 assertions associated with NAME. */
2232 n = XNEW (struct assert_locus);
2233 n->bb = dest_bb;
2234 n->e = e;
2235 n->si = si;
2236 n->comp_code = comp_code;
2237 n->val = val;
2238 n->expr = expr;
2239 n->next = NULL;
2241 if (last_loc)
2242 last_loc->next = n;
2243 else
2244 asserts_for[SSA_NAME_VERSION (name)] = n;
2246 bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
2249 /* (COND_OP0 COND_CODE COND_OP1) is a predicate which uses NAME.
2250 Extract a suitable test code and value and store them into *CODE_P and
2251 *VAL_P so the predicate is normalized to NAME *CODE_P *VAL_P.
2253 If no extraction was possible, return FALSE, otherwise return TRUE.
2255 If INVERT is true, then we invert the result stored into *CODE_P. */
2257 static bool
2258 extract_code_and_val_from_cond_with_ops (tree name, enum tree_code cond_code,
2259 tree cond_op0, tree cond_op1,
2260 bool invert, enum tree_code *code_p,
2261 tree *val_p)
2263 enum tree_code comp_code;
2264 tree val;
2266 /* Otherwise, we have a comparison of the form NAME COMP VAL
2267 or VAL COMP NAME. */
2268 if (name == cond_op1)
2270 /* If the predicate is of the form VAL COMP NAME, flip
2271 COMP around because we need to register NAME as the
2272 first operand in the predicate. */
2273 comp_code = swap_tree_comparison (cond_code);
2274 val = cond_op0;
2276 else if (name == cond_op0)
2278 /* The comparison is of the form NAME COMP VAL, so the
2279 comparison code remains unchanged. */
2280 comp_code = cond_code;
2281 val = cond_op1;
2283 else
2284 gcc_unreachable ();
2286 /* Invert the comparison code as necessary. */
2287 if (invert)
2288 comp_code = invert_tree_comparison (comp_code, 0);
2290 /* VRP only handles integral and pointer types. */
2291 if (! INTEGRAL_TYPE_P (TREE_TYPE (val))
2292 && ! POINTER_TYPE_P (TREE_TYPE (val)))
2293 return false;
2295 /* Do not register always-false predicates.
2296 FIXME: this works around a limitation in fold() when dealing with
2297 enumerations. Given 'enum { N1, N2 } x;', fold will not
2298 fold 'if (x > N2)' to 'if (0)'. */
2299 if ((comp_code == GT_EXPR || comp_code == LT_EXPR)
2300 && INTEGRAL_TYPE_P (TREE_TYPE (val)))
2302 tree min = TYPE_MIN_VALUE (TREE_TYPE (val));
2303 tree max = TYPE_MAX_VALUE (TREE_TYPE (val));
2305 if (comp_code == GT_EXPR
2306 && (!max
2307 || compare_values (val, max) == 0))
2308 return false;
2310 if (comp_code == LT_EXPR
2311 && (!min
2312 || compare_values (val, min) == 0))
2313 return false;
2315 *code_p = comp_code;
2316 *val_p = val;
2317 return true;
2320 /* Find out smallest RES where RES > VAL && (RES & MASK) == RES, if any
2321 (otherwise return VAL). VAL and MASK must be zero-extended for
2322 precision PREC. If SGNBIT is non-zero, first xor VAL with SGNBIT
2323 (to transform signed values into unsigned) and at the end xor
2324 SGNBIT back. */
2326 static wide_int
2327 masked_increment (const wide_int &val_in, const wide_int &mask,
2328 const wide_int &sgnbit, unsigned int prec)
2330 wide_int bit = wi::one (prec), res;
2331 unsigned int i;
2333 wide_int val = val_in ^ sgnbit;
2334 for (i = 0; i < prec; i++, bit += bit)
2336 res = mask;
2337 if ((res & bit) == 0)
2338 continue;
2339 res = bit - 1;
2340 res = wi::bit_and_not (val + bit, res);
2341 res &= mask;
2342 if (wi::gtu_p (res, val))
2343 return res ^ sgnbit;
2345 return val ^ sgnbit;
2348 /* Helper for overflow_comparison_p
2350 OP0 CODE OP1 is a comparison. Examine the comparison and potentially
2351 OP1's defining statement to see if it ultimately has the form
2352 OP0 CODE (OP0 PLUS INTEGER_CST)
2354 If so, return TRUE indicating this is an overflow test and store into
2355 *NEW_CST an updated constant that can be used in a narrowed range test.
2357 REVERSED indicates if the comparison was originally:
2359 OP1 CODE' OP0.
2361 This affects how we build the updated constant. */
2363 static bool
2364 overflow_comparison_p_1 (enum tree_code code, tree op0, tree op1,
2365 bool follow_assert_exprs, bool reversed, tree *new_cst)
2367 /* See if this is a relational operation between two SSA_NAMES with
2368 unsigned, overflow wrapping values. If so, check it more deeply. */
2369 if ((code == LT_EXPR || code == LE_EXPR
2370 || code == GE_EXPR || code == GT_EXPR)
2371 && TREE_CODE (op0) == SSA_NAME
2372 && TREE_CODE (op1) == SSA_NAME
2373 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
2374 && TYPE_UNSIGNED (TREE_TYPE (op0))
2375 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0)))
2377 gimple *op1_def = SSA_NAME_DEF_STMT (op1);
2379 /* If requested, follow any ASSERT_EXPRs backwards for OP1. */
2380 if (follow_assert_exprs)
2382 while (gimple_assign_single_p (op1_def)
2383 && TREE_CODE (gimple_assign_rhs1 (op1_def)) == ASSERT_EXPR)
2385 op1 = TREE_OPERAND (gimple_assign_rhs1 (op1_def), 0);
2386 if (TREE_CODE (op1) != SSA_NAME)
2387 break;
2388 op1_def = SSA_NAME_DEF_STMT (op1);
2392 /* Now look at the defining statement of OP1 to see if it adds
2393 or subtracts a nonzero constant from another operand. */
2394 if (op1_def
2395 && is_gimple_assign (op1_def)
2396 && gimple_assign_rhs_code (op1_def) == PLUS_EXPR
2397 && TREE_CODE (gimple_assign_rhs2 (op1_def)) == INTEGER_CST
2398 && !integer_zerop (gimple_assign_rhs2 (op1_def)))
2400 tree target = gimple_assign_rhs1 (op1_def);
2402 /* If requested, follow ASSERT_EXPRs backwards for op0 looking
2403 for one where TARGET appears on the RHS. */
2404 if (follow_assert_exprs)
2406 /* Now see if that "other operand" is op0, following the chain
2407 of ASSERT_EXPRs if necessary. */
2408 gimple *op0_def = SSA_NAME_DEF_STMT (op0);
2409 while (op0 != target
2410 && gimple_assign_single_p (op0_def)
2411 && TREE_CODE (gimple_assign_rhs1 (op0_def)) == ASSERT_EXPR)
2413 op0 = TREE_OPERAND (gimple_assign_rhs1 (op0_def), 0);
2414 if (TREE_CODE (op0) != SSA_NAME)
2415 break;
2416 op0_def = SSA_NAME_DEF_STMT (op0);
2420 /* If we did not find our target SSA_NAME, then this is not
2421 an overflow test. */
2422 if (op0 != target)
2423 return false;
2425 tree type = TREE_TYPE (op0);
2426 wide_int max = wi::max_value (TYPE_PRECISION (type), UNSIGNED);
2427 tree inc = gimple_assign_rhs2 (op1_def);
2428 if (reversed)
2429 *new_cst = wide_int_to_tree (type, max + wi::to_wide (inc));
2430 else
2431 *new_cst = wide_int_to_tree (type, max - wi::to_wide (inc));
2432 return true;
2435 return false;
2438 /* OP0 CODE OP1 is a comparison. Examine the comparison and potentially
2439 OP1's defining statement to see if it ultimately has the form
2440 OP0 CODE (OP0 PLUS INTEGER_CST)
2442 If so, return TRUE indicating this is an overflow test and store into
2443 *NEW_CST an updated constant that can be used in a narrowed range test.
2445 These statements are left as-is in the IL to facilitate discovery of
2446 {ADD,SUB}_OVERFLOW sequences later in the optimizer pipeline. But
2447 the alternate range representation is often useful within VRP. */
2449 bool
2450 overflow_comparison_p (tree_code code, tree name, tree val,
2451 bool use_equiv_p, tree *new_cst)
2453 if (overflow_comparison_p_1 (code, name, val, use_equiv_p, false, new_cst))
2454 return true;
2455 return overflow_comparison_p_1 (swap_tree_comparison (code), val, name,
2456 use_equiv_p, true, new_cst);
2460 /* Try to register an edge assertion for SSA name NAME on edge E for
2461 the condition COND contributing to the conditional jump pointed to by BSI.
2462 Invert the condition COND if INVERT is true. */
2464 static void
2465 register_edge_assert_for_2 (tree name, edge e,
2466 enum tree_code cond_code,
2467 tree cond_op0, tree cond_op1, bool invert,
2468 vec<assert_info> &asserts)
2470 tree val;
2471 enum tree_code comp_code;
2473 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
2474 cond_op0,
2475 cond_op1,
2476 invert, &comp_code, &val))
2477 return;
2479 /* Queue the assert. */
2480 tree x;
2481 if (overflow_comparison_p (comp_code, name, val, false, &x))
2483 enum tree_code new_code = ((comp_code == GT_EXPR || comp_code == GE_EXPR)
2484 ? GT_EXPR : LE_EXPR);
2485 add_assert_info (asserts, name, name, new_code, x);
2487 add_assert_info (asserts, name, name, comp_code, val);
2489 /* In the case of NAME <= CST and NAME being defined as
2490 NAME = (unsigned) NAME2 + CST2 we can assert NAME2 >= -CST2
2491 and NAME2 <= CST - CST2. We can do the same for NAME > CST.
2492 This catches range and anti-range tests. */
2493 if ((comp_code == LE_EXPR
2494 || comp_code == GT_EXPR)
2495 && TREE_CODE (val) == INTEGER_CST
2496 && TYPE_UNSIGNED (TREE_TYPE (val)))
2498 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
2499 tree cst2 = NULL_TREE, name2 = NULL_TREE, name3 = NULL_TREE;
2501 /* Extract CST2 from the (optional) addition. */
2502 if (is_gimple_assign (def_stmt)
2503 && gimple_assign_rhs_code (def_stmt) == PLUS_EXPR)
2505 name2 = gimple_assign_rhs1 (def_stmt);
2506 cst2 = gimple_assign_rhs2 (def_stmt);
2507 if (TREE_CODE (name2) == SSA_NAME
2508 && TREE_CODE (cst2) == INTEGER_CST)
2509 def_stmt = SSA_NAME_DEF_STMT (name2);
2512 /* Extract NAME2 from the (optional) sign-changing cast. */
2513 if (gimple_assign_cast_p (def_stmt))
2515 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt))
2516 && ! TYPE_UNSIGNED (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
2517 && (TYPE_PRECISION (gimple_expr_type (def_stmt))
2518 == TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))))
2519 name3 = gimple_assign_rhs1 (def_stmt);
2522 /* If name3 is used later, create an ASSERT_EXPR for it. */
2523 if (name3 != NULL_TREE
2524 && TREE_CODE (name3) == SSA_NAME
2525 && (cst2 == NULL_TREE
2526 || TREE_CODE (cst2) == INTEGER_CST)
2527 && INTEGRAL_TYPE_P (TREE_TYPE (name3)))
2529 tree tmp;
2531 /* Build an expression for the range test. */
2532 tmp = build1 (NOP_EXPR, TREE_TYPE (name), name3);
2533 if (cst2 != NULL_TREE)
2534 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
2536 if (dump_file)
2538 fprintf (dump_file, "Adding assert for ");
2539 print_generic_expr (dump_file, name3);
2540 fprintf (dump_file, " from ");
2541 print_generic_expr (dump_file, tmp);
2542 fprintf (dump_file, "\n");
2545 add_assert_info (asserts, name3, tmp, comp_code, val);
2548 /* If name2 is used later, create an ASSERT_EXPR for it. */
2549 if (name2 != NULL_TREE
2550 && TREE_CODE (name2) == SSA_NAME
2551 && TREE_CODE (cst2) == INTEGER_CST
2552 && INTEGRAL_TYPE_P (TREE_TYPE (name2)))
2554 tree tmp;
2556 /* Build an expression for the range test. */
2557 tmp = name2;
2558 if (TREE_TYPE (name) != TREE_TYPE (name2))
2559 tmp = build1 (NOP_EXPR, TREE_TYPE (name), tmp);
2560 if (cst2 != NULL_TREE)
2561 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
2563 if (dump_file)
2565 fprintf (dump_file, "Adding assert for ");
2566 print_generic_expr (dump_file, name2);
2567 fprintf (dump_file, " from ");
2568 print_generic_expr (dump_file, tmp);
2569 fprintf (dump_file, "\n");
2572 add_assert_info (asserts, name2, tmp, comp_code, val);
2576 /* In the case of post-in/decrement tests like if (i++) ... and uses
2577 of the in/decremented value on the edge the extra name we want to
2578 assert for is not on the def chain of the name compared. Instead
2579 it is in the set of use stmts.
2580 Similar cases happen for conversions that were simplified through
2581 fold_{sign_changed,widened}_comparison. */
2582 if ((comp_code == NE_EXPR
2583 || comp_code == EQ_EXPR)
2584 && TREE_CODE (val) == INTEGER_CST)
2586 imm_use_iterator ui;
2587 gimple *use_stmt;
2588 FOR_EACH_IMM_USE_STMT (use_stmt, ui, name)
2590 if (!is_gimple_assign (use_stmt))
2591 continue;
2593 /* Cut off to use-stmts that are dominating the predecessor. */
2594 if (!dominated_by_p (CDI_DOMINATORS, e->src, gimple_bb (use_stmt)))
2595 continue;
2597 tree name2 = gimple_assign_lhs (use_stmt);
2598 if (TREE_CODE (name2) != SSA_NAME)
2599 continue;
2601 enum tree_code code = gimple_assign_rhs_code (use_stmt);
2602 tree cst;
2603 if (code == PLUS_EXPR
2604 || code == MINUS_EXPR)
2606 cst = gimple_assign_rhs2 (use_stmt);
2607 if (TREE_CODE (cst) != INTEGER_CST)
2608 continue;
2609 cst = int_const_binop (code, val, cst);
2611 else if (CONVERT_EXPR_CODE_P (code))
2613 /* For truncating conversions we cannot record
2614 an inequality. */
2615 if (comp_code == NE_EXPR
2616 && (TYPE_PRECISION (TREE_TYPE (name2))
2617 < TYPE_PRECISION (TREE_TYPE (name))))
2618 continue;
2619 cst = fold_convert (TREE_TYPE (name2), val);
2621 else
2622 continue;
2624 if (TREE_OVERFLOW_P (cst))
2625 cst = drop_tree_overflow (cst);
2626 add_assert_info (asserts, name2, name2, comp_code, cst);
2630 if (TREE_CODE_CLASS (comp_code) == tcc_comparison
2631 && TREE_CODE (val) == INTEGER_CST)
2633 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
2634 tree name2 = NULL_TREE, names[2], cst2 = NULL_TREE;
2635 tree val2 = NULL_TREE;
2636 unsigned int prec = TYPE_PRECISION (TREE_TYPE (val));
2637 wide_int mask = wi::zero (prec);
2638 unsigned int nprec = prec;
2639 enum tree_code rhs_code = ERROR_MARK;
2641 if (is_gimple_assign (def_stmt))
2642 rhs_code = gimple_assign_rhs_code (def_stmt);
2644 /* In the case of NAME != CST1 where NAME = A +- CST2 we can
2645 assert that A != CST1 -+ CST2. */
2646 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
2647 && (rhs_code == PLUS_EXPR || rhs_code == MINUS_EXPR))
2649 tree op0 = gimple_assign_rhs1 (def_stmt);
2650 tree op1 = gimple_assign_rhs2 (def_stmt);
2651 if (TREE_CODE (op0) == SSA_NAME
2652 && TREE_CODE (op1) == INTEGER_CST)
2654 enum tree_code reverse_op = (rhs_code == PLUS_EXPR
2655 ? MINUS_EXPR : PLUS_EXPR);
2656 op1 = int_const_binop (reverse_op, val, op1);
2657 if (TREE_OVERFLOW (op1))
2658 op1 = drop_tree_overflow (op1);
2659 add_assert_info (asserts, op0, op0, comp_code, op1);
2663 /* Add asserts for NAME cmp CST and NAME being defined
2664 as NAME = (int) NAME2. */
2665 if (!TYPE_UNSIGNED (TREE_TYPE (val))
2666 && (comp_code == LE_EXPR || comp_code == LT_EXPR
2667 || comp_code == GT_EXPR || comp_code == GE_EXPR)
2668 && gimple_assign_cast_p (def_stmt))
2670 name2 = gimple_assign_rhs1 (def_stmt);
2671 if (CONVERT_EXPR_CODE_P (rhs_code)
2672 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
2673 && TYPE_UNSIGNED (TREE_TYPE (name2))
2674 && prec == TYPE_PRECISION (TREE_TYPE (name2))
2675 && (comp_code == LE_EXPR || comp_code == GT_EXPR
2676 || !tree_int_cst_equal (val,
2677 TYPE_MIN_VALUE (TREE_TYPE (val)))))
2679 tree tmp, cst;
2680 enum tree_code new_comp_code = comp_code;
2682 cst = fold_convert (TREE_TYPE (name2),
2683 TYPE_MIN_VALUE (TREE_TYPE (val)));
2684 /* Build an expression for the range test. */
2685 tmp = build2 (PLUS_EXPR, TREE_TYPE (name2), name2, cst);
2686 cst = fold_build2 (PLUS_EXPR, TREE_TYPE (name2), cst,
2687 fold_convert (TREE_TYPE (name2), val));
2688 if (comp_code == LT_EXPR || comp_code == GE_EXPR)
2690 new_comp_code = comp_code == LT_EXPR ? LE_EXPR : GT_EXPR;
2691 cst = fold_build2 (MINUS_EXPR, TREE_TYPE (name2), cst,
2692 build_int_cst (TREE_TYPE (name2), 1));
2695 if (dump_file)
2697 fprintf (dump_file, "Adding assert for ");
2698 print_generic_expr (dump_file, name2);
2699 fprintf (dump_file, " from ");
2700 print_generic_expr (dump_file, tmp);
2701 fprintf (dump_file, "\n");
2704 add_assert_info (asserts, name2, tmp, new_comp_code, cst);
2708 /* Add asserts for NAME cmp CST and NAME being defined as
2709 NAME = NAME2 >> CST2.
2711 Extract CST2 from the right shift. */
2712 if (rhs_code == RSHIFT_EXPR)
2714 name2 = gimple_assign_rhs1 (def_stmt);
2715 cst2 = gimple_assign_rhs2 (def_stmt);
2716 if (TREE_CODE (name2) == SSA_NAME
2717 && tree_fits_uhwi_p (cst2)
2718 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
2719 && IN_RANGE (tree_to_uhwi (cst2), 1, prec - 1)
2720 && type_has_mode_precision_p (TREE_TYPE (val)))
2722 mask = wi::mask (tree_to_uhwi (cst2), false, prec);
2723 val2 = fold_binary (LSHIFT_EXPR, TREE_TYPE (val), val, cst2);
2726 if (val2 != NULL_TREE
2727 && TREE_CODE (val2) == INTEGER_CST
2728 && simple_cst_equal (fold_build2 (RSHIFT_EXPR,
2729 TREE_TYPE (val),
2730 val2, cst2), val))
2732 enum tree_code new_comp_code = comp_code;
2733 tree tmp, new_val;
2735 tmp = name2;
2736 if (comp_code == EQ_EXPR || comp_code == NE_EXPR)
2738 if (!TYPE_UNSIGNED (TREE_TYPE (val)))
2740 tree type = build_nonstandard_integer_type (prec, 1);
2741 tmp = build1 (NOP_EXPR, type, name2);
2742 val2 = fold_convert (type, val2);
2744 tmp = fold_build2 (MINUS_EXPR, TREE_TYPE (tmp), tmp, val2);
2745 new_val = wide_int_to_tree (TREE_TYPE (tmp), mask);
2746 new_comp_code = comp_code == EQ_EXPR ? LE_EXPR : GT_EXPR;
2748 else if (comp_code == LT_EXPR || comp_code == GE_EXPR)
2750 wide_int minval
2751 = wi::min_value (prec, TYPE_SIGN (TREE_TYPE (val)));
2752 new_val = val2;
2753 if (minval == wi::to_wide (new_val))
2754 new_val = NULL_TREE;
2756 else
2758 wide_int maxval
2759 = wi::max_value (prec, TYPE_SIGN (TREE_TYPE (val)));
2760 mask |= wi::to_wide (val2);
2761 if (wi::eq_p (mask, maxval))
2762 new_val = NULL_TREE;
2763 else
2764 new_val = wide_int_to_tree (TREE_TYPE (val2), mask);
2767 if (new_val)
2769 if (dump_file)
2771 fprintf (dump_file, "Adding assert for ");
2772 print_generic_expr (dump_file, name2);
2773 fprintf (dump_file, " from ");
2774 print_generic_expr (dump_file, tmp);
2775 fprintf (dump_file, "\n");
2778 add_assert_info (asserts, name2, tmp, new_comp_code, new_val);
2782 /* Add asserts for NAME cmp CST and NAME being defined as
2783 NAME = NAME2 & CST2.
2785 Extract CST2 from the and.
2787 Also handle
2788 NAME = (unsigned) NAME2;
2789 casts where NAME's type is unsigned and has smaller precision
2790 than NAME2's type as if it was NAME = NAME2 & MASK. */
2791 names[0] = NULL_TREE;
2792 names[1] = NULL_TREE;
2793 cst2 = NULL_TREE;
2794 if (rhs_code == BIT_AND_EXPR
2795 || (CONVERT_EXPR_CODE_P (rhs_code)
2796 && INTEGRAL_TYPE_P (TREE_TYPE (val))
2797 && TYPE_UNSIGNED (TREE_TYPE (val))
2798 && TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
2799 > prec))
2801 name2 = gimple_assign_rhs1 (def_stmt);
2802 if (rhs_code == BIT_AND_EXPR)
2803 cst2 = gimple_assign_rhs2 (def_stmt);
2804 else
2806 cst2 = TYPE_MAX_VALUE (TREE_TYPE (val));
2807 nprec = TYPE_PRECISION (TREE_TYPE (name2));
2809 if (TREE_CODE (name2) == SSA_NAME
2810 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
2811 && TREE_CODE (cst2) == INTEGER_CST
2812 && !integer_zerop (cst2)
2813 && (nprec > 1
2814 || TYPE_UNSIGNED (TREE_TYPE (val))))
2816 gimple *def_stmt2 = SSA_NAME_DEF_STMT (name2);
2817 if (gimple_assign_cast_p (def_stmt2))
2819 names[1] = gimple_assign_rhs1 (def_stmt2);
2820 if (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt2))
2821 || !INTEGRAL_TYPE_P (TREE_TYPE (names[1]))
2822 || (TYPE_PRECISION (TREE_TYPE (name2))
2823 != TYPE_PRECISION (TREE_TYPE (names[1]))))
2824 names[1] = NULL_TREE;
2826 names[0] = name2;
2829 if (names[0] || names[1])
2831 wide_int minv, maxv, valv, cst2v;
2832 wide_int tem, sgnbit;
2833 bool valid_p = false, valn, cst2n;
2834 enum tree_code ccode = comp_code;
2836 valv = wide_int::from (wi::to_wide (val), nprec, UNSIGNED);
2837 cst2v = wide_int::from (wi::to_wide (cst2), nprec, UNSIGNED);
2838 valn = wi::neg_p (valv, TYPE_SIGN (TREE_TYPE (val)));
2839 cst2n = wi::neg_p (cst2v, TYPE_SIGN (TREE_TYPE (val)));
2840 /* If CST2 doesn't have most significant bit set,
2841 but VAL is negative, we have comparison like
2842 if ((x & 0x123) > -4) (always true). Just give up. */
2843 if (!cst2n && valn)
2844 ccode = ERROR_MARK;
2845 if (cst2n)
2846 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
2847 else
2848 sgnbit = wi::zero (nprec);
2849 minv = valv & cst2v;
2850 switch (ccode)
2852 case EQ_EXPR:
2853 /* Minimum unsigned value for equality is VAL & CST2
2854 (should be equal to VAL, otherwise we probably should
2855 have folded the comparison into false) and
2856 maximum unsigned value is VAL | ~CST2. */
2857 maxv = valv | ~cst2v;
2858 valid_p = true;
2859 break;
2861 case NE_EXPR:
2862 tem = valv | ~cst2v;
2863 /* If VAL is 0, handle (X & CST2) != 0 as (X & CST2) > 0U. */
2864 if (valv == 0)
2866 cst2n = false;
2867 sgnbit = wi::zero (nprec);
2868 goto gt_expr;
2870 /* If (VAL | ~CST2) is all ones, handle it as
2871 (X & CST2) < VAL. */
2872 if (tem == -1)
2874 cst2n = false;
2875 valn = false;
2876 sgnbit = wi::zero (nprec);
2877 goto lt_expr;
2879 if (!cst2n && wi::neg_p (cst2v))
2880 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
2881 if (sgnbit != 0)
2883 if (valv == sgnbit)
2885 cst2n = true;
2886 valn = true;
2887 goto gt_expr;
2889 if (tem == wi::mask (nprec - 1, false, nprec))
2891 cst2n = true;
2892 goto lt_expr;
2894 if (!cst2n)
2895 sgnbit = wi::zero (nprec);
2897 break;
2899 case GE_EXPR:
2900 /* Minimum unsigned value for >= if (VAL & CST2) == VAL
2901 is VAL and maximum unsigned value is ~0. For signed
2902 comparison, if CST2 doesn't have most significant bit
2903 set, handle it similarly. If CST2 has MSB set,
2904 the minimum is the same, and maximum is ~0U/2. */
2905 if (minv != valv)
2907 /* If (VAL & CST2) != VAL, X & CST2 can't be equal to
2908 VAL. */
2909 minv = masked_increment (valv, cst2v, sgnbit, nprec);
2910 if (minv == valv)
2911 break;
2913 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
2914 valid_p = true;
2915 break;
2917 case GT_EXPR:
2918 gt_expr:
2919 /* Find out smallest MINV where MINV > VAL
2920 && (MINV & CST2) == MINV, if any. If VAL is signed and
2921 CST2 has MSB set, compute it biased by 1 << (nprec - 1). */
2922 minv = masked_increment (valv, cst2v, sgnbit, nprec);
2923 if (minv == valv)
2924 break;
2925 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
2926 valid_p = true;
2927 break;
2929 case LE_EXPR:
2930 /* Minimum unsigned value for <= is 0 and maximum
2931 unsigned value is VAL | ~CST2 if (VAL & CST2) == VAL.
2932 Otherwise, find smallest VAL2 where VAL2 > VAL
2933 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
2934 as maximum.
2935 For signed comparison, if CST2 doesn't have most
2936 significant bit set, handle it similarly. If CST2 has
2937 MSB set, the maximum is the same and minimum is INT_MIN. */
2938 if (minv == valv)
2939 maxv = valv;
2940 else
2942 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
2943 if (maxv == valv)
2944 break;
2945 maxv -= 1;
2947 maxv |= ~cst2v;
2948 minv = sgnbit;
2949 valid_p = true;
2950 break;
2952 case LT_EXPR:
2953 lt_expr:
2954 /* Minimum unsigned value for < is 0 and maximum
2955 unsigned value is (VAL-1) | ~CST2 if (VAL & CST2) == VAL.
2956 Otherwise, find smallest VAL2 where VAL2 > VAL
2957 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
2958 as maximum.
2959 For signed comparison, if CST2 doesn't have most
2960 significant bit set, handle it similarly. If CST2 has
2961 MSB set, the maximum is the same and minimum is INT_MIN. */
2962 if (minv == valv)
2964 if (valv == sgnbit)
2965 break;
2966 maxv = valv;
2968 else
2970 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
2971 if (maxv == valv)
2972 break;
2974 maxv -= 1;
2975 maxv |= ~cst2v;
2976 minv = sgnbit;
2977 valid_p = true;
2978 break;
2980 default:
2981 break;
2983 if (valid_p
2984 && (maxv - minv) != -1)
2986 tree tmp, new_val, type;
2987 int i;
2989 for (i = 0; i < 2; i++)
2990 if (names[i])
2992 wide_int maxv2 = maxv;
2993 tmp = names[i];
2994 type = TREE_TYPE (names[i]);
2995 if (!TYPE_UNSIGNED (type))
2997 type = build_nonstandard_integer_type (nprec, 1);
2998 tmp = build1 (NOP_EXPR, type, names[i]);
3000 if (minv != 0)
3002 tmp = build2 (PLUS_EXPR, type, tmp,
3003 wide_int_to_tree (type, -minv));
3004 maxv2 = maxv - minv;
3006 new_val = wide_int_to_tree (type, maxv2);
3008 if (dump_file)
3010 fprintf (dump_file, "Adding assert for ");
3011 print_generic_expr (dump_file, names[i]);
3012 fprintf (dump_file, " from ");
3013 print_generic_expr (dump_file, tmp);
3014 fprintf (dump_file, "\n");
3017 add_assert_info (asserts, names[i], tmp, LE_EXPR, new_val);
3024 /* OP is an operand of a truth value expression which is known to have
3025 a particular value. Register any asserts for OP and for any
3026 operands in OP's defining statement.
3028 If CODE is EQ_EXPR, then we want to register OP is zero (false),
3029 if CODE is NE_EXPR, then we want to register OP is nonzero (true). */
3031 static void
3032 register_edge_assert_for_1 (tree op, enum tree_code code,
3033 edge e, vec<assert_info> &asserts)
3035 gimple *op_def;
3036 tree val;
3037 enum tree_code rhs_code;
3039 /* We only care about SSA_NAMEs. */
3040 if (TREE_CODE (op) != SSA_NAME)
3041 return;
3043 /* We know that OP will have a zero or nonzero value. */
3044 val = build_int_cst (TREE_TYPE (op), 0);
3045 add_assert_info (asserts, op, op, code, val);
3047 /* Now look at how OP is set. If it's set from a comparison,
3048 a truth operation or some bit operations, then we may be able
3049 to register information about the operands of that assignment. */
3050 op_def = SSA_NAME_DEF_STMT (op);
3051 if (gimple_code (op_def) != GIMPLE_ASSIGN)
3052 return;
3054 rhs_code = gimple_assign_rhs_code (op_def);
3056 if (TREE_CODE_CLASS (rhs_code) == tcc_comparison)
3058 bool invert = (code == EQ_EXPR ? true : false);
3059 tree op0 = gimple_assign_rhs1 (op_def);
3060 tree op1 = gimple_assign_rhs2 (op_def);
3062 if (TREE_CODE (op0) == SSA_NAME)
3063 register_edge_assert_for_2 (op0, e, rhs_code, op0, op1, invert, asserts);
3064 if (TREE_CODE (op1) == SSA_NAME)
3065 register_edge_assert_for_2 (op1, e, rhs_code, op0, op1, invert, asserts);
3067 else if ((code == NE_EXPR
3068 && gimple_assign_rhs_code (op_def) == BIT_AND_EXPR)
3069 || (code == EQ_EXPR
3070 && gimple_assign_rhs_code (op_def) == BIT_IOR_EXPR))
3072 /* Recurse on each operand. */
3073 tree op0 = gimple_assign_rhs1 (op_def);
3074 tree op1 = gimple_assign_rhs2 (op_def);
3075 if (TREE_CODE (op0) == SSA_NAME
3076 && has_single_use (op0))
3077 register_edge_assert_for_1 (op0, code, e, asserts);
3078 if (TREE_CODE (op1) == SSA_NAME
3079 && has_single_use (op1))
3080 register_edge_assert_for_1 (op1, code, e, asserts);
3082 else if (gimple_assign_rhs_code (op_def) == BIT_NOT_EXPR
3083 && TYPE_PRECISION (TREE_TYPE (gimple_assign_lhs (op_def))) == 1)
3085 /* Recurse, flipping CODE. */
3086 code = invert_tree_comparison (code, false);
3087 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
3089 else if (gimple_assign_rhs_code (op_def) == SSA_NAME)
3091 /* Recurse through the copy. */
3092 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
3094 else if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (op_def)))
3096 /* Recurse through the type conversion, unless it is a narrowing
3097 conversion or conversion from non-integral type. */
3098 tree rhs = gimple_assign_rhs1 (op_def);
3099 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs))
3100 && (TYPE_PRECISION (TREE_TYPE (rhs))
3101 <= TYPE_PRECISION (TREE_TYPE (op))))
3102 register_edge_assert_for_1 (rhs, code, e, asserts);
3106 /* Check if comparison
3107 NAME COND_OP INTEGER_CST
3108 has a form of
3109 (X & 11...100..0) COND_OP XX...X00...0
3110 Such comparison can yield assertions like
3111 X >= XX...X00...0
3112 X <= XX...X11...1
3113 in case of COND_OP being EQ_EXPR or
3114 X < XX...X00...0
3115 X > XX...X11...1
3116 in case of NE_EXPR. */
3118 static bool
3119 is_masked_range_test (tree name, tree valt, enum tree_code cond_code,
3120 tree *new_name, tree *low, enum tree_code *low_code,
3121 tree *high, enum tree_code *high_code)
3123 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3125 if (!is_gimple_assign (def_stmt)
3126 || gimple_assign_rhs_code (def_stmt) != BIT_AND_EXPR)
3127 return false;
3129 tree t = gimple_assign_rhs1 (def_stmt);
3130 tree maskt = gimple_assign_rhs2 (def_stmt);
3131 if (TREE_CODE (t) != SSA_NAME || TREE_CODE (maskt) != INTEGER_CST)
3132 return false;
3134 wi::tree_to_wide_ref mask = wi::to_wide (maskt);
3135 wide_int inv_mask = ~mask;
3136 /* Must have been removed by now so don't bother optimizing. */
3137 if (mask == 0 || inv_mask == 0)
3138 return false;
3140 /* Assume VALT is INTEGER_CST. */
3141 wi::tree_to_wide_ref val = wi::to_wide (valt);
3143 if ((inv_mask & (inv_mask + 1)) != 0
3144 || (val & mask) != val)
3145 return false;
3147 bool is_range = cond_code == EQ_EXPR;
3149 tree type = TREE_TYPE (t);
3150 wide_int min = wi::min_value (type),
3151 max = wi::max_value (type);
3153 if (is_range)
3155 *low_code = val == min ? ERROR_MARK : GE_EXPR;
3156 *high_code = val == max ? ERROR_MARK : LE_EXPR;
3158 else
3160 /* We can still generate assertion if one of alternatives
3161 is known to always be false. */
3162 if (val == min)
3164 *low_code = (enum tree_code) 0;
3165 *high_code = GT_EXPR;
3167 else if ((val | inv_mask) == max)
3169 *low_code = LT_EXPR;
3170 *high_code = (enum tree_code) 0;
3172 else
3173 return false;
3176 *new_name = t;
3177 *low = wide_int_to_tree (type, val);
3178 *high = wide_int_to_tree (type, val | inv_mask);
3180 return true;
3183 /* Try to register an edge assertion for SSA name NAME on edge E for
3184 the condition COND contributing to the conditional jump pointed to by
3185 SI. */
3187 void
3188 register_edge_assert_for (tree name, edge e,
3189 enum tree_code cond_code, tree cond_op0,
3190 tree cond_op1, vec<assert_info> &asserts)
3192 tree val;
3193 enum tree_code comp_code;
3194 bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
3196 /* Do not attempt to infer anything in names that flow through
3197 abnormal edges. */
3198 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
3199 return;
3201 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
3202 cond_op0, cond_op1,
3203 is_else_edge,
3204 &comp_code, &val))
3205 return;
3207 /* Register ASSERT_EXPRs for name. */
3208 register_edge_assert_for_2 (name, e, cond_code, cond_op0,
3209 cond_op1, is_else_edge, asserts);
3212 /* If COND is effectively an equality test of an SSA_NAME against
3213 the value zero or one, then we may be able to assert values
3214 for SSA_NAMEs which flow into COND. */
3216 /* In the case of NAME == 1 or NAME != 0, for BIT_AND_EXPR defining
3217 statement of NAME we can assert both operands of the BIT_AND_EXPR
3218 have nonzero value. */
3219 if (((comp_code == EQ_EXPR && integer_onep (val))
3220 || (comp_code == NE_EXPR && integer_zerop (val))))
3222 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3224 if (is_gimple_assign (def_stmt)
3225 && gimple_assign_rhs_code (def_stmt) == BIT_AND_EXPR)
3227 tree op0 = gimple_assign_rhs1 (def_stmt);
3228 tree op1 = gimple_assign_rhs2 (def_stmt);
3229 register_edge_assert_for_1 (op0, NE_EXPR, e, asserts);
3230 register_edge_assert_for_1 (op1, NE_EXPR, e, asserts);
3234 /* In the case of NAME == 0 or NAME != 1, for BIT_IOR_EXPR defining
3235 statement of NAME we can assert both operands of the BIT_IOR_EXPR
3236 have zero value. */
3237 if (((comp_code == EQ_EXPR && integer_zerop (val))
3238 || (comp_code == NE_EXPR && integer_onep (val))))
3240 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3242 /* For BIT_IOR_EXPR only if NAME == 0 both operands have
3243 necessarily zero value, or if type-precision is one. */
3244 if (is_gimple_assign (def_stmt)
3245 && (gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR
3246 && (TYPE_PRECISION (TREE_TYPE (name)) == 1
3247 || comp_code == EQ_EXPR)))
3249 tree op0 = gimple_assign_rhs1 (def_stmt);
3250 tree op1 = gimple_assign_rhs2 (def_stmt);
3251 register_edge_assert_for_1 (op0, EQ_EXPR, e, asserts);
3252 register_edge_assert_for_1 (op1, EQ_EXPR, e, asserts);
3256 /* Sometimes we can infer ranges from (NAME & MASK) == VALUE. */
3257 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
3258 && TREE_CODE (val) == INTEGER_CST)
3260 enum tree_code low_code, high_code;
3261 tree low, high;
3262 if (is_masked_range_test (name, val, comp_code, &name, &low,
3263 &low_code, &high, &high_code))
3265 if (low_code != ERROR_MARK)
3266 register_edge_assert_for_2 (name, e, low_code, name,
3267 low, /*invert*/false, asserts);
3268 if (high_code != ERROR_MARK)
3269 register_edge_assert_for_2 (name, e, high_code, name,
3270 high, /*invert*/false, asserts);
3275 /* Finish found ASSERTS for E and register them at GSI. */
3277 static void
3278 finish_register_edge_assert_for (edge e, gimple_stmt_iterator gsi,
3279 vec<assert_info> &asserts)
3281 for (unsigned i = 0; i < asserts.length (); ++i)
3282 /* Only register an ASSERT_EXPR if NAME was found in the sub-graph
3283 reachable from E. */
3284 if (live_on_edge (e, asserts[i].name))
3285 register_new_assert_for (asserts[i].name, asserts[i].expr,
3286 asserts[i].comp_code, asserts[i].val,
3287 NULL, e, gsi);
3292 /* Determine whether the outgoing edges of BB should receive an
3293 ASSERT_EXPR for each of the operands of BB's LAST statement.
3294 The last statement of BB must be a COND_EXPR.
3296 If any of the sub-graphs rooted at BB have an interesting use of
3297 the predicate operands, an assert location node is added to the
3298 list of assertions for the corresponding operands. */
3300 static void
3301 find_conditional_asserts (basic_block bb, gcond *last)
3303 gimple_stmt_iterator bsi;
3304 tree op;
3305 edge_iterator ei;
3306 edge e;
3307 ssa_op_iter iter;
3309 bsi = gsi_for_stmt (last);
3311 /* Look for uses of the operands in each of the sub-graphs
3312 rooted at BB. We need to check each of the outgoing edges
3313 separately, so that we know what kind of ASSERT_EXPR to
3314 insert. */
3315 FOR_EACH_EDGE (e, ei, bb->succs)
3317 if (e->dest == bb)
3318 continue;
3320 /* Register the necessary assertions for each operand in the
3321 conditional predicate. */
3322 auto_vec<assert_info, 8> asserts;
3323 FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
3324 register_edge_assert_for (op, e,
3325 gimple_cond_code (last),
3326 gimple_cond_lhs (last),
3327 gimple_cond_rhs (last), asserts);
3328 finish_register_edge_assert_for (e, bsi, asserts);
3332 struct case_info
3334 tree expr;
3335 basic_block bb;
3338 /* Compare two case labels sorting first by the destination bb index
3339 and then by the case value. */
3341 static int
3342 compare_case_labels (const void *p1, const void *p2)
3344 const struct case_info *ci1 = (const struct case_info *) p1;
3345 const struct case_info *ci2 = (const struct case_info *) p2;
3346 int idx1 = ci1->bb->index;
3347 int idx2 = ci2->bb->index;
3349 if (idx1 < idx2)
3350 return -1;
3351 else if (idx1 == idx2)
3353 /* Make sure the default label is first in a group. */
3354 if (!CASE_LOW (ci1->expr))
3355 return -1;
3356 else if (!CASE_LOW (ci2->expr))
3357 return 1;
3358 else
3359 return tree_int_cst_compare (CASE_LOW (ci1->expr),
3360 CASE_LOW (ci2->expr));
3362 else
3363 return 1;
3366 /* Determine whether the outgoing edges of BB should receive an
3367 ASSERT_EXPR for each of the operands of BB's LAST statement.
3368 The last statement of BB must be a SWITCH_EXPR.
3370 If any of the sub-graphs rooted at BB have an interesting use of
3371 the predicate operands, an assert location node is added to the
3372 list of assertions for the corresponding operands. */
3374 static void
3375 find_switch_asserts (basic_block bb, gswitch *last)
3377 gimple_stmt_iterator bsi;
3378 tree op;
3379 edge e;
3380 struct case_info *ci;
3381 size_t n = gimple_switch_num_labels (last);
3382 #if GCC_VERSION >= 4000
3383 unsigned int idx;
3384 #else
3385 /* Work around GCC 3.4 bug (PR 37086). */
3386 volatile unsigned int idx;
3387 #endif
3389 bsi = gsi_for_stmt (last);
3390 op = gimple_switch_index (last);
3391 if (TREE_CODE (op) != SSA_NAME)
3392 return;
3394 /* Build a vector of case labels sorted by destination label. */
3395 ci = XNEWVEC (struct case_info, n);
3396 for (idx = 0; idx < n; ++idx)
3398 ci[idx].expr = gimple_switch_label (last, idx);
3399 ci[idx].bb = label_to_block (cfun, CASE_LABEL (ci[idx].expr));
3401 edge default_edge = find_edge (bb, ci[0].bb);
3402 qsort (ci, n, sizeof (struct case_info), compare_case_labels);
3404 for (idx = 0; idx < n; ++idx)
3406 tree min, max;
3407 tree cl = ci[idx].expr;
3408 basic_block cbb = ci[idx].bb;
3410 min = CASE_LOW (cl);
3411 max = CASE_HIGH (cl);
3413 /* If there are multiple case labels with the same destination
3414 we need to combine them to a single value range for the edge. */
3415 if (idx + 1 < n && cbb == ci[idx + 1].bb)
3417 /* Skip labels until the last of the group. */
3418 do {
3419 ++idx;
3420 } while (idx < n && cbb == ci[idx].bb);
3421 --idx;
3423 /* Pick up the maximum of the case label range. */
3424 if (CASE_HIGH (ci[idx].expr))
3425 max = CASE_HIGH (ci[idx].expr);
3426 else
3427 max = CASE_LOW (ci[idx].expr);
3430 /* Can't extract a useful assertion out of a range that includes the
3431 default label. */
3432 if (min == NULL_TREE)
3433 continue;
3435 /* Find the edge to register the assert expr on. */
3436 e = find_edge (bb, cbb);
3438 /* Register the necessary assertions for the operand in the
3439 SWITCH_EXPR. */
3440 auto_vec<assert_info, 8> asserts;
3441 register_edge_assert_for (op, e,
3442 max ? GE_EXPR : EQ_EXPR,
3443 op, fold_convert (TREE_TYPE (op), min),
3444 asserts);
3445 if (max)
3446 register_edge_assert_for (op, e, LE_EXPR, op,
3447 fold_convert (TREE_TYPE (op), max),
3448 asserts);
3449 finish_register_edge_assert_for (e, bsi, asserts);
3452 XDELETEVEC (ci);
3454 if (!live_on_edge (default_edge, op))
3455 return;
3457 /* Now register along the default label assertions that correspond to the
3458 anti-range of each label. */
3459 int insertion_limit = PARAM_VALUE (PARAM_MAX_VRP_SWITCH_ASSERTIONS);
3460 if (insertion_limit == 0)
3461 return;
3463 /* We can't do this if the default case shares a label with another case. */
3464 tree default_cl = gimple_switch_default_label (last);
3465 for (idx = 1; idx < n; idx++)
3467 tree min, max;
3468 tree cl = gimple_switch_label (last, idx);
3469 if (CASE_LABEL (cl) == CASE_LABEL (default_cl))
3470 continue;
3472 min = CASE_LOW (cl);
3473 max = CASE_HIGH (cl);
3475 /* Combine contiguous case ranges to reduce the number of assertions
3476 to insert. */
3477 for (idx = idx + 1; idx < n; idx++)
3479 tree next_min, next_max;
3480 tree next_cl = gimple_switch_label (last, idx);
3481 if (CASE_LABEL (next_cl) == CASE_LABEL (default_cl))
3482 break;
3484 next_min = CASE_LOW (next_cl);
3485 next_max = CASE_HIGH (next_cl);
3487 wide_int difference = (wi::to_wide (next_min)
3488 - wi::to_wide (max ? max : min));
3489 if (wi::eq_p (difference, 1))
3490 max = next_max ? next_max : next_min;
3491 else
3492 break;
3494 idx--;
3496 if (max == NULL_TREE)
3498 /* Register the assertion OP != MIN. */
3499 auto_vec<assert_info, 8> asserts;
3500 min = fold_convert (TREE_TYPE (op), min);
3501 register_edge_assert_for (op, default_edge, NE_EXPR, op, min,
3502 asserts);
3503 finish_register_edge_assert_for (default_edge, bsi, asserts);
3505 else
3507 /* Register the assertion (unsigned)OP - MIN > (MAX - MIN),
3508 which will give OP the anti-range ~[MIN,MAX]. */
3509 tree uop = fold_convert (unsigned_type_for (TREE_TYPE (op)), op);
3510 min = fold_convert (TREE_TYPE (uop), min);
3511 max = fold_convert (TREE_TYPE (uop), max);
3513 tree lhs = fold_build2 (MINUS_EXPR, TREE_TYPE (uop), uop, min);
3514 tree rhs = int_const_binop (MINUS_EXPR, max, min);
3515 register_new_assert_for (op, lhs, GT_EXPR, rhs,
3516 NULL, default_edge, bsi);
3519 if (--insertion_limit == 0)
3520 break;
3525 /* Traverse all the statements in block BB looking for statements that
3526 may generate useful assertions for the SSA names in their operand.
3527 If a statement produces a useful assertion A for name N_i, then the
3528 list of assertions already generated for N_i is scanned to
3529 determine if A is actually needed.
3531 If N_i already had the assertion A at a location dominating the
3532 current location, then nothing needs to be done. Otherwise, the
3533 new location for A is recorded instead.
3535 1- For every statement S in BB, all the variables used by S are
3536 added to bitmap FOUND_IN_SUBGRAPH.
3538 2- If statement S uses an operand N in a way that exposes a known
3539 value range for N, then if N was not already generated by an
3540 ASSERT_EXPR, create a new assert location for N. For instance,
3541 if N is a pointer and the statement dereferences it, we can
3542 assume that N is not NULL.
3544 3- COND_EXPRs are a special case of #2. We can derive range
3545 information from the predicate but need to insert different
3546 ASSERT_EXPRs for each of the sub-graphs rooted at the
3547 conditional block. If the last statement of BB is a conditional
3548 expression of the form 'X op Y', then
3550 a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
3552 b) If the conditional is the only entry point to the sub-graph
3553 corresponding to the THEN_CLAUSE, recurse into it. On
3554 return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
3555 an ASSERT_EXPR is added for the corresponding variable.
3557 c) Repeat step (b) on the ELSE_CLAUSE.
3559 d) Mark X and Y in FOUND_IN_SUBGRAPH.
3561 For instance,
3563 if (a == 9)
3564 b = a;
3565 else
3566 b = c + 1;
3568 In this case, an assertion on the THEN clause is useful to
3569 determine that 'a' is always 9 on that edge. However, an assertion
3570 on the ELSE clause would be unnecessary.
3572 4- If BB does not end in a conditional expression, then we recurse
3573 into BB's dominator children.
3575 At the end of the recursive traversal, every SSA name will have a
3576 list of locations where ASSERT_EXPRs should be added. When a new
3577 location for name N is found, it is registered by calling
3578 register_new_assert_for. That function keeps track of all the
3579 registered assertions to prevent adding unnecessary assertions.
3580 For instance, if a pointer P_4 is dereferenced more than once in a
3581 dominator tree, only the location dominating all the dereference of
3582 P_4 will receive an ASSERT_EXPR. */
3584 static void
3585 find_assert_locations_1 (basic_block bb, sbitmap live)
3587 gimple *last;
3589 last = last_stmt (bb);
3591 /* If BB's last statement is a conditional statement involving integer
3592 operands, determine if we need to add ASSERT_EXPRs. */
3593 if (last
3594 && gimple_code (last) == GIMPLE_COND
3595 && !fp_predicate (last)
3596 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
3597 find_conditional_asserts (bb, as_a <gcond *> (last));
3599 /* If BB's last statement is a switch statement involving integer
3600 operands, determine if we need to add ASSERT_EXPRs. */
3601 if (last
3602 && gimple_code (last) == GIMPLE_SWITCH
3603 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
3604 find_switch_asserts (bb, as_a <gswitch *> (last));
3606 /* Traverse all the statements in BB marking used names and looking
3607 for statements that may infer assertions for their used operands. */
3608 for (gimple_stmt_iterator si = gsi_last_bb (bb); !gsi_end_p (si);
3609 gsi_prev (&si))
3611 gimple *stmt;
3612 tree op;
3613 ssa_op_iter i;
3615 stmt = gsi_stmt (si);
3617 if (is_gimple_debug (stmt))
3618 continue;
3620 /* See if we can derive an assertion for any of STMT's operands. */
3621 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
3623 tree value;
3624 enum tree_code comp_code;
3626 /* If op is not live beyond this stmt, do not bother to insert
3627 asserts for it. */
3628 if (!bitmap_bit_p (live, SSA_NAME_VERSION (op)))
3629 continue;
3631 /* If OP is used in such a way that we can infer a value
3632 range for it, and we don't find a previous assertion for
3633 it, create a new assertion location node for OP. */
3634 if (infer_value_range (stmt, op, &comp_code, &value))
3636 /* If we are able to infer a nonzero value range for OP,
3637 then walk backwards through the use-def chain to see if OP
3638 was set via a typecast.
3640 If so, then we can also infer a nonzero value range
3641 for the operand of the NOP_EXPR. */
3642 if (comp_code == NE_EXPR && integer_zerop (value))
3644 tree t = op;
3645 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
3647 while (is_gimple_assign (def_stmt)
3648 && CONVERT_EXPR_CODE_P
3649 (gimple_assign_rhs_code (def_stmt))
3650 && TREE_CODE
3651 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
3652 && POINTER_TYPE_P
3653 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
3655 t = gimple_assign_rhs1 (def_stmt);
3656 def_stmt = SSA_NAME_DEF_STMT (t);
3658 /* Note we want to register the assert for the
3659 operand of the NOP_EXPR after SI, not after the
3660 conversion. */
3661 if (bitmap_bit_p (live, SSA_NAME_VERSION (t)))
3662 register_new_assert_for (t, t, comp_code, value,
3663 bb, NULL, si);
3667 register_new_assert_for (op, op, comp_code, value, bb, NULL, si);
3671 /* Update live. */
3672 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
3673 bitmap_set_bit (live, SSA_NAME_VERSION (op));
3674 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_DEF)
3675 bitmap_clear_bit (live, SSA_NAME_VERSION (op));
3678 /* Traverse all PHI nodes in BB, updating live. */
3679 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
3680 gsi_next (&si))
3682 use_operand_p arg_p;
3683 ssa_op_iter i;
3684 gphi *phi = si.phi ();
3685 tree res = gimple_phi_result (phi);
3687 if (virtual_operand_p (res))
3688 continue;
3690 FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
3692 tree arg = USE_FROM_PTR (arg_p);
3693 if (TREE_CODE (arg) == SSA_NAME)
3694 bitmap_set_bit (live, SSA_NAME_VERSION (arg));
3697 bitmap_clear_bit (live, SSA_NAME_VERSION (res));
3701 /* Do an RPO walk over the function computing SSA name liveness
3702 on-the-fly and deciding on assert expressions to insert. */
3704 static void
3705 find_assert_locations (void)
3707 int *rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
3708 int *bb_rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
3709 int *last_rpo = XCNEWVEC (int, last_basic_block_for_fn (cfun));
3710 int rpo_cnt, i;
3712 live = XCNEWVEC (sbitmap, last_basic_block_for_fn (cfun));
3713 rpo_cnt = pre_and_rev_post_order_compute (NULL, rpo, false);
3714 for (i = 0; i < rpo_cnt; ++i)
3715 bb_rpo[rpo[i]] = i;
3717 /* Pre-seed loop latch liveness from loop header PHI nodes. Due to
3718 the order we compute liveness and insert asserts we otherwise
3719 fail to insert asserts into the loop latch. */
3720 loop_p loop;
3721 FOR_EACH_LOOP (loop, 0)
3723 i = loop->latch->index;
3724 unsigned int j = single_succ_edge (loop->latch)->dest_idx;
3725 for (gphi_iterator gsi = gsi_start_phis (loop->header);
3726 !gsi_end_p (gsi); gsi_next (&gsi))
3728 gphi *phi = gsi.phi ();
3729 if (virtual_operand_p (gimple_phi_result (phi)))
3730 continue;
3731 tree arg = gimple_phi_arg_def (phi, j);
3732 if (TREE_CODE (arg) == SSA_NAME)
3734 if (live[i] == NULL)
3736 live[i] = sbitmap_alloc (num_ssa_names);
3737 bitmap_clear (live[i]);
3739 bitmap_set_bit (live[i], SSA_NAME_VERSION (arg));
3744 for (i = rpo_cnt - 1; i >= 0; --i)
3746 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, rpo[i]);
3747 edge e;
3748 edge_iterator ei;
3750 if (!live[rpo[i]])
3752 live[rpo[i]] = sbitmap_alloc (num_ssa_names);
3753 bitmap_clear (live[rpo[i]]);
3756 /* Process BB and update the live information with uses in
3757 this block. */
3758 find_assert_locations_1 (bb, live[rpo[i]]);
3760 /* Merge liveness into the predecessor blocks and free it. */
3761 if (!bitmap_empty_p (live[rpo[i]]))
3763 int pred_rpo = i;
3764 FOR_EACH_EDGE (e, ei, bb->preds)
3766 int pred = e->src->index;
3767 if ((e->flags & EDGE_DFS_BACK) || pred == ENTRY_BLOCK)
3768 continue;
3770 if (!live[pred])
3772 live[pred] = sbitmap_alloc (num_ssa_names);
3773 bitmap_clear (live[pred]);
3775 bitmap_ior (live[pred], live[pred], live[rpo[i]]);
3777 if (bb_rpo[pred] < pred_rpo)
3778 pred_rpo = bb_rpo[pred];
3781 /* Record the RPO number of the last visited block that needs
3782 live information from this block. */
3783 last_rpo[rpo[i]] = pred_rpo;
3785 else
3787 sbitmap_free (live[rpo[i]]);
3788 live[rpo[i]] = NULL;
3791 /* We can free all successors live bitmaps if all their
3792 predecessors have been visited already. */
3793 FOR_EACH_EDGE (e, ei, bb->succs)
3794 if (last_rpo[e->dest->index] == i
3795 && live[e->dest->index])
3797 sbitmap_free (live[e->dest->index]);
3798 live[e->dest->index] = NULL;
3802 XDELETEVEC (rpo);
3803 XDELETEVEC (bb_rpo);
3804 XDELETEVEC (last_rpo);
3805 for (i = 0; i < last_basic_block_for_fn (cfun); ++i)
3806 if (live[i])
3807 sbitmap_free (live[i]);
3808 XDELETEVEC (live);
3811 /* Create an ASSERT_EXPR for NAME and insert it in the location
3812 indicated by LOC. Return true if we made any edge insertions. */
3814 static bool
3815 process_assert_insertions_for (tree name, assert_locus *loc)
3817 /* Build the comparison expression NAME_i COMP_CODE VAL. */
3818 gimple *stmt;
3819 tree cond;
3820 gimple *assert_stmt;
3821 edge_iterator ei;
3822 edge e;
3824 /* If we have X <=> X do not insert an assert expr for that. */
3825 if (loc->expr == loc->val)
3826 return false;
3828 cond = build2 (loc->comp_code, boolean_type_node, loc->expr, loc->val);
3829 assert_stmt = build_assert_expr_for (cond, name);
3830 if (loc->e)
3832 /* We have been asked to insert the assertion on an edge. This
3833 is used only by COND_EXPR and SWITCH_EXPR assertions. */
3834 gcc_checking_assert (gimple_code (gsi_stmt (loc->si)) == GIMPLE_COND
3835 || (gimple_code (gsi_stmt (loc->si))
3836 == GIMPLE_SWITCH));
3838 gsi_insert_on_edge (loc->e, assert_stmt);
3839 return true;
3842 /* If the stmt iterator points at the end then this is an insertion
3843 at the beginning of a block. */
3844 if (gsi_end_p (loc->si))
3846 gimple_stmt_iterator si = gsi_after_labels (loc->bb);
3847 gsi_insert_before (&si, assert_stmt, GSI_SAME_STMT);
3848 return false;
3851 /* Otherwise, we can insert right after LOC->SI iff the
3852 statement must not be the last statement in the block. */
3853 stmt = gsi_stmt (loc->si);
3854 if (!stmt_ends_bb_p (stmt))
3856 gsi_insert_after (&loc->si, assert_stmt, GSI_SAME_STMT);
3857 return false;
3860 /* If STMT must be the last statement in BB, we can only insert new
3861 assertions on the non-abnormal edge out of BB. Note that since
3862 STMT is not control flow, there may only be one non-abnormal/eh edge
3863 out of BB. */
3864 FOR_EACH_EDGE (e, ei, loc->bb->succs)
3865 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
3867 gsi_insert_on_edge (e, assert_stmt);
3868 return true;
3871 gcc_unreachable ();
3874 /* Qsort helper for sorting assert locations. If stable is true, don't
3875 use iterative_hash_expr because it can be unstable for -fcompare-debug,
3876 on the other side some pointers might be NULL. */
3878 template <bool stable>
3879 static int
3880 compare_assert_loc (const void *pa, const void *pb)
3882 assert_locus * const a = *(assert_locus * const *)pa;
3883 assert_locus * const b = *(assert_locus * const *)pb;
3885 /* If stable, some asserts might be optimized away already, sort
3886 them last. */
3887 if (stable)
3889 if (a == NULL)
3890 return b != NULL;
3891 else if (b == NULL)
3892 return -1;
3895 if (a->e == NULL && b->e != NULL)
3896 return 1;
3897 else if (a->e != NULL && b->e == NULL)
3898 return -1;
3900 /* After the above checks, we know that (a->e == NULL) == (b->e == NULL),
3901 no need to test both a->e and b->e. */
3903 /* Sort after destination index. */
3904 if (a->e == NULL)
3906 else if (a->e->dest->index > b->e->dest->index)
3907 return 1;
3908 else if (a->e->dest->index < b->e->dest->index)
3909 return -1;
3911 /* Sort after comp_code. */
3912 if (a->comp_code > b->comp_code)
3913 return 1;
3914 else if (a->comp_code < b->comp_code)
3915 return -1;
3917 hashval_t ha, hb;
3919 /* E.g. if a->val is ADDR_EXPR of a VAR_DECL, iterative_hash_expr
3920 uses DECL_UID of the VAR_DECL, so sorting might differ between
3921 -g and -g0. When doing the removal of redundant assert exprs
3922 and commonization to successors, this does not matter, but for
3923 the final sort needs to be stable. */
3924 if (stable)
3926 ha = 0;
3927 hb = 0;
3929 else
3931 ha = iterative_hash_expr (a->expr, iterative_hash_expr (a->val, 0));
3932 hb = iterative_hash_expr (b->expr, iterative_hash_expr (b->val, 0));
3935 /* Break the tie using hashing and source/bb index. */
3936 if (ha == hb)
3937 return (a->e != NULL
3938 ? a->e->src->index - b->e->src->index
3939 : a->bb->index - b->bb->index);
3940 return ha > hb ? 1 : -1;
3943 /* Process all the insertions registered for every name N_i registered
3944 in NEED_ASSERT_FOR. The list of assertions to be inserted are
3945 found in ASSERTS_FOR[i]. */
3947 static void
3948 process_assert_insertions (void)
3950 unsigned i;
3951 bitmap_iterator bi;
3952 bool update_edges_p = false;
3953 int num_asserts = 0;
3955 if (dump_file && (dump_flags & TDF_DETAILS))
3956 dump_all_asserts (dump_file);
3958 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
3960 assert_locus *loc = asserts_for[i];
3961 gcc_assert (loc);
3963 auto_vec<assert_locus *, 16> asserts;
3964 for (; loc; loc = loc->next)
3965 asserts.safe_push (loc);
3966 asserts.qsort (compare_assert_loc<false>);
3968 /* Push down common asserts to successors and remove redundant ones. */
3969 unsigned ecnt = 0;
3970 assert_locus *common = NULL;
3971 unsigned commonj = 0;
3972 for (unsigned j = 0; j < asserts.length (); ++j)
3974 loc = asserts[j];
3975 if (! loc->e)
3976 common = NULL;
3977 else if (! common
3978 || loc->e->dest != common->e->dest
3979 || loc->comp_code != common->comp_code
3980 || ! operand_equal_p (loc->val, common->val, 0)
3981 || ! operand_equal_p (loc->expr, common->expr, 0))
3983 commonj = j;
3984 common = loc;
3985 ecnt = 1;
3987 else if (loc->e == asserts[j-1]->e)
3989 /* Remove duplicate asserts. */
3990 if (commonj == j - 1)
3992 commonj = j;
3993 common = loc;
3995 free (asserts[j-1]);
3996 asserts[j-1] = NULL;
3998 else
4000 ecnt++;
4001 if (EDGE_COUNT (common->e->dest->preds) == ecnt)
4003 /* We have the same assertion on all incoming edges of a BB.
4004 Insert it at the beginning of that block. */
4005 loc->bb = loc->e->dest;
4006 loc->e = NULL;
4007 loc->si = gsi_none ();
4008 common = NULL;
4009 /* Clear asserts commoned. */
4010 for (; commonj != j; ++commonj)
4011 if (asserts[commonj])
4013 free (asserts[commonj]);
4014 asserts[commonj] = NULL;
4020 /* The asserts vector sorting above might be unstable for
4021 -fcompare-debug, sort again to ensure a stable sort. */
4022 asserts.qsort (compare_assert_loc<true>);
4023 for (unsigned j = 0; j < asserts.length (); ++j)
4025 loc = asserts[j];
4026 if (! loc)
4027 break;
4028 update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
4029 num_asserts++;
4030 free (loc);
4034 if (update_edges_p)
4035 gsi_commit_edge_inserts ();
4037 statistics_counter_event (cfun, "Number of ASSERT_EXPR expressions inserted",
4038 num_asserts);
4042 /* Traverse the flowgraph looking for conditional jumps to insert range
4043 expressions. These range expressions are meant to provide information
4044 to optimizations that need to reason in terms of value ranges. They
4045 will not be expanded into RTL. For instance, given:
4047 x = ...
4048 y = ...
4049 if (x < y)
4050 y = x - 2;
4051 else
4052 x = y + 3;
4054 this pass will transform the code into:
4056 x = ...
4057 y = ...
4058 if (x < y)
4060 x = ASSERT_EXPR <x, x < y>
4061 y = x - 2
4063 else
4065 y = ASSERT_EXPR <y, x >= y>
4066 x = y + 3
4069 The idea is that once copy and constant propagation have run, other
4070 optimizations will be able to determine what ranges of values can 'x'
4071 take in different paths of the code, simply by checking the reaching
4072 definition of 'x'. */
4074 static void
4075 insert_range_assertions (void)
4077 need_assert_for = BITMAP_ALLOC (NULL);
4078 asserts_for = XCNEWVEC (assert_locus *, num_ssa_names);
4080 calculate_dominance_info (CDI_DOMINATORS);
4082 find_assert_locations ();
4083 if (!bitmap_empty_p (need_assert_for))
4085 process_assert_insertions ();
4086 update_ssa (TODO_update_ssa_no_phi);
4089 if (dump_file && (dump_flags & TDF_DETAILS))
4091 fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
4092 dump_function_to_file (current_function_decl, dump_file, dump_flags);
4095 free (asserts_for);
4096 BITMAP_FREE (need_assert_for);
4099 class vrp_prop : public ssa_propagation_engine
4101 public:
4102 enum ssa_prop_result visit_stmt (gimple *, edge *, tree *) FINAL OVERRIDE;
4103 enum ssa_prop_result visit_phi (gphi *) FINAL OVERRIDE;
4105 void vrp_initialize (void);
4106 void vrp_finalize (bool);
4107 void check_all_array_refs (void);
4108 void check_array_ref (location_t, tree, bool);
4109 void check_mem_ref (location_t, tree, bool);
4110 void search_for_addr_array (tree, location_t);
4112 class vr_values vr_values;
4113 /* Temporary delegator to minimize code churn. */
4114 value_range *get_value_range (const_tree op)
4115 { return vr_values.get_value_range (op); }
4116 void set_defs_to_varying (gimple *stmt)
4117 { return vr_values.set_defs_to_varying (stmt); }
4118 void extract_range_from_stmt (gimple *stmt, edge *taken_edge_p,
4119 tree *output_p, value_range *vr)
4120 { vr_values.extract_range_from_stmt (stmt, taken_edge_p, output_p, vr); }
4121 bool update_value_range (const_tree op, value_range *vr)
4122 { return vr_values.update_value_range (op, vr); }
4123 void extract_range_basic (value_range *vr, gimple *stmt)
4124 { vr_values.extract_range_basic (vr, stmt); }
4125 void extract_range_from_phi_node (gphi *phi, value_range *vr)
4126 { vr_values.extract_range_from_phi_node (phi, vr); }
4128 /* Checks one ARRAY_REF in REF, located at LOCUS. Ignores flexible arrays
4129 and "struct" hacks. If VRP can determine that the
4130 array subscript is a constant, check if it is outside valid
4131 range. If the array subscript is a RANGE, warn if it is
4132 non-overlapping with valid range.
4133 IGNORE_OFF_BY_ONE is true if the ARRAY_REF is inside a ADDR_EXPR. */
4135 void
4136 vrp_prop::check_array_ref (location_t location, tree ref,
4137 bool ignore_off_by_one)
4139 const value_range *vr = NULL;
4140 tree low_sub, up_sub;
4141 tree low_bound, up_bound, up_bound_p1;
4143 if (TREE_NO_WARNING (ref))
4144 return;
4146 low_sub = up_sub = TREE_OPERAND (ref, 1);
4147 up_bound = array_ref_up_bound (ref);
4149 if (!up_bound
4150 || TREE_CODE (up_bound) != INTEGER_CST
4151 || (warn_array_bounds < 2
4152 && array_at_struct_end_p (ref)))
4154 /* Accesses to trailing arrays via pointers may access storage
4155 beyond the types array bounds. For such arrays, or for flexible
4156 array members, as well as for other arrays of an unknown size,
4157 replace the upper bound with a more permissive one that assumes
4158 the size of the largest object is PTRDIFF_MAX. */
4159 tree eltsize = array_ref_element_size (ref);
4161 if (TREE_CODE (eltsize) != INTEGER_CST
4162 || integer_zerop (eltsize))
4164 up_bound = NULL_TREE;
4165 up_bound_p1 = NULL_TREE;
4167 else
4169 tree maxbound = TYPE_MAX_VALUE (ptrdiff_type_node);
4170 tree arg = TREE_OPERAND (ref, 0);
4171 poly_int64 off;
4173 if (get_addr_base_and_unit_offset (arg, &off) && known_gt (off, 0))
4174 maxbound = wide_int_to_tree (sizetype,
4175 wi::sub (wi::to_wide (maxbound),
4176 off));
4177 else
4178 maxbound = fold_convert (sizetype, maxbound);
4180 up_bound_p1 = int_const_binop (TRUNC_DIV_EXPR, maxbound, eltsize);
4182 up_bound = int_const_binop (MINUS_EXPR, up_bound_p1,
4183 build_int_cst (ptrdiff_type_node, 1));
4186 else
4187 up_bound_p1 = int_const_binop (PLUS_EXPR, up_bound,
4188 build_int_cst (TREE_TYPE (up_bound), 1));
4190 low_bound = array_ref_low_bound (ref);
4192 tree artype = TREE_TYPE (TREE_OPERAND (ref, 0));
4194 bool warned = false;
4196 /* Empty array. */
4197 if (up_bound && tree_int_cst_equal (low_bound, up_bound_p1))
4198 warned = warning_at (location, OPT_Warray_bounds,
4199 "array subscript %E is above array bounds of %qT",
4200 low_bound, artype);
4202 if (TREE_CODE (low_sub) == SSA_NAME)
4204 vr = get_value_range (low_sub);
4205 if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
4207 low_sub = vr->type == VR_RANGE ? vr->max : vr->min;
4208 up_sub = vr->type == VR_RANGE ? vr->min : vr->max;
4212 if (vr && vr->type == VR_ANTI_RANGE)
4214 if (up_bound
4215 && TREE_CODE (up_sub) == INTEGER_CST
4216 && (ignore_off_by_one
4217 ? tree_int_cst_lt (up_bound, up_sub)
4218 : tree_int_cst_le (up_bound, up_sub))
4219 && TREE_CODE (low_sub) == INTEGER_CST
4220 && tree_int_cst_le (low_sub, low_bound))
4221 warned = warning_at (location, OPT_Warray_bounds,
4222 "array subscript [%E, %E] is outside "
4223 "array bounds of %qT",
4224 low_sub, up_sub, artype);
4226 else if (up_bound
4227 && TREE_CODE (up_sub) == INTEGER_CST
4228 && (ignore_off_by_one
4229 ? !tree_int_cst_le (up_sub, up_bound_p1)
4230 : !tree_int_cst_le (up_sub, up_bound)))
4232 if (dump_file && (dump_flags & TDF_DETAILS))
4234 fprintf (dump_file, "Array bound warning for ");
4235 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
4236 fprintf (dump_file, "\n");
4238 warned = warning_at (location, OPT_Warray_bounds,
4239 "array subscript %E is above array bounds of %qT",
4240 up_sub, artype);
4242 else if (TREE_CODE (low_sub) == INTEGER_CST
4243 && tree_int_cst_lt (low_sub, low_bound))
4245 if (dump_file && (dump_flags & TDF_DETAILS))
4247 fprintf (dump_file, "Array bound warning for ");
4248 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
4249 fprintf (dump_file, "\n");
4251 warned = warning_at (location, OPT_Warray_bounds,
4252 "array subscript %E is below array bounds of %qT",
4253 low_sub, artype);
4256 if (warned)
4258 ref = TREE_OPERAND (ref, 0);
4260 if (DECL_P (ref))
4261 inform (DECL_SOURCE_LOCATION (ref), "while referencing %qD", ref);
4263 TREE_NO_WARNING (ref) = 1;
4267 /* Checks one MEM_REF in REF, located at LOCATION, for out-of-bounds
4268 references to string constants. If VRP can determine that the array
4269 subscript is a constant, check if it is outside valid range.
4270 If the array subscript is a RANGE, warn if it is non-overlapping
4271 with valid range.
4272 IGNORE_OFF_BY_ONE is true if the MEM_REF is inside an ADDR_EXPR
4273 (used to allow one-past-the-end indices for code that takes
4274 the address of the just-past-the-end element of an array). */
4276 void
4277 vrp_prop::check_mem_ref (location_t location, tree ref,
4278 bool ignore_off_by_one)
4280 if (TREE_NO_WARNING (ref))
4281 return;
4283 tree arg = TREE_OPERAND (ref, 0);
4284 /* The constant and variable offset of the reference. */
4285 tree cstoff = TREE_OPERAND (ref, 1);
4286 tree varoff = NULL_TREE;
4288 const offset_int maxobjsize = tree_to_shwi (max_object_size ());
4290 /* The array or string constant bounds in bytes. Initially set
4291 to [-MAXOBJSIZE - 1, MAXOBJSIZE] until a tighter bound is
4292 determined. */
4293 offset_int arrbounds[2] = { -maxobjsize - 1, maxobjsize };
4295 /* The minimum and maximum intermediate offset. For a reference
4296 to be valid, not only does the final offset/subscript must be
4297 in bounds but all intermediate offsets should be as well.
4298 GCC may be able to deal gracefully with such out-of-bounds
4299 offsets so the checking is only enbaled at -Warray-bounds=2
4300 where it may help detect bugs in uses of the intermediate
4301 offsets that could otherwise not be detectable. */
4302 offset_int ioff = wi::to_offset (fold_convert (ptrdiff_type_node, cstoff));
4303 offset_int extrema[2] = { 0, wi::abs (ioff) };
4305 /* The range of the byte offset into the reference. */
4306 offset_int offrange[2] = { 0, 0 };
4308 const value_range *vr = NULL;
4310 /* Determine the offsets and increment OFFRANGE for the bounds of each.
4311 The loop computes the the range of the final offset for expressions
4312 such as (A + i0 + ... + iN)[CSTOFF] where i0 through iN are SSA_NAMEs
4313 in some range. */
4314 while (TREE_CODE (arg) == SSA_NAME)
4316 gimple *def = SSA_NAME_DEF_STMT (arg);
4317 if (!is_gimple_assign (def))
4318 break;
4320 tree_code code = gimple_assign_rhs_code (def);
4321 if (code == POINTER_PLUS_EXPR)
4323 arg = gimple_assign_rhs1 (def);
4324 varoff = gimple_assign_rhs2 (def);
4326 else if (code == ASSERT_EXPR)
4328 arg = TREE_OPERAND (gimple_assign_rhs1 (def), 0);
4329 continue;
4331 else
4332 return;
4334 /* VAROFF should always be a SSA_NAME here (and not even
4335 INTEGER_CST) but there's no point in taking chances. */
4336 if (TREE_CODE (varoff) != SSA_NAME)
4337 break;
4339 vr = get_value_range (varoff);
4340 if (!vr || vr->type == VR_UNDEFINED || !vr->min || !vr->max)
4341 break;
4343 if (TREE_CODE (vr->min) != INTEGER_CST
4344 || TREE_CODE (vr->max) != INTEGER_CST)
4345 break;
4347 if (vr->type == VR_RANGE)
4349 if (tree_int_cst_lt (vr->min, vr->max))
4351 offset_int min
4352 = wi::to_offset (fold_convert (ptrdiff_type_node, vr->min));
4353 offset_int max
4354 = wi::to_offset (fold_convert (ptrdiff_type_node, vr->max));
4355 if (min < max)
4357 offrange[0] += min;
4358 offrange[1] += max;
4360 else
4362 offrange[0] += max;
4363 offrange[1] += min;
4366 else
4368 /* Conservatively add [-MAXOBJSIZE -1, MAXOBJSIZE]
4369 to OFFRANGE. */
4370 offrange[0] += arrbounds[0];
4371 offrange[1] += arrbounds[1];
4374 else
4376 /* For an anti-range, analogously to the above, conservatively
4377 add [-MAXOBJSIZE -1, MAXOBJSIZE] to OFFRANGE. */
4378 offrange[0] += arrbounds[0];
4379 offrange[1] += arrbounds[1];
4382 /* Keep track of the minimum and maximum offset. */
4383 if (offrange[1] < 0 && offrange[1] < extrema[0])
4384 extrema[0] = offrange[1];
4385 if (offrange[0] > 0 && offrange[0] > extrema[1])
4386 extrema[1] = offrange[0];
4388 if (offrange[0] < arrbounds[0])
4389 offrange[0] = arrbounds[0];
4391 if (offrange[1] > arrbounds[1])
4392 offrange[1] = arrbounds[1];
4395 if (TREE_CODE (arg) == ADDR_EXPR)
4397 arg = TREE_OPERAND (arg, 0);
4398 if (TREE_CODE (arg) != STRING_CST
4399 && TREE_CODE (arg) != VAR_DECL)
4400 return;
4402 else
4403 return;
4405 /* The type of the object being referred to. It can be an array,
4406 string literal, or a non-array type when the MEM_REF represents
4407 a reference/subscript via a pointer to an object that is not
4408 an element of an array. References to members of structs and
4409 unions are excluded because MEM_REF doesn't make it possible
4410 to identify the member where the reference originated.
4411 Incomplete types are excluded as well because their size is
4412 not known. */
4413 tree reftype = TREE_TYPE (arg);
4414 if (POINTER_TYPE_P (reftype)
4415 || !COMPLETE_TYPE_P (reftype)
4416 || TREE_CODE (TYPE_SIZE_UNIT (reftype)) != INTEGER_CST
4417 || RECORD_OR_UNION_TYPE_P (reftype))
4418 return;
4420 offset_int eltsize;
4421 if (TREE_CODE (reftype) == ARRAY_TYPE)
4423 eltsize = wi::to_offset (TYPE_SIZE_UNIT (TREE_TYPE (reftype)));
4425 if (tree dom = TYPE_DOMAIN (reftype))
4427 tree bnds[] = { TYPE_MIN_VALUE (dom), TYPE_MAX_VALUE (dom) };
4428 if (array_at_struct_end_p (arg)
4429 || !bnds[0] || !bnds[1])
4431 arrbounds[0] = 0;
4432 arrbounds[1] = wi::lrshift (maxobjsize, wi::floor_log2 (eltsize));
4434 else
4436 arrbounds[0] = wi::to_offset (bnds[0]) * eltsize;
4437 arrbounds[1] = (wi::to_offset (bnds[1]) + 1) * eltsize;
4440 else
4442 arrbounds[0] = 0;
4443 arrbounds[1] = wi::lrshift (maxobjsize, wi::floor_log2 (eltsize));
4446 if (TREE_CODE (ref) == MEM_REF)
4448 /* For MEM_REF determine a tighter bound of the non-array
4449 element type. */
4450 tree eltype = TREE_TYPE (reftype);
4451 while (TREE_CODE (eltype) == ARRAY_TYPE)
4452 eltype = TREE_TYPE (eltype);
4453 eltsize = wi::to_offset (TYPE_SIZE_UNIT (eltype));
4456 else
4458 eltsize = 1;
4459 arrbounds[0] = 0;
4460 arrbounds[1] = wi::to_offset (TYPE_SIZE_UNIT (reftype));
4463 offrange[0] += ioff;
4464 offrange[1] += ioff;
4466 /* Compute the more permissive upper bound when IGNORE_OFF_BY_ONE
4467 is set (when taking the address of the one-past-last element
4468 of an array) but always use the stricter bound in diagnostics. */
4469 offset_int ubound = arrbounds[1];
4470 if (ignore_off_by_one)
4471 ubound += 1;
4473 if (offrange[0] >= ubound || offrange[1] < arrbounds[0])
4475 /* Treat a reference to a non-array object as one to an array
4476 of a single element. */
4477 if (TREE_CODE (reftype) != ARRAY_TYPE)
4478 reftype = build_array_type_nelts (reftype, 1);
4480 if (TREE_CODE (ref) == MEM_REF)
4482 /* Extract the element type out of MEM_REF and use its size
4483 to compute the index to print in the diagnostic; arrays
4484 in MEM_REF don't mean anything. */
4485 tree type = TREE_TYPE (ref);
4486 while (TREE_CODE (type) == ARRAY_TYPE)
4487 type = TREE_TYPE (type);
4488 tree size = TYPE_SIZE_UNIT (type);
4489 offrange[0] = offrange[0] / wi::to_offset (size);
4490 offrange[1] = offrange[1] / wi::to_offset (size);
4492 else
4494 /* For anything other than MEM_REF, compute the index to
4495 print in the diagnostic as the offset over element size. */
4496 offrange[0] = offrange[0] / eltsize;
4497 offrange[1] = offrange[1] / eltsize;
4500 bool warned;
4501 if (offrange[0] == offrange[1])
4502 warned = warning_at (location, OPT_Warray_bounds,
4503 "array subscript %wi is outside array bounds "
4504 "of %qT",
4505 offrange[0].to_shwi (), reftype);
4506 else
4507 warned = warning_at (location, OPT_Warray_bounds,
4508 "array subscript [%wi, %wi] is outside "
4509 "array bounds of %qT",
4510 offrange[0].to_shwi (),
4511 offrange[1].to_shwi (), reftype);
4512 if (warned && DECL_P (arg))
4513 inform (DECL_SOURCE_LOCATION (arg), "while referencing %qD", arg);
4515 TREE_NO_WARNING (ref) = 1;
4516 return;
4519 if (warn_array_bounds < 2)
4520 return;
4522 /* At level 2 check also intermediate offsets. */
4523 int i = 0;
4524 if (extrema[i] < -arrbounds[1] || extrema[i = 1] > ubound)
4526 HOST_WIDE_INT tmpidx = extrema[i].to_shwi () / eltsize.to_shwi ();
4528 warning_at (location, OPT_Warray_bounds,
4529 "intermediate array offset %wi is outside array bounds "
4530 "of %qT",
4531 tmpidx, reftype);
4532 TREE_NO_WARNING (ref) = 1;
4536 /* Searches if the expr T, located at LOCATION computes
4537 address of an ARRAY_REF, and call check_array_ref on it. */
4539 void
4540 vrp_prop::search_for_addr_array (tree t, location_t location)
4542 /* Check each ARRAY_REF and MEM_REF in the reference chain. */
4545 if (TREE_CODE (t) == ARRAY_REF)
4546 check_array_ref (location, t, true /*ignore_off_by_one*/);
4547 else if (TREE_CODE (t) == MEM_REF)
4548 check_mem_ref (location, t, true /*ignore_off_by_one*/);
4550 t = TREE_OPERAND (t, 0);
4552 while (handled_component_p (t) || TREE_CODE (t) == MEM_REF);
4554 if (TREE_CODE (t) != MEM_REF
4555 || TREE_CODE (TREE_OPERAND (t, 0)) != ADDR_EXPR
4556 || TREE_NO_WARNING (t))
4557 return;
4559 tree tem = TREE_OPERAND (TREE_OPERAND (t, 0), 0);
4560 tree low_bound, up_bound, el_sz;
4561 if (TREE_CODE (TREE_TYPE (tem)) != ARRAY_TYPE
4562 || TREE_CODE (TREE_TYPE (TREE_TYPE (tem))) == ARRAY_TYPE
4563 || !TYPE_DOMAIN (TREE_TYPE (tem)))
4564 return;
4566 low_bound = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
4567 up_bound = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
4568 el_sz = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (tem)));
4569 if (!low_bound
4570 || TREE_CODE (low_bound) != INTEGER_CST
4571 || !up_bound
4572 || TREE_CODE (up_bound) != INTEGER_CST
4573 || !el_sz
4574 || TREE_CODE (el_sz) != INTEGER_CST)
4575 return;
4577 offset_int idx;
4578 if (!mem_ref_offset (t).is_constant (&idx))
4579 return;
4581 bool warned = false;
4582 idx = wi::sdiv_trunc (idx, wi::to_offset (el_sz));
4583 if (idx < 0)
4585 if (dump_file && (dump_flags & TDF_DETAILS))
4587 fprintf (dump_file, "Array bound warning for ");
4588 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
4589 fprintf (dump_file, "\n");
4591 warned = warning_at (location, OPT_Warray_bounds,
4592 "array subscript %wi is below "
4593 "array bounds of %qT",
4594 idx.to_shwi (), TREE_TYPE (tem));
4596 else if (idx > (wi::to_offset (up_bound)
4597 - wi::to_offset (low_bound) + 1))
4599 if (dump_file && (dump_flags & TDF_DETAILS))
4601 fprintf (dump_file, "Array bound warning for ");
4602 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
4603 fprintf (dump_file, "\n");
4605 warned = warning_at (location, OPT_Warray_bounds,
4606 "array subscript %wu is above "
4607 "array bounds of %qT",
4608 idx.to_uhwi (), TREE_TYPE (tem));
4611 if (warned)
4613 if (DECL_P (t))
4614 inform (DECL_SOURCE_LOCATION (t), "while referencing %qD", t);
4616 TREE_NO_WARNING (t) = 1;
4620 /* walk_tree() callback that checks if *TP is
4621 an ARRAY_REF inside an ADDR_EXPR (in which an array
4622 subscript one outside the valid range is allowed). Call
4623 check_array_ref for each ARRAY_REF found. The location is
4624 passed in DATA. */
4626 static tree
4627 check_array_bounds (tree *tp, int *walk_subtree, void *data)
4629 tree t = *tp;
4630 struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
4631 location_t location;
4633 if (EXPR_HAS_LOCATION (t))
4634 location = EXPR_LOCATION (t);
4635 else
4636 location = gimple_location (wi->stmt);
4638 *walk_subtree = TRUE;
4640 vrp_prop *vrp_prop = (class vrp_prop *)wi->info;
4641 if (TREE_CODE (t) == ARRAY_REF)
4642 vrp_prop->check_array_ref (location, t, false /*ignore_off_by_one*/);
4643 else if (TREE_CODE (t) == MEM_REF)
4644 vrp_prop->check_mem_ref (location, t, false /*ignore_off_by_one*/);
4645 else if (TREE_CODE (t) == ADDR_EXPR)
4647 vrp_prop->search_for_addr_array (t, location);
4648 *walk_subtree = FALSE;
4651 return NULL_TREE;
4654 /* A dom_walker subclass for use by vrp_prop::check_all_array_refs,
4655 to walk over all statements of all reachable BBs and call
4656 check_array_bounds on them. */
4658 class check_array_bounds_dom_walker : public dom_walker
4660 public:
4661 check_array_bounds_dom_walker (vrp_prop *prop)
4662 : dom_walker (CDI_DOMINATORS,
4663 /* Discover non-executable edges, preserving EDGE_EXECUTABLE
4664 flags, so that we can merge in information on
4665 non-executable edges from vrp_folder . */
4666 REACHABLE_BLOCKS_PRESERVING_FLAGS),
4667 m_prop (prop) {}
4668 ~check_array_bounds_dom_walker () {}
4670 edge before_dom_children (basic_block) FINAL OVERRIDE;
4672 private:
4673 vrp_prop *m_prop;
4676 /* Implementation of dom_walker::before_dom_children.
4678 Walk over all statements of BB and call check_array_bounds on them,
4679 and determine if there's a unique successor edge. */
4681 edge
4682 check_array_bounds_dom_walker::before_dom_children (basic_block bb)
4684 gimple_stmt_iterator si;
4685 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
4687 gimple *stmt = gsi_stmt (si);
4688 struct walk_stmt_info wi;
4689 if (!gimple_has_location (stmt)
4690 || is_gimple_debug (stmt))
4691 continue;
4693 memset (&wi, 0, sizeof (wi));
4695 wi.info = m_prop;
4697 walk_gimple_op (stmt, check_array_bounds, &wi);
4700 /* Determine if there's a unique successor edge, and if so, return
4701 that back to dom_walker, ensuring that we don't visit blocks that
4702 became unreachable during the VRP propagation
4703 (PR tree-optimization/83312). */
4704 return find_taken_edge (bb, NULL_TREE);
4707 /* Walk over all statements of all reachable BBs and call check_array_bounds
4708 on them. */
4710 void
4711 vrp_prop::check_all_array_refs ()
4713 check_array_bounds_dom_walker w (this);
4714 w.walk (ENTRY_BLOCK_PTR_FOR_FN (cfun));
4717 /* Return true if all imm uses of VAR are either in STMT, or
4718 feed (optionally through a chain of single imm uses) GIMPLE_COND
4719 in basic block COND_BB. */
4721 static bool
4722 all_imm_uses_in_stmt_or_feed_cond (tree var, gimple *stmt, basic_block cond_bb)
4724 use_operand_p use_p, use2_p;
4725 imm_use_iterator iter;
4727 FOR_EACH_IMM_USE_FAST (use_p, iter, var)
4728 if (USE_STMT (use_p) != stmt)
4730 gimple *use_stmt = USE_STMT (use_p), *use_stmt2;
4731 if (is_gimple_debug (use_stmt))
4732 continue;
4733 while (is_gimple_assign (use_stmt)
4734 && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
4735 && single_imm_use (gimple_assign_lhs (use_stmt),
4736 &use2_p, &use_stmt2))
4737 use_stmt = use_stmt2;
4738 if (gimple_code (use_stmt) != GIMPLE_COND
4739 || gimple_bb (use_stmt) != cond_bb)
4740 return false;
4742 return true;
4745 /* Handle
4746 _4 = x_3 & 31;
4747 if (_4 != 0)
4748 goto <bb 6>;
4749 else
4750 goto <bb 7>;
4751 <bb 6>:
4752 __builtin_unreachable ();
4753 <bb 7>:
4754 x_5 = ASSERT_EXPR <x_3, ...>;
4755 If x_3 has no other immediate uses (checked by caller),
4756 var is the x_3 var from ASSERT_EXPR, we can clear low 5 bits
4757 from the non-zero bitmask. */
4759 void
4760 maybe_set_nonzero_bits (edge e, tree var)
4762 basic_block cond_bb = e->src;
4763 gimple *stmt = last_stmt (cond_bb);
4764 tree cst;
4766 if (stmt == NULL
4767 || gimple_code (stmt) != GIMPLE_COND
4768 || gimple_cond_code (stmt) != ((e->flags & EDGE_TRUE_VALUE)
4769 ? EQ_EXPR : NE_EXPR)
4770 || TREE_CODE (gimple_cond_lhs (stmt)) != SSA_NAME
4771 || !integer_zerop (gimple_cond_rhs (stmt)))
4772 return;
4774 stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt));
4775 if (!is_gimple_assign (stmt)
4776 || gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
4777 || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
4778 return;
4779 if (gimple_assign_rhs1 (stmt) != var)
4781 gimple *stmt2;
4783 if (TREE_CODE (gimple_assign_rhs1 (stmt)) != SSA_NAME)
4784 return;
4785 stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
4786 if (!gimple_assign_cast_p (stmt2)
4787 || gimple_assign_rhs1 (stmt2) != var
4788 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt2))
4789 || (TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (stmt)))
4790 != TYPE_PRECISION (TREE_TYPE (var))))
4791 return;
4793 cst = gimple_assign_rhs2 (stmt);
4794 set_nonzero_bits (var, wi::bit_and_not (get_nonzero_bits (var),
4795 wi::to_wide (cst)));
4798 /* Convert range assertion expressions into the implied copies and
4799 copy propagate away the copies. Doing the trivial copy propagation
4800 here avoids the need to run the full copy propagation pass after
4801 VRP.
4803 FIXME, this will eventually lead to copy propagation removing the
4804 names that had useful range information attached to them. For
4805 instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
4806 then N_i will have the range [3, +INF].
4808 However, by converting the assertion into the implied copy
4809 operation N_i = N_j, we will then copy-propagate N_j into the uses
4810 of N_i and lose the range information. We may want to hold on to
4811 ASSERT_EXPRs a little while longer as the ranges could be used in
4812 things like jump threading.
4814 The problem with keeping ASSERT_EXPRs around is that passes after
4815 VRP need to handle them appropriately.
4817 Another approach would be to make the range information a first
4818 class property of the SSA_NAME so that it can be queried from
4819 any pass. This is made somewhat more complex by the need for
4820 multiple ranges to be associated with one SSA_NAME. */
4822 static void
4823 remove_range_assertions (void)
4825 basic_block bb;
4826 gimple_stmt_iterator si;
4827 /* 1 if looking at ASSERT_EXPRs immediately at the beginning of
4828 a basic block preceeded by GIMPLE_COND branching to it and
4829 __builtin_trap, -1 if not yet checked, 0 otherwise. */
4830 int is_unreachable;
4832 /* Note that the BSI iterator bump happens at the bottom of the
4833 loop and no bump is necessary if we're removing the statement
4834 referenced by the current BSI. */
4835 FOR_EACH_BB_FN (bb, cfun)
4836 for (si = gsi_after_labels (bb), is_unreachable = -1; !gsi_end_p (si);)
4838 gimple *stmt = gsi_stmt (si);
4840 if (is_gimple_assign (stmt)
4841 && gimple_assign_rhs_code (stmt) == ASSERT_EXPR)
4843 tree lhs = gimple_assign_lhs (stmt);
4844 tree rhs = gimple_assign_rhs1 (stmt);
4845 tree var;
4847 var = ASSERT_EXPR_VAR (rhs);
4849 if (TREE_CODE (var) == SSA_NAME
4850 && !POINTER_TYPE_P (TREE_TYPE (lhs))
4851 && SSA_NAME_RANGE_INFO (lhs))
4853 if (is_unreachable == -1)
4855 is_unreachable = 0;
4856 if (single_pred_p (bb)
4857 && assert_unreachable_fallthru_edge_p
4858 (single_pred_edge (bb)))
4859 is_unreachable = 1;
4861 /* Handle
4862 if (x_7 >= 10 && x_7 < 20)
4863 __builtin_unreachable ();
4864 x_8 = ASSERT_EXPR <x_7, ...>;
4865 if the only uses of x_7 are in the ASSERT_EXPR and
4866 in the condition. In that case, we can copy the
4867 range info from x_8 computed in this pass also
4868 for x_7. */
4869 if (is_unreachable
4870 && all_imm_uses_in_stmt_or_feed_cond (var, stmt,
4871 single_pred (bb)))
4873 set_range_info (var, SSA_NAME_RANGE_TYPE (lhs),
4874 SSA_NAME_RANGE_INFO (lhs)->get_min (),
4875 SSA_NAME_RANGE_INFO (lhs)->get_max ());
4876 maybe_set_nonzero_bits (single_pred_edge (bb), var);
4880 /* Propagate the RHS into every use of the LHS. For SSA names
4881 also propagate abnormals as it merely restores the original
4882 IL in this case (an replace_uses_by would assert). */
4883 if (TREE_CODE (var) == SSA_NAME)
4885 imm_use_iterator iter;
4886 use_operand_p use_p;
4887 gimple *use_stmt;
4888 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
4889 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
4890 SET_USE (use_p, var);
4892 else
4893 replace_uses_by (lhs, var);
4895 /* And finally, remove the copy, it is not needed. */
4896 gsi_remove (&si, true);
4897 release_defs (stmt);
4899 else
4901 if (!is_gimple_debug (gsi_stmt (si)))
4902 is_unreachable = 0;
4903 gsi_next (&si);
4908 /* Return true if STMT is interesting for VRP. */
4910 bool
4911 stmt_interesting_for_vrp (gimple *stmt)
4913 if (gimple_code (stmt) == GIMPLE_PHI)
4915 tree res = gimple_phi_result (stmt);
4916 return (!virtual_operand_p (res)
4917 && (INTEGRAL_TYPE_P (TREE_TYPE (res))
4918 || POINTER_TYPE_P (TREE_TYPE (res))));
4920 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
4922 tree lhs = gimple_get_lhs (stmt);
4924 /* In general, assignments with virtual operands are not useful
4925 for deriving ranges, with the obvious exception of calls to
4926 builtin functions. */
4927 if (lhs && TREE_CODE (lhs) == SSA_NAME
4928 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
4929 || POINTER_TYPE_P (TREE_TYPE (lhs)))
4930 && (is_gimple_call (stmt)
4931 || !gimple_vuse (stmt)))
4932 return true;
4933 else if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
4934 switch (gimple_call_internal_fn (stmt))
4936 case IFN_ADD_OVERFLOW:
4937 case IFN_SUB_OVERFLOW:
4938 case IFN_MUL_OVERFLOW:
4939 case IFN_ATOMIC_COMPARE_EXCHANGE:
4940 /* These internal calls return _Complex integer type,
4941 but are interesting to VRP nevertheless. */
4942 if (lhs && TREE_CODE (lhs) == SSA_NAME)
4943 return true;
4944 break;
4945 default:
4946 break;
4949 else if (gimple_code (stmt) == GIMPLE_COND
4950 || gimple_code (stmt) == GIMPLE_SWITCH)
4951 return true;
4953 return false;
4956 /* Initialization required by ssa_propagate engine. */
4958 void
4959 vrp_prop::vrp_initialize ()
4961 basic_block bb;
4963 FOR_EACH_BB_FN (bb, cfun)
4965 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
4966 gsi_next (&si))
4968 gphi *phi = si.phi ();
4969 if (!stmt_interesting_for_vrp (phi))
4971 tree lhs = PHI_RESULT (phi);
4972 set_value_range_to_varying (get_value_range (lhs));
4973 prop_set_simulate_again (phi, false);
4975 else
4976 prop_set_simulate_again (phi, true);
4979 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
4980 gsi_next (&si))
4982 gimple *stmt = gsi_stmt (si);
4984 /* If the statement is a control insn, then we do not
4985 want to avoid simulating the statement once. Failure
4986 to do so means that those edges will never get added. */
4987 if (stmt_ends_bb_p (stmt))
4988 prop_set_simulate_again (stmt, true);
4989 else if (!stmt_interesting_for_vrp (stmt))
4991 set_defs_to_varying (stmt);
4992 prop_set_simulate_again (stmt, false);
4994 else
4995 prop_set_simulate_again (stmt, true);
5000 /* Searches the case label vector VEC for the index *IDX of the CASE_LABEL
5001 that includes the value VAL. The search is restricted to the range
5002 [START_IDX, n - 1] where n is the size of VEC.
5004 If there is a CASE_LABEL for VAL, its index is placed in IDX and true is
5005 returned.
5007 If there is no CASE_LABEL for VAL and there is one that is larger than VAL,
5008 it is placed in IDX and false is returned.
5010 If VAL is larger than any CASE_LABEL, n is placed on IDX and false is
5011 returned. */
5013 bool
5014 find_case_label_index (gswitch *stmt, size_t start_idx, tree val, size_t *idx)
5016 size_t n = gimple_switch_num_labels (stmt);
5017 size_t low, high;
5019 /* Find case label for minimum of the value range or the next one.
5020 At each iteration we are searching in [low, high - 1]. */
5022 for (low = start_idx, high = n; high != low; )
5024 tree t;
5025 int cmp;
5026 /* Note that i != high, so we never ask for n. */
5027 size_t i = (high + low) / 2;
5028 t = gimple_switch_label (stmt, i);
5030 /* Cache the result of comparing CASE_LOW and val. */
5031 cmp = tree_int_cst_compare (CASE_LOW (t), val);
5033 if (cmp == 0)
5035 /* Ranges cannot be empty. */
5036 *idx = i;
5037 return true;
5039 else if (cmp > 0)
5040 high = i;
5041 else
5043 low = i + 1;
5044 if (CASE_HIGH (t) != NULL
5045 && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
5047 *idx = i;
5048 return true;
5053 *idx = high;
5054 return false;
5057 /* Searches the case label vector VEC for the range of CASE_LABELs that is used
5058 for values between MIN and MAX. The first index is placed in MIN_IDX. The
5059 last index is placed in MAX_IDX. If the range of CASE_LABELs is empty
5060 then MAX_IDX < MIN_IDX.
5061 Returns true if the default label is not needed. */
5063 bool
5064 find_case_label_range (gswitch *stmt, tree min, tree max, size_t *min_idx,
5065 size_t *max_idx)
5067 size_t i, j;
5068 bool min_take_default = !find_case_label_index (stmt, 1, min, &i);
5069 bool max_take_default = !find_case_label_index (stmt, i, max, &j);
5071 if (i == j
5072 && min_take_default
5073 && max_take_default)
5075 /* Only the default case label reached.
5076 Return an empty range. */
5077 *min_idx = 1;
5078 *max_idx = 0;
5079 return false;
5081 else
5083 bool take_default = min_take_default || max_take_default;
5084 tree low, high;
5085 size_t k;
5087 if (max_take_default)
5088 j--;
5090 /* If the case label range is continuous, we do not need
5091 the default case label. Verify that. */
5092 high = CASE_LOW (gimple_switch_label (stmt, i));
5093 if (CASE_HIGH (gimple_switch_label (stmt, i)))
5094 high = CASE_HIGH (gimple_switch_label (stmt, i));
5095 for (k = i + 1; k <= j; ++k)
5097 low = CASE_LOW (gimple_switch_label (stmt, k));
5098 if (!integer_onep (int_const_binop (MINUS_EXPR, low, high)))
5100 take_default = true;
5101 break;
5103 high = low;
5104 if (CASE_HIGH (gimple_switch_label (stmt, k)))
5105 high = CASE_HIGH (gimple_switch_label (stmt, k));
5108 *min_idx = i;
5109 *max_idx = j;
5110 return !take_default;
5114 /* Evaluate statement STMT. If the statement produces a useful range,
5115 return SSA_PROP_INTERESTING and record the SSA name with the
5116 interesting range into *OUTPUT_P.
5118 If STMT is a conditional branch and we can determine its truth
5119 value, the taken edge is recorded in *TAKEN_EDGE_P.
5121 If STMT produces a varying value, return SSA_PROP_VARYING. */
5123 enum ssa_prop_result
5124 vrp_prop::visit_stmt (gimple *stmt, edge *taken_edge_p, tree *output_p)
5126 value_range vr = VR_INITIALIZER;
5127 tree lhs = gimple_get_lhs (stmt);
5128 extract_range_from_stmt (stmt, taken_edge_p, output_p, &vr);
5130 if (*output_p)
5132 if (update_value_range (*output_p, &vr))
5134 if (dump_file && (dump_flags & TDF_DETAILS))
5136 fprintf (dump_file, "Found new range for ");
5137 print_generic_expr (dump_file, *output_p);
5138 fprintf (dump_file, ": ");
5139 dump_value_range (dump_file, &vr);
5140 fprintf (dump_file, "\n");
5143 if (vr.type == VR_VARYING)
5144 return SSA_PROP_VARYING;
5146 return SSA_PROP_INTERESTING;
5148 return SSA_PROP_NOT_INTERESTING;
5151 if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
5152 switch (gimple_call_internal_fn (stmt))
5154 case IFN_ADD_OVERFLOW:
5155 case IFN_SUB_OVERFLOW:
5156 case IFN_MUL_OVERFLOW:
5157 case IFN_ATOMIC_COMPARE_EXCHANGE:
5158 /* These internal calls return _Complex integer type,
5159 which VRP does not track, but the immediate uses
5160 thereof might be interesting. */
5161 if (lhs && TREE_CODE (lhs) == SSA_NAME)
5163 imm_use_iterator iter;
5164 use_operand_p use_p;
5165 enum ssa_prop_result res = SSA_PROP_VARYING;
5167 set_value_range_to_varying (get_value_range (lhs));
5169 FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
5171 gimple *use_stmt = USE_STMT (use_p);
5172 if (!is_gimple_assign (use_stmt))
5173 continue;
5174 enum tree_code rhs_code = gimple_assign_rhs_code (use_stmt);
5175 if (rhs_code != REALPART_EXPR && rhs_code != IMAGPART_EXPR)
5176 continue;
5177 tree rhs1 = gimple_assign_rhs1 (use_stmt);
5178 tree use_lhs = gimple_assign_lhs (use_stmt);
5179 if (TREE_CODE (rhs1) != rhs_code
5180 || TREE_OPERAND (rhs1, 0) != lhs
5181 || TREE_CODE (use_lhs) != SSA_NAME
5182 || !stmt_interesting_for_vrp (use_stmt)
5183 || (!INTEGRAL_TYPE_P (TREE_TYPE (use_lhs))
5184 || !TYPE_MIN_VALUE (TREE_TYPE (use_lhs))
5185 || !TYPE_MAX_VALUE (TREE_TYPE (use_lhs))))
5186 continue;
5188 /* If there is a change in the value range for any of the
5189 REALPART_EXPR/IMAGPART_EXPR immediate uses, return
5190 SSA_PROP_INTERESTING. If there are any REALPART_EXPR
5191 or IMAGPART_EXPR immediate uses, but none of them have
5192 a change in their value ranges, return
5193 SSA_PROP_NOT_INTERESTING. If there are no
5194 {REAL,IMAG}PART_EXPR uses at all,
5195 return SSA_PROP_VARYING. */
5196 value_range new_vr = VR_INITIALIZER;
5197 extract_range_basic (&new_vr, use_stmt);
5198 const value_range *old_vr = get_value_range (use_lhs);
5199 if (old_vr->type != new_vr.type
5200 || !vrp_operand_equal_p (old_vr->min, new_vr.min)
5201 || !vrp_operand_equal_p (old_vr->max, new_vr.max)
5202 || !vrp_bitmap_equal_p (old_vr->equiv, new_vr.equiv))
5203 res = SSA_PROP_INTERESTING;
5204 else
5205 res = SSA_PROP_NOT_INTERESTING;
5206 BITMAP_FREE (new_vr.equiv);
5207 if (res == SSA_PROP_INTERESTING)
5209 *output_p = lhs;
5210 return res;
5214 return res;
5216 break;
5217 default:
5218 break;
5221 /* All other statements produce nothing of interest for VRP, so mark
5222 their outputs varying and prevent further simulation. */
5223 set_defs_to_varying (stmt);
5225 return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
5228 /* Union the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
5229 { VR1TYPE, VR0MIN, VR0MAX } and store the result
5230 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
5231 possible such range. The resulting range is not canonicalized. */
5233 static void
5234 union_ranges (enum value_range_type *vr0type,
5235 tree *vr0min, tree *vr0max,
5236 enum value_range_type vr1type,
5237 tree vr1min, tree vr1max)
5239 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
5240 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
5242 /* [] is vr0, () is vr1 in the following classification comments. */
5243 if (mineq && maxeq)
5245 /* [( )] */
5246 if (*vr0type == vr1type)
5247 /* Nothing to do for equal ranges. */
5249 else if ((*vr0type == VR_RANGE
5250 && vr1type == VR_ANTI_RANGE)
5251 || (*vr0type == VR_ANTI_RANGE
5252 && vr1type == VR_RANGE))
5254 /* For anti-range with range union the result is varying. */
5255 goto give_up;
5257 else
5258 gcc_unreachable ();
5260 else if (operand_less_p (*vr0max, vr1min) == 1
5261 || operand_less_p (vr1max, *vr0min) == 1)
5263 /* [ ] ( ) or ( ) [ ]
5264 If the ranges have an empty intersection, result of the union
5265 operation is the anti-range or if both are anti-ranges
5266 it covers all. */
5267 if (*vr0type == VR_ANTI_RANGE
5268 && vr1type == VR_ANTI_RANGE)
5269 goto give_up;
5270 else if (*vr0type == VR_ANTI_RANGE
5271 && vr1type == VR_RANGE)
5273 else if (*vr0type == VR_RANGE
5274 && vr1type == VR_ANTI_RANGE)
5276 *vr0type = vr1type;
5277 *vr0min = vr1min;
5278 *vr0max = vr1max;
5280 else if (*vr0type == VR_RANGE
5281 && vr1type == VR_RANGE)
5283 /* The result is the convex hull of both ranges. */
5284 if (operand_less_p (*vr0max, vr1min) == 1)
5286 /* If the result can be an anti-range, create one. */
5287 if (TREE_CODE (*vr0max) == INTEGER_CST
5288 && TREE_CODE (vr1min) == INTEGER_CST
5289 && vrp_val_is_min (*vr0min)
5290 && vrp_val_is_max (vr1max))
5292 tree min = int_const_binop (PLUS_EXPR,
5293 *vr0max,
5294 build_int_cst (TREE_TYPE (*vr0max), 1));
5295 tree max = int_const_binop (MINUS_EXPR,
5296 vr1min,
5297 build_int_cst (TREE_TYPE (vr1min), 1));
5298 if (!operand_less_p (max, min))
5300 *vr0type = VR_ANTI_RANGE;
5301 *vr0min = min;
5302 *vr0max = max;
5304 else
5305 *vr0max = vr1max;
5307 else
5308 *vr0max = vr1max;
5310 else
5312 /* If the result can be an anti-range, create one. */
5313 if (TREE_CODE (vr1max) == INTEGER_CST
5314 && TREE_CODE (*vr0min) == INTEGER_CST
5315 && vrp_val_is_min (vr1min)
5316 && vrp_val_is_max (*vr0max))
5318 tree min = int_const_binop (PLUS_EXPR,
5319 vr1max,
5320 build_int_cst (TREE_TYPE (vr1max), 1));
5321 tree max = int_const_binop (MINUS_EXPR,
5322 *vr0min,
5323 build_int_cst (TREE_TYPE (*vr0min), 1));
5324 if (!operand_less_p (max, min))
5326 *vr0type = VR_ANTI_RANGE;
5327 *vr0min = min;
5328 *vr0max = max;
5330 else
5331 *vr0min = vr1min;
5333 else
5334 *vr0min = vr1min;
5337 else
5338 gcc_unreachable ();
5340 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
5341 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
5343 /* [ ( ) ] or [( ) ] or [ ( )] */
5344 if (*vr0type == VR_RANGE
5345 && vr1type == VR_RANGE)
5347 else if (*vr0type == VR_ANTI_RANGE
5348 && vr1type == VR_ANTI_RANGE)
5350 *vr0type = vr1type;
5351 *vr0min = vr1min;
5352 *vr0max = vr1max;
5354 else if (*vr0type == VR_ANTI_RANGE
5355 && vr1type == VR_RANGE)
5357 /* Arbitrarily choose the right or left gap. */
5358 if (!mineq && TREE_CODE (vr1min) == INTEGER_CST)
5359 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5360 build_int_cst (TREE_TYPE (vr1min), 1));
5361 else if (!maxeq && TREE_CODE (vr1max) == INTEGER_CST)
5362 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5363 build_int_cst (TREE_TYPE (vr1max), 1));
5364 else
5365 goto give_up;
5367 else if (*vr0type == VR_RANGE
5368 && vr1type == VR_ANTI_RANGE)
5369 /* The result covers everything. */
5370 goto give_up;
5371 else
5372 gcc_unreachable ();
5374 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
5375 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
5377 /* ( [ ] ) or ([ ] ) or ( [ ]) */
5378 if (*vr0type == VR_RANGE
5379 && vr1type == VR_RANGE)
5381 *vr0type = vr1type;
5382 *vr0min = vr1min;
5383 *vr0max = vr1max;
5385 else if (*vr0type == VR_ANTI_RANGE
5386 && vr1type == VR_ANTI_RANGE)
5388 else if (*vr0type == VR_RANGE
5389 && vr1type == VR_ANTI_RANGE)
5391 *vr0type = VR_ANTI_RANGE;
5392 if (!mineq && TREE_CODE (*vr0min) == INTEGER_CST)
5394 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5395 build_int_cst (TREE_TYPE (*vr0min), 1));
5396 *vr0min = vr1min;
5398 else if (!maxeq && TREE_CODE (*vr0max) == INTEGER_CST)
5400 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5401 build_int_cst (TREE_TYPE (*vr0max), 1));
5402 *vr0max = vr1max;
5404 else
5405 goto give_up;
5407 else if (*vr0type == VR_ANTI_RANGE
5408 && vr1type == VR_RANGE)
5409 /* The result covers everything. */
5410 goto give_up;
5411 else
5412 gcc_unreachable ();
5414 else if ((operand_less_p (vr1min, *vr0max) == 1
5415 || operand_equal_p (vr1min, *vr0max, 0))
5416 && operand_less_p (*vr0min, vr1min) == 1
5417 && operand_less_p (*vr0max, vr1max) == 1)
5419 /* [ ( ] ) or [ ]( ) */
5420 if (*vr0type == VR_RANGE
5421 && vr1type == VR_RANGE)
5422 *vr0max = vr1max;
5423 else if (*vr0type == VR_ANTI_RANGE
5424 && vr1type == VR_ANTI_RANGE)
5425 *vr0min = vr1min;
5426 else if (*vr0type == VR_ANTI_RANGE
5427 && vr1type == VR_RANGE)
5429 if (TREE_CODE (vr1min) == INTEGER_CST)
5430 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5431 build_int_cst (TREE_TYPE (vr1min), 1));
5432 else
5433 goto give_up;
5435 else if (*vr0type == VR_RANGE
5436 && vr1type == VR_ANTI_RANGE)
5438 if (TREE_CODE (*vr0max) == INTEGER_CST)
5440 *vr0type = vr1type;
5441 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5442 build_int_cst (TREE_TYPE (*vr0max), 1));
5443 *vr0max = vr1max;
5445 else
5446 goto give_up;
5448 else
5449 gcc_unreachable ();
5451 else if ((operand_less_p (*vr0min, vr1max) == 1
5452 || operand_equal_p (*vr0min, vr1max, 0))
5453 && operand_less_p (vr1min, *vr0min) == 1
5454 && operand_less_p (vr1max, *vr0max) == 1)
5456 /* ( [ ) ] or ( )[ ] */
5457 if (*vr0type == VR_RANGE
5458 && vr1type == VR_RANGE)
5459 *vr0min = vr1min;
5460 else if (*vr0type == VR_ANTI_RANGE
5461 && vr1type == VR_ANTI_RANGE)
5462 *vr0max = vr1max;
5463 else if (*vr0type == VR_ANTI_RANGE
5464 && vr1type == VR_RANGE)
5466 if (TREE_CODE (vr1max) == INTEGER_CST)
5467 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5468 build_int_cst (TREE_TYPE (vr1max), 1));
5469 else
5470 goto give_up;
5472 else if (*vr0type == VR_RANGE
5473 && vr1type == VR_ANTI_RANGE)
5475 if (TREE_CODE (*vr0min) == INTEGER_CST)
5477 *vr0type = vr1type;
5478 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5479 build_int_cst (TREE_TYPE (*vr0min), 1));
5480 *vr0min = vr1min;
5482 else
5483 goto give_up;
5485 else
5486 gcc_unreachable ();
5488 else
5489 goto give_up;
5491 return;
5493 give_up:
5494 *vr0type = VR_VARYING;
5495 *vr0min = NULL_TREE;
5496 *vr0max = NULL_TREE;
5499 /* Intersect the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
5500 { VR1TYPE, VR0MIN, VR0MAX } and store the result
5501 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
5502 possible such range. The resulting range is not canonicalized. */
5504 static void
5505 intersect_ranges (enum value_range_type *vr0type,
5506 tree *vr0min, tree *vr0max,
5507 enum value_range_type vr1type,
5508 tree vr1min, tree vr1max)
5510 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
5511 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
5513 /* [] is vr0, () is vr1 in the following classification comments. */
5514 if (mineq && maxeq)
5516 /* [( )] */
5517 if (*vr0type == vr1type)
5518 /* Nothing to do for equal ranges. */
5520 else if ((*vr0type == VR_RANGE
5521 && vr1type == VR_ANTI_RANGE)
5522 || (*vr0type == VR_ANTI_RANGE
5523 && vr1type == VR_RANGE))
5525 /* For anti-range with range intersection the result is empty. */
5526 *vr0type = VR_UNDEFINED;
5527 *vr0min = NULL_TREE;
5528 *vr0max = NULL_TREE;
5530 else
5531 gcc_unreachable ();
5533 else if (operand_less_p (*vr0max, vr1min) == 1
5534 || operand_less_p (vr1max, *vr0min) == 1)
5536 /* [ ] ( ) or ( ) [ ]
5537 If the ranges have an empty intersection, the result of the
5538 intersect operation is the range for intersecting an
5539 anti-range with a range or empty when intersecting two ranges. */
5540 if (*vr0type == VR_RANGE
5541 && vr1type == VR_ANTI_RANGE)
5543 else if (*vr0type == VR_ANTI_RANGE
5544 && vr1type == VR_RANGE)
5546 *vr0type = vr1type;
5547 *vr0min = vr1min;
5548 *vr0max = vr1max;
5550 else if (*vr0type == VR_RANGE
5551 && vr1type == VR_RANGE)
5553 *vr0type = VR_UNDEFINED;
5554 *vr0min = NULL_TREE;
5555 *vr0max = NULL_TREE;
5557 else if (*vr0type == VR_ANTI_RANGE
5558 && vr1type == VR_ANTI_RANGE)
5560 /* If the anti-ranges are adjacent to each other merge them. */
5561 if (TREE_CODE (*vr0max) == INTEGER_CST
5562 && TREE_CODE (vr1min) == INTEGER_CST
5563 && operand_less_p (*vr0max, vr1min) == 1
5564 && integer_onep (int_const_binop (MINUS_EXPR,
5565 vr1min, *vr0max)))
5566 *vr0max = vr1max;
5567 else if (TREE_CODE (vr1max) == INTEGER_CST
5568 && TREE_CODE (*vr0min) == INTEGER_CST
5569 && operand_less_p (vr1max, *vr0min) == 1
5570 && integer_onep (int_const_binop (MINUS_EXPR,
5571 *vr0min, vr1max)))
5572 *vr0min = vr1min;
5573 /* Else arbitrarily take VR0. */
5576 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
5577 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
5579 /* [ ( ) ] or [( ) ] or [ ( )] */
5580 if (*vr0type == VR_RANGE
5581 && vr1type == VR_RANGE)
5583 /* If both are ranges the result is the inner one. */
5584 *vr0type = vr1type;
5585 *vr0min = vr1min;
5586 *vr0max = vr1max;
5588 else if (*vr0type == VR_RANGE
5589 && vr1type == VR_ANTI_RANGE)
5591 /* Choose the right gap if the left one is empty. */
5592 if (mineq)
5594 if (TREE_CODE (vr1max) != INTEGER_CST)
5595 *vr0min = vr1max;
5596 else if (TYPE_PRECISION (TREE_TYPE (vr1max)) == 1
5597 && !TYPE_UNSIGNED (TREE_TYPE (vr1max)))
5598 *vr0min
5599 = int_const_binop (MINUS_EXPR, vr1max,
5600 build_int_cst (TREE_TYPE (vr1max), -1));
5601 else
5602 *vr0min
5603 = int_const_binop (PLUS_EXPR, vr1max,
5604 build_int_cst (TREE_TYPE (vr1max), 1));
5606 /* Choose the left gap if the right one is empty. */
5607 else if (maxeq)
5609 if (TREE_CODE (vr1min) != INTEGER_CST)
5610 *vr0max = vr1min;
5611 else if (TYPE_PRECISION (TREE_TYPE (vr1min)) == 1
5612 && !TYPE_UNSIGNED (TREE_TYPE (vr1min)))
5613 *vr0max
5614 = int_const_binop (PLUS_EXPR, vr1min,
5615 build_int_cst (TREE_TYPE (vr1min), -1));
5616 else
5617 *vr0max
5618 = int_const_binop (MINUS_EXPR, vr1min,
5619 build_int_cst (TREE_TYPE (vr1min), 1));
5621 /* Choose the anti-range if the range is effectively varying. */
5622 else if (vrp_val_is_min (*vr0min)
5623 && vrp_val_is_max (*vr0max))
5625 *vr0type = vr1type;
5626 *vr0min = vr1min;
5627 *vr0max = vr1max;
5629 /* Else choose the range. */
5631 else if (*vr0type == VR_ANTI_RANGE
5632 && vr1type == VR_ANTI_RANGE)
5633 /* If both are anti-ranges the result is the outer one. */
5635 else if (*vr0type == VR_ANTI_RANGE
5636 && vr1type == VR_RANGE)
5638 /* The intersection is empty. */
5639 *vr0type = VR_UNDEFINED;
5640 *vr0min = NULL_TREE;
5641 *vr0max = NULL_TREE;
5643 else
5644 gcc_unreachable ();
5646 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
5647 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
5649 /* ( [ ] ) or ([ ] ) or ( [ ]) */
5650 if (*vr0type == VR_RANGE
5651 && vr1type == VR_RANGE)
5652 /* Choose the inner range. */
5654 else if (*vr0type == VR_ANTI_RANGE
5655 && vr1type == VR_RANGE)
5657 /* Choose the right gap if the left is empty. */
5658 if (mineq)
5660 *vr0type = VR_RANGE;
5661 if (TREE_CODE (*vr0max) != INTEGER_CST)
5662 *vr0min = *vr0max;
5663 else if (TYPE_PRECISION (TREE_TYPE (*vr0max)) == 1
5664 && !TYPE_UNSIGNED (TREE_TYPE (*vr0max)))
5665 *vr0min
5666 = int_const_binop (MINUS_EXPR, *vr0max,
5667 build_int_cst (TREE_TYPE (*vr0max), -1));
5668 else
5669 *vr0min
5670 = int_const_binop (PLUS_EXPR, *vr0max,
5671 build_int_cst (TREE_TYPE (*vr0max), 1));
5672 *vr0max = vr1max;
5674 /* Choose the left gap if the right is empty. */
5675 else if (maxeq)
5677 *vr0type = VR_RANGE;
5678 if (TREE_CODE (*vr0min) != INTEGER_CST)
5679 *vr0max = *vr0min;
5680 else if (TYPE_PRECISION (TREE_TYPE (*vr0min)) == 1
5681 && !TYPE_UNSIGNED (TREE_TYPE (*vr0min)))
5682 *vr0max
5683 = int_const_binop (PLUS_EXPR, *vr0min,
5684 build_int_cst (TREE_TYPE (*vr0min), -1));
5685 else
5686 *vr0max
5687 = int_const_binop (MINUS_EXPR, *vr0min,
5688 build_int_cst (TREE_TYPE (*vr0min), 1));
5689 *vr0min = vr1min;
5691 /* Choose the anti-range if the range is effectively varying. */
5692 else if (vrp_val_is_min (vr1min)
5693 && vrp_val_is_max (vr1max))
5695 /* Choose the anti-range if it is ~[0,0], that range is special
5696 enough to special case when vr1's range is relatively wide.
5697 At least for types bigger than int - this covers pointers
5698 and arguments to functions like ctz. */
5699 else if (*vr0min == *vr0max
5700 && integer_zerop (*vr0min)
5701 && ((TYPE_PRECISION (TREE_TYPE (*vr0min))
5702 >= TYPE_PRECISION (integer_type_node))
5703 || POINTER_TYPE_P (TREE_TYPE (*vr0min)))
5704 && TREE_CODE (vr1max) == INTEGER_CST
5705 && TREE_CODE (vr1min) == INTEGER_CST
5706 && (wi::clz (wi::to_wide (vr1max) - wi::to_wide (vr1min))
5707 < TYPE_PRECISION (TREE_TYPE (*vr0min)) / 2))
5709 /* Else choose the range. */
5710 else
5712 *vr0type = vr1type;
5713 *vr0min = vr1min;
5714 *vr0max = vr1max;
5717 else if (*vr0type == VR_ANTI_RANGE
5718 && vr1type == VR_ANTI_RANGE)
5720 /* If both are anti-ranges the result is the outer one. */
5721 *vr0type = vr1type;
5722 *vr0min = vr1min;
5723 *vr0max = vr1max;
5725 else if (vr1type == VR_ANTI_RANGE
5726 && *vr0type == VR_RANGE)
5728 /* The intersection is empty. */
5729 *vr0type = VR_UNDEFINED;
5730 *vr0min = NULL_TREE;
5731 *vr0max = NULL_TREE;
5733 else
5734 gcc_unreachable ();
5736 else if ((operand_less_p (vr1min, *vr0max) == 1
5737 || operand_equal_p (vr1min, *vr0max, 0))
5738 && operand_less_p (*vr0min, vr1min) == 1)
5740 /* [ ( ] ) or [ ]( ) */
5741 if (*vr0type == VR_ANTI_RANGE
5742 && vr1type == VR_ANTI_RANGE)
5743 *vr0max = vr1max;
5744 else if (*vr0type == VR_RANGE
5745 && vr1type == VR_RANGE)
5746 *vr0min = vr1min;
5747 else if (*vr0type == VR_RANGE
5748 && vr1type == VR_ANTI_RANGE)
5750 if (TREE_CODE (vr1min) == INTEGER_CST)
5751 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5752 build_int_cst (TREE_TYPE (vr1min), 1));
5753 else
5754 *vr0max = vr1min;
5756 else if (*vr0type == VR_ANTI_RANGE
5757 && vr1type == VR_RANGE)
5759 *vr0type = VR_RANGE;
5760 if (TREE_CODE (*vr0max) == INTEGER_CST)
5761 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5762 build_int_cst (TREE_TYPE (*vr0max), 1));
5763 else
5764 *vr0min = *vr0max;
5765 *vr0max = vr1max;
5767 else
5768 gcc_unreachable ();
5770 else if ((operand_less_p (*vr0min, vr1max) == 1
5771 || operand_equal_p (*vr0min, vr1max, 0))
5772 && operand_less_p (vr1min, *vr0min) == 1)
5774 /* ( [ ) ] or ( )[ ] */
5775 if (*vr0type == VR_ANTI_RANGE
5776 && vr1type == VR_ANTI_RANGE)
5777 *vr0min = vr1min;
5778 else if (*vr0type == VR_RANGE
5779 && vr1type == VR_RANGE)
5780 *vr0max = vr1max;
5781 else if (*vr0type == VR_RANGE
5782 && vr1type == VR_ANTI_RANGE)
5784 if (TREE_CODE (vr1max) == INTEGER_CST)
5785 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5786 build_int_cst (TREE_TYPE (vr1max), 1));
5787 else
5788 *vr0min = vr1max;
5790 else if (*vr0type == VR_ANTI_RANGE
5791 && vr1type == VR_RANGE)
5793 *vr0type = VR_RANGE;
5794 if (TREE_CODE (*vr0min) == INTEGER_CST)
5795 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5796 build_int_cst (TREE_TYPE (*vr0min), 1));
5797 else
5798 *vr0max = *vr0min;
5799 *vr0min = vr1min;
5801 else
5802 gcc_unreachable ();
5805 /* As a fallback simply use { *VRTYPE, *VR0MIN, *VR0MAX } as
5806 result for the intersection. That's always a conservative
5807 correct estimate unless VR1 is a constant singleton range
5808 in which case we choose that. */
5809 if (vr1type == VR_RANGE
5810 && is_gimple_min_invariant (vr1min)
5811 && vrp_operand_equal_p (vr1min, vr1max))
5813 *vr0type = vr1type;
5814 *vr0min = vr1min;
5815 *vr0max = vr1max;
5818 return;
5822 /* Intersect the two value-ranges *VR0 and *VR1 and store the result
5823 in *VR0. This may not be the smallest possible such range. */
5825 static void
5826 vrp_intersect_ranges_1 (value_range *vr0, const value_range *vr1)
5828 value_range saved;
5830 /* If either range is VR_VARYING the other one wins. */
5831 if (vr1->type == VR_VARYING)
5832 return;
5833 if (vr0->type == VR_VARYING)
5835 copy_value_range (vr0, vr1);
5836 return;
5839 /* When either range is VR_UNDEFINED the resulting range is
5840 VR_UNDEFINED, too. */
5841 if (vr0->type == VR_UNDEFINED)
5842 return;
5843 if (vr1->type == VR_UNDEFINED)
5845 set_value_range_to_undefined (vr0);
5846 return;
5849 /* Save the original vr0 so we can return it as conservative intersection
5850 result when our worker turns things to varying. */
5851 saved = *vr0;
5852 intersect_ranges (&vr0->type, &vr0->min, &vr0->max,
5853 vr1->type, vr1->min, vr1->max);
5854 /* Make sure to canonicalize the result though as the inversion of a
5855 VR_RANGE can still be a VR_RANGE. */
5856 set_and_canonicalize_value_range (vr0, vr0->type,
5857 vr0->min, vr0->max, vr0->equiv);
5858 /* If that failed, use the saved original VR0. */
5859 if (vr0->type == VR_VARYING)
5861 *vr0 = saved;
5862 return;
5864 /* If the result is VR_UNDEFINED there is no need to mess with
5865 the equivalencies. */
5866 if (vr0->type == VR_UNDEFINED)
5867 return;
5869 /* The resulting set of equivalences for range intersection is the union of
5870 the two sets. */
5871 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
5872 bitmap_ior_into (vr0->equiv, vr1->equiv);
5873 else if (vr1->equiv && !vr0->equiv)
5875 /* All equivalence bitmaps are allocated from the same obstack. So
5876 we can use the obstack associated with VR to allocate vr0->equiv. */
5877 vr0->equiv = BITMAP_ALLOC (vr1->equiv->obstack);
5878 bitmap_copy (vr0->equiv, vr1->equiv);
5882 void
5883 vrp_intersect_ranges (value_range *vr0, const value_range *vr1)
5885 if (dump_file && (dump_flags & TDF_DETAILS))
5887 fprintf (dump_file, "Intersecting\n ");
5888 dump_value_range (dump_file, vr0);
5889 fprintf (dump_file, "\nand\n ");
5890 dump_value_range (dump_file, vr1);
5891 fprintf (dump_file, "\n");
5893 vrp_intersect_ranges_1 (vr0, vr1);
5894 if (dump_file && (dump_flags & TDF_DETAILS))
5896 fprintf (dump_file, "to\n ");
5897 dump_value_range (dump_file, vr0);
5898 fprintf (dump_file, "\n");
5902 /* Meet operation for value ranges. Given two value ranges VR0 and
5903 VR1, store in VR0 a range that contains both VR0 and VR1. This
5904 may not be the smallest possible such range. */
5906 static void
5907 vrp_meet_1 (value_range *vr0, const value_range *vr1)
5909 value_range saved;
5911 if (vr0->type == VR_UNDEFINED)
5913 set_value_range (vr0, vr1->type, vr1->min, vr1->max, vr1->equiv);
5914 return;
5917 if (vr1->type == VR_UNDEFINED)
5919 /* VR0 already has the resulting range. */
5920 return;
5923 if (vr0->type == VR_VARYING)
5925 /* Nothing to do. VR0 already has the resulting range. */
5926 return;
5929 if (vr1->type == VR_VARYING)
5931 set_value_range_to_varying (vr0);
5932 return;
5935 saved = *vr0;
5936 union_ranges (&vr0->type, &vr0->min, &vr0->max,
5937 vr1->type, vr1->min, vr1->max);
5938 if (vr0->type == VR_VARYING)
5940 /* Failed to find an efficient meet. Before giving up and setting
5941 the result to VARYING, see if we can at least derive a useful
5942 anti-range. */
5943 if (range_includes_zero_p (&saved) == 0
5944 && range_includes_zero_p (vr1) == 0)
5946 set_value_range_to_nonnull (vr0, TREE_TYPE (saved.min));
5948 /* Since this meet operation did not result from the meeting of
5949 two equivalent names, VR0 cannot have any equivalences. */
5950 if (vr0->equiv)
5951 bitmap_clear (vr0->equiv);
5952 return;
5955 set_value_range_to_varying (vr0);
5956 return;
5958 set_and_canonicalize_value_range (vr0, vr0->type, vr0->min, vr0->max,
5959 vr0->equiv);
5960 if (vr0->type == VR_VARYING)
5961 return;
5963 /* The resulting set of equivalences is always the intersection of
5964 the two sets. */
5965 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
5966 bitmap_and_into (vr0->equiv, vr1->equiv);
5967 else if (vr0->equiv && !vr1->equiv)
5968 bitmap_clear (vr0->equiv);
5971 void
5972 vrp_meet (value_range *vr0, const value_range *vr1)
5974 if (dump_file && (dump_flags & TDF_DETAILS))
5976 fprintf (dump_file, "Meeting\n ");
5977 dump_value_range (dump_file, vr0);
5978 fprintf (dump_file, "\nand\n ");
5979 dump_value_range (dump_file, vr1);
5980 fprintf (dump_file, "\n");
5982 vrp_meet_1 (vr0, vr1);
5983 if (dump_file && (dump_flags & TDF_DETAILS))
5985 fprintf (dump_file, "to\n ");
5986 dump_value_range (dump_file, vr0);
5987 fprintf (dump_file, "\n");
5992 /* Visit all arguments for PHI node PHI that flow through executable
5993 edges. If a valid value range can be derived from all the incoming
5994 value ranges, set a new range for the LHS of PHI. */
5996 enum ssa_prop_result
5997 vrp_prop::visit_phi (gphi *phi)
5999 tree lhs = PHI_RESULT (phi);
6000 value_range vr_result = VR_INITIALIZER;
6001 extract_range_from_phi_node (phi, &vr_result);
6002 if (update_value_range (lhs, &vr_result))
6004 if (dump_file && (dump_flags & TDF_DETAILS))
6006 fprintf (dump_file, "Found new range for ");
6007 print_generic_expr (dump_file, lhs);
6008 fprintf (dump_file, ": ");
6009 dump_value_range (dump_file, &vr_result);
6010 fprintf (dump_file, "\n");
6013 if (vr_result.type == VR_VARYING)
6014 return SSA_PROP_VARYING;
6016 return SSA_PROP_INTERESTING;
6019 /* Nothing changed, don't add outgoing edges. */
6020 return SSA_PROP_NOT_INTERESTING;
6023 class vrp_folder : public substitute_and_fold_engine
6025 public:
6026 tree get_value (tree) FINAL OVERRIDE;
6027 bool fold_stmt (gimple_stmt_iterator *) FINAL OVERRIDE;
6028 bool fold_predicate_in (gimple_stmt_iterator *);
6030 class vr_values *vr_values;
6032 /* Delegators. */
6033 tree vrp_evaluate_conditional (tree_code code, tree op0,
6034 tree op1, gimple *stmt)
6035 { return vr_values->vrp_evaluate_conditional (code, op0, op1, stmt); }
6036 bool simplify_stmt_using_ranges (gimple_stmt_iterator *gsi)
6037 { return vr_values->simplify_stmt_using_ranges (gsi); }
6038 tree op_with_constant_singleton_value_range (tree op)
6039 { return vr_values->op_with_constant_singleton_value_range (op); }
6042 /* If the statement pointed by SI has a predicate whose value can be
6043 computed using the value range information computed by VRP, compute
6044 its value and return true. Otherwise, return false. */
6046 bool
6047 vrp_folder::fold_predicate_in (gimple_stmt_iterator *si)
6049 bool assignment_p = false;
6050 tree val;
6051 gimple *stmt = gsi_stmt (*si);
6053 if (is_gimple_assign (stmt)
6054 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
6056 assignment_p = true;
6057 val = vrp_evaluate_conditional (gimple_assign_rhs_code (stmt),
6058 gimple_assign_rhs1 (stmt),
6059 gimple_assign_rhs2 (stmt),
6060 stmt);
6062 else if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
6063 val = vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
6064 gimple_cond_lhs (cond_stmt),
6065 gimple_cond_rhs (cond_stmt),
6066 stmt);
6067 else
6068 return false;
6070 if (val)
6072 if (assignment_p)
6073 val = fold_convert (gimple_expr_type (stmt), val);
6075 if (dump_file)
6077 fprintf (dump_file, "Folding predicate ");
6078 print_gimple_expr (dump_file, stmt, 0);
6079 fprintf (dump_file, " to ");
6080 print_generic_expr (dump_file, val);
6081 fprintf (dump_file, "\n");
6084 if (is_gimple_assign (stmt))
6085 gimple_assign_set_rhs_from_tree (si, val);
6086 else
6088 gcc_assert (gimple_code (stmt) == GIMPLE_COND);
6089 gcond *cond_stmt = as_a <gcond *> (stmt);
6090 if (integer_zerop (val))
6091 gimple_cond_make_false (cond_stmt);
6092 else if (integer_onep (val))
6093 gimple_cond_make_true (cond_stmt);
6094 else
6095 gcc_unreachable ();
6098 return true;
6101 return false;
6104 /* Callback for substitute_and_fold folding the stmt at *SI. */
6106 bool
6107 vrp_folder::fold_stmt (gimple_stmt_iterator *si)
6109 if (fold_predicate_in (si))
6110 return true;
6112 return simplify_stmt_using_ranges (si);
6115 /* If OP has a value range with a single constant value return that,
6116 otherwise return NULL_TREE. This returns OP itself if OP is a
6117 constant.
6119 Implemented as a pure wrapper right now, but this will change. */
6121 tree
6122 vrp_folder::get_value (tree op)
6124 return op_with_constant_singleton_value_range (op);
6127 /* Return the LHS of any ASSERT_EXPR where OP appears as the first
6128 argument to the ASSERT_EXPR and in which the ASSERT_EXPR dominates
6129 BB. If no such ASSERT_EXPR is found, return OP. */
6131 static tree
6132 lhs_of_dominating_assert (tree op, basic_block bb, gimple *stmt)
6134 imm_use_iterator imm_iter;
6135 gimple *use_stmt;
6136 use_operand_p use_p;
6138 if (TREE_CODE (op) == SSA_NAME)
6140 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, op)
6142 use_stmt = USE_STMT (use_p);
6143 if (use_stmt != stmt
6144 && gimple_assign_single_p (use_stmt)
6145 && TREE_CODE (gimple_assign_rhs1 (use_stmt)) == ASSERT_EXPR
6146 && TREE_OPERAND (gimple_assign_rhs1 (use_stmt), 0) == op
6147 && dominated_by_p (CDI_DOMINATORS, bb, gimple_bb (use_stmt)))
6148 return gimple_assign_lhs (use_stmt);
6151 return op;
6154 /* A hack. */
6155 static class vr_values *x_vr_values;
6157 /* A trivial wrapper so that we can present the generic jump threading
6158 code with a simple API for simplifying statements. STMT is the
6159 statement we want to simplify, WITHIN_STMT provides the location
6160 for any overflow warnings. */
6162 static tree
6163 simplify_stmt_for_jump_threading (gimple *stmt, gimple *within_stmt,
6164 class avail_exprs_stack *avail_exprs_stack ATTRIBUTE_UNUSED,
6165 basic_block bb)
6167 /* First see if the conditional is in the hash table. */
6168 tree cached_lhs = avail_exprs_stack->lookup_avail_expr (stmt, false, true);
6169 if (cached_lhs && is_gimple_min_invariant (cached_lhs))
6170 return cached_lhs;
6172 vr_values *vr_values = x_vr_values;
6173 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
6175 tree op0 = gimple_cond_lhs (cond_stmt);
6176 op0 = lhs_of_dominating_assert (op0, bb, stmt);
6178 tree op1 = gimple_cond_rhs (cond_stmt);
6179 op1 = lhs_of_dominating_assert (op1, bb, stmt);
6181 return vr_values->vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
6182 op0, op1, within_stmt);
6185 /* We simplify a switch statement by trying to determine which case label
6186 will be taken. If we are successful then we return the corresponding
6187 CASE_LABEL_EXPR. */
6188 if (gswitch *switch_stmt = dyn_cast <gswitch *> (stmt))
6190 tree op = gimple_switch_index (switch_stmt);
6191 if (TREE_CODE (op) != SSA_NAME)
6192 return NULL_TREE;
6194 op = lhs_of_dominating_assert (op, bb, stmt);
6196 const value_range *vr = vr_values->get_value_range (op);
6197 if ((vr->type != VR_RANGE && vr->type != VR_ANTI_RANGE)
6198 || symbolic_range_p (vr))
6199 return NULL_TREE;
6201 if (vr->type == VR_RANGE)
6203 size_t i, j;
6204 /* Get the range of labels that contain a part of the operand's
6205 value range. */
6206 find_case_label_range (switch_stmt, vr->min, vr->max, &i, &j);
6208 /* Is there only one such label? */
6209 if (i == j)
6211 tree label = gimple_switch_label (switch_stmt, i);
6213 /* The i'th label will be taken only if the value range of the
6214 operand is entirely within the bounds of this label. */
6215 if (CASE_HIGH (label) != NULL_TREE
6216 ? (tree_int_cst_compare (CASE_LOW (label), vr->min) <= 0
6217 && tree_int_cst_compare (CASE_HIGH (label), vr->max) >= 0)
6218 : (tree_int_cst_equal (CASE_LOW (label), vr->min)
6219 && tree_int_cst_equal (vr->min, vr->max)))
6220 return label;
6223 /* If there are no such labels then the default label will be
6224 taken. */
6225 if (i > j)
6226 return gimple_switch_label (switch_stmt, 0);
6229 if (vr->type == VR_ANTI_RANGE)
6231 unsigned n = gimple_switch_num_labels (switch_stmt);
6232 tree min_label = gimple_switch_label (switch_stmt, 1);
6233 tree max_label = gimple_switch_label (switch_stmt, n - 1);
6235 /* The default label will be taken only if the anti-range of the
6236 operand is entirely outside the bounds of all the (non-default)
6237 case labels. */
6238 if (tree_int_cst_compare (vr->min, CASE_LOW (min_label)) <= 0
6239 && (CASE_HIGH (max_label) != NULL_TREE
6240 ? tree_int_cst_compare (vr->max, CASE_HIGH (max_label)) >= 0
6241 : tree_int_cst_compare (vr->max, CASE_LOW (max_label)) >= 0))
6242 return gimple_switch_label (switch_stmt, 0);
6245 return NULL_TREE;
6248 if (gassign *assign_stmt = dyn_cast <gassign *> (stmt))
6250 tree lhs = gimple_assign_lhs (assign_stmt);
6251 if (TREE_CODE (lhs) == SSA_NAME
6252 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
6253 || POINTER_TYPE_P (TREE_TYPE (lhs)))
6254 && stmt_interesting_for_vrp (stmt))
6256 edge dummy_e;
6257 tree dummy_tree;
6258 value_range new_vr = VR_INITIALIZER;
6259 vr_values->extract_range_from_stmt (stmt, &dummy_e,
6260 &dummy_tree, &new_vr);
6261 if (range_int_cst_singleton_p (&new_vr))
6262 return new_vr.min;
6266 return NULL_TREE;
6269 class vrp_dom_walker : public dom_walker
6271 public:
6272 vrp_dom_walker (cdi_direction direction,
6273 class const_and_copies *const_and_copies,
6274 class avail_exprs_stack *avail_exprs_stack)
6275 : dom_walker (direction, REACHABLE_BLOCKS),
6276 m_const_and_copies (const_and_copies),
6277 m_avail_exprs_stack (avail_exprs_stack),
6278 m_dummy_cond (NULL) {}
6280 virtual edge before_dom_children (basic_block);
6281 virtual void after_dom_children (basic_block);
6283 class vr_values *vr_values;
6285 private:
6286 class const_and_copies *m_const_and_copies;
6287 class avail_exprs_stack *m_avail_exprs_stack;
6289 gcond *m_dummy_cond;
6293 /* Called before processing dominator children of BB. We want to look
6294 at ASSERT_EXPRs and record information from them in the appropriate
6295 tables.
6297 We could look at other statements here. It's not seen as likely
6298 to significantly increase the jump threads we discover. */
6300 edge
6301 vrp_dom_walker::before_dom_children (basic_block bb)
6303 gimple_stmt_iterator gsi;
6305 m_avail_exprs_stack->push_marker ();
6306 m_const_and_copies->push_marker ();
6307 for (gsi = gsi_start_nondebug_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
6309 gimple *stmt = gsi_stmt (gsi);
6310 if (gimple_assign_single_p (stmt)
6311 && TREE_CODE (gimple_assign_rhs1 (stmt)) == ASSERT_EXPR)
6313 tree rhs1 = gimple_assign_rhs1 (stmt);
6314 tree cond = TREE_OPERAND (rhs1, 1);
6315 tree inverted = invert_truthvalue (cond);
6316 vec<cond_equivalence> p;
6317 p.create (3);
6318 record_conditions (&p, cond, inverted);
6319 for (unsigned int i = 0; i < p.length (); i++)
6320 m_avail_exprs_stack->record_cond (&p[i]);
6322 tree lhs = gimple_assign_lhs (stmt);
6323 m_const_and_copies->record_const_or_copy (lhs,
6324 TREE_OPERAND (rhs1, 0));
6325 p.release ();
6326 continue;
6328 break;
6330 return NULL;
6333 /* Called after processing dominator children of BB. This is where we
6334 actually call into the threader. */
6335 void
6336 vrp_dom_walker::after_dom_children (basic_block bb)
6338 if (!m_dummy_cond)
6339 m_dummy_cond = gimple_build_cond (NE_EXPR,
6340 integer_zero_node, integer_zero_node,
6341 NULL, NULL);
6343 x_vr_values = vr_values;
6344 thread_outgoing_edges (bb, m_dummy_cond, m_const_and_copies,
6345 m_avail_exprs_stack, NULL,
6346 simplify_stmt_for_jump_threading);
6347 x_vr_values = NULL;
6349 m_avail_exprs_stack->pop_to_marker ();
6350 m_const_and_copies->pop_to_marker ();
6353 /* Blocks which have more than one predecessor and more than
6354 one successor present jump threading opportunities, i.e.,
6355 when the block is reached from a specific predecessor, we
6356 may be able to determine which of the outgoing edges will
6357 be traversed. When this optimization applies, we are able
6358 to avoid conditionals at runtime and we may expose secondary
6359 optimization opportunities.
6361 This routine is effectively a driver for the generic jump
6362 threading code. It basically just presents the generic code
6363 with edges that may be suitable for jump threading.
6365 Unlike DOM, we do not iterate VRP if jump threading was successful.
6366 While iterating may expose new opportunities for VRP, it is expected
6367 those opportunities would be very limited and the compile time cost
6368 to expose those opportunities would be significant.
6370 As jump threading opportunities are discovered, they are registered
6371 for later realization. */
6373 static void
6374 identify_jump_threads (class vr_values *vr_values)
6376 /* Ugh. When substituting values earlier in this pass we can
6377 wipe the dominance information. So rebuild the dominator
6378 information as we need it within the jump threading code. */
6379 calculate_dominance_info (CDI_DOMINATORS);
6381 /* We do not allow VRP information to be used for jump threading
6382 across a back edge in the CFG. Otherwise it becomes too
6383 difficult to avoid eliminating loop exit tests. Of course
6384 EDGE_DFS_BACK is not accurate at this time so we have to
6385 recompute it. */
6386 mark_dfs_back_edges ();
6388 /* Allocate our unwinder stack to unwind any temporary equivalences
6389 that might be recorded. */
6390 const_and_copies *equiv_stack = new const_and_copies ();
6392 hash_table<expr_elt_hasher> *avail_exprs
6393 = new hash_table<expr_elt_hasher> (1024);
6394 avail_exprs_stack *avail_exprs_stack
6395 = new class avail_exprs_stack (avail_exprs);
6397 vrp_dom_walker walker (CDI_DOMINATORS, equiv_stack, avail_exprs_stack);
6398 walker.vr_values = vr_values;
6399 walker.walk (cfun->cfg->x_entry_block_ptr);
6401 /* We do not actually update the CFG or SSA graphs at this point as
6402 ASSERT_EXPRs are still in the IL and cfg cleanup code does not yet
6403 handle ASSERT_EXPRs gracefully. */
6404 delete equiv_stack;
6405 delete avail_exprs;
6406 delete avail_exprs_stack;
6409 /* Traverse all the blocks folding conditionals with known ranges. */
6411 void
6412 vrp_prop::vrp_finalize (bool warn_array_bounds_p)
6414 size_t i;
6416 /* We have completed propagating through the lattice. */
6417 vr_values.set_lattice_propagation_complete ();
6419 if (dump_file)
6421 fprintf (dump_file, "\nValue ranges after VRP:\n\n");
6422 vr_values.dump_all_value_ranges (dump_file);
6423 fprintf (dump_file, "\n");
6426 /* Set value range to non pointer SSA_NAMEs. */
6427 for (i = 0; i < num_ssa_names; i++)
6429 tree name = ssa_name (i);
6430 if (!name)
6431 continue;
6433 const value_range *vr = get_value_range (name);
6434 if (!name
6435 || (vr->type == VR_VARYING)
6436 || (vr->type == VR_UNDEFINED)
6437 || (TREE_CODE (vr->min) != INTEGER_CST)
6438 || (TREE_CODE (vr->max) != INTEGER_CST))
6439 continue;
6441 if (POINTER_TYPE_P (TREE_TYPE (name))
6442 && range_includes_zero_p (vr) == 0)
6443 set_ptr_nonnull (name);
6444 else if (!POINTER_TYPE_P (TREE_TYPE (name)))
6445 set_range_info (name, vr->type,
6446 wi::to_wide (vr->min),
6447 wi::to_wide (vr->max));
6450 /* If we're checking array refs, we want to merge information on
6451 the executability of each edge between vrp_folder and the
6452 check_array_bounds_dom_walker: each can clear the
6453 EDGE_EXECUTABLE flag on edges, in different ways.
6455 Hence, if we're going to call check_all_array_refs, set
6456 the flag on every edge now, rather than in
6457 check_array_bounds_dom_walker's ctor; vrp_folder may clear
6458 it from some edges. */
6459 if (warn_array_bounds && warn_array_bounds_p)
6460 set_all_edges_as_executable (cfun);
6462 class vrp_folder vrp_folder;
6463 vrp_folder.vr_values = &vr_values;
6464 vrp_folder.substitute_and_fold ();
6466 if (warn_array_bounds && warn_array_bounds_p)
6467 check_all_array_refs ();
6470 /* Main entry point to VRP (Value Range Propagation). This pass is
6471 loosely based on J. R. C. Patterson, ``Accurate Static Branch
6472 Prediction by Value Range Propagation,'' in SIGPLAN Conference on
6473 Programming Language Design and Implementation, pp. 67-78, 1995.
6474 Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
6476 This is essentially an SSA-CCP pass modified to deal with ranges
6477 instead of constants.
6479 While propagating ranges, we may find that two or more SSA name
6480 have equivalent, though distinct ranges. For instance,
6482 1 x_9 = p_3->a;
6483 2 p_4 = ASSERT_EXPR <p_3, p_3 != 0>
6484 3 if (p_4 == q_2)
6485 4 p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
6486 5 endif
6487 6 if (q_2)
6489 In the code above, pointer p_5 has range [q_2, q_2], but from the
6490 code we can also determine that p_5 cannot be NULL and, if q_2 had
6491 a non-varying range, p_5's range should also be compatible with it.
6493 These equivalences are created by two expressions: ASSERT_EXPR and
6494 copy operations. Since p_5 is an assertion on p_4, and p_4 was the
6495 result of another assertion, then we can use the fact that p_5 and
6496 p_4 are equivalent when evaluating p_5's range.
6498 Together with value ranges, we also propagate these equivalences
6499 between names so that we can take advantage of information from
6500 multiple ranges when doing final replacement. Note that this
6501 equivalency relation is transitive but not symmetric.
6503 In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
6504 cannot assert that q_2 is equivalent to p_5 because q_2 may be used
6505 in contexts where that assertion does not hold (e.g., in line 6).
6507 TODO, the main difference between this pass and Patterson's is that
6508 we do not propagate edge probabilities. We only compute whether
6509 edges can be taken or not. That is, instead of having a spectrum
6510 of jump probabilities between 0 and 1, we only deal with 0, 1 and
6511 DON'T KNOW. In the future, it may be worthwhile to propagate
6512 probabilities to aid branch prediction. */
6514 static unsigned int
6515 execute_vrp (bool warn_array_bounds_p)
6518 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
6519 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
6520 scev_initialize ();
6522 /* ??? This ends up using stale EDGE_DFS_BACK for liveness computation.
6523 Inserting assertions may split edges which will invalidate
6524 EDGE_DFS_BACK. */
6525 insert_range_assertions ();
6527 threadedge_initialize_values ();
6529 /* For visiting PHI nodes we need EDGE_DFS_BACK computed. */
6530 mark_dfs_back_edges ();
6532 class vrp_prop vrp_prop;
6533 vrp_prop.vrp_initialize ();
6534 vrp_prop.ssa_propagate ();
6535 vrp_prop.vrp_finalize (warn_array_bounds_p);
6537 /* We must identify jump threading opportunities before we release
6538 the datastructures built by VRP. */
6539 identify_jump_threads (&vrp_prop.vr_values);
6541 /* A comparison of an SSA_NAME against a constant where the SSA_NAME
6542 was set by a type conversion can often be rewritten to use the
6543 RHS of the type conversion.
6545 However, doing so inhibits jump threading through the comparison.
6546 So that transformation is not performed until after jump threading
6547 is complete. */
6548 basic_block bb;
6549 FOR_EACH_BB_FN (bb, cfun)
6551 gimple *last = last_stmt (bb);
6552 if (last && gimple_code (last) == GIMPLE_COND)
6553 vrp_prop.vr_values.simplify_cond_using_ranges_2 (as_a <gcond *> (last));
6556 free_numbers_of_iterations_estimates (cfun);
6558 /* ASSERT_EXPRs must be removed before finalizing jump threads
6559 as finalizing jump threads calls the CFG cleanup code which
6560 does not properly handle ASSERT_EXPRs. */
6561 remove_range_assertions ();
6563 /* If we exposed any new variables, go ahead and put them into
6564 SSA form now, before we handle jump threading. This simplifies
6565 interactions between rewriting of _DECL nodes into SSA form
6566 and rewriting SSA_NAME nodes into SSA form after block
6567 duplication and CFG manipulation. */
6568 update_ssa (TODO_update_ssa);
6570 /* We identified all the jump threading opportunities earlier, but could
6571 not transform the CFG at that time. This routine transforms the
6572 CFG and arranges for the dominator tree to be rebuilt if necessary.
6574 Note the SSA graph update will occur during the normal TODO
6575 processing by the pass manager. */
6576 thread_through_all_blocks (false);
6578 vrp_prop.vr_values.cleanup_edges_and_switches ();
6579 threadedge_finalize_values ();
6581 scev_finalize ();
6582 loop_optimizer_finalize ();
6583 return 0;
6586 namespace {
6588 const pass_data pass_data_vrp =
6590 GIMPLE_PASS, /* type */
6591 "vrp", /* name */
6592 OPTGROUP_NONE, /* optinfo_flags */
6593 TV_TREE_VRP, /* tv_id */
6594 PROP_ssa, /* properties_required */
6595 0, /* properties_provided */
6596 0, /* properties_destroyed */
6597 0, /* todo_flags_start */
6598 ( TODO_cleanup_cfg | TODO_update_ssa ), /* todo_flags_finish */
6601 class pass_vrp : public gimple_opt_pass
6603 public:
6604 pass_vrp (gcc::context *ctxt)
6605 : gimple_opt_pass (pass_data_vrp, ctxt), warn_array_bounds_p (false)
6608 /* opt_pass methods: */
6609 opt_pass * clone () { return new pass_vrp (m_ctxt); }
6610 void set_pass_param (unsigned int n, bool param)
6612 gcc_assert (n == 0);
6613 warn_array_bounds_p = param;
6615 virtual bool gate (function *) { return flag_tree_vrp != 0; }
6616 virtual unsigned int execute (function *)
6617 { return execute_vrp (warn_array_bounds_p); }
6619 private:
6620 bool warn_array_bounds_p;
6621 }; // class pass_vrp
6623 } // anon namespace
6625 gimple_opt_pass *
6626 make_pass_vrp (gcc::context *ctxt)
6628 return new pass_vrp (ctxt);
6632 /* Worker for determine_value_range. */
6634 static void
6635 determine_value_range_1 (value_range *vr, tree expr)
6637 if (BINARY_CLASS_P (expr))
6639 value_range vr0 = VR_INITIALIZER, vr1 = VR_INITIALIZER;
6640 determine_value_range_1 (&vr0, TREE_OPERAND (expr, 0));
6641 determine_value_range_1 (&vr1, TREE_OPERAND (expr, 1));
6642 extract_range_from_binary_expr_1 (vr, TREE_CODE (expr), TREE_TYPE (expr),
6643 &vr0, &vr1);
6645 else if (UNARY_CLASS_P (expr))
6647 value_range vr0 = VR_INITIALIZER;
6648 determine_value_range_1 (&vr0, TREE_OPERAND (expr, 0));
6649 extract_range_from_unary_expr (vr, TREE_CODE (expr), TREE_TYPE (expr),
6650 &vr0, TREE_TYPE (TREE_OPERAND (expr, 0)));
6652 else if (TREE_CODE (expr) == INTEGER_CST)
6653 set_value_range_to_value (vr, expr, NULL);
6654 else
6656 value_range_type kind;
6657 wide_int min, max;
6658 /* For SSA names try to extract range info computed by VRP. Otherwise
6659 fall back to varying. */
6660 if (TREE_CODE (expr) == SSA_NAME
6661 && INTEGRAL_TYPE_P (TREE_TYPE (expr))
6662 && (kind = get_range_info (expr, &min, &max)) != VR_VARYING)
6663 set_value_range (vr, kind, wide_int_to_tree (TREE_TYPE (expr), min),
6664 wide_int_to_tree (TREE_TYPE (expr), max), NULL);
6665 else
6666 set_value_range_to_varying (vr);
6670 /* Compute a value-range for EXPR and set it in *MIN and *MAX. Return
6671 the determined range type. */
6673 value_range_type
6674 determine_value_range (tree expr, wide_int *min, wide_int *max)
6676 value_range vr = VR_INITIALIZER;
6677 determine_value_range_1 (&vr, expr);
6678 if ((vr.type == VR_RANGE
6679 || vr.type == VR_ANTI_RANGE)
6680 && !symbolic_range_p (&vr))
6682 *min = wi::to_wide (vr.min);
6683 *max = wi::to_wide (vr.max);
6684 return vr.type;
6687 return VR_VARYING;