Add missing '|' as wrong patch was applied.
[official-gcc.git] / gcc / tree-vrp.c
blob65865a7f5b61c040db96bd77d013e0f65d34e603
1 /* Support routines for Value Range Propagation (VRP).
2 Copyright (C) 2005-2018 Free Software Foundation, Inc.
3 Contributed by Diego Novillo <dnovillo@redhat.com>.
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "backend.h"
25 #include "insn-codes.h"
26 #include "rtl.h"
27 #include "tree.h"
28 #include "gimple.h"
29 #include "cfghooks.h"
30 #include "tree-pass.h"
31 #include "ssa.h"
32 #include "optabs-tree.h"
33 #include "gimple-pretty-print.h"
34 #include "diagnostic-core.h"
35 #include "flags.h"
36 #include "fold-const.h"
37 #include "stor-layout.h"
38 #include "calls.h"
39 #include "cfganal.h"
40 #include "gimple-fold.h"
41 #include "tree-eh.h"
42 #include "gimple-iterator.h"
43 #include "gimple-walk.h"
44 #include "tree-cfg.h"
45 #include "tree-dfa.h"
46 #include "tree-ssa-loop-manip.h"
47 #include "tree-ssa-loop-niter.h"
48 #include "tree-ssa-loop.h"
49 #include "tree-into-ssa.h"
50 #include "tree-ssa.h"
51 #include "intl.h"
52 #include "cfgloop.h"
53 #include "tree-scalar-evolution.h"
54 #include "tree-ssa-propagate.h"
55 #include "tree-chrec.h"
56 #include "tree-ssa-threadupdate.h"
57 #include "tree-ssa-scopedtables.h"
58 #include "tree-ssa-threadedge.h"
59 #include "omp-general.h"
60 #include "target.h"
61 #include "case-cfn-macros.h"
62 #include "params.h"
63 #include "alloc-pool.h"
64 #include "domwalk.h"
65 #include "tree-cfgcleanup.h"
66 #include "stringpool.h"
67 #include "attribs.h"
68 #include "vr-values.h"
69 #include "builtins.h"
71 /* Set of SSA names found live during the RPO traversal of the function
72 for still active basic-blocks. */
73 static sbitmap *live;
75 /* Return true if the SSA name NAME is live on the edge E. */
77 static bool
78 live_on_edge (edge e, tree name)
80 return (live[e->dest->index]
81 && bitmap_bit_p (live[e->dest->index], SSA_NAME_VERSION (name)));
84 /* Location information for ASSERT_EXPRs. Each instance of this
85 structure describes an ASSERT_EXPR for an SSA name. Since a single
86 SSA name may have more than one assertion associated with it, these
87 locations are kept in a linked list attached to the corresponding
88 SSA name. */
89 struct assert_locus
91 /* Basic block where the assertion would be inserted. */
92 basic_block bb;
94 /* Some assertions need to be inserted on an edge (e.g., assertions
95 generated by COND_EXPRs). In those cases, BB will be NULL. */
96 edge e;
98 /* Pointer to the statement that generated this assertion. */
99 gimple_stmt_iterator si;
101 /* Predicate code for the ASSERT_EXPR. Must be COMPARISON_CLASS_P. */
102 enum tree_code comp_code;
104 /* Value being compared against. */
105 tree val;
107 /* Expression to compare. */
108 tree expr;
110 /* Next node in the linked list. */
111 assert_locus *next;
114 /* If bit I is present, it means that SSA name N_i has a list of
115 assertions that should be inserted in the IL. */
116 static bitmap need_assert_for;
118 /* Array of locations lists where to insert assertions. ASSERTS_FOR[I]
119 holds a list of ASSERT_LOCUS_T nodes that describe where
120 ASSERT_EXPRs for SSA name N_I should be inserted. */
121 static assert_locus **asserts_for;
123 vec<edge> to_remove_edges;
124 vec<switch_update> to_update_switch_stmts;
127 /* Return the maximum value for TYPE. */
129 tree
130 vrp_val_max (const_tree type)
132 if (!INTEGRAL_TYPE_P (type))
133 return NULL_TREE;
135 return TYPE_MAX_VALUE (type);
138 /* Return the minimum value for TYPE. */
140 tree
141 vrp_val_min (const_tree type)
143 if (!INTEGRAL_TYPE_P (type))
144 return NULL_TREE;
146 return TYPE_MIN_VALUE (type);
149 /* Return whether VAL is equal to the maximum value of its type.
150 We can't do a simple equality comparison with TYPE_MAX_VALUE because
151 C typedefs and Ada subtypes can produce types whose TYPE_MAX_VALUE
152 is not == to the integer constant with the same value in the type. */
154 bool
155 vrp_val_is_max (const_tree val)
157 tree type_max = vrp_val_max (TREE_TYPE (val));
158 return (val == type_max
159 || (type_max != NULL_TREE
160 && operand_equal_p (val, type_max, 0)));
163 /* Return whether VAL is equal to the minimum value of its type. */
165 bool
166 vrp_val_is_min (const_tree val)
168 tree type_min = vrp_val_min (TREE_TYPE (val));
169 return (val == type_min
170 || (type_min != NULL_TREE
171 && operand_equal_p (val, type_min, 0)));
174 /* VR_TYPE describes a range with mininum value *MIN and maximum
175 value *MAX. Restrict the range to the set of values that have
176 no bits set outside NONZERO_BITS. Update *MIN and *MAX and
177 return the new range type.
179 SGN gives the sign of the values described by the range. */
181 enum value_range_type
182 intersect_range_with_nonzero_bits (enum value_range_type vr_type,
183 wide_int *min, wide_int *max,
184 const wide_int &nonzero_bits,
185 signop sgn)
187 if (vr_type == VR_ANTI_RANGE)
189 /* The VR_ANTI_RANGE is equivalent to the union of the ranges
190 A: [-INF, *MIN) and B: (*MAX, +INF]. First use NONZERO_BITS
191 to create an inclusive upper bound for A and an inclusive lower
192 bound for B. */
193 wide_int a_max = wi::round_down_for_mask (*min - 1, nonzero_bits);
194 wide_int b_min = wi::round_up_for_mask (*max + 1, nonzero_bits);
196 /* If the calculation of A_MAX wrapped, A is effectively empty
197 and A_MAX is the highest value that satisfies NONZERO_BITS.
198 Likewise if the calculation of B_MIN wrapped, B is effectively
199 empty and B_MIN is the lowest value that satisfies NONZERO_BITS. */
200 bool a_empty = wi::ge_p (a_max, *min, sgn);
201 bool b_empty = wi::le_p (b_min, *max, sgn);
203 /* If both A and B are empty, there are no valid values. */
204 if (a_empty && b_empty)
205 return VR_UNDEFINED;
207 /* If exactly one of A or B is empty, return a VR_RANGE for the
208 other one. */
209 if (a_empty || b_empty)
211 *min = b_min;
212 *max = a_max;
213 gcc_checking_assert (wi::le_p (*min, *max, sgn));
214 return VR_RANGE;
217 /* Update the VR_ANTI_RANGE bounds. */
218 *min = a_max + 1;
219 *max = b_min - 1;
220 gcc_checking_assert (wi::le_p (*min, *max, sgn));
222 /* Now check whether the excluded range includes any values that
223 satisfy NONZERO_BITS. If not, switch to a full VR_RANGE. */
224 if (wi::round_up_for_mask (*min, nonzero_bits) == b_min)
226 unsigned int precision = min->get_precision ();
227 *min = wi::min_value (precision, sgn);
228 *max = wi::max_value (precision, sgn);
229 vr_type = VR_RANGE;
232 if (vr_type == VR_RANGE)
234 *max = wi::round_down_for_mask (*max, nonzero_bits);
236 /* Check that the range contains at least one valid value. */
237 if (wi::gt_p (*min, *max, sgn))
238 return VR_UNDEFINED;
240 *min = wi::round_up_for_mask (*min, nonzero_bits);
241 gcc_checking_assert (wi::le_p (*min, *max, sgn));
243 return vr_type;
246 /* Set value range VR to VR_UNDEFINED. */
248 static inline void
249 set_value_range_to_undefined (value_range *vr)
251 vr->type = VR_UNDEFINED;
252 vr->min = vr->max = NULL_TREE;
253 if (vr->equiv)
254 bitmap_clear (vr->equiv);
257 /* Set value range VR to VR_VARYING. */
259 void
260 set_value_range_to_varying (value_range *vr)
262 vr->type = VR_VARYING;
263 vr->min = vr->max = NULL_TREE;
264 if (vr->equiv)
265 bitmap_clear (vr->equiv);
268 /* Set value range VR to {T, MIN, MAX, EQUIV}. */
270 void
271 set_value_range (value_range *vr, enum value_range_type t, tree min,
272 tree max, bitmap equiv)
274 /* Check the validity of the range. */
275 if (flag_checking
276 && (t == VR_RANGE || t == VR_ANTI_RANGE))
278 int cmp;
280 gcc_assert (min && max);
282 gcc_assert (!TREE_OVERFLOW_P (min) && !TREE_OVERFLOW_P (max));
284 if (INTEGRAL_TYPE_P (TREE_TYPE (min)) && t == VR_ANTI_RANGE)
285 gcc_assert (!vrp_val_is_min (min) || !vrp_val_is_max (max));
287 cmp = compare_values (min, max);
288 gcc_assert (cmp == 0 || cmp == -1 || cmp == -2);
291 if (flag_checking
292 && (t == VR_UNDEFINED || t == VR_VARYING))
294 gcc_assert (min == NULL_TREE && max == NULL_TREE);
295 gcc_assert (equiv == NULL || bitmap_empty_p (equiv));
298 vr->type = t;
299 vr->min = min;
300 vr->max = max;
302 /* Since updating the equivalence set involves deep copying the
303 bitmaps, only do it if absolutely necessary.
305 All equivalence bitmaps are allocated from the same obstack. So
306 we can use the obstack associated with EQUIV to allocate vr->equiv. */
307 if (vr->equiv == NULL
308 && equiv != NULL)
309 vr->equiv = BITMAP_ALLOC (equiv->obstack);
311 if (equiv != vr->equiv)
313 if (equiv && !bitmap_empty_p (equiv))
314 bitmap_copy (vr->equiv, equiv);
315 else
316 bitmap_clear (vr->equiv);
321 /* Set value range VR to the canonical form of {T, MIN, MAX, EQUIV}.
322 This means adjusting T, MIN and MAX representing the case of a
323 wrapping range with MAX < MIN covering [MIN, type_max] U [type_min, MAX]
324 as anti-rage ~[MAX+1, MIN-1]. Likewise for wrapping anti-ranges.
325 In corner cases where MAX+1 or MIN-1 wraps this will fall back
326 to varying.
327 This routine exists to ease canonicalization in the case where we
328 extract ranges from var + CST op limit. */
330 void
331 set_and_canonicalize_value_range (value_range *vr, enum value_range_type t,
332 tree min, tree max, bitmap equiv)
334 /* Use the canonical setters for VR_UNDEFINED and VR_VARYING. */
335 if (t == VR_UNDEFINED)
337 set_value_range_to_undefined (vr);
338 return;
340 else if (t == VR_VARYING)
342 set_value_range_to_varying (vr);
343 return;
346 /* Nothing to canonicalize for symbolic ranges. */
347 if (TREE_CODE (min) != INTEGER_CST
348 || TREE_CODE (max) != INTEGER_CST)
350 set_value_range (vr, t, min, max, equiv);
351 return;
354 /* Wrong order for min and max, to swap them and the VR type we need
355 to adjust them. */
356 if (tree_int_cst_lt (max, min))
358 tree one, tmp;
360 /* For one bit precision if max < min, then the swapped
361 range covers all values, so for VR_RANGE it is varying and
362 for VR_ANTI_RANGE empty range, so drop to varying as well. */
363 if (TYPE_PRECISION (TREE_TYPE (min)) == 1)
365 set_value_range_to_varying (vr);
366 return;
369 one = build_int_cst (TREE_TYPE (min), 1);
370 tmp = int_const_binop (PLUS_EXPR, max, one);
371 max = int_const_binop (MINUS_EXPR, min, one);
372 min = tmp;
374 /* There's one corner case, if we had [C+1, C] before we now have
375 that again. But this represents an empty value range, so drop
376 to varying in this case. */
377 if (tree_int_cst_lt (max, min))
379 set_value_range_to_varying (vr);
380 return;
383 t = t == VR_RANGE ? VR_ANTI_RANGE : VR_RANGE;
386 /* Anti-ranges that can be represented as ranges should be so. */
387 if (t == VR_ANTI_RANGE)
389 /* For -fstrict-enums we may receive out-of-range ranges so consider
390 values < -INF and values > INF as -INF/INF as well. */
391 tree type = TREE_TYPE (min);
392 bool is_min = (INTEGRAL_TYPE_P (type)
393 && tree_int_cst_compare (min, TYPE_MIN_VALUE (type)) <= 0);
394 bool is_max = (INTEGRAL_TYPE_P (type)
395 && tree_int_cst_compare (max, TYPE_MAX_VALUE (type)) >= 0);
397 if (is_min && is_max)
399 /* We cannot deal with empty ranges, drop to varying.
400 ??? This could be VR_UNDEFINED instead. */
401 set_value_range_to_varying (vr);
402 return;
404 else if (TYPE_PRECISION (TREE_TYPE (min)) == 1
405 && (is_min || is_max))
407 /* Non-empty boolean ranges can always be represented
408 as a singleton range. */
409 if (is_min)
410 min = max = vrp_val_max (TREE_TYPE (min));
411 else
412 min = max = vrp_val_min (TREE_TYPE (min));
413 t = VR_RANGE;
415 else if (is_min
416 /* As a special exception preserve non-null ranges. */
417 && !(TYPE_UNSIGNED (TREE_TYPE (min))
418 && integer_zerop (max)))
420 tree one = build_int_cst (TREE_TYPE (max), 1);
421 min = int_const_binop (PLUS_EXPR, max, one);
422 max = vrp_val_max (TREE_TYPE (max));
423 t = VR_RANGE;
425 else if (is_max)
427 tree one = build_int_cst (TREE_TYPE (min), 1);
428 max = int_const_binop (MINUS_EXPR, min, one);
429 min = vrp_val_min (TREE_TYPE (min));
430 t = VR_RANGE;
434 /* Do not drop [-INF(OVF), +INF(OVF)] to varying. (OVF) has to be sticky
435 to make sure VRP iteration terminates, otherwise we can get into
436 oscillations. */
438 set_value_range (vr, t, min, max, equiv);
441 /* Copy value range FROM into value range TO. */
443 void
444 copy_value_range (value_range *to, value_range *from)
446 set_value_range (to, from->type, from->min, from->max, from->equiv);
449 /* Set value range VR to a single value. This function is only called
450 with values we get from statements, and exists to clear the
451 TREE_OVERFLOW flag. */
453 void
454 set_value_range_to_value (value_range *vr, tree val, bitmap equiv)
456 gcc_assert (is_gimple_min_invariant (val));
457 if (TREE_OVERFLOW_P (val))
458 val = drop_tree_overflow (val);
459 set_value_range (vr, VR_RANGE, val, val, equiv);
462 /* Set value range VR to a non-NULL range of type TYPE. */
464 void
465 set_value_range_to_nonnull (value_range *vr, tree type)
467 tree zero = build_int_cst (type, 0);
468 set_value_range (vr, VR_ANTI_RANGE, zero, zero, vr->equiv);
472 /* Set value range VR to a NULL range of type TYPE. */
474 void
475 set_value_range_to_null (value_range *vr, tree type)
477 set_value_range_to_value (vr, build_int_cst (type, 0), vr->equiv);
481 /* If abs (min) < abs (max), set VR to [-max, max], if
482 abs (min) >= abs (max), set VR to [-min, min]. */
484 static void
485 abs_extent_range (value_range *vr, tree min, tree max)
487 int cmp;
489 gcc_assert (TREE_CODE (min) == INTEGER_CST);
490 gcc_assert (TREE_CODE (max) == INTEGER_CST);
491 gcc_assert (INTEGRAL_TYPE_P (TREE_TYPE (min)));
492 gcc_assert (!TYPE_UNSIGNED (TREE_TYPE (min)));
493 min = fold_unary (ABS_EXPR, TREE_TYPE (min), min);
494 max = fold_unary (ABS_EXPR, TREE_TYPE (max), max);
495 if (TREE_OVERFLOW (min) || TREE_OVERFLOW (max))
497 set_value_range_to_varying (vr);
498 return;
500 cmp = compare_values (min, max);
501 if (cmp == -1)
502 min = fold_unary (NEGATE_EXPR, TREE_TYPE (min), max);
503 else if (cmp == 0 || cmp == 1)
505 max = min;
506 min = fold_unary (NEGATE_EXPR, TREE_TYPE (min), min);
508 else
510 set_value_range_to_varying (vr);
511 return;
513 set_and_canonicalize_value_range (vr, VR_RANGE, min, max, NULL);
516 /* Return true, if VAL1 and VAL2 are equal values for VRP purposes. */
518 bool
519 vrp_operand_equal_p (const_tree val1, const_tree val2)
521 if (val1 == val2)
522 return true;
523 if (!val1 || !val2 || !operand_equal_p (val1, val2, 0))
524 return false;
525 return true;
528 /* Return true, if the bitmaps B1 and B2 are equal. */
530 bool
531 vrp_bitmap_equal_p (const_bitmap b1, const_bitmap b2)
533 return (b1 == b2
534 || ((!b1 || bitmap_empty_p (b1))
535 && (!b2 || bitmap_empty_p (b2)))
536 || (b1 && b2
537 && bitmap_equal_p (b1, b2)));
540 /* Return true if VR is ~[0, 0]. */
542 bool
543 range_is_nonnull (value_range *vr)
545 return vr->type == VR_ANTI_RANGE
546 && integer_zerop (vr->min)
547 && integer_zerop (vr->max);
551 /* Return true if VR is [0, 0]. */
553 static inline bool
554 range_is_null (value_range *vr)
556 return vr->type == VR_RANGE
557 && integer_zerop (vr->min)
558 && integer_zerop (vr->max);
561 /* Return true if max and min of VR are INTEGER_CST. It's not necessary
562 a singleton. */
564 bool
565 range_int_cst_p (value_range *vr)
567 return (vr->type == VR_RANGE
568 && TREE_CODE (vr->max) == INTEGER_CST
569 && TREE_CODE (vr->min) == INTEGER_CST);
572 /* Return true if VR is a INTEGER_CST singleton. */
574 bool
575 range_int_cst_singleton_p (value_range *vr)
577 return (range_int_cst_p (vr)
578 && tree_int_cst_equal (vr->min, vr->max));
581 /* Return true if value range VR involves at least one symbol. */
583 bool
584 symbolic_range_p (value_range *vr)
586 return (!is_gimple_min_invariant (vr->min)
587 || !is_gimple_min_invariant (vr->max));
590 /* Return the single symbol (an SSA_NAME) contained in T if any, or NULL_TREE
591 otherwise. We only handle additive operations and set NEG to true if the
592 symbol is negated and INV to the invariant part, if any. */
594 tree
595 get_single_symbol (tree t, bool *neg, tree *inv)
597 bool neg_;
598 tree inv_;
600 *inv = NULL_TREE;
601 *neg = false;
603 if (TREE_CODE (t) == PLUS_EXPR
604 || TREE_CODE (t) == POINTER_PLUS_EXPR
605 || TREE_CODE (t) == MINUS_EXPR)
607 if (is_gimple_min_invariant (TREE_OPERAND (t, 0)))
609 neg_ = (TREE_CODE (t) == MINUS_EXPR);
610 inv_ = TREE_OPERAND (t, 0);
611 t = TREE_OPERAND (t, 1);
613 else if (is_gimple_min_invariant (TREE_OPERAND (t, 1)))
615 neg_ = false;
616 inv_ = TREE_OPERAND (t, 1);
617 t = TREE_OPERAND (t, 0);
619 else
620 return NULL_TREE;
622 else
624 neg_ = false;
625 inv_ = NULL_TREE;
628 if (TREE_CODE (t) == NEGATE_EXPR)
630 t = TREE_OPERAND (t, 0);
631 neg_ = !neg_;
634 if (TREE_CODE (t) != SSA_NAME)
635 return NULL_TREE;
637 if (inv_ && TREE_OVERFLOW_P (inv_))
638 inv_ = drop_tree_overflow (inv_);
640 *neg = neg_;
641 *inv = inv_;
642 return t;
645 /* The reverse operation: build a symbolic expression with TYPE
646 from symbol SYM, negated according to NEG, and invariant INV. */
648 static tree
649 build_symbolic_expr (tree type, tree sym, bool neg, tree inv)
651 const bool pointer_p = POINTER_TYPE_P (type);
652 tree t = sym;
654 if (neg)
655 t = build1 (NEGATE_EXPR, type, t);
657 if (integer_zerop (inv))
658 return t;
660 return build2 (pointer_p ? POINTER_PLUS_EXPR : PLUS_EXPR, type, t, inv);
663 /* Return
664 1 if VAL < VAL2
665 0 if !(VAL < VAL2)
666 -2 if those are incomparable. */
668 operand_less_p (tree val, tree val2)
670 /* LT is folded faster than GE and others. Inline the common case. */
671 if (TREE_CODE (val) == INTEGER_CST && TREE_CODE (val2) == INTEGER_CST)
672 return tree_int_cst_lt (val, val2);
673 else
675 tree tcmp;
677 fold_defer_overflow_warnings ();
679 tcmp = fold_binary_to_constant (LT_EXPR, boolean_type_node, val, val2);
681 fold_undefer_and_ignore_overflow_warnings ();
683 if (!tcmp
684 || TREE_CODE (tcmp) != INTEGER_CST)
685 return -2;
687 if (!integer_zerop (tcmp))
688 return 1;
691 return 0;
694 /* Compare two values VAL1 and VAL2. Return
696 -2 if VAL1 and VAL2 cannot be compared at compile-time,
697 -1 if VAL1 < VAL2,
698 0 if VAL1 == VAL2,
699 +1 if VAL1 > VAL2, and
700 +2 if VAL1 != VAL2
702 This is similar to tree_int_cst_compare but supports pointer values
703 and values that cannot be compared at compile time.
705 If STRICT_OVERFLOW_P is not NULL, then set *STRICT_OVERFLOW_P to
706 true if the return value is only valid if we assume that signed
707 overflow is undefined. */
710 compare_values_warnv (tree val1, tree val2, bool *strict_overflow_p)
712 if (val1 == val2)
713 return 0;
715 /* Below we rely on the fact that VAL1 and VAL2 are both pointers or
716 both integers. */
717 gcc_assert (POINTER_TYPE_P (TREE_TYPE (val1))
718 == POINTER_TYPE_P (TREE_TYPE (val2)));
720 /* Convert the two values into the same type. This is needed because
721 sizetype causes sign extension even for unsigned types. */
722 val2 = fold_convert (TREE_TYPE (val1), val2);
723 STRIP_USELESS_TYPE_CONVERSION (val2);
725 const bool overflow_undefined
726 = INTEGRAL_TYPE_P (TREE_TYPE (val1))
727 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1));
728 tree inv1, inv2;
729 bool neg1, neg2;
730 tree sym1 = get_single_symbol (val1, &neg1, &inv1);
731 tree sym2 = get_single_symbol (val2, &neg2, &inv2);
733 /* If VAL1 and VAL2 are of the form '[-]NAME [+ CST]', return -1 or +1
734 accordingly. If VAL1 and VAL2 don't use the same name, return -2. */
735 if (sym1 && sym2)
737 /* Both values must use the same name with the same sign. */
738 if (sym1 != sym2 || neg1 != neg2)
739 return -2;
741 /* [-]NAME + CST == [-]NAME + CST. */
742 if (inv1 == inv2)
743 return 0;
745 /* If overflow is defined we cannot simplify more. */
746 if (!overflow_undefined)
747 return -2;
749 if (strict_overflow_p != NULL
750 /* Symbolic range building sets TREE_NO_WARNING to declare
751 that overflow doesn't happen. */
752 && (!inv1 || !TREE_NO_WARNING (val1))
753 && (!inv2 || !TREE_NO_WARNING (val2)))
754 *strict_overflow_p = true;
756 if (!inv1)
757 inv1 = build_int_cst (TREE_TYPE (val1), 0);
758 if (!inv2)
759 inv2 = build_int_cst (TREE_TYPE (val2), 0);
761 return wi::cmp (wi::to_wide (inv1), wi::to_wide (inv2),
762 TYPE_SIGN (TREE_TYPE (val1)));
765 const bool cst1 = is_gimple_min_invariant (val1);
766 const bool cst2 = is_gimple_min_invariant (val2);
768 /* If one is of the form '[-]NAME + CST' and the other is constant, then
769 it might be possible to say something depending on the constants. */
770 if ((sym1 && inv1 && cst2) || (sym2 && inv2 && cst1))
772 if (!overflow_undefined)
773 return -2;
775 if (strict_overflow_p != NULL
776 /* Symbolic range building sets TREE_NO_WARNING to declare
777 that overflow doesn't happen. */
778 && (!sym1 || !TREE_NO_WARNING (val1))
779 && (!sym2 || !TREE_NO_WARNING (val2)))
780 *strict_overflow_p = true;
782 const signop sgn = TYPE_SIGN (TREE_TYPE (val1));
783 tree cst = cst1 ? val1 : val2;
784 tree inv = cst1 ? inv2 : inv1;
786 /* Compute the difference between the constants. If it overflows or
787 underflows, this means that we can trivially compare the NAME with
788 it and, consequently, the two values with each other. */
789 wide_int diff = wi::to_wide (cst) - wi::to_wide (inv);
790 if (wi::cmp (0, wi::to_wide (inv), sgn)
791 != wi::cmp (diff, wi::to_wide (cst), sgn))
793 const int res = wi::cmp (wi::to_wide (cst), wi::to_wide (inv), sgn);
794 return cst1 ? res : -res;
797 return -2;
800 /* We cannot say anything more for non-constants. */
801 if (!cst1 || !cst2)
802 return -2;
804 if (!POINTER_TYPE_P (TREE_TYPE (val1)))
806 /* We cannot compare overflowed values. */
807 if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
808 return -2;
810 if (TREE_CODE (val1) == INTEGER_CST
811 && TREE_CODE (val2) == INTEGER_CST)
812 return tree_int_cst_compare (val1, val2);
814 if (poly_int_tree_p (val1) && poly_int_tree_p (val2))
816 if (known_eq (wi::to_poly_widest (val1),
817 wi::to_poly_widest (val2)))
818 return 0;
819 if (known_lt (wi::to_poly_widest (val1),
820 wi::to_poly_widest (val2)))
821 return -1;
822 if (known_gt (wi::to_poly_widest (val1),
823 wi::to_poly_widest (val2)))
824 return 1;
827 return -2;
829 else
831 tree t;
833 /* First see if VAL1 and VAL2 are not the same. */
834 if (val1 == val2 || operand_equal_p (val1, val2, 0))
835 return 0;
837 /* If VAL1 is a lower address than VAL2, return -1. */
838 if (operand_less_p (val1, val2) == 1)
839 return -1;
841 /* If VAL1 is a higher address than VAL2, return +1. */
842 if (operand_less_p (val2, val1) == 1)
843 return 1;
845 /* If VAL1 is different than VAL2, return +2.
846 For integer constants we either have already returned -1 or 1
847 or they are equivalent. We still might succeed in proving
848 something about non-trivial operands. */
849 if (TREE_CODE (val1) != INTEGER_CST
850 || TREE_CODE (val2) != INTEGER_CST)
852 t = fold_binary_to_constant (NE_EXPR, boolean_type_node, val1, val2);
853 if (t && integer_onep (t))
854 return 2;
857 return -2;
861 /* Compare values like compare_values_warnv. */
864 compare_values (tree val1, tree val2)
866 bool sop;
867 return compare_values_warnv (val1, val2, &sop);
871 /* Return 1 if VAL is inside value range MIN <= VAL <= MAX,
872 0 if VAL is not inside [MIN, MAX],
873 -2 if we cannot tell either way.
875 Benchmark compile/20001226-1.c compilation time after changing this
876 function. */
879 value_inside_range (tree val, tree min, tree max)
881 int cmp1, cmp2;
883 cmp1 = operand_less_p (val, min);
884 if (cmp1 == -2)
885 return -2;
886 if (cmp1 == 1)
887 return 0;
889 cmp2 = operand_less_p (max, val);
890 if (cmp2 == -2)
891 return -2;
893 return !cmp2;
897 /* Return true if value ranges VR0 and VR1 have a non-empty
898 intersection.
900 Benchmark compile/20001226-1.c compilation time after changing this
901 function.
904 static inline bool
905 value_ranges_intersect_p (value_range *vr0, value_range *vr1)
907 /* The value ranges do not intersect if the maximum of the first range is
908 less than the minimum of the second range or vice versa.
909 When those relations are unknown, we can't do any better. */
910 if (operand_less_p (vr0->max, vr1->min) != 0)
911 return false;
912 if (operand_less_p (vr1->max, vr0->min) != 0)
913 return false;
914 return true;
918 /* Return 1 if [MIN, MAX] includes the value zero, 0 if it does not
919 include the value zero, -2 if we cannot tell. */
922 range_includes_zero_p (tree min, tree max)
924 tree zero = build_int_cst (TREE_TYPE (min), 0);
925 return value_inside_range (zero, min, max);
928 /* Return true if *VR is know to only contain nonnegative values. */
930 static inline bool
931 value_range_nonnegative_p (value_range *vr)
933 /* Testing for VR_ANTI_RANGE is not useful here as any anti-range
934 which would return a useful value should be encoded as a
935 VR_RANGE. */
936 if (vr->type == VR_RANGE)
938 int result = compare_values (vr->min, integer_zero_node);
939 return (result == 0 || result == 1);
942 return false;
945 /* If *VR has a value rante that is a single constant value return that,
946 otherwise return NULL_TREE. */
948 tree
949 value_range_constant_singleton (value_range *vr)
951 if (vr->type == VR_RANGE
952 && vrp_operand_equal_p (vr->min, vr->max)
953 && is_gimple_min_invariant (vr->min))
954 return vr->min;
956 return NULL_TREE;
959 /* Wrapper around int_const_binop. Return true if we can compute the
960 result; i.e. if the operation doesn't overflow or if the overflow is
961 undefined. In the latter case (if the operation overflows and
962 overflow is undefined), then adjust the result to be -INF or +INF
963 depending on CODE, VAL1 and VAL2. Return the value in *RES.
965 Return false for division by zero, for which the result is
966 indeterminate. */
968 static bool
969 vrp_int_const_binop (enum tree_code code, tree val1, tree val2, wide_int *res)
971 bool overflow = false;
972 signop sign = TYPE_SIGN (TREE_TYPE (val1));
974 switch (code)
976 case RSHIFT_EXPR:
977 case LSHIFT_EXPR:
979 wide_int wval2 = wi::to_wide (val2, TYPE_PRECISION (TREE_TYPE (val1)));
980 if (wi::neg_p (wval2))
982 wval2 = -wval2;
983 if (code == RSHIFT_EXPR)
984 code = LSHIFT_EXPR;
985 else
986 code = RSHIFT_EXPR;
989 if (code == RSHIFT_EXPR)
990 /* It's unclear from the C standard whether shifts can overflow.
991 The following code ignores overflow; perhaps a C standard
992 interpretation ruling is needed. */
993 *res = wi::rshift (wi::to_wide (val1), wval2, sign);
994 else
995 *res = wi::lshift (wi::to_wide (val1), wval2);
996 break;
999 case MULT_EXPR:
1000 *res = wi::mul (wi::to_wide (val1),
1001 wi::to_wide (val2), sign, &overflow);
1002 break;
1004 case TRUNC_DIV_EXPR:
1005 case EXACT_DIV_EXPR:
1006 if (val2 == 0)
1007 return false;
1008 else
1009 *res = wi::div_trunc (wi::to_wide (val1),
1010 wi::to_wide (val2), sign, &overflow);
1011 break;
1013 case FLOOR_DIV_EXPR:
1014 if (val2 == 0)
1015 return false;
1016 *res = wi::div_floor (wi::to_wide (val1),
1017 wi::to_wide (val2), sign, &overflow);
1018 break;
1020 case CEIL_DIV_EXPR:
1021 if (val2 == 0)
1022 return false;
1023 *res = wi::div_ceil (wi::to_wide (val1),
1024 wi::to_wide (val2), sign, &overflow);
1025 break;
1027 case ROUND_DIV_EXPR:
1028 if (val2 == 0)
1029 return false;
1030 *res = wi::div_round (wi::to_wide (val1),
1031 wi::to_wide (val2), sign, &overflow);
1032 break;
1034 default:
1035 gcc_unreachable ();
1038 if (overflow
1039 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1)))
1041 /* If the operation overflowed return -INF or +INF depending
1042 on the operation and the combination of signs of the operands. */
1043 int sgn1 = tree_int_cst_sgn (val1);
1044 int sgn2 = tree_int_cst_sgn (val2);
1046 /* Notice that we only need to handle the restricted set of
1047 operations handled by extract_range_from_binary_expr.
1048 Among them, only multiplication, addition and subtraction
1049 can yield overflow without overflown operands because we
1050 are working with integral types only... except in the
1051 case VAL1 = -INF and VAL2 = -1 which overflows to +INF
1052 for division too. */
1054 /* For multiplication, the sign of the overflow is given
1055 by the comparison of the signs of the operands. */
1056 if ((code == MULT_EXPR && sgn1 == sgn2)
1057 /* For addition, the operands must be of the same sign
1058 to yield an overflow. Its sign is therefore that
1059 of one of the operands, for example the first. */
1060 || (code == PLUS_EXPR && sgn1 >= 0)
1061 /* For subtraction, operands must be of
1062 different signs to yield an overflow. Its sign is
1063 therefore that of the first operand or the opposite of
1064 that of the second operand. A first operand of 0 counts
1065 as positive here, for the corner case 0 - (-INF), which
1066 overflows, but must yield +INF. */
1067 || (code == MINUS_EXPR && sgn1 >= 0)
1068 /* For division, the only case is -INF / -1 = +INF. */
1069 || code == TRUNC_DIV_EXPR
1070 || code == FLOOR_DIV_EXPR
1071 || code == CEIL_DIV_EXPR
1072 || code == EXACT_DIV_EXPR
1073 || code == ROUND_DIV_EXPR)
1074 *res = wi::max_value (TYPE_PRECISION (TREE_TYPE (val1)),
1075 TYPE_SIGN (TREE_TYPE (val1)));
1076 else
1077 *res = wi::min_value (TYPE_PRECISION (TREE_TYPE (val1)),
1078 TYPE_SIGN (TREE_TYPE (val1)));
1079 return true;
1082 return !overflow;
1086 /* For range VR compute two wide_int bitmasks. In *MAY_BE_NONZERO
1087 bitmask if some bit is unset, it means for all numbers in the range
1088 the bit is 0, otherwise it might be 0 or 1. In *MUST_BE_NONZERO
1089 bitmask if some bit is set, it means for all numbers in the range
1090 the bit is 1, otherwise it might be 0 or 1. */
1092 bool
1093 zero_nonzero_bits_from_vr (const tree expr_type,
1094 value_range *vr,
1095 wide_int *may_be_nonzero,
1096 wide_int *must_be_nonzero)
1098 *may_be_nonzero = wi::minus_one (TYPE_PRECISION (expr_type));
1099 *must_be_nonzero = wi::zero (TYPE_PRECISION (expr_type));
1100 if (!range_int_cst_p (vr))
1101 return false;
1103 if (range_int_cst_singleton_p (vr))
1105 *may_be_nonzero = wi::to_wide (vr->min);
1106 *must_be_nonzero = *may_be_nonzero;
1108 else if (tree_int_cst_sgn (vr->min) >= 0
1109 || tree_int_cst_sgn (vr->max) < 0)
1111 wide_int xor_mask = wi::to_wide (vr->min) ^ wi::to_wide (vr->max);
1112 *may_be_nonzero = wi::to_wide (vr->min) | wi::to_wide (vr->max);
1113 *must_be_nonzero = wi::to_wide (vr->min) & wi::to_wide (vr->max);
1114 if (xor_mask != 0)
1116 wide_int mask = wi::mask (wi::floor_log2 (xor_mask), false,
1117 may_be_nonzero->get_precision ());
1118 *may_be_nonzero = *may_be_nonzero | mask;
1119 *must_be_nonzero = wi::bit_and_not (*must_be_nonzero, mask);
1123 return true;
1126 /* Create two value-ranges in *VR0 and *VR1 from the anti-range *AR
1127 so that *VR0 U *VR1 == *AR. Returns true if that is possible,
1128 false otherwise. If *AR can be represented with a single range
1129 *VR1 will be VR_UNDEFINED. */
1131 static bool
1132 ranges_from_anti_range (value_range *ar,
1133 value_range *vr0, value_range *vr1)
1135 tree type = TREE_TYPE (ar->min);
1137 vr0->type = VR_UNDEFINED;
1138 vr1->type = VR_UNDEFINED;
1140 if (ar->type != VR_ANTI_RANGE
1141 || TREE_CODE (ar->min) != INTEGER_CST
1142 || TREE_CODE (ar->max) != INTEGER_CST
1143 || !vrp_val_min (type)
1144 || !vrp_val_max (type))
1145 return false;
1147 if (!vrp_val_is_min (ar->min))
1149 vr0->type = VR_RANGE;
1150 vr0->min = vrp_val_min (type);
1151 vr0->max = wide_int_to_tree (type, wi::to_wide (ar->min) - 1);
1153 if (!vrp_val_is_max (ar->max))
1155 vr1->type = VR_RANGE;
1156 vr1->min = wide_int_to_tree (type, wi::to_wide (ar->max) + 1);
1157 vr1->max = vrp_val_max (type);
1159 if (vr0->type == VR_UNDEFINED)
1161 *vr0 = *vr1;
1162 vr1->type = VR_UNDEFINED;
1165 return vr0->type != VR_UNDEFINED;
1168 /* Helper to extract a value-range *VR for a multiplicative operation
1169 *VR0 CODE *VR1. */
1171 static void
1172 extract_range_from_multiplicative_op_1 (value_range *vr,
1173 enum tree_code code,
1174 value_range *vr0, value_range *vr1)
1176 enum value_range_type rtype;
1177 wide_int val, min, max;
1178 tree type;
1180 /* Multiplications, divisions and shifts are a bit tricky to handle,
1181 depending on the mix of signs we have in the two ranges, we
1182 need to operate on different values to get the minimum and
1183 maximum values for the new range. One approach is to figure
1184 out all the variations of range combinations and do the
1185 operations.
1187 However, this involves several calls to compare_values and it
1188 is pretty convoluted. It's simpler to do the 4 operations
1189 (MIN0 OP MIN1, MIN0 OP MAX1, MAX0 OP MIN1 and MAX0 OP MAX0 OP
1190 MAX1) and then figure the smallest and largest values to form
1191 the new range. */
1192 gcc_assert (code == MULT_EXPR
1193 || code == TRUNC_DIV_EXPR
1194 || code == FLOOR_DIV_EXPR
1195 || code == CEIL_DIV_EXPR
1196 || code == EXACT_DIV_EXPR
1197 || code == ROUND_DIV_EXPR
1198 || code == RSHIFT_EXPR
1199 || code == LSHIFT_EXPR);
1200 gcc_assert (vr0->type == VR_RANGE
1201 && vr0->type == vr1->type);
1203 rtype = vr0->type;
1204 type = TREE_TYPE (vr0->min);
1205 signop sgn = TYPE_SIGN (type);
1207 /* Compute the 4 cross operations and their minimum and maximum value. */
1208 if (!vrp_int_const_binop (code, vr0->min, vr1->min, &val))
1210 set_value_range_to_varying (vr);
1211 return;
1213 min = max = val;
1215 if (vr1->max != vr1->min)
1217 if (!vrp_int_const_binop (code, vr0->min, vr1->max, &val))
1219 set_value_range_to_varying (vr);
1220 return;
1222 if (wi::lt_p (val, min, sgn))
1223 min = val;
1224 else if (wi::gt_p (val, max, sgn))
1225 max = val;
1228 if (vr0->max != vr0->min)
1230 if (!vrp_int_const_binop (code, vr0->max, vr1->min, &val))
1232 set_value_range_to_varying (vr);
1233 return;
1235 if (wi::lt_p (val, min, sgn))
1236 min = val;
1237 else if (wi::gt_p (val, max, sgn))
1238 max = val;
1241 if (vr0->min != vr0->max && vr1->min != vr1->max)
1243 if (!vrp_int_const_binop (code, vr0->max, vr1->max, &val))
1245 set_value_range_to_varying (vr);
1246 return;
1248 if (wi::lt_p (val, min, sgn))
1249 min = val;
1250 else if (wi::gt_p (val, max, sgn))
1251 max = val;
1254 /* If the new range has its limits swapped around (MIN > MAX),
1255 then the operation caused one of them to wrap around, mark
1256 the new range VARYING. */
1257 if (wi::gt_p (min, max, sgn))
1259 set_value_range_to_varying (vr);
1260 return;
1263 /* We punt for [-INF, +INF].
1264 We learn nothing when we have INF on both sides.
1265 Note that we do accept [-INF, -INF] and [+INF, +INF]. */
1266 if (wi::eq_p (min, wi::min_value (TYPE_PRECISION (type), sgn))
1267 && wi::eq_p (max, wi::max_value (TYPE_PRECISION (type), sgn)))
1269 set_value_range_to_varying (vr);
1270 return;
1273 set_value_range (vr, rtype,
1274 wide_int_to_tree (type, min),
1275 wide_int_to_tree (type, max), NULL);
1278 /* If BOUND will include a symbolic bound, adjust it accordingly,
1279 otherwise leave it as is.
1281 CODE is the original operation that combined the bounds (PLUS_EXPR
1282 or MINUS_EXPR).
1284 TYPE is the type of the original operation.
1286 SYM_OPn is the symbolic for OPn if it has a symbolic.
1288 NEG_OPn is TRUE if the OPn was negated. */
1290 static void
1291 adjust_symbolic_bound (tree &bound, enum tree_code code, tree type,
1292 tree sym_op0, tree sym_op1,
1293 bool neg_op0, bool neg_op1)
1295 bool minus_p = (code == MINUS_EXPR);
1296 /* If the result bound is constant, we're done; otherwise, build the
1297 symbolic lower bound. */
1298 if (sym_op0 == sym_op1)
1300 else if (sym_op0)
1301 bound = build_symbolic_expr (type, sym_op0,
1302 neg_op0, bound);
1303 else if (sym_op1)
1305 /* We may not negate if that might introduce
1306 undefined overflow. */
1307 if (!minus_p
1308 || neg_op1
1309 || TYPE_OVERFLOW_WRAPS (type))
1310 bound = build_symbolic_expr (type, sym_op1,
1311 neg_op1 ^ minus_p, bound);
1312 else
1313 bound = NULL_TREE;
1317 /* Combine OP1 and OP1, which are two parts of a bound, into one wide
1318 int bound according to CODE. CODE is the operation combining the
1319 bound (either a PLUS_EXPR or a MINUS_EXPR).
1321 TYPE is the type of the combine operation.
1323 WI is the wide int to store the result.
1325 OVF is -1 if an underflow occurred, +1 if an overflow occurred or 0
1326 if over/underflow occurred. */
1328 static void
1329 combine_bound (enum tree_code code, wide_int &wi, int &ovf,
1330 tree type, tree op0, tree op1)
1332 bool minus_p = (code == MINUS_EXPR);
1333 const signop sgn = TYPE_SIGN (type);
1334 const unsigned int prec = TYPE_PRECISION (type);
1336 /* Combine the bounds, if any. */
1337 if (op0 && op1)
1339 if (minus_p)
1341 wi = wi::to_wide (op0) - wi::to_wide (op1);
1343 /* Check for overflow. */
1344 if (wi::cmp (0, wi::to_wide (op1), sgn)
1345 != wi::cmp (wi, wi::to_wide (op0), sgn))
1346 ovf = wi::cmp (wi::to_wide (op0),
1347 wi::to_wide (op1), sgn);
1349 else
1351 wi = wi::to_wide (op0) + wi::to_wide (op1);
1353 /* Check for overflow. */
1354 if (wi::cmp (wi::to_wide (op1), 0, sgn)
1355 != wi::cmp (wi, wi::to_wide (op0), sgn))
1356 ovf = wi::cmp (wi::to_wide (op0), wi, sgn);
1359 else if (op0)
1360 wi = wi::to_wide (op0);
1361 else if (op1)
1363 if (minus_p)
1365 wi = -wi::to_wide (op1);
1367 /* Check for overflow. */
1368 if (sgn == SIGNED
1369 && wi::neg_p (wi::to_wide (op1))
1370 && wi::neg_p (wi))
1371 ovf = 1;
1372 else if (sgn == UNSIGNED && wi::to_wide (op1) != 0)
1373 ovf = -1;
1375 else
1376 wi = wi::to_wide (op1);
1378 else
1379 wi = wi::shwi (0, prec);
1382 /* Given a range in [WMIN, WMAX], adjust it for possible overflow and
1383 put the result in VR.
1385 TYPE is the type of the range.
1387 MIN_OVF and MAX_OVF indicate what type of overflow, if any,
1388 occurred while originally calculating WMIN or WMAX. -1 indicates
1389 underflow. +1 indicates overflow. 0 indicates neither. */
1391 static void
1392 set_value_range_with_overflow (value_range &vr,
1393 tree type,
1394 const wide_int &wmin, const wide_int &wmax,
1395 int min_ovf, int max_ovf)
1397 const signop sgn = TYPE_SIGN (type);
1398 const unsigned int prec = TYPE_PRECISION (type);
1399 vr.type = VR_RANGE;
1400 vr.equiv = NULL;
1401 if (TYPE_OVERFLOW_WRAPS (type))
1403 /* If overflow wraps, truncate the values and adjust the
1404 range kind and bounds appropriately. */
1405 wide_int tmin = wide_int::from (wmin, prec, sgn);
1406 wide_int tmax = wide_int::from (wmax, prec, sgn);
1407 if (min_ovf == max_ovf)
1409 /* No overflow or both overflow or underflow. The
1410 range kind stays VR_RANGE. */
1411 vr.min = wide_int_to_tree (type, tmin);
1412 vr.max = wide_int_to_tree (type, tmax);
1414 else if ((min_ovf == -1 && max_ovf == 0)
1415 || (max_ovf == 1 && min_ovf == 0))
1417 /* Min underflow or max overflow. The range kind
1418 changes to VR_ANTI_RANGE. */
1419 bool covers = false;
1420 wide_int tem = tmin;
1421 vr.type = VR_ANTI_RANGE;
1422 tmin = tmax + 1;
1423 if (wi::cmp (tmin, tmax, sgn) < 0)
1424 covers = true;
1425 tmax = tem - 1;
1426 if (wi::cmp (tmax, tem, sgn) > 0)
1427 covers = true;
1428 /* If the anti-range would cover nothing, drop to varying.
1429 Likewise if the anti-range bounds are outside of the
1430 types values. */
1431 if (covers || wi::cmp (tmin, tmax, sgn) > 0)
1433 set_value_range_to_varying (&vr);
1434 return;
1436 vr.min = wide_int_to_tree (type, tmin);
1437 vr.max = wide_int_to_tree (type, tmax);
1439 else
1441 /* Other underflow and/or overflow, drop to VR_VARYING. */
1442 set_value_range_to_varying (&vr);
1443 return;
1446 else
1448 /* If overflow does not wrap, saturate to the types min/max
1449 value. */
1450 wide_int type_min = wi::min_value (prec, sgn);
1451 wide_int type_max = wi::max_value (prec, sgn);
1452 if (min_ovf == -1)
1453 vr.min = wide_int_to_tree (type, type_min);
1454 else if (min_ovf == 1)
1455 vr.min = wide_int_to_tree (type, type_max);
1456 else
1457 vr.min = wide_int_to_tree (type, wmin);
1459 if (max_ovf == -1)
1460 vr.max = wide_int_to_tree (type, type_min);
1461 else if (max_ovf == 1)
1462 vr.max = wide_int_to_tree (type, type_max);
1463 else
1464 vr.max = wide_int_to_tree (type, wmax);
1468 /* Extract range information from a binary operation CODE based on
1469 the ranges of each of its operands *VR0 and *VR1 with resulting
1470 type EXPR_TYPE. The resulting range is stored in *VR. */
1472 void
1473 extract_range_from_binary_expr_1 (value_range *vr,
1474 enum tree_code code, tree expr_type,
1475 value_range *vr0_, value_range *vr1_)
1477 value_range vr0 = *vr0_, vr1 = *vr1_;
1478 value_range vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
1479 enum value_range_type type;
1480 tree min = NULL_TREE, max = NULL_TREE;
1481 int cmp;
1483 if (!INTEGRAL_TYPE_P (expr_type)
1484 && !POINTER_TYPE_P (expr_type))
1486 set_value_range_to_varying (vr);
1487 return;
1490 /* Not all binary expressions can be applied to ranges in a
1491 meaningful way. Handle only arithmetic operations. */
1492 if (code != PLUS_EXPR
1493 && code != MINUS_EXPR
1494 && code != POINTER_PLUS_EXPR
1495 && code != MULT_EXPR
1496 && code != TRUNC_DIV_EXPR
1497 && code != FLOOR_DIV_EXPR
1498 && code != CEIL_DIV_EXPR
1499 && code != EXACT_DIV_EXPR
1500 && code != ROUND_DIV_EXPR
1501 && code != TRUNC_MOD_EXPR
1502 && code != RSHIFT_EXPR
1503 && code != LSHIFT_EXPR
1504 && code != MIN_EXPR
1505 && code != MAX_EXPR
1506 && code != BIT_AND_EXPR
1507 && code != BIT_IOR_EXPR
1508 && code != BIT_XOR_EXPR)
1510 set_value_range_to_varying (vr);
1511 return;
1514 /* If both ranges are UNDEFINED, so is the result. */
1515 if (vr0.type == VR_UNDEFINED && vr1.type == VR_UNDEFINED)
1517 set_value_range_to_undefined (vr);
1518 return;
1520 /* If one of the ranges is UNDEFINED drop it to VARYING for the following
1521 code. At some point we may want to special-case operations that
1522 have UNDEFINED result for all or some value-ranges of the not UNDEFINED
1523 operand. */
1524 else if (vr0.type == VR_UNDEFINED)
1525 set_value_range_to_varying (&vr0);
1526 else if (vr1.type == VR_UNDEFINED)
1527 set_value_range_to_varying (&vr1);
1529 /* We get imprecise results from ranges_from_anti_range when
1530 code is EXACT_DIV_EXPR. We could mask out bits in the resulting
1531 range, but then we also need to hack up vrp_meet. It's just
1532 easier to special case when vr0 is ~[0,0] for EXACT_DIV_EXPR. */
1533 if (code == EXACT_DIV_EXPR
1534 && vr0.type == VR_ANTI_RANGE
1535 && vr0.min == vr0.max
1536 && integer_zerop (vr0.min))
1538 set_value_range_to_nonnull (vr, expr_type);
1539 return;
1542 /* Now canonicalize anti-ranges to ranges when they are not symbolic
1543 and express ~[] op X as ([]' op X) U ([]'' op X). */
1544 if (vr0.type == VR_ANTI_RANGE
1545 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
1547 extract_range_from_binary_expr_1 (vr, code, expr_type, &vrtem0, vr1_);
1548 if (vrtem1.type != VR_UNDEFINED)
1550 value_range vrres = VR_INITIALIZER;
1551 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
1552 &vrtem1, vr1_);
1553 vrp_meet (vr, &vrres);
1555 return;
1557 /* Likewise for X op ~[]. */
1558 if (vr1.type == VR_ANTI_RANGE
1559 && ranges_from_anti_range (&vr1, &vrtem0, &vrtem1))
1561 extract_range_from_binary_expr_1 (vr, code, expr_type, vr0_, &vrtem0);
1562 if (vrtem1.type != VR_UNDEFINED)
1564 value_range vrres = VR_INITIALIZER;
1565 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
1566 vr0_, &vrtem1);
1567 vrp_meet (vr, &vrres);
1569 return;
1572 /* The type of the resulting value range defaults to VR0.TYPE. */
1573 type = vr0.type;
1575 /* Refuse to operate on VARYING ranges, ranges of different kinds
1576 and symbolic ranges. As an exception, we allow BIT_{AND,IOR}
1577 because we may be able to derive a useful range even if one of
1578 the operands is VR_VARYING or symbolic range. Similarly for
1579 divisions, MIN/MAX and PLUS/MINUS.
1581 TODO, we may be able to derive anti-ranges in some cases. */
1582 if (code != BIT_AND_EXPR
1583 && code != BIT_IOR_EXPR
1584 && code != TRUNC_DIV_EXPR
1585 && code != FLOOR_DIV_EXPR
1586 && code != CEIL_DIV_EXPR
1587 && code != EXACT_DIV_EXPR
1588 && code != ROUND_DIV_EXPR
1589 && code != TRUNC_MOD_EXPR
1590 && code != MIN_EXPR
1591 && code != MAX_EXPR
1592 && code != PLUS_EXPR
1593 && code != MINUS_EXPR
1594 && code != RSHIFT_EXPR
1595 && (vr0.type == VR_VARYING
1596 || vr1.type == VR_VARYING
1597 || vr0.type != vr1.type
1598 || symbolic_range_p (&vr0)
1599 || symbolic_range_p (&vr1)))
1601 set_value_range_to_varying (vr);
1602 return;
1605 /* Now evaluate the expression to determine the new range. */
1606 if (POINTER_TYPE_P (expr_type))
1608 if (code == MIN_EXPR || code == MAX_EXPR)
1610 /* For MIN/MAX expressions with pointers, we only care about
1611 nullness, if both are non null, then the result is nonnull.
1612 If both are null, then the result is null. Otherwise they
1613 are varying. */
1614 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
1615 set_value_range_to_nonnull (vr, expr_type);
1616 else if (range_is_null (&vr0) && range_is_null (&vr1))
1617 set_value_range_to_null (vr, expr_type);
1618 else
1619 set_value_range_to_varying (vr);
1621 else if (code == POINTER_PLUS_EXPR)
1623 /* For pointer types, we are really only interested in asserting
1624 whether the expression evaluates to non-NULL. */
1625 if (range_is_nonnull (&vr0) || range_is_nonnull (&vr1))
1626 set_value_range_to_nonnull (vr, expr_type);
1627 else if (range_is_null (&vr0) && range_is_null (&vr1))
1628 set_value_range_to_null (vr, expr_type);
1629 else
1630 set_value_range_to_varying (vr);
1632 else if (code == BIT_AND_EXPR)
1634 /* For pointer types, we are really only interested in asserting
1635 whether the expression evaluates to non-NULL. */
1636 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
1637 set_value_range_to_nonnull (vr, expr_type);
1638 else if (range_is_null (&vr0) || range_is_null (&vr1))
1639 set_value_range_to_null (vr, expr_type);
1640 else
1641 set_value_range_to_varying (vr);
1643 else
1644 set_value_range_to_varying (vr);
1646 return;
1649 /* For integer ranges, apply the operation to each end of the
1650 range and see what we end up with. */
1651 if (code == PLUS_EXPR || code == MINUS_EXPR)
1653 const bool minus_p = (code == MINUS_EXPR);
1654 tree min_op0 = vr0.min;
1655 tree min_op1 = minus_p ? vr1.max : vr1.min;
1656 tree max_op0 = vr0.max;
1657 tree max_op1 = minus_p ? vr1.min : vr1.max;
1658 tree sym_min_op0 = NULL_TREE;
1659 tree sym_min_op1 = NULL_TREE;
1660 tree sym_max_op0 = NULL_TREE;
1661 tree sym_max_op1 = NULL_TREE;
1662 bool neg_min_op0, neg_min_op1, neg_max_op0, neg_max_op1;
1664 neg_min_op0 = neg_min_op1 = neg_max_op0 = neg_max_op1 = false;
1666 /* If we have a PLUS or MINUS with two VR_RANGEs, either constant or
1667 single-symbolic ranges, try to compute the precise resulting range,
1668 but only if we know that this resulting range will also be constant
1669 or single-symbolic. */
1670 if (vr0.type == VR_RANGE && vr1.type == VR_RANGE
1671 && (TREE_CODE (min_op0) == INTEGER_CST
1672 || (sym_min_op0
1673 = get_single_symbol (min_op0, &neg_min_op0, &min_op0)))
1674 && (TREE_CODE (min_op1) == INTEGER_CST
1675 || (sym_min_op1
1676 = get_single_symbol (min_op1, &neg_min_op1, &min_op1)))
1677 && (!(sym_min_op0 && sym_min_op1)
1678 || (sym_min_op0 == sym_min_op1
1679 && neg_min_op0 == (minus_p ? neg_min_op1 : !neg_min_op1)))
1680 && (TREE_CODE (max_op0) == INTEGER_CST
1681 || (sym_max_op0
1682 = get_single_symbol (max_op0, &neg_max_op0, &max_op0)))
1683 && (TREE_CODE (max_op1) == INTEGER_CST
1684 || (sym_max_op1
1685 = get_single_symbol (max_op1, &neg_max_op1, &max_op1)))
1686 && (!(sym_max_op0 && sym_max_op1)
1687 || (sym_max_op0 == sym_max_op1
1688 && neg_max_op0 == (minus_p ? neg_max_op1 : !neg_max_op1))))
1690 wide_int wmin, wmax;
1691 int min_ovf = 0;
1692 int max_ovf = 0;
1694 /* Build the bounds. */
1695 combine_bound (code, wmin, min_ovf, expr_type, min_op0, min_op1);
1696 combine_bound (code, wmax, max_ovf, expr_type, max_op0, max_op1);
1698 /* If we have overflow for the constant part and the resulting
1699 range will be symbolic, drop to VR_VARYING. */
1700 if ((min_ovf && sym_min_op0 != sym_min_op1)
1701 || (max_ovf && sym_max_op0 != sym_max_op1))
1703 set_value_range_to_varying (vr);
1704 return;
1707 /* Adjust the range for possible overflow. */
1708 set_value_range_with_overflow (*vr, expr_type,
1709 wmin, wmax, min_ovf, max_ovf);
1710 if (vr->type == VR_VARYING)
1711 return;
1713 /* Build the symbolic bounds if needed. */
1714 adjust_symbolic_bound (vr->min, code, expr_type,
1715 sym_min_op0, sym_min_op1,
1716 neg_min_op0, neg_min_op1);
1717 adjust_symbolic_bound (vr->max, code, expr_type,
1718 sym_max_op0, sym_max_op1,
1719 neg_max_op0, neg_max_op1);
1720 /* ?? It would probably be cleaner to eliminate min/max/type
1721 entirely and hold these values in VR directly. */
1722 min = vr->min;
1723 max = vr->max;
1724 type = vr->type;
1726 else
1728 /* For other cases, for example if we have a PLUS_EXPR with two
1729 VR_ANTI_RANGEs, drop to VR_VARYING. It would take more effort
1730 to compute a precise range for such a case.
1731 ??? General even mixed range kind operations can be expressed
1732 by for example transforming ~[3, 5] + [1, 2] to range-only
1733 operations and a union primitive:
1734 [-INF, 2] + [1, 2] U [5, +INF] + [1, 2]
1735 [-INF+1, 4] U [6, +INF(OVF)]
1736 though usually the union is not exactly representable with
1737 a single range or anti-range as the above is
1738 [-INF+1, +INF(OVF)] intersected with ~[5, 5]
1739 but one could use a scheme similar to equivalences for this. */
1740 set_value_range_to_varying (vr);
1741 return;
1744 else if (code == MIN_EXPR
1745 || code == MAX_EXPR)
1747 if (vr0.type == VR_RANGE
1748 && !symbolic_range_p (&vr0))
1750 type = VR_RANGE;
1751 if (vr1.type == VR_RANGE
1752 && !symbolic_range_p (&vr1))
1754 /* For operations that make the resulting range directly
1755 proportional to the original ranges, apply the operation to
1756 the same end of each range. */
1757 min = int_const_binop (code, vr0.min, vr1.min);
1758 max = int_const_binop (code, vr0.max, vr1.max);
1760 else if (code == MIN_EXPR)
1762 min = vrp_val_min (expr_type);
1763 max = vr0.max;
1765 else if (code == MAX_EXPR)
1767 min = vr0.min;
1768 max = vrp_val_max (expr_type);
1771 else if (vr1.type == VR_RANGE
1772 && !symbolic_range_p (&vr1))
1774 type = VR_RANGE;
1775 if (code == MIN_EXPR)
1777 min = vrp_val_min (expr_type);
1778 max = vr1.max;
1780 else if (code == MAX_EXPR)
1782 min = vr1.min;
1783 max = vrp_val_max (expr_type);
1786 else
1788 set_value_range_to_varying (vr);
1789 return;
1792 else if (code == MULT_EXPR)
1794 /* Fancy code so that with unsigned, [-3,-1]*[-3,-1] does not
1795 drop to varying. This test requires 2*prec bits if both
1796 operands are signed and 2*prec + 2 bits if either is not. */
1798 signop sign = TYPE_SIGN (expr_type);
1799 unsigned int prec = TYPE_PRECISION (expr_type);
1801 if (!range_int_cst_p (&vr0)
1802 || !range_int_cst_p (&vr1))
1804 set_value_range_to_varying (vr);
1805 return;
1808 if (TYPE_OVERFLOW_WRAPS (expr_type))
1810 typedef FIXED_WIDE_INT (WIDE_INT_MAX_PRECISION * 2) vrp_int;
1811 typedef generic_wide_int
1812 <wi::extended_tree <WIDE_INT_MAX_PRECISION * 2> > vrp_int_cst;
1813 vrp_int sizem1 = wi::mask <vrp_int> (prec, false);
1814 vrp_int size = sizem1 + 1;
1816 /* Extend the values using the sign of the result to PREC2.
1817 From here on out, everthing is just signed math no matter
1818 what the input types were. */
1819 vrp_int min0 = vrp_int_cst (vr0.min);
1820 vrp_int max0 = vrp_int_cst (vr0.max);
1821 vrp_int min1 = vrp_int_cst (vr1.min);
1822 vrp_int max1 = vrp_int_cst (vr1.max);
1823 /* Canonicalize the intervals. */
1824 if (sign == UNSIGNED)
1826 if (wi::ltu_p (size, min0 + max0))
1828 min0 -= size;
1829 max0 -= size;
1832 if (wi::ltu_p (size, min1 + max1))
1834 min1 -= size;
1835 max1 -= size;
1839 vrp_int prod0 = min0 * min1;
1840 vrp_int prod1 = min0 * max1;
1841 vrp_int prod2 = max0 * min1;
1842 vrp_int prod3 = max0 * max1;
1844 /* Sort the 4 products so that min is in prod0 and max is in
1845 prod3. */
1846 /* min0min1 > max0max1 */
1847 if (prod0 > prod3)
1848 std::swap (prod0, prod3);
1850 /* min0max1 > max0min1 */
1851 if (prod1 > prod2)
1852 std::swap (prod1, prod2);
1854 if (prod0 > prod1)
1855 std::swap (prod0, prod1);
1857 if (prod2 > prod3)
1858 std::swap (prod2, prod3);
1860 /* diff = max - min. */
1861 prod2 = prod3 - prod0;
1862 if (wi::geu_p (prod2, sizem1))
1864 /* the range covers all values. */
1865 set_value_range_to_varying (vr);
1866 return;
1869 /* The following should handle the wrapping and selecting
1870 VR_ANTI_RANGE for us. */
1871 min = wide_int_to_tree (expr_type, prod0);
1872 max = wide_int_to_tree (expr_type, prod3);
1873 set_and_canonicalize_value_range (vr, VR_RANGE, min, max, NULL);
1874 return;
1877 /* If we have an unsigned MULT_EXPR with two VR_ANTI_RANGEs,
1878 drop to VR_VARYING. It would take more effort to compute a
1879 precise range for such a case. For example, if we have
1880 op0 == 65536 and op1 == 65536 with their ranges both being
1881 ~[0,0] on a 32-bit machine, we would have op0 * op1 == 0, so
1882 we cannot claim that the product is in ~[0,0]. Note that we
1883 are guaranteed to have vr0.type == vr1.type at this
1884 point. */
1885 if (vr0.type == VR_ANTI_RANGE
1886 && !TYPE_OVERFLOW_UNDEFINED (expr_type))
1888 set_value_range_to_varying (vr);
1889 return;
1892 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
1893 return;
1895 else if (code == RSHIFT_EXPR
1896 || code == LSHIFT_EXPR)
1898 /* If we have a RSHIFT_EXPR with any shift values outside [0..prec-1],
1899 then drop to VR_VARYING. Outside of this range we get undefined
1900 behavior from the shift operation. We cannot even trust
1901 SHIFT_COUNT_TRUNCATED at this stage, because that applies to rtl
1902 shifts, and the operation at the tree level may be widened. */
1903 if (range_int_cst_p (&vr1)
1904 && compare_tree_int (vr1.min, 0) >= 0
1905 && compare_tree_int (vr1.max, TYPE_PRECISION (expr_type)) == -1)
1907 if (code == RSHIFT_EXPR)
1909 /* Even if vr0 is VARYING or otherwise not usable, we can derive
1910 useful ranges just from the shift count. E.g.
1911 x >> 63 for signed 64-bit x is always [-1, 0]. */
1912 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
1914 vr0.type = type = VR_RANGE;
1915 vr0.min = vrp_val_min (expr_type);
1916 vr0.max = vrp_val_max (expr_type);
1918 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
1919 return;
1921 /* We can map lshifts by constants to MULT_EXPR handling. */
1922 else if (code == LSHIFT_EXPR
1923 && range_int_cst_singleton_p (&vr1))
1925 bool saved_flag_wrapv;
1926 value_range vr1p = VR_INITIALIZER;
1927 vr1p.type = VR_RANGE;
1928 vr1p.min = (wide_int_to_tree
1929 (expr_type,
1930 wi::set_bit_in_zero (tree_to_shwi (vr1.min),
1931 TYPE_PRECISION (expr_type))));
1932 vr1p.max = vr1p.min;
1933 /* We have to use a wrapping multiply though as signed overflow
1934 on lshifts is implementation defined in C89. */
1935 saved_flag_wrapv = flag_wrapv;
1936 flag_wrapv = 1;
1937 extract_range_from_binary_expr_1 (vr, MULT_EXPR, expr_type,
1938 &vr0, &vr1p);
1939 flag_wrapv = saved_flag_wrapv;
1940 return;
1942 else if (code == LSHIFT_EXPR
1943 && range_int_cst_p (&vr0))
1945 int prec = TYPE_PRECISION (expr_type);
1946 int overflow_pos = prec;
1947 int bound_shift;
1948 wide_int low_bound, high_bound;
1949 bool uns = TYPE_UNSIGNED (expr_type);
1950 bool in_bounds = false;
1952 if (!uns)
1953 overflow_pos -= 1;
1955 bound_shift = overflow_pos - tree_to_shwi (vr1.max);
1956 /* If bound_shift == HOST_BITS_PER_WIDE_INT, the llshift can
1957 overflow. However, for that to happen, vr1.max needs to be
1958 zero, which means vr1 is a singleton range of zero, which
1959 means it should be handled by the previous LSHIFT_EXPR
1960 if-clause. */
1961 wide_int bound = wi::set_bit_in_zero (bound_shift, prec);
1962 wide_int complement = ~(bound - 1);
1964 if (uns)
1966 low_bound = bound;
1967 high_bound = complement;
1968 if (wi::ltu_p (wi::to_wide (vr0.max), low_bound))
1970 /* [5, 6] << [1, 2] == [10, 24]. */
1971 /* We're shifting out only zeroes, the value increases
1972 monotonically. */
1973 in_bounds = true;
1975 else if (wi::ltu_p (high_bound, wi::to_wide (vr0.min)))
1977 /* [0xffffff00, 0xffffffff] << [1, 2]
1978 == [0xfffffc00, 0xfffffffe]. */
1979 /* We're shifting out only ones, the value decreases
1980 monotonically. */
1981 in_bounds = true;
1984 else
1986 /* [-1, 1] << [1, 2] == [-4, 4]. */
1987 low_bound = complement;
1988 high_bound = bound;
1989 if (wi::lts_p (wi::to_wide (vr0.max), high_bound)
1990 && wi::lts_p (low_bound, wi::to_wide (vr0.min)))
1992 /* For non-negative numbers, we're shifting out only
1993 zeroes, the value increases monotonically.
1994 For negative numbers, we're shifting out only ones, the
1995 value decreases monotomically. */
1996 in_bounds = true;
2000 if (in_bounds)
2002 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2003 return;
2007 set_value_range_to_varying (vr);
2008 return;
2010 else if (code == TRUNC_DIV_EXPR
2011 || code == FLOOR_DIV_EXPR
2012 || code == CEIL_DIV_EXPR
2013 || code == EXACT_DIV_EXPR
2014 || code == ROUND_DIV_EXPR)
2016 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
2018 /* For division, if op1 has VR_RANGE but op0 does not, something
2019 can be deduced just from that range. Say [min, max] / [4, max]
2020 gives [min / 4, max / 4] range. */
2021 if (vr1.type == VR_RANGE
2022 && !symbolic_range_p (&vr1)
2023 && range_includes_zero_p (vr1.min, vr1.max) == 0)
2025 vr0.type = type = VR_RANGE;
2026 vr0.min = vrp_val_min (expr_type);
2027 vr0.max = vrp_val_max (expr_type);
2029 else
2031 set_value_range_to_varying (vr);
2032 return;
2036 /* For divisions, if flag_non_call_exceptions is true, we must
2037 not eliminate a division by zero. */
2038 if (cfun->can_throw_non_call_exceptions
2039 && (vr1.type != VR_RANGE
2040 || range_includes_zero_p (vr1.min, vr1.max) != 0))
2042 set_value_range_to_varying (vr);
2043 return;
2046 /* For divisions, if op0 is VR_RANGE, we can deduce a range
2047 even if op1 is VR_VARYING, VR_ANTI_RANGE, symbolic or can
2048 include 0. */
2049 if (vr0.type == VR_RANGE
2050 && (vr1.type != VR_RANGE
2051 || range_includes_zero_p (vr1.min, vr1.max) != 0))
2053 tree zero = build_int_cst (TREE_TYPE (vr0.min), 0);
2054 int cmp;
2056 min = NULL_TREE;
2057 max = NULL_TREE;
2058 if (TYPE_UNSIGNED (expr_type)
2059 || value_range_nonnegative_p (&vr1))
2061 /* For unsigned division or when divisor is known
2062 to be non-negative, the range has to cover
2063 all numbers from 0 to max for positive max
2064 and all numbers from min to 0 for negative min. */
2065 cmp = compare_values (vr0.max, zero);
2066 if (cmp == -1)
2068 /* When vr0.max < 0, vr1.min != 0 and value
2069 ranges for dividend and divisor are available. */
2070 if (vr1.type == VR_RANGE
2071 && !symbolic_range_p (&vr0)
2072 && !symbolic_range_p (&vr1)
2073 && compare_values (vr1.min, zero) != 0)
2074 max = int_const_binop (code, vr0.max, vr1.min);
2075 else
2076 max = zero;
2078 else if (cmp == 0 || cmp == 1)
2079 max = vr0.max;
2080 else
2081 type = VR_VARYING;
2082 cmp = compare_values (vr0.min, zero);
2083 if (cmp == 1)
2085 /* For unsigned division when value ranges for dividend
2086 and divisor are available. */
2087 if (vr1.type == VR_RANGE
2088 && !symbolic_range_p (&vr0)
2089 && !symbolic_range_p (&vr1)
2090 && compare_values (vr1.max, zero) != 0)
2091 min = int_const_binop (code, vr0.min, vr1.max);
2092 else
2093 min = zero;
2095 else if (cmp == 0 || cmp == -1)
2096 min = vr0.min;
2097 else
2098 type = VR_VARYING;
2100 else
2102 /* Otherwise the range is -max .. max or min .. -min
2103 depending on which bound is bigger in absolute value,
2104 as the division can change the sign. */
2105 abs_extent_range (vr, vr0.min, vr0.max);
2106 return;
2108 if (type == VR_VARYING)
2110 set_value_range_to_varying (vr);
2111 return;
2114 else if (range_int_cst_p (&vr0) && range_int_cst_p (&vr1))
2116 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2117 return;
2120 else if (code == TRUNC_MOD_EXPR)
2122 if (range_is_null (&vr1))
2124 set_value_range_to_undefined (vr);
2125 return;
2127 /* ABS (A % B) < ABS (B) and either
2128 0 <= A % B <= A or A <= A % B <= 0. */
2129 type = VR_RANGE;
2130 signop sgn = TYPE_SIGN (expr_type);
2131 unsigned int prec = TYPE_PRECISION (expr_type);
2132 wide_int wmin, wmax, tmp;
2133 if (vr1.type == VR_RANGE && !symbolic_range_p (&vr1))
2135 wmax = wi::to_wide (vr1.max) - 1;
2136 if (sgn == SIGNED)
2138 tmp = -1 - wi::to_wide (vr1.min);
2139 wmax = wi::smax (wmax, tmp);
2142 else
2144 wmax = wi::max_value (prec, sgn);
2145 /* X % INT_MIN may be INT_MAX. */
2146 if (sgn == UNSIGNED)
2147 wmax = wmax - 1;
2150 if (sgn == UNSIGNED)
2151 wmin = wi::zero (prec);
2152 else
2154 wmin = -wmax;
2155 if (vr0.type == VR_RANGE && TREE_CODE (vr0.min) == INTEGER_CST)
2157 tmp = wi::to_wide (vr0.min);
2158 if (wi::gts_p (tmp, 0))
2159 tmp = wi::zero (prec);
2160 wmin = wi::smax (wmin, tmp);
2164 if (vr0.type == VR_RANGE && TREE_CODE (vr0.max) == INTEGER_CST)
2166 tmp = wi::to_wide (vr0.max);
2167 if (sgn == SIGNED && wi::neg_p (tmp))
2168 tmp = wi::zero (prec);
2169 wmax = wi::min (wmax, tmp, sgn);
2172 min = wide_int_to_tree (expr_type, wmin);
2173 max = wide_int_to_tree (expr_type, wmax);
2175 else if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR || code == BIT_XOR_EXPR)
2177 bool int_cst_range0, int_cst_range1;
2178 wide_int may_be_nonzero0, may_be_nonzero1;
2179 wide_int must_be_nonzero0, must_be_nonzero1;
2181 int_cst_range0 = zero_nonzero_bits_from_vr (expr_type, &vr0,
2182 &may_be_nonzero0,
2183 &must_be_nonzero0);
2184 int_cst_range1 = zero_nonzero_bits_from_vr (expr_type, &vr1,
2185 &may_be_nonzero1,
2186 &must_be_nonzero1);
2188 if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR)
2190 value_range *vr0p = NULL, *vr1p = NULL;
2191 if (range_int_cst_singleton_p (&vr1))
2193 vr0p = &vr0;
2194 vr1p = &vr1;
2196 else if (range_int_cst_singleton_p (&vr0))
2198 vr0p = &vr1;
2199 vr1p = &vr0;
2201 /* For op & or | attempt to optimize:
2202 [x, y] op z into [x op z, y op z]
2203 if z is a constant which (for op | its bitwise not) has n
2204 consecutive least significant bits cleared followed by m 1
2205 consecutive bits set immediately above it and either
2206 m + n == precision, or (x >> (m + n)) == (y >> (m + n)).
2207 The least significant n bits of all the values in the range are
2208 cleared or set, the m bits above it are preserved and any bits
2209 above these are required to be the same for all values in the
2210 range. */
2211 if (vr0p && range_int_cst_p (vr0p))
2213 wide_int w = wi::to_wide (vr1p->min);
2214 int m = 0, n = 0;
2215 if (code == BIT_IOR_EXPR)
2216 w = ~w;
2217 if (wi::eq_p (w, 0))
2218 n = TYPE_PRECISION (expr_type);
2219 else
2221 n = wi::ctz (w);
2222 w = ~(w | wi::mask (n, false, w.get_precision ()));
2223 if (wi::eq_p (w, 0))
2224 m = TYPE_PRECISION (expr_type) - n;
2225 else
2226 m = wi::ctz (w) - n;
2228 wide_int mask = wi::mask (m + n, true, w.get_precision ());
2229 if ((mask & wi::to_wide (vr0p->min))
2230 == (mask & wi::to_wide (vr0p->max)))
2232 min = int_const_binop (code, vr0p->min, vr1p->min);
2233 max = int_const_binop (code, vr0p->max, vr1p->min);
2238 type = VR_RANGE;
2239 if (min && max)
2240 /* Optimized above already. */;
2241 else if (code == BIT_AND_EXPR)
2243 min = wide_int_to_tree (expr_type,
2244 must_be_nonzero0 & must_be_nonzero1);
2245 wide_int wmax = may_be_nonzero0 & may_be_nonzero1;
2246 /* If both input ranges contain only negative values we can
2247 truncate the result range maximum to the minimum of the
2248 input range maxima. */
2249 if (int_cst_range0 && int_cst_range1
2250 && tree_int_cst_sgn (vr0.max) < 0
2251 && tree_int_cst_sgn (vr1.max) < 0)
2253 wmax = wi::min (wmax, wi::to_wide (vr0.max),
2254 TYPE_SIGN (expr_type));
2255 wmax = wi::min (wmax, wi::to_wide (vr1.max),
2256 TYPE_SIGN (expr_type));
2258 /* If either input range contains only non-negative values
2259 we can truncate the result range maximum to the respective
2260 maximum of the input range. */
2261 if (int_cst_range0 && tree_int_cst_sgn (vr0.min) >= 0)
2262 wmax = wi::min (wmax, wi::to_wide (vr0.max),
2263 TYPE_SIGN (expr_type));
2264 if (int_cst_range1 && tree_int_cst_sgn (vr1.min) >= 0)
2265 wmax = wi::min (wmax, wi::to_wide (vr1.max),
2266 TYPE_SIGN (expr_type));
2267 max = wide_int_to_tree (expr_type, wmax);
2268 cmp = compare_values (min, max);
2269 /* PR68217: In case of signed & sign-bit-CST should
2270 result in [-INF, 0] instead of [-INF, INF]. */
2271 if (cmp == -2 || cmp == 1)
2273 wide_int sign_bit
2274 = wi::set_bit_in_zero (TYPE_PRECISION (expr_type) - 1,
2275 TYPE_PRECISION (expr_type));
2276 if (!TYPE_UNSIGNED (expr_type)
2277 && ((int_cst_range0
2278 && value_range_constant_singleton (&vr0)
2279 && !wi::cmps (wi::to_wide (vr0.min), sign_bit))
2280 || (int_cst_range1
2281 && value_range_constant_singleton (&vr1)
2282 && !wi::cmps (wi::to_wide (vr1.min), sign_bit))))
2284 min = TYPE_MIN_VALUE (expr_type);
2285 max = build_int_cst (expr_type, 0);
2289 else if (code == BIT_IOR_EXPR)
2291 max = wide_int_to_tree (expr_type,
2292 may_be_nonzero0 | may_be_nonzero1);
2293 wide_int wmin = must_be_nonzero0 | must_be_nonzero1;
2294 /* If the input ranges contain only positive values we can
2295 truncate the minimum of the result range to the maximum
2296 of the input range minima. */
2297 if (int_cst_range0 && int_cst_range1
2298 && tree_int_cst_sgn (vr0.min) >= 0
2299 && tree_int_cst_sgn (vr1.min) >= 0)
2301 wmin = wi::max (wmin, wi::to_wide (vr0.min),
2302 TYPE_SIGN (expr_type));
2303 wmin = wi::max (wmin, wi::to_wide (vr1.min),
2304 TYPE_SIGN (expr_type));
2306 /* If either input range contains only negative values
2307 we can truncate the minimum of the result range to the
2308 respective minimum range. */
2309 if (int_cst_range0 && tree_int_cst_sgn (vr0.max) < 0)
2310 wmin = wi::max (wmin, wi::to_wide (vr0.min),
2311 TYPE_SIGN (expr_type));
2312 if (int_cst_range1 && tree_int_cst_sgn (vr1.max) < 0)
2313 wmin = wi::max (wmin, wi::to_wide (vr1.min),
2314 TYPE_SIGN (expr_type));
2315 min = wide_int_to_tree (expr_type, wmin);
2317 else if (code == BIT_XOR_EXPR)
2319 wide_int result_zero_bits = ((must_be_nonzero0 & must_be_nonzero1)
2320 | ~(may_be_nonzero0 | may_be_nonzero1));
2321 wide_int result_one_bits
2322 = (wi::bit_and_not (must_be_nonzero0, may_be_nonzero1)
2323 | wi::bit_and_not (must_be_nonzero1, may_be_nonzero0));
2324 max = wide_int_to_tree (expr_type, ~result_zero_bits);
2325 min = wide_int_to_tree (expr_type, result_one_bits);
2326 /* If the range has all positive or all negative values the
2327 result is better than VARYING. */
2328 if (tree_int_cst_sgn (min) < 0
2329 || tree_int_cst_sgn (max) >= 0)
2331 else
2332 max = min = NULL_TREE;
2335 else
2336 gcc_unreachable ();
2338 /* If either MIN or MAX overflowed, then set the resulting range to
2339 VARYING. */
2340 if (min == NULL_TREE
2341 || TREE_OVERFLOW_P (min)
2342 || max == NULL_TREE
2343 || TREE_OVERFLOW_P (max))
2345 set_value_range_to_varying (vr);
2346 return;
2349 /* We punt for [-INF, +INF].
2350 We learn nothing when we have INF on both sides.
2351 Note that we do accept [-INF, -INF] and [+INF, +INF]. */
2352 if (vrp_val_is_min (min) && vrp_val_is_max (max))
2354 set_value_range_to_varying (vr);
2355 return;
2358 cmp = compare_values (min, max);
2359 if (cmp == -2 || cmp == 1)
2361 /* If the new range has its limits swapped around (MIN > MAX),
2362 then the operation caused one of them to wrap around, mark
2363 the new range VARYING. */
2364 set_value_range_to_varying (vr);
2366 else
2367 set_value_range (vr, type, min, max, NULL);
2370 /* Calculates the absolute value of a range and puts the result in VR.
2371 VR0 is the input range. TYPE is the type of the resulting
2372 range. */
2374 static void
2375 extract_range_from_abs_expr (value_range &vr, tree type, value_range &vr0)
2377 /* Pass through vr0 in the easy cases. */
2378 if (TYPE_UNSIGNED (type)
2379 || value_range_nonnegative_p (&vr0))
2381 copy_value_range (&vr, &vr0);
2382 return;
2385 /* For the remaining varying or symbolic ranges we can't do anything
2386 useful. */
2387 if (vr0.type == VR_VARYING
2388 || symbolic_range_p (&vr0))
2390 set_value_range_to_varying (&vr);
2391 return;
2394 /* -TYPE_MIN_VALUE = TYPE_MIN_VALUE with flag_wrapv so we can't get a
2395 useful range. */
2396 if (!TYPE_OVERFLOW_UNDEFINED (type)
2397 && ((vr0.type == VR_RANGE
2398 && vrp_val_is_min (vr0.min))
2399 || (vr0.type == VR_ANTI_RANGE
2400 && !vrp_val_is_min (vr0.min))))
2402 set_value_range_to_varying (&vr);
2403 return;
2406 /* ABS_EXPR may flip the range around, if the original range
2407 included negative values. */
2408 tree min, max;
2409 if (!vrp_val_is_min (vr0.min))
2410 min = fold_unary_to_constant (ABS_EXPR, type, vr0.min);
2411 else
2412 min = TYPE_MAX_VALUE (type);
2414 if (!vrp_val_is_min (vr0.max))
2415 max = fold_unary_to_constant (ABS_EXPR, type, vr0.max);
2416 else
2417 max = TYPE_MAX_VALUE (type);
2419 int cmp = compare_values (min, max);
2420 gcc_assert (vr0.type != VR_ANTI_RANGE);
2422 /* If the range contains zero then we know that the minimum value in the
2423 range will be zero. */
2424 if (range_includes_zero_p (vr0.min, vr0.max) == 1)
2426 if (cmp == 1)
2427 max = min;
2428 min = build_int_cst (type, 0);
2430 else
2432 /* If the range was reversed, swap MIN and MAX. */
2433 if (cmp == 1)
2434 std::swap (min, max);
2437 cmp = compare_values (min, max);
2438 if (cmp == -2 || cmp == 1)
2440 /* If the new range has its limits swapped around (MIN > MAX),
2441 then the operation caused one of them to wrap around, mark
2442 the new range VARYING. */
2443 set_value_range_to_varying (&vr);
2445 else
2446 set_value_range (&vr, vr0.type, min, max, NULL);
2449 /* Extract range information from a unary operation CODE based on
2450 the range of its operand *VR0 with type OP0_TYPE with resulting type TYPE.
2451 The resulting range is stored in *VR. */
2453 void
2454 extract_range_from_unary_expr (value_range *vr,
2455 enum tree_code code, tree type,
2456 value_range *vr0_, tree op0_type)
2458 value_range vr0 = *vr0_, vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
2460 /* VRP only operates on integral and pointer types. */
2461 if (!(INTEGRAL_TYPE_P (op0_type)
2462 || POINTER_TYPE_P (op0_type))
2463 || !(INTEGRAL_TYPE_P (type)
2464 || POINTER_TYPE_P (type)))
2466 set_value_range_to_varying (vr);
2467 return;
2470 /* If VR0 is UNDEFINED, so is the result. */
2471 if (vr0.type == VR_UNDEFINED)
2473 set_value_range_to_undefined (vr);
2474 return;
2477 /* Handle operations that we express in terms of others. */
2478 if (code == PAREN_EXPR || code == OBJ_TYPE_REF)
2480 /* PAREN_EXPR and OBJ_TYPE_REF are simple copies. */
2481 copy_value_range (vr, &vr0);
2482 return;
2484 else if (code == NEGATE_EXPR)
2486 /* -X is simply 0 - X, so re-use existing code that also handles
2487 anti-ranges fine. */
2488 value_range zero = VR_INITIALIZER;
2489 set_value_range_to_value (&zero, build_int_cst (type, 0), NULL);
2490 extract_range_from_binary_expr_1 (vr, MINUS_EXPR, type, &zero, &vr0);
2491 return;
2493 else if (code == BIT_NOT_EXPR)
2495 /* ~X is simply -1 - X, so re-use existing code that also handles
2496 anti-ranges fine. */
2497 value_range minusone = VR_INITIALIZER;
2498 set_value_range_to_value (&minusone, build_int_cst (type, -1), NULL);
2499 extract_range_from_binary_expr_1 (vr, MINUS_EXPR,
2500 type, &minusone, &vr0);
2501 return;
2504 /* Now canonicalize anti-ranges to ranges when they are not symbolic
2505 and express op ~[] as (op []') U (op []''). */
2506 if (vr0.type == VR_ANTI_RANGE
2507 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
2509 extract_range_from_unary_expr (vr, code, type, &vrtem0, op0_type);
2510 if (vrtem1.type != VR_UNDEFINED)
2512 value_range vrres = VR_INITIALIZER;
2513 extract_range_from_unary_expr (&vrres, code, type,
2514 &vrtem1, op0_type);
2515 vrp_meet (vr, &vrres);
2517 return;
2520 if (CONVERT_EXPR_CODE_P (code))
2522 tree inner_type = op0_type;
2523 tree outer_type = type;
2525 /* If the expression evaluates to a pointer, we are only interested in
2526 determining if it evaluates to NULL [0, 0] or non-NULL (~[0, 0]). */
2527 if (POINTER_TYPE_P (type))
2529 if (range_is_nonnull (&vr0))
2530 set_value_range_to_nonnull (vr, type);
2531 else if (range_is_null (&vr0))
2532 set_value_range_to_null (vr, type);
2533 else
2534 set_value_range_to_varying (vr);
2535 return;
2538 /* If VR0 is varying and we increase the type precision, assume
2539 a full range for the following transformation. */
2540 if (vr0.type == VR_VARYING
2541 && INTEGRAL_TYPE_P (inner_type)
2542 && TYPE_PRECISION (inner_type) < TYPE_PRECISION (outer_type))
2544 vr0.type = VR_RANGE;
2545 vr0.min = TYPE_MIN_VALUE (inner_type);
2546 vr0.max = TYPE_MAX_VALUE (inner_type);
2549 /* If VR0 is a constant range or anti-range and the conversion is
2550 not truncating we can convert the min and max values and
2551 canonicalize the resulting range. Otherwise we can do the
2552 conversion if the size of the range is less than what the
2553 precision of the target type can represent and the range is
2554 not an anti-range. */
2555 if ((vr0.type == VR_RANGE
2556 || vr0.type == VR_ANTI_RANGE)
2557 && TREE_CODE (vr0.min) == INTEGER_CST
2558 && TREE_CODE (vr0.max) == INTEGER_CST
2559 && (TYPE_PRECISION (outer_type) >= TYPE_PRECISION (inner_type)
2560 || (vr0.type == VR_RANGE
2561 && integer_zerop (int_const_binop (RSHIFT_EXPR,
2562 int_const_binop (MINUS_EXPR, vr0.max, vr0.min),
2563 size_int (TYPE_PRECISION (outer_type)))))))
2565 tree new_min, new_max;
2566 new_min = force_fit_type (outer_type, wi::to_widest (vr0.min),
2567 0, false);
2568 new_max = force_fit_type (outer_type, wi::to_widest (vr0.max),
2569 0, false);
2570 set_and_canonicalize_value_range (vr, vr0.type,
2571 new_min, new_max, NULL);
2572 return;
2575 set_value_range_to_varying (vr);
2576 return;
2578 else if (code == ABS_EXPR)
2579 return extract_range_from_abs_expr (*vr, type, vr0);
2581 /* For unhandled operations fall back to varying. */
2582 set_value_range_to_varying (vr);
2583 return;
2586 /* Debugging dumps. */
2588 void dump_value_range (FILE *, const value_range *);
2589 void debug_value_range (value_range *);
2590 void dump_all_value_ranges (FILE *);
2591 void dump_vr_equiv (FILE *, bitmap);
2592 void debug_vr_equiv (bitmap);
2595 /* Dump value range VR to FILE. */
2597 void
2598 dump_value_range (FILE *file, const value_range *vr)
2600 if (vr == NULL)
2601 fprintf (file, "[]");
2602 else if (vr->type == VR_UNDEFINED)
2603 fprintf (file, "UNDEFINED");
2604 else if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
2606 tree type = TREE_TYPE (vr->min);
2608 fprintf (file, "%s[", (vr->type == VR_ANTI_RANGE) ? "~" : "");
2610 if (INTEGRAL_TYPE_P (type)
2611 && !TYPE_UNSIGNED (type)
2612 && vrp_val_is_min (vr->min))
2613 fprintf (file, "-INF");
2614 else
2615 print_generic_expr (file, vr->min);
2617 fprintf (file, ", ");
2619 if (INTEGRAL_TYPE_P (type)
2620 && vrp_val_is_max (vr->max))
2621 fprintf (file, "+INF");
2622 else
2623 print_generic_expr (file, vr->max);
2625 fprintf (file, "]");
2627 if (vr->equiv)
2629 bitmap_iterator bi;
2630 unsigned i, c = 0;
2632 fprintf (file, " EQUIVALENCES: { ");
2634 EXECUTE_IF_SET_IN_BITMAP (vr->equiv, 0, i, bi)
2636 print_generic_expr (file, ssa_name (i));
2637 fprintf (file, " ");
2638 c++;
2641 fprintf (file, "} (%u elements)", c);
2644 else if (vr->type == VR_VARYING)
2645 fprintf (file, "VARYING");
2646 else
2647 fprintf (file, "INVALID RANGE");
2651 /* Dump value range VR to stderr. */
2653 DEBUG_FUNCTION void
2654 debug_value_range (value_range *vr)
2656 dump_value_range (stderr, vr);
2657 fprintf (stderr, "\n");
2661 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
2662 create a new SSA name N and return the assertion assignment
2663 'N = ASSERT_EXPR <V, V OP W>'. */
2665 static gimple *
2666 build_assert_expr_for (tree cond, tree v)
2668 tree a;
2669 gassign *assertion;
2671 gcc_assert (TREE_CODE (v) == SSA_NAME
2672 && COMPARISON_CLASS_P (cond));
2674 a = build2 (ASSERT_EXPR, TREE_TYPE (v), v, cond);
2675 assertion = gimple_build_assign (NULL_TREE, a);
2677 /* The new ASSERT_EXPR, creates a new SSA name that replaces the
2678 operand of the ASSERT_EXPR. Create it so the new name and the old one
2679 are registered in the replacement table so that we can fix the SSA web
2680 after adding all the ASSERT_EXPRs. */
2681 tree new_def = create_new_def_for (v, assertion, NULL);
2682 /* Make sure we preserve abnormalness throughout an ASSERT_EXPR chain
2683 given we have to be able to fully propagate those out to re-create
2684 valid SSA when removing the asserts. */
2685 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (v))
2686 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_def) = 1;
2688 return assertion;
2692 /* Return false if EXPR is a predicate expression involving floating
2693 point values. */
2695 static inline bool
2696 fp_predicate (gimple *stmt)
2698 GIMPLE_CHECK (stmt, GIMPLE_COND);
2700 return FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)));
2703 /* If the range of values taken by OP can be inferred after STMT executes,
2704 return the comparison code (COMP_CODE_P) and value (VAL_P) that
2705 describes the inferred range. Return true if a range could be
2706 inferred. */
2708 bool
2709 infer_value_range (gimple *stmt, tree op, tree_code *comp_code_p, tree *val_p)
2711 *val_p = NULL_TREE;
2712 *comp_code_p = ERROR_MARK;
2714 /* Do not attempt to infer anything in names that flow through
2715 abnormal edges. */
2716 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
2717 return false;
2719 /* If STMT is the last statement of a basic block with no normal
2720 successors, there is no point inferring anything about any of its
2721 operands. We would not be able to find a proper insertion point
2722 for the assertion, anyway. */
2723 if (stmt_ends_bb_p (stmt))
2725 edge_iterator ei;
2726 edge e;
2728 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
2729 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
2730 break;
2731 if (e == NULL)
2732 return false;
2735 if (infer_nonnull_range (stmt, op))
2737 *val_p = build_int_cst (TREE_TYPE (op), 0);
2738 *comp_code_p = NE_EXPR;
2739 return true;
2742 return false;
2746 void dump_asserts_for (FILE *, tree);
2747 void debug_asserts_for (tree);
2748 void dump_all_asserts (FILE *);
2749 void debug_all_asserts (void);
2751 /* Dump all the registered assertions for NAME to FILE. */
2753 void
2754 dump_asserts_for (FILE *file, tree name)
2756 assert_locus *loc;
2758 fprintf (file, "Assertions to be inserted for ");
2759 print_generic_expr (file, name);
2760 fprintf (file, "\n");
2762 loc = asserts_for[SSA_NAME_VERSION (name)];
2763 while (loc)
2765 fprintf (file, "\t");
2766 print_gimple_stmt (file, gsi_stmt (loc->si), 0);
2767 fprintf (file, "\n\tBB #%d", loc->bb->index);
2768 if (loc->e)
2770 fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
2771 loc->e->dest->index);
2772 dump_edge_info (file, loc->e, dump_flags, 0);
2774 fprintf (file, "\n\tPREDICATE: ");
2775 print_generic_expr (file, loc->expr);
2776 fprintf (file, " %s ", get_tree_code_name (loc->comp_code));
2777 print_generic_expr (file, loc->val);
2778 fprintf (file, "\n\n");
2779 loc = loc->next;
2782 fprintf (file, "\n");
2786 /* Dump all the registered assertions for NAME to stderr. */
2788 DEBUG_FUNCTION void
2789 debug_asserts_for (tree name)
2791 dump_asserts_for (stderr, name);
2795 /* Dump all the registered assertions for all the names to FILE. */
2797 void
2798 dump_all_asserts (FILE *file)
2800 unsigned i;
2801 bitmap_iterator bi;
2803 fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
2804 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
2805 dump_asserts_for (file, ssa_name (i));
2806 fprintf (file, "\n");
2810 /* Dump all the registered assertions for all the names to stderr. */
2812 DEBUG_FUNCTION void
2813 debug_all_asserts (void)
2815 dump_all_asserts (stderr);
2818 /* Push the assert info for NAME, EXPR, COMP_CODE and VAL to ASSERTS. */
2820 static void
2821 add_assert_info (vec<assert_info> &asserts,
2822 tree name, tree expr, enum tree_code comp_code, tree val)
2824 assert_info info;
2825 info.comp_code = comp_code;
2826 info.name = name;
2827 if (TREE_OVERFLOW_P (val))
2828 val = drop_tree_overflow (val);
2829 info.val = val;
2830 info.expr = expr;
2831 asserts.safe_push (info);
2834 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
2835 'EXPR COMP_CODE VAL' at a location that dominates block BB or
2836 E->DEST, then register this location as a possible insertion point
2837 for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
2839 BB, E and SI provide the exact insertion point for the new
2840 ASSERT_EXPR. If BB is NULL, then the ASSERT_EXPR is to be inserted
2841 on edge E. Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
2842 BB. If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
2843 must not be NULL. */
2845 static void
2846 register_new_assert_for (tree name, tree expr,
2847 enum tree_code comp_code,
2848 tree val,
2849 basic_block bb,
2850 edge e,
2851 gimple_stmt_iterator si)
2853 assert_locus *n, *loc, *last_loc;
2854 basic_block dest_bb;
2856 gcc_checking_assert (bb == NULL || e == NULL);
2858 if (e == NULL)
2859 gcc_checking_assert (gimple_code (gsi_stmt (si)) != GIMPLE_COND
2860 && gimple_code (gsi_stmt (si)) != GIMPLE_SWITCH);
2862 /* Never build an assert comparing against an integer constant with
2863 TREE_OVERFLOW set. This confuses our undefined overflow warning
2864 machinery. */
2865 if (TREE_OVERFLOW_P (val))
2866 val = drop_tree_overflow (val);
2868 /* The new assertion A will be inserted at BB or E. We need to
2869 determine if the new location is dominated by a previously
2870 registered location for A. If we are doing an edge insertion,
2871 assume that A will be inserted at E->DEST. Note that this is not
2872 necessarily true.
2874 If E is a critical edge, it will be split. But even if E is
2875 split, the new block will dominate the same set of blocks that
2876 E->DEST dominates.
2878 The reverse, however, is not true, blocks dominated by E->DEST
2879 will not be dominated by the new block created to split E. So,
2880 if the insertion location is on a critical edge, we will not use
2881 the new location to move another assertion previously registered
2882 at a block dominated by E->DEST. */
2883 dest_bb = (bb) ? bb : e->dest;
2885 /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
2886 VAL at a block dominating DEST_BB, then we don't need to insert a new
2887 one. Similarly, if the same assertion already exists at a block
2888 dominated by DEST_BB and the new location is not on a critical
2889 edge, then update the existing location for the assertion (i.e.,
2890 move the assertion up in the dominance tree).
2892 Note, this is implemented as a simple linked list because there
2893 should not be more than a handful of assertions registered per
2894 name. If this becomes a performance problem, a table hashed by
2895 COMP_CODE and VAL could be implemented. */
2896 loc = asserts_for[SSA_NAME_VERSION (name)];
2897 last_loc = loc;
2898 while (loc)
2900 if (loc->comp_code == comp_code
2901 && (loc->val == val
2902 || operand_equal_p (loc->val, val, 0))
2903 && (loc->expr == expr
2904 || operand_equal_p (loc->expr, expr, 0)))
2906 /* If E is not a critical edge and DEST_BB
2907 dominates the existing location for the assertion, move
2908 the assertion up in the dominance tree by updating its
2909 location information. */
2910 if ((e == NULL || !EDGE_CRITICAL_P (e))
2911 && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
2913 loc->bb = dest_bb;
2914 loc->e = e;
2915 loc->si = si;
2916 return;
2920 /* Update the last node of the list and move to the next one. */
2921 last_loc = loc;
2922 loc = loc->next;
2925 /* If we didn't find an assertion already registered for
2926 NAME COMP_CODE VAL, add a new one at the end of the list of
2927 assertions associated with NAME. */
2928 n = XNEW (struct assert_locus);
2929 n->bb = dest_bb;
2930 n->e = e;
2931 n->si = si;
2932 n->comp_code = comp_code;
2933 n->val = val;
2934 n->expr = expr;
2935 n->next = NULL;
2937 if (last_loc)
2938 last_loc->next = n;
2939 else
2940 asserts_for[SSA_NAME_VERSION (name)] = n;
2942 bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
2945 /* (COND_OP0 COND_CODE COND_OP1) is a predicate which uses NAME.
2946 Extract a suitable test code and value and store them into *CODE_P and
2947 *VAL_P so the predicate is normalized to NAME *CODE_P *VAL_P.
2949 If no extraction was possible, return FALSE, otherwise return TRUE.
2951 If INVERT is true, then we invert the result stored into *CODE_P. */
2953 static bool
2954 extract_code_and_val_from_cond_with_ops (tree name, enum tree_code cond_code,
2955 tree cond_op0, tree cond_op1,
2956 bool invert, enum tree_code *code_p,
2957 tree *val_p)
2959 enum tree_code comp_code;
2960 tree val;
2962 /* Otherwise, we have a comparison of the form NAME COMP VAL
2963 or VAL COMP NAME. */
2964 if (name == cond_op1)
2966 /* If the predicate is of the form VAL COMP NAME, flip
2967 COMP around because we need to register NAME as the
2968 first operand in the predicate. */
2969 comp_code = swap_tree_comparison (cond_code);
2970 val = cond_op0;
2972 else if (name == cond_op0)
2974 /* The comparison is of the form NAME COMP VAL, so the
2975 comparison code remains unchanged. */
2976 comp_code = cond_code;
2977 val = cond_op1;
2979 else
2980 gcc_unreachable ();
2982 /* Invert the comparison code as necessary. */
2983 if (invert)
2984 comp_code = invert_tree_comparison (comp_code, 0);
2986 /* VRP only handles integral and pointer types. */
2987 if (! INTEGRAL_TYPE_P (TREE_TYPE (val))
2988 && ! POINTER_TYPE_P (TREE_TYPE (val)))
2989 return false;
2991 /* Do not register always-false predicates.
2992 FIXME: this works around a limitation in fold() when dealing with
2993 enumerations. Given 'enum { N1, N2 } x;', fold will not
2994 fold 'if (x > N2)' to 'if (0)'. */
2995 if ((comp_code == GT_EXPR || comp_code == LT_EXPR)
2996 && INTEGRAL_TYPE_P (TREE_TYPE (val)))
2998 tree min = TYPE_MIN_VALUE (TREE_TYPE (val));
2999 tree max = TYPE_MAX_VALUE (TREE_TYPE (val));
3001 if (comp_code == GT_EXPR
3002 && (!max
3003 || compare_values (val, max) == 0))
3004 return false;
3006 if (comp_code == LT_EXPR
3007 && (!min
3008 || compare_values (val, min) == 0))
3009 return false;
3011 *code_p = comp_code;
3012 *val_p = val;
3013 return true;
3016 /* Find out smallest RES where RES > VAL && (RES & MASK) == RES, if any
3017 (otherwise return VAL). VAL and MASK must be zero-extended for
3018 precision PREC. If SGNBIT is non-zero, first xor VAL with SGNBIT
3019 (to transform signed values into unsigned) and at the end xor
3020 SGNBIT back. */
3022 static wide_int
3023 masked_increment (const wide_int &val_in, const wide_int &mask,
3024 const wide_int &sgnbit, unsigned int prec)
3026 wide_int bit = wi::one (prec), res;
3027 unsigned int i;
3029 wide_int val = val_in ^ sgnbit;
3030 for (i = 0; i < prec; i++, bit += bit)
3032 res = mask;
3033 if ((res & bit) == 0)
3034 continue;
3035 res = bit - 1;
3036 res = wi::bit_and_not (val + bit, res);
3037 res &= mask;
3038 if (wi::gtu_p (res, val))
3039 return res ^ sgnbit;
3041 return val ^ sgnbit;
3044 /* Helper for overflow_comparison_p
3046 OP0 CODE OP1 is a comparison. Examine the comparison and potentially
3047 OP1's defining statement to see if it ultimately has the form
3048 OP0 CODE (OP0 PLUS INTEGER_CST)
3050 If so, return TRUE indicating this is an overflow test and store into
3051 *NEW_CST an updated constant that can be used in a narrowed range test.
3053 REVERSED indicates if the comparison was originally:
3055 OP1 CODE' OP0.
3057 This affects how we build the updated constant. */
3059 static bool
3060 overflow_comparison_p_1 (enum tree_code code, tree op0, tree op1,
3061 bool follow_assert_exprs, bool reversed, tree *new_cst)
3063 /* See if this is a relational operation between two SSA_NAMES with
3064 unsigned, overflow wrapping values. If so, check it more deeply. */
3065 if ((code == LT_EXPR || code == LE_EXPR
3066 || code == GE_EXPR || code == GT_EXPR)
3067 && TREE_CODE (op0) == SSA_NAME
3068 && TREE_CODE (op1) == SSA_NAME
3069 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
3070 && TYPE_UNSIGNED (TREE_TYPE (op0))
3071 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0)))
3073 gimple *op1_def = SSA_NAME_DEF_STMT (op1);
3075 /* If requested, follow any ASSERT_EXPRs backwards for OP1. */
3076 if (follow_assert_exprs)
3078 while (gimple_assign_single_p (op1_def)
3079 && TREE_CODE (gimple_assign_rhs1 (op1_def)) == ASSERT_EXPR)
3081 op1 = TREE_OPERAND (gimple_assign_rhs1 (op1_def), 0);
3082 if (TREE_CODE (op1) != SSA_NAME)
3083 break;
3084 op1_def = SSA_NAME_DEF_STMT (op1);
3088 /* Now look at the defining statement of OP1 to see if it adds
3089 or subtracts a nonzero constant from another operand. */
3090 if (op1_def
3091 && is_gimple_assign (op1_def)
3092 && gimple_assign_rhs_code (op1_def) == PLUS_EXPR
3093 && TREE_CODE (gimple_assign_rhs2 (op1_def)) == INTEGER_CST
3094 && !integer_zerop (gimple_assign_rhs2 (op1_def)))
3096 tree target = gimple_assign_rhs1 (op1_def);
3098 /* If requested, follow ASSERT_EXPRs backwards for op0 looking
3099 for one where TARGET appears on the RHS. */
3100 if (follow_assert_exprs)
3102 /* Now see if that "other operand" is op0, following the chain
3103 of ASSERT_EXPRs if necessary. */
3104 gimple *op0_def = SSA_NAME_DEF_STMT (op0);
3105 while (op0 != target
3106 && gimple_assign_single_p (op0_def)
3107 && TREE_CODE (gimple_assign_rhs1 (op0_def)) == ASSERT_EXPR)
3109 op0 = TREE_OPERAND (gimple_assign_rhs1 (op0_def), 0);
3110 if (TREE_CODE (op0) != SSA_NAME)
3111 break;
3112 op0_def = SSA_NAME_DEF_STMT (op0);
3116 /* If we did not find our target SSA_NAME, then this is not
3117 an overflow test. */
3118 if (op0 != target)
3119 return false;
3121 tree type = TREE_TYPE (op0);
3122 wide_int max = wi::max_value (TYPE_PRECISION (type), UNSIGNED);
3123 tree inc = gimple_assign_rhs2 (op1_def);
3124 if (reversed)
3125 *new_cst = wide_int_to_tree (type, max + wi::to_wide (inc));
3126 else
3127 *new_cst = wide_int_to_tree (type, max - wi::to_wide (inc));
3128 return true;
3131 return false;
3134 /* OP0 CODE OP1 is a comparison. Examine the comparison and potentially
3135 OP1's defining statement to see if it ultimately has the form
3136 OP0 CODE (OP0 PLUS INTEGER_CST)
3138 If so, return TRUE indicating this is an overflow test and store into
3139 *NEW_CST an updated constant that can be used in a narrowed range test.
3141 These statements are left as-is in the IL to facilitate discovery of
3142 {ADD,SUB}_OVERFLOW sequences later in the optimizer pipeline. But
3143 the alternate range representation is often useful within VRP. */
3145 bool
3146 overflow_comparison_p (tree_code code, tree name, tree val,
3147 bool use_equiv_p, tree *new_cst)
3149 if (overflow_comparison_p_1 (code, name, val, use_equiv_p, false, new_cst))
3150 return true;
3151 return overflow_comparison_p_1 (swap_tree_comparison (code), val, name,
3152 use_equiv_p, true, new_cst);
3156 /* Try to register an edge assertion for SSA name NAME on edge E for
3157 the condition COND contributing to the conditional jump pointed to by BSI.
3158 Invert the condition COND if INVERT is true. */
3160 static void
3161 register_edge_assert_for_2 (tree name, edge e,
3162 enum tree_code cond_code,
3163 tree cond_op0, tree cond_op1, bool invert,
3164 vec<assert_info> &asserts)
3166 tree val;
3167 enum tree_code comp_code;
3169 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
3170 cond_op0,
3171 cond_op1,
3172 invert, &comp_code, &val))
3173 return;
3175 /* Queue the assert. */
3176 tree x;
3177 if (overflow_comparison_p (comp_code, name, val, false, &x))
3179 enum tree_code new_code = ((comp_code == GT_EXPR || comp_code == GE_EXPR)
3180 ? GT_EXPR : LE_EXPR);
3181 add_assert_info (asserts, name, name, new_code, x);
3183 add_assert_info (asserts, name, name, comp_code, val);
3185 /* In the case of NAME <= CST and NAME being defined as
3186 NAME = (unsigned) NAME2 + CST2 we can assert NAME2 >= -CST2
3187 and NAME2 <= CST - CST2. We can do the same for NAME > CST.
3188 This catches range and anti-range tests. */
3189 if ((comp_code == LE_EXPR
3190 || comp_code == GT_EXPR)
3191 && TREE_CODE (val) == INTEGER_CST
3192 && TYPE_UNSIGNED (TREE_TYPE (val)))
3194 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3195 tree cst2 = NULL_TREE, name2 = NULL_TREE, name3 = NULL_TREE;
3197 /* Extract CST2 from the (optional) addition. */
3198 if (is_gimple_assign (def_stmt)
3199 && gimple_assign_rhs_code (def_stmt) == PLUS_EXPR)
3201 name2 = gimple_assign_rhs1 (def_stmt);
3202 cst2 = gimple_assign_rhs2 (def_stmt);
3203 if (TREE_CODE (name2) == SSA_NAME
3204 && TREE_CODE (cst2) == INTEGER_CST)
3205 def_stmt = SSA_NAME_DEF_STMT (name2);
3208 /* Extract NAME2 from the (optional) sign-changing cast. */
3209 if (gimple_assign_cast_p (def_stmt))
3211 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt))
3212 && ! TYPE_UNSIGNED (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
3213 && (TYPE_PRECISION (gimple_expr_type (def_stmt))
3214 == TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))))
3215 name3 = gimple_assign_rhs1 (def_stmt);
3218 /* If name3 is used later, create an ASSERT_EXPR for it. */
3219 if (name3 != NULL_TREE
3220 && TREE_CODE (name3) == SSA_NAME
3221 && (cst2 == NULL_TREE
3222 || TREE_CODE (cst2) == INTEGER_CST)
3223 && INTEGRAL_TYPE_P (TREE_TYPE (name3)))
3225 tree tmp;
3227 /* Build an expression for the range test. */
3228 tmp = build1 (NOP_EXPR, TREE_TYPE (name), name3);
3229 if (cst2 != NULL_TREE)
3230 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
3232 if (dump_file)
3234 fprintf (dump_file, "Adding assert for ");
3235 print_generic_expr (dump_file, name3);
3236 fprintf (dump_file, " from ");
3237 print_generic_expr (dump_file, tmp);
3238 fprintf (dump_file, "\n");
3241 add_assert_info (asserts, name3, tmp, comp_code, val);
3244 /* If name2 is used later, create an ASSERT_EXPR for it. */
3245 if (name2 != NULL_TREE
3246 && TREE_CODE (name2) == SSA_NAME
3247 && TREE_CODE (cst2) == INTEGER_CST
3248 && INTEGRAL_TYPE_P (TREE_TYPE (name2)))
3250 tree tmp;
3252 /* Build an expression for the range test. */
3253 tmp = name2;
3254 if (TREE_TYPE (name) != TREE_TYPE (name2))
3255 tmp = build1 (NOP_EXPR, TREE_TYPE (name), tmp);
3256 if (cst2 != NULL_TREE)
3257 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
3259 if (dump_file)
3261 fprintf (dump_file, "Adding assert for ");
3262 print_generic_expr (dump_file, name2);
3263 fprintf (dump_file, " from ");
3264 print_generic_expr (dump_file, tmp);
3265 fprintf (dump_file, "\n");
3268 add_assert_info (asserts, name2, tmp, comp_code, val);
3272 /* In the case of post-in/decrement tests like if (i++) ... and uses
3273 of the in/decremented value on the edge the extra name we want to
3274 assert for is not on the def chain of the name compared. Instead
3275 it is in the set of use stmts.
3276 Similar cases happen for conversions that were simplified through
3277 fold_{sign_changed,widened}_comparison. */
3278 if ((comp_code == NE_EXPR
3279 || comp_code == EQ_EXPR)
3280 && TREE_CODE (val) == INTEGER_CST)
3282 imm_use_iterator ui;
3283 gimple *use_stmt;
3284 FOR_EACH_IMM_USE_STMT (use_stmt, ui, name)
3286 if (!is_gimple_assign (use_stmt))
3287 continue;
3289 /* Cut off to use-stmts that are dominating the predecessor. */
3290 if (!dominated_by_p (CDI_DOMINATORS, e->src, gimple_bb (use_stmt)))
3291 continue;
3293 tree name2 = gimple_assign_lhs (use_stmt);
3294 if (TREE_CODE (name2) != SSA_NAME)
3295 continue;
3297 enum tree_code code = gimple_assign_rhs_code (use_stmt);
3298 tree cst;
3299 if (code == PLUS_EXPR
3300 || code == MINUS_EXPR)
3302 cst = gimple_assign_rhs2 (use_stmt);
3303 if (TREE_CODE (cst) != INTEGER_CST)
3304 continue;
3305 cst = int_const_binop (code, val, cst);
3307 else if (CONVERT_EXPR_CODE_P (code))
3309 /* For truncating conversions we cannot record
3310 an inequality. */
3311 if (comp_code == NE_EXPR
3312 && (TYPE_PRECISION (TREE_TYPE (name2))
3313 < TYPE_PRECISION (TREE_TYPE (name))))
3314 continue;
3315 cst = fold_convert (TREE_TYPE (name2), val);
3317 else
3318 continue;
3320 if (TREE_OVERFLOW_P (cst))
3321 cst = drop_tree_overflow (cst);
3322 add_assert_info (asserts, name2, name2, comp_code, cst);
3326 if (TREE_CODE_CLASS (comp_code) == tcc_comparison
3327 && TREE_CODE (val) == INTEGER_CST)
3329 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3330 tree name2 = NULL_TREE, names[2], cst2 = NULL_TREE;
3331 tree val2 = NULL_TREE;
3332 unsigned int prec = TYPE_PRECISION (TREE_TYPE (val));
3333 wide_int mask = wi::zero (prec);
3334 unsigned int nprec = prec;
3335 enum tree_code rhs_code = ERROR_MARK;
3337 if (is_gimple_assign (def_stmt))
3338 rhs_code = gimple_assign_rhs_code (def_stmt);
3340 /* In the case of NAME != CST1 where NAME = A +- CST2 we can
3341 assert that A != CST1 -+ CST2. */
3342 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
3343 && (rhs_code == PLUS_EXPR || rhs_code == MINUS_EXPR))
3345 tree op0 = gimple_assign_rhs1 (def_stmt);
3346 tree op1 = gimple_assign_rhs2 (def_stmt);
3347 if (TREE_CODE (op0) == SSA_NAME
3348 && TREE_CODE (op1) == INTEGER_CST)
3350 enum tree_code reverse_op = (rhs_code == PLUS_EXPR
3351 ? MINUS_EXPR : PLUS_EXPR);
3352 op1 = int_const_binop (reverse_op, val, op1);
3353 if (TREE_OVERFLOW (op1))
3354 op1 = drop_tree_overflow (op1);
3355 add_assert_info (asserts, op0, op0, comp_code, op1);
3359 /* Add asserts for NAME cmp CST and NAME being defined
3360 as NAME = (int) NAME2. */
3361 if (!TYPE_UNSIGNED (TREE_TYPE (val))
3362 && (comp_code == LE_EXPR || comp_code == LT_EXPR
3363 || comp_code == GT_EXPR || comp_code == GE_EXPR)
3364 && gimple_assign_cast_p (def_stmt))
3366 name2 = gimple_assign_rhs1 (def_stmt);
3367 if (CONVERT_EXPR_CODE_P (rhs_code)
3368 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
3369 && TYPE_UNSIGNED (TREE_TYPE (name2))
3370 && prec == TYPE_PRECISION (TREE_TYPE (name2))
3371 && (comp_code == LE_EXPR || comp_code == GT_EXPR
3372 || !tree_int_cst_equal (val,
3373 TYPE_MIN_VALUE (TREE_TYPE (val)))))
3375 tree tmp, cst;
3376 enum tree_code new_comp_code = comp_code;
3378 cst = fold_convert (TREE_TYPE (name2),
3379 TYPE_MIN_VALUE (TREE_TYPE (val)));
3380 /* Build an expression for the range test. */
3381 tmp = build2 (PLUS_EXPR, TREE_TYPE (name2), name2, cst);
3382 cst = fold_build2 (PLUS_EXPR, TREE_TYPE (name2), cst,
3383 fold_convert (TREE_TYPE (name2), val));
3384 if (comp_code == LT_EXPR || comp_code == GE_EXPR)
3386 new_comp_code = comp_code == LT_EXPR ? LE_EXPR : GT_EXPR;
3387 cst = fold_build2 (MINUS_EXPR, TREE_TYPE (name2), cst,
3388 build_int_cst (TREE_TYPE (name2), 1));
3391 if (dump_file)
3393 fprintf (dump_file, "Adding assert for ");
3394 print_generic_expr (dump_file, name2);
3395 fprintf (dump_file, " from ");
3396 print_generic_expr (dump_file, tmp);
3397 fprintf (dump_file, "\n");
3400 add_assert_info (asserts, name2, tmp, new_comp_code, cst);
3404 /* Add asserts for NAME cmp CST and NAME being defined as
3405 NAME = NAME2 >> CST2.
3407 Extract CST2 from the right shift. */
3408 if (rhs_code == RSHIFT_EXPR)
3410 name2 = gimple_assign_rhs1 (def_stmt);
3411 cst2 = gimple_assign_rhs2 (def_stmt);
3412 if (TREE_CODE (name2) == SSA_NAME
3413 && tree_fits_uhwi_p (cst2)
3414 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
3415 && IN_RANGE (tree_to_uhwi (cst2), 1, prec - 1)
3416 && type_has_mode_precision_p (TREE_TYPE (val)))
3418 mask = wi::mask (tree_to_uhwi (cst2), false, prec);
3419 val2 = fold_binary (LSHIFT_EXPR, TREE_TYPE (val), val, cst2);
3422 if (val2 != NULL_TREE
3423 && TREE_CODE (val2) == INTEGER_CST
3424 && simple_cst_equal (fold_build2 (RSHIFT_EXPR,
3425 TREE_TYPE (val),
3426 val2, cst2), val))
3428 enum tree_code new_comp_code = comp_code;
3429 tree tmp, new_val;
3431 tmp = name2;
3432 if (comp_code == EQ_EXPR || comp_code == NE_EXPR)
3434 if (!TYPE_UNSIGNED (TREE_TYPE (val)))
3436 tree type = build_nonstandard_integer_type (prec, 1);
3437 tmp = build1 (NOP_EXPR, type, name2);
3438 val2 = fold_convert (type, val2);
3440 tmp = fold_build2 (MINUS_EXPR, TREE_TYPE (tmp), tmp, val2);
3441 new_val = wide_int_to_tree (TREE_TYPE (tmp), mask);
3442 new_comp_code = comp_code == EQ_EXPR ? LE_EXPR : GT_EXPR;
3444 else if (comp_code == LT_EXPR || comp_code == GE_EXPR)
3446 wide_int minval
3447 = wi::min_value (prec, TYPE_SIGN (TREE_TYPE (val)));
3448 new_val = val2;
3449 if (minval == wi::to_wide (new_val))
3450 new_val = NULL_TREE;
3452 else
3454 wide_int maxval
3455 = wi::max_value (prec, TYPE_SIGN (TREE_TYPE (val)));
3456 mask |= wi::to_wide (val2);
3457 if (wi::eq_p (mask, maxval))
3458 new_val = NULL_TREE;
3459 else
3460 new_val = wide_int_to_tree (TREE_TYPE (val2), mask);
3463 if (new_val)
3465 if (dump_file)
3467 fprintf (dump_file, "Adding assert for ");
3468 print_generic_expr (dump_file, name2);
3469 fprintf (dump_file, " from ");
3470 print_generic_expr (dump_file, tmp);
3471 fprintf (dump_file, "\n");
3474 add_assert_info (asserts, name2, tmp, new_comp_code, new_val);
3478 /* Add asserts for NAME cmp CST and NAME being defined as
3479 NAME = NAME2 & CST2.
3481 Extract CST2 from the and.
3483 Also handle
3484 NAME = (unsigned) NAME2;
3485 casts where NAME's type is unsigned and has smaller precision
3486 than NAME2's type as if it was NAME = NAME2 & MASK. */
3487 names[0] = NULL_TREE;
3488 names[1] = NULL_TREE;
3489 cst2 = NULL_TREE;
3490 if (rhs_code == BIT_AND_EXPR
3491 || (CONVERT_EXPR_CODE_P (rhs_code)
3492 && INTEGRAL_TYPE_P (TREE_TYPE (val))
3493 && TYPE_UNSIGNED (TREE_TYPE (val))
3494 && TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
3495 > prec))
3497 name2 = gimple_assign_rhs1 (def_stmt);
3498 if (rhs_code == BIT_AND_EXPR)
3499 cst2 = gimple_assign_rhs2 (def_stmt);
3500 else
3502 cst2 = TYPE_MAX_VALUE (TREE_TYPE (val));
3503 nprec = TYPE_PRECISION (TREE_TYPE (name2));
3505 if (TREE_CODE (name2) == SSA_NAME
3506 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
3507 && TREE_CODE (cst2) == INTEGER_CST
3508 && !integer_zerop (cst2)
3509 && (nprec > 1
3510 || TYPE_UNSIGNED (TREE_TYPE (val))))
3512 gimple *def_stmt2 = SSA_NAME_DEF_STMT (name2);
3513 if (gimple_assign_cast_p (def_stmt2))
3515 names[1] = gimple_assign_rhs1 (def_stmt2);
3516 if (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt2))
3517 || !INTEGRAL_TYPE_P (TREE_TYPE (names[1]))
3518 || (TYPE_PRECISION (TREE_TYPE (name2))
3519 != TYPE_PRECISION (TREE_TYPE (names[1]))))
3520 names[1] = NULL_TREE;
3522 names[0] = name2;
3525 if (names[0] || names[1])
3527 wide_int minv, maxv, valv, cst2v;
3528 wide_int tem, sgnbit;
3529 bool valid_p = false, valn, cst2n;
3530 enum tree_code ccode = comp_code;
3532 valv = wide_int::from (wi::to_wide (val), nprec, UNSIGNED);
3533 cst2v = wide_int::from (wi::to_wide (cst2), nprec, UNSIGNED);
3534 valn = wi::neg_p (valv, TYPE_SIGN (TREE_TYPE (val)));
3535 cst2n = wi::neg_p (cst2v, TYPE_SIGN (TREE_TYPE (val)));
3536 /* If CST2 doesn't have most significant bit set,
3537 but VAL is negative, we have comparison like
3538 if ((x & 0x123) > -4) (always true). Just give up. */
3539 if (!cst2n && valn)
3540 ccode = ERROR_MARK;
3541 if (cst2n)
3542 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
3543 else
3544 sgnbit = wi::zero (nprec);
3545 minv = valv & cst2v;
3546 switch (ccode)
3548 case EQ_EXPR:
3549 /* Minimum unsigned value for equality is VAL & CST2
3550 (should be equal to VAL, otherwise we probably should
3551 have folded the comparison into false) and
3552 maximum unsigned value is VAL | ~CST2. */
3553 maxv = valv | ~cst2v;
3554 valid_p = true;
3555 break;
3557 case NE_EXPR:
3558 tem = valv | ~cst2v;
3559 /* If VAL is 0, handle (X & CST2) != 0 as (X & CST2) > 0U. */
3560 if (valv == 0)
3562 cst2n = false;
3563 sgnbit = wi::zero (nprec);
3564 goto gt_expr;
3566 /* If (VAL | ~CST2) is all ones, handle it as
3567 (X & CST2) < VAL. */
3568 if (tem == -1)
3570 cst2n = false;
3571 valn = false;
3572 sgnbit = wi::zero (nprec);
3573 goto lt_expr;
3575 if (!cst2n && wi::neg_p (cst2v))
3576 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
3577 if (sgnbit != 0)
3579 if (valv == sgnbit)
3581 cst2n = true;
3582 valn = true;
3583 goto gt_expr;
3585 if (tem == wi::mask (nprec - 1, false, nprec))
3587 cst2n = true;
3588 goto lt_expr;
3590 if (!cst2n)
3591 sgnbit = wi::zero (nprec);
3593 break;
3595 case GE_EXPR:
3596 /* Minimum unsigned value for >= if (VAL & CST2) == VAL
3597 is VAL and maximum unsigned value is ~0. For signed
3598 comparison, if CST2 doesn't have most significant bit
3599 set, handle it similarly. If CST2 has MSB set,
3600 the minimum is the same, and maximum is ~0U/2. */
3601 if (minv != valv)
3603 /* If (VAL & CST2) != VAL, X & CST2 can't be equal to
3604 VAL. */
3605 minv = masked_increment (valv, cst2v, sgnbit, nprec);
3606 if (minv == valv)
3607 break;
3609 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
3610 valid_p = true;
3611 break;
3613 case GT_EXPR:
3614 gt_expr:
3615 /* Find out smallest MINV where MINV > VAL
3616 && (MINV & CST2) == MINV, if any. If VAL is signed and
3617 CST2 has MSB set, compute it biased by 1 << (nprec - 1). */
3618 minv = masked_increment (valv, cst2v, sgnbit, nprec);
3619 if (minv == valv)
3620 break;
3621 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
3622 valid_p = true;
3623 break;
3625 case LE_EXPR:
3626 /* Minimum unsigned value for <= is 0 and maximum
3627 unsigned value is VAL | ~CST2 if (VAL & CST2) == VAL.
3628 Otherwise, find smallest VAL2 where VAL2 > VAL
3629 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
3630 as maximum.
3631 For signed comparison, if CST2 doesn't have most
3632 significant bit set, handle it similarly. If CST2 has
3633 MSB set, the maximum is the same and minimum is INT_MIN. */
3634 if (minv == valv)
3635 maxv = valv;
3636 else
3638 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
3639 if (maxv == valv)
3640 break;
3641 maxv -= 1;
3643 maxv |= ~cst2v;
3644 minv = sgnbit;
3645 valid_p = true;
3646 break;
3648 case LT_EXPR:
3649 lt_expr:
3650 /* Minimum unsigned value for < is 0 and maximum
3651 unsigned value is (VAL-1) | ~CST2 if (VAL & CST2) == VAL.
3652 Otherwise, find smallest VAL2 where VAL2 > VAL
3653 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
3654 as maximum.
3655 For signed comparison, if CST2 doesn't have most
3656 significant bit set, handle it similarly. If CST2 has
3657 MSB set, the maximum is the same and minimum is INT_MIN. */
3658 if (minv == valv)
3660 if (valv == sgnbit)
3661 break;
3662 maxv = valv;
3664 else
3666 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
3667 if (maxv == valv)
3668 break;
3670 maxv -= 1;
3671 maxv |= ~cst2v;
3672 minv = sgnbit;
3673 valid_p = true;
3674 break;
3676 default:
3677 break;
3679 if (valid_p
3680 && (maxv - minv) != -1)
3682 tree tmp, new_val, type;
3683 int i;
3685 for (i = 0; i < 2; i++)
3686 if (names[i])
3688 wide_int maxv2 = maxv;
3689 tmp = names[i];
3690 type = TREE_TYPE (names[i]);
3691 if (!TYPE_UNSIGNED (type))
3693 type = build_nonstandard_integer_type (nprec, 1);
3694 tmp = build1 (NOP_EXPR, type, names[i]);
3696 if (minv != 0)
3698 tmp = build2 (PLUS_EXPR, type, tmp,
3699 wide_int_to_tree (type, -minv));
3700 maxv2 = maxv - minv;
3702 new_val = wide_int_to_tree (type, maxv2);
3704 if (dump_file)
3706 fprintf (dump_file, "Adding assert for ");
3707 print_generic_expr (dump_file, names[i]);
3708 fprintf (dump_file, " from ");
3709 print_generic_expr (dump_file, tmp);
3710 fprintf (dump_file, "\n");
3713 add_assert_info (asserts, names[i], tmp, LE_EXPR, new_val);
3720 /* OP is an operand of a truth value expression which is known to have
3721 a particular value. Register any asserts for OP and for any
3722 operands in OP's defining statement.
3724 If CODE is EQ_EXPR, then we want to register OP is zero (false),
3725 if CODE is NE_EXPR, then we want to register OP is nonzero (true). */
3727 static void
3728 register_edge_assert_for_1 (tree op, enum tree_code code,
3729 edge e, vec<assert_info> &asserts)
3731 gimple *op_def;
3732 tree val;
3733 enum tree_code rhs_code;
3735 /* We only care about SSA_NAMEs. */
3736 if (TREE_CODE (op) != SSA_NAME)
3737 return;
3739 /* We know that OP will have a zero or nonzero value. */
3740 val = build_int_cst (TREE_TYPE (op), 0);
3741 add_assert_info (asserts, op, op, code, val);
3743 /* Now look at how OP is set. If it's set from a comparison,
3744 a truth operation or some bit operations, then we may be able
3745 to register information about the operands of that assignment. */
3746 op_def = SSA_NAME_DEF_STMT (op);
3747 if (gimple_code (op_def) != GIMPLE_ASSIGN)
3748 return;
3750 rhs_code = gimple_assign_rhs_code (op_def);
3752 if (TREE_CODE_CLASS (rhs_code) == tcc_comparison)
3754 bool invert = (code == EQ_EXPR ? true : false);
3755 tree op0 = gimple_assign_rhs1 (op_def);
3756 tree op1 = gimple_assign_rhs2 (op_def);
3758 if (TREE_CODE (op0) == SSA_NAME)
3759 register_edge_assert_for_2 (op0, e, rhs_code, op0, op1, invert, asserts);
3760 if (TREE_CODE (op1) == SSA_NAME)
3761 register_edge_assert_for_2 (op1, e, rhs_code, op0, op1, invert, asserts);
3763 else if ((code == NE_EXPR
3764 && gimple_assign_rhs_code (op_def) == BIT_AND_EXPR)
3765 || (code == EQ_EXPR
3766 && gimple_assign_rhs_code (op_def) == BIT_IOR_EXPR))
3768 /* Recurse on each operand. */
3769 tree op0 = gimple_assign_rhs1 (op_def);
3770 tree op1 = gimple_assign_rhs2 (op_def);
3771 if (TREE_CODE (op0) == SSA_NAME
3772 && has_single_use (op0))
3773 register_edge_assert_for_1 (op0, code, e, asserts);
3774 if (TREE_CODE (op1) == SSA_NAME
3775 && has_single_use (op1))
3776 register_edge_assert_for_1 (op1, code, e, asserts);
3778 else if (gimple_assign_rhs_code (op_def) == BIT_NOT_EXPR
3779 && TYPE_PRECISION (TREE_TYPE (gimple_assign_lhs (op_def))) == 1)
3781 /* Recurse, flipping CODE. */
3782 code = invert_tree_comparison (code, false);
3783 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
3785 else if (gimple_assign_rhs_code (op_def) == SSA_NAME)
3787 /* Recurse through the copy. */
3788 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
3790 else if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (op_def)))
3792 /* Recurse through the type conversion, unless it is a narrowing
3793 conversion or conversion from non-integral type. */
3794 tree rhs = gimple_assign_rhs1 (op_def);
3795 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs))
3796 && (TYPE_PRECISION (TREE_TYPE (rhs))
3797 <= TYPE_PRECISION (TREE_TYPE (op))))
3798 register_edge_assert_for_1 (rhs, code, e, asserts);
3802 /* Check if comparison
3803 NAME COND_OP INTEGER_CST
3804 has a form of
3805 (X & 11...100..0) COND_OP XX...X00...0
3806 Such comparison can yield assertions like
3807 X >= XX...X00...0
3808 X <= XX...X11...1
3809 in case of COND_OP being EQ_EXPR or
3810 X < XX...X00...0
3811 X > XX...X11...1
3812 in case of NE_EXPR. */
3814 static bool
3815 is_masked_range_test (tree name, tree valt, enum tree_code cond_code,
3816 tree *new_name, tree *low, enum tree_code *low_code,
3817 tree *high, enum tree_code *high_code)
3819 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3821 if (!is_gimple_assign (def_stmt)
3822 || gimple_assign_rhs_code (def_stmt) != BIT_AND_EXPR)
3823 return false;
3825 tree t = gimple_assign_rhs1 (def_stmt);
3826 tree maskt = gimple_assign_rhs2 (def_stmt);
3827 if (TREE_CODE (t) != SSA_NAME || TREE_CODE (maskt) != INTEGER_CST)
3828 return false;
3830 wi::tree_to_wide_ref mask = wi::to_wide (maskt);
3831 wide_int inv_mask = ~mask;
3832 /* Must have been removed by now so don't bother optimizing. */
3833 if (mask == 0 || inv_mask == 0)
3834 return false;
3836 /* Assume VALT is INTEGER_CST. */
3837 wi::tree_to_wide_ref val = wi::to_wide (valt);
3839 if ((inv_mask & (inv_mask + 1)) != 0
3840 || (val & mask) != val)
3841 return false;
3843 bool is_range = cond_code == EQ_EXPR;
3845 tree type = TREE_TYPE (t);
3846 wide_int min = wi::min_value (type),
3847 max = wi::max_value (type);
3849 if (is_range)
3851 *low_code = val == min ? ERROR_MARK : GE_EXPR;
3852 *high_code = val == max ? ERROR_MARK : LE_EXPR;
3854 else
3856 /* We can still generate assertion if one of alternatives
3857 is known to always be false. */
3858 if (val == min)
3860 *low_code = (enum tree_code) 0;
3861 *high_code = GT_EXPR;
3863 else if ((val | inv_mask) == max)
3865 *low_code = LT_EXPR;
3866 *high_code = (enum tree_code) 0;
3868 else
3869 return false;
3872 *new_name = t;
3873 *low = wide_int_to_tree (type, val);
3874 *high = wide_int_to_tree (type, val | inv_mask);
3876 return true;
3879 /* Try to register an edge assertion for SSA name NAME on edge E for
3880 the condition COND contributing to the conditional jump pointed to by
3881 SI. */
3883 void
3884 register_edge_assert_for (tree name, edge e,
3885 enum tree_code cond_code, tree cond_op0,
3886 tree cond_op1, vec<assert_info> &asserts)
3888 tree val;
3889 enum tree_code comp_code;
3890 bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
3892 /* Do not attempt to infer anything in names that flow through
3893 abnormal edges. */
3894 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
3895 return;
3897 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
3898 cond_op0, cond_op1,
3899 is_else_edge,
3900 &comp_code, &val))
3901 return;
3903 /* Register ASSERT_EXPRs for name. */
3904 register_edge_assert_for_2 (name, e, cond_code, cond_op0,
3905 cond_op1, is_else_edge, asserts);
3908 /* If COND is effectively an equality test of an SSA_NAME against
3909 the value zero or one, then we may be able to assert values
3910 for SSA_NAMEs which flow into COND. */
3912 /* In the case of NAME == 1 or NAME != 0, for BIT_AND_EXPR defining
3913 statement of NAME we can assert both operands of the BIT_AND_EXPR
3914 have nonzero value. */
3915 if (((comp_code == EQ_EXPR && integer_onep (val))
3916 || (comp_code == NE_EXPR && integer_zerop (val))))
3918 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3920 if (is_gimple_assign (def_stmt)
3921 && gimple_assign_rhs_code (def_stmt) == BIT_AND_EXPR)
3923 tree op0 = gimple_assign_rhs1 (def_stmt);
3924 tree op1 = gimple_assign_rhs2 (def_stmt);
3925 register_edge_assert_for_1 (op0, NE_EXPR, e, asserts);
3926 register_edge_assert_for_1 (op1, NE_EXPR, e, asserts);
3930 /* In the case of NAME == 0 or NAME != 1, for BIT_IOR_EXPR defining
3931 statement of NAME we can assert both operands of the BIT_IOR_EXPR
3932 have zero value. */
3933 if (((comp_code == EQ_EXPR && integer_zerop (val))
3934 || (comp_code == NE_EXPR && integer_onep (val))))
3936 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3938 /* For BIT_IOR_EXPR only if NAME == 0 both operands have
3939 necessarily zero value, or if type-precision is one. */
3940 if (is_gimple_assign (def_stmt)
3941 && (gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR
3942 && (TYPE_PRECISION (TREE_TYPE (name)) == 1
3943 || comp_code == EQ_EXPR)))
3945 tree op0 = gimple_assign_rhs1 (def_stmt);
3946 tree op1 = gimple_assign_rhs2 (def_stmt);
3947 register_edge_assert_for_1 (op0, EQ_EXPR, e, asserts);
3948 register_edge_assert_for_1 (op1, EQ_EXPR, e, asserts);
3952 /* Sometimes we can infer ranges from (NAME & MASK) == VALUE. */
3953 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
3954 && TREE_CODE (val) == INTEGER_CST)
3956 enum tree_code low_code, high_code;
3957 tree low, high;
3958 if (is_masked_range_test (name, val, comp_code, &name, &low,
3959 &low_code, &high, &high_code))
3961 if (low_code != ERROR_MARK)
3962 register_edge_assert_for_2 (name, e, low_code, name,
3963 low, /*invert*/false, asserts);
3964 if (high_code != ERROR_MARK)
3965 register_edge_assert_for_2 (name, e, high_code, name,
3966 high, /*invert*/false, asserts);
3971 /* Finish found ASSERTS for E and register them at GSI. */
3973 static void
3974 finish_register_edge_assert_for (edge e, gimple_stmt_iterator gsi,
3975 vec<assert_info> &asserts)
3977 for (unsigned i = 0; i < asserts.length (); ++i)
3978 /* Only register an ASSERT_EXPR if NAME was found in the sub-graph
3979 reachable from E. */
3980 if (live_on_edge (e, asserts[i].name))
3981 register_new_assert_for (asserts[i].name, asserts[i].expr,
3982 asserts[i].comp_code, asserts[i].val,
3983 NULL, e, gsi);
3988 /* Determine whether the outgoing edges of BB should receive an
3989 ASSERT_EXPR for each of the operands of BB's LAST statement.
3990 The last statement of BB must be a COND_EXPR.
3992 If any of the sub-graphs rooted at BB have an interesting use of
3993 the predicate operands, an assert location node is added to the
3994 list of assertions for the corresponding operands. */
3996 static void
3997 find_conditional_asserts (basic_block bb, gcond *last)
3999 gimple_stmt_iterator bsi;
4000 tree op;
4001 edge_iterator ei;
4002 edge e;
4003 ssa_op_iter iter;
4005 bsi = gsi_for_stmt (last);
4007 /* Look for uses of the operands in each of the sub-graphs
4008 rooted at BB. We need to check each of the outgoing edges
4009 separately, so that we know what kind of ASSERT_EXPR to
4010 insert. */
4011 FOR_EACH_EDGE (e, ei, bb->succs)
4013 if (e->dest == bb)
4014 continue;
4016 /* Register the necessary assertions for each operand in the
4017 conditional predicate. */
4018 auto_vec<assert_info, 8> asserts;
4019 FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
4020 register_edge_assert_for (op, e,
4021 gimple_cond_code (last),
4022 gimple_cond_lhs (last),
4023 gimple_cond_rhs (last), asserts);
4024 finish_register_edge_assert_for (e, bsi, asserts);
4028 struct case_info
4030 tree expr;
4031 basic_block bb;
4034 /* Compare two case labels sorting first by the destination bb index
4035 and then by the case value. */
4037 static int
4038 compare_case_labels (const void *p1, const void *p2)
4040 const struct case_info *ci1 = (const struct case_info *) p1;
4041 const struct case_info *ci2 = (const struct case_info *) p2;
4042 int idx1 = ci1->bb->index;
4043 int idx2 = ci2->bb->index;
4045 if (idx1 < idx2)
4046 return -1;
4047 else if (idx1 == idx2)
4049 /* Make sure the default label is first in a group. */
4050 if (!CASE_LOW (ci1->expr))
4051 return -1;
4052 else if (!CASE_LOW (ci2->expr))
4053 return 1;
4054 else
4055 return tree_int_cst_compare (CASE_LOW (ci1->expr),
4056 CASE_LOW (ci2->expr));
4058 else
4059 return 1;
4062 /* Determine whether the outgoing edges of BB should receive an
4063 ASSERT_EXPR for each of the operands of BB's LAST statement.
4064 The last statement of BB must be a SWITCH_EXPR.
4066 If any of the sub-graphs rooted at BB have an interesting use of
4067 the predicate operands, an assert location node is added to the
4068 list of assertions for the corresponding operands. */
4070 static void
4071 find_switch_asserts (basic_block bb, gswitch *last)
4073 gimple_stmt_iterator bsi;
4074 tree op;
4075 edge e;
4076 struct case_info *ci;
4077 size_t n = gimple_switch_num_labels (last);
4078 #if GCC_VERSION >= 4000
4079 unsigned int idx;
4080 #else
4081 /* Work around GCC 3.4 bug (PR 37086). */
4082 volatile unsigned int idx;
4083 #endif
4085 bsi = gsi_for_stmt (last);
4086 op = gimple_switch_index (last);
4087 if (TREE_CODE (op) != SSA_NAME)
4088 return;
4090 /* Build a vector of case labels sorted by destination label. */
4091 ci = XNEWVEC (struct case_info, n);
4092 for (idx = 0; idx < n; ++idx)
4094 ci[idx].expr = gimple_switch_label (last, idx);
4095 ci[idx].bb = label_to_block (CASE_LABEL (ci[idx].expr));
4097 edge default_edge = find_edge (bb, ci[0].bb);
4098 qsort (ci, n, sizeof (struct case_info), compare_case_labels);
4100 for (idx = 0; idx < n; ++idx)
4102 tree min, max;
4103 tree cl = ci[idx].expr;
4104 basic_block cbb = ci[idx].bb;
4106 min = CASE_LOW (cl);
4107 max = CASE_HIGH (cl);
4109 /* If there are multiple case labels with the same destination
4110 we need to combine them to a single value range for the edge. */
4111 if (idx + 1 < n && cbb == ci[idx + 1].bb)
4113 /* Skip labels until the last of the group. */
4114 do {
4115 ++idx;
4116 } while (idx < n && cbb == ci[idx].bb);
4117 --idx;
4119 /* Pick up the maximum of the case label range. */
4120 if (CASE_HIGH (ci[idx].expr))
4121 max = CASE_HIGH (ci[idx].expr);
4122 else
4123 max = CASE_LOW (ci[idx].expr);
4126 /* Can't extract a useful assertion out of a range that includes the
4127 default label. */
4128 if (min == NULL_TREE)
4129 continue;
4131 /* Find the edge to register the assert expr on. */
4132 e = find_edge (bb, cbb);
4134 /* Register the necessary assertions for the operand in the
4135 SWITCH_EXPR. */
4136 auto_vec<assert_info, 8> asserts;
4137 register_edge_assert_for (op, e,
4138 max ? GE_EXPR : EQ_EXPR,
4139 op, fold_convert (TREE_TYPE (op), min),
4140 asserts);
4141 if (max)
4142 register_edge_assert_for (op, e, LE_EXPR, op,
4143 fold_convert (TREE_TYPE (op), max),
4144 asserts);
4145 finish_register_edge_assert_for (e, bsi, asserts);
4148 XDELETEVEC (ci);
4150 if (!live_on_edge (default_edge, op))
4151 return;
4153 /* Now register along the default label assertions that correspond to the
4154 anti-range of each label. */
4155 int insertion_limit = PARAM_VALUE (PARAM_MAX_VRP_SWITCH_ASSERTIONS);
4156 if (insertion_limit == 0)
4157 return;
4159 /* We can't do this if the default case shares a label with another case. */
4160 tree default_cl = gimple_switch_default_label (last);
4161 for (idx = 1; idx < n; idx++)
4163 tree min, max;
4164 tree cl = gimple_switch_label (last, idx);
4165 if (CASE_LABEL (cl) == CASE_LABEL (default_cl))
4166 continue;
4168 min = CASE_LOW (cl);
4169 max = CASE_HIGH (cl);
4171 /* Combine contiguous case ranges to reduce the number of assertions
4172 to insert. */
4173 for (idx = idx + 1; idx < n; idx++)
4175 tree next_min, next_max;
4176 tree next_cl = gimple_switch_label (last, idx);
4177 if (CASE_LABEL (next_cl) == CASE_LABEL (default_cl))
4178 break;
4180 next_min = CASE_LOW (next_cl);
4181 next_max = CASE_HIGH (next_cl);
4183 wide_int difference = (wi::to_wide (next_min)
4184 - wi::to_wide (max ? max : min));
4185 if (wi::eq_p (difference, 1))
4186 max = next_max ? next_max : next_min;
4187 else
4188 break;
4190 idx--;
4192 if (max == NULL_TREE)
4194 /* Register the assertion OP != MIN. */
4195 auto_vec<assert_info, 8> asserts;
4196 min = fold_convert (TREE_TYPE (op), min);
4197 register_edge_assert_for (op, default_edge, NE_EXPR, op, min,
4198 asserts);
4199 finish_register_edge_assert_for (default_edge, bsi, asserts);
4201 else
4203 /* Register the assertion (unsigned)OP - MIN > (MAX - MIN),
4204 which will give OP the anti-range ~[MIN,MAX]. */
4205 tree uop = fold_convert (unsigned_type_for (TREE_TYPE (op)), op);
4206 min = fold_convert (TREE_TYPE (uop), min);
4207 max = fold_convert (TREE_TYPE (uop), max);
4209 tree lhs = fold_build2 (MINUS_EXPR, TREE_TYPE (uop), uop, min);
4210 tree rhs = int_const_binop (MINUS_EXPR, max, min);
4211 register_new_assert_for (op, lhs, GT_EXPR, rhs,
4212 NULL, default_edge, bsi);
4215 if (--insertion_limit == 0)
4216 break;
4221 /* Traverse all the statements in block BB looking for statements that
4222 may generate useful assertions for the SSA names in their operand.
4223 If a statement produces a useful assertion A for name N_i, then the
4224 list of assertions already generated for N_i is scanned to
4225 determine if A is actually needed.
4227 If N_i already had the assertion A at a location dominating the
4228 current location, then nothing needs to be done. Otherwise, the
4229 new location for A is recorded instead.
4231 1- For every statement S in BB, all the variables used by S are
4232 added to bitmap FOUND_IN_SUBGRAPH.
4234 2- If statement S uses an operand N in a way that exposes a known
4235 value range for N, then if N was not already generated by an
4236 ASSERT_EXPR, create a new assert location for N. For instance,
4237 if N is a pointer and the statement dereferences it, we can
4238 assume that N is not NULL.
4240 3- COND_EXPRs are a special case of #2. We can derive range
4241 information from the predicate but need to insert different
4242 ASSERT_EXPRs for each of the sub-graphs rooted at the
4243 conditional block. If the last statement of BB is a conditional
4244 expression of the form 'X op Y', then
4246 a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
4248 b) If the conditional is the only entry point to the sub-graph
4249 corresponding to the THEN_CLAUSE, recurse into it. On
4250 return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
4251 an ASSERT_EXPR is added for the corresponding variable.
4253 c) Repeat step (b) on the ELSE_CLAUSE.
4255 d) Mark X and Y in FOUND_IN_SUBGRAPH.
4257 For instance,
4259 if (a == 9)
4260 b = a;
4261 else
4262 b = c + 1;
4264 In this case, an assertion on the THEN clause is useful to
4265 determine that 'a' is always 9 on that edge. However, an assertion
4266 on the ELSE clause would be unnecessary.
4268 4- If BB does not end in a conditional expression, then we recurse
4269 into BB's dominator children.
4271 At the end of the recursive traversal, every SSA name will have a
4272 list of locations where ASSERT_EXPRs should be added. When a new
4273 location for name N is found, it is registered by calling
4274 register_new_assert_for. That function keeps track of all the
4275 registered assertions to prevent adding unnecessary assertions.
4276 For instance, if a pointer P_4 is dereferenced more than once in a
4277 dominator tree, only the location dominating all the dereference of
4278 P_4 will receive an ASSERT_EXPR. */
4280 static void
4281 find_assert_locations_1 (basic_block bb, sbitmap live)
4283 gimple *last;
4285 last = last_stmt (bb);
4287 /* If BB's last statement is a conditional statement involving integer
4288 operands, determine if we need to add ASSERT_EXPRs. */
4289 if (last
4290 && gimple_code (last) == GIMPLE_COND
4291 && !fp_predicate (last)
4292 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
4293 find_conditional_asserts (bb, as_a <gcond *> (last));
4295 /* If BB's last statement is a switch statement involving integer
4296 operands, determine if we need to add ASSERT_EXPRs. */
4297 if (last
4298 && gimple_code (last) == GIMPLE_SWITCH
4299 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
4300 find_switch_asserts (bb, as_a <gswitch *> (last));
4302 /* Traverse all the statements in BB marking used names and looking
4303 for statements that may infer assertions for their used operands. */
4304 for (gimple_stmt_iterator si = gsi_last_bb (bb); !gsi_end_p (si);
4305 gsi_prev (&si))
4307 gimple *stmt;
4308 tree op;
4309 ssa_op_iter i;
4311 stmt = gsi_stmt (si);
4313 if (is_gimple_debug (stmt))
4314 continue;
4316 /* See if we can derive an assertion for any of STMT's operands. */
4317 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
4319 tree value;
4320 enum tree_code comp_code;
4322 /* If op is not live beyond this stmt, do not bother to insert
4323 asserts for it. */
4324 if (!bitmap_bit_p (live, SSA_NAME_VERSION (op)))
4325 continue;
4327 /* If OP is used in such a way that we can infer a value
4328 range for it, and we don't find a previous assertion for
4329 it, create a new assertion location node for OP. */
4330 if (infer_value_range (stmt, op, &comp_code, &value))
4332 /* If we are able to infer a nonzero value range for OP,
4333 then walk backwards through the use-def chain to see if OP
4334 was set via a typecast.
4336 If so, then we can also infer a nonzero value range
4337 for the operand of the NOP_EXPR. */
4338 if (comp_code == NE_EXPR && integer_zerop (value))
4340 tree t = op;
4341 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
4343 while (is_gimple_assign (def_stmt)
4344 && CONVERT_EXPR_CODE_P
4345 (gimple_assign_rhs_code (def_stmt))
4346 && TREE_CODE
4347 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
4348 && POINTER_TYPE_P
4349 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
4351 t = gimple_assign_rhs1 (def_stmt);
4352 def_stmt = SSA_NAME_DEF_STMT (t);
4354 /* Note we want to register the assert for the
4355 operand of the NOP_EXPR after SI, not after the
4356 conversion. */
4357 if (bitmap_bit_p (live, SSA_NAME_VERSION (t)))
4358 register_new_assert_for (t, t, comp_code, value,
4359 bb, NULL, si);
4363 register_new_assert_for (op, op, comp_code, value, bb, NULL, si);
4367 /* Update live. */
4368 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
4369 bitmap_set_bit (live, SSA_NAME_VERSION (op));
4370 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_DEF)
4371 bitmap_clear_bit (live, SSA_NAME_VERSION (op));
4374 /* Traverse all PHI nodes in BB, updating live. */
4375 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
4376 gsi_next (&si))
4378 use_operand_p arg_p;
4379 ssa_op_iter i;
4380 gphi *phi = si.phi ();
4381 tree res = gimple_phi_result (phi);
4383 if (virtual_operand_p (res))
4384 continue;
4386 FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
4388 tree arg = USE_FROM_PTR (arg_p);
4389 if (TREE_CODE (arg) == SSA_NAME)
4390 bitmap_set_bit (live, SSA_NAME_VERSION (arg));
4393 bitmap_clear_bit (live, SSA_NAME_VERSION (res));
4397 /* Do an RPO walk over the function computing SSA name liveness
4398 on-the-fly and deciding on assert expressions to insert. */
4400 static void
4401 find_assert_locations (void)
4403 int *rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
4404 int *bb_rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
4405 int *last_rpo = XCNEWVEC (int, last_basic_block_for_fn (cfun));
4406 int rpo_cnt, i;
4408 live = XCNEWVEC (sbitmap, last_basic_block_for_fn (cfun));
4409 rpo_cnt = pre_and_rev_post_order_compute (NULL, rpo, false);
4410 for (i = 0; i < rpo_cnt; ++i)
4411 bb_rpo[rpo[i]] = i;
4413 /* Pre-seed loop latch liveness from loop header PHI nodes. Due to
4414 the order we compute liveness and insert asserts we otherwise
4415 fail to insert asserts into the loop latch. */
4416 loop_p loop;
4417 FOR_EACH_LOOP (loop, 0)
4419 i = loop->latch->index;
4420 unsigned int j = single_succ_edge (loop->latch)->dest_idx;
4421 for (gphi_iterator gsi = gsi_start_phis (loop->header);
4422 !gsi_end_p (gsi); gsi_next (&gsi))
4424 gphi *phi = gsi.phi ();
4425 if (virtual_operand_p (gimple_phi_result (phi)))
4426 continue;
4427 tree arg = gimple_phi_arg_def (phi, j);
4428 if (TREE_CODE (arg) == SSA_NAME)
4430 if (live[i] == NULL)
4432 live[i] = sbitmap_alloc (num_ssa_names);
4433 bitmap_clear (live[i]);
4435 bitmap_set_bit (live[i], SSA_NAME_VERSION (arg));
4440 for (i = rpo_cnt - 1; i >= 0; --i)
4442 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, rpo[i]);
4443 edge e;
4444 edge_iterator ei;
4446 if (!live[rpo[i]])
4448 live[rpo[i]] = sbitmap_alloc (num_ssa_names);
4449 bitmap_clear (live[rpo[i]]);
4452 /* Process BB and update the live information with uses in
4453 this block. */
4454 find_assert_locations_1 (bb, live[rpo[i]]);
4456 /* Merge liveness into the predecessor blocks and free it. */
4457 if (!bitmap_empty_p (live[rpo[i]]))
4459 int pred_rpo = i;
4460 FOR_EACH_EDGE (e, ei, bb->preds)
4462 int pred = e->src->index;
4463 if ((e->flags & EDGE_DFS_BACK) || pred == ENTRY_BLOCK)
4464 continue;
4466 if (!live[pred])
4468 live[pred] = sbitmap_alloc (num_ssa_names);
4469 bitmap_clear (live[pred]);
4471 bitmap_ior (live[pred], live[pred], live[rpo[i]]);
4473 if (bb_rpo[pred] < pred_rpo)
4474 pred_rpo = bb_rpo[pred];
4477 /* Record the RPO number of the last visited block that needs
4478 live information from this block. */
4479 last_rpo[rpo[i]] = pred_rpo;
4481 else
4483 sbitmap_free (live[rpo[i]]);
4484 live[rpo[i]] = NULL;
4487 /* We can free all successors live bitmaps if all their
4488 predecessors have been visited already. */
4489 FOR_EACH_EDGE (e, ei, bb->succs)
4490 if (last_rpo[e->dest->index] == i
4491 && live[e->dest->index])
4493 sbitmap_free (live[e->dest->index]);
4494 live[e->dest->index] = NULL;
4498 XDELETEVEC (rpo);
4499 XDELETEVEC (bb_rpo);
4500 XDELETEVEC (last_rpo);
4501 for (i = 0; i < last_basic_block_for_fn (cfun); ++i)
4502 if (live[i])
4503 sbitmap_free (live[i]);
4504 XDELETEVEC (live);
4507 /* Create an ASSERT_EXPR for NAME and insert it in the location
4508 indicated by LOC. Return true if we made any edge insertions. */
4510 static bool
4511 process_assert_insertions_for (tree name, assert_locus *loc)
4513 /* Build the comparison expression NAME_i COMP_CODE VAL. */
4514 gimple *stmt;
4515 tree cond;
4516 gimple *assert_stmt;
4517 edge_iterator ei;
4518 edge e;
4520 /* If we have X <=> X do not insert an assert expr for that. */
4521 if (loc->expr == loc->val)
4522 return false;
4524 cond = build2 (loc->comp_code, boolean_type_node, loc->expr, loc->val);
4525 assert_stmt = build_assert_expr_for (cond, name);
4526 if (loc->e)
4528 /* We have been asked to insert the assertion on an edge. This
4529 is used only by COND_EXPR and SWITCH_EXPR assertions. */
4530 gcc_checking_assert (gimple_code (gsi_stmt (loc->si)) == GIMPLE_COND
4531 || (gimple_code (gsi_stmt (loc->si))
4532 == GIMPLE_SWITCH));
4534 gsi_insert_on_edge (loc->e, assert_stmt);
4535 return true;
4538 /* If the stmt iterator points at the end then this is an insertion
4539 at the beginning of a block. */
4540 if (gsi_end_p (loc->si))
4542 gimple_stmt_iterator si = gsi_after_labels (loc->bb);
4543 gsi_insert_before (&si, assert_stmt, GSI_SAME_STMT);
4544 return false;
4547 /* Otherwise, we can insert right after LOC->SI iff the
4548 statement must not be the last statement in the block. */
4549 stmt = gsi_stmt (loc->si);
4550 if (!stmt_ends_bb_p (stmt))
4552 gsi_insert_after (&loc->si, assert_stmt, GSI_SAME_STMT);
4553 return false;
4556 /* If STMT must be the last statement in BB, we can only insert new
4557 assertions on the non-abnormal edge out of BB. Note that since
4558 STMT is not control flow, there may only be one non-abnormal/eh edge
4559 out of BB. */
4560 FOR_EACH_EDGE (e, ei, loc->bb->succs)
4561 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
4563 gsi_insert_on_edge (e, assert_stmt);
4564 return true;
4567 gcc_unreachable ();
4570 /* Qsort helper for sorting assert locations. If stable is true, don't
4571 use iterative_hash_expr because it can be unstable for -fcompare-debug,
4572 on the other side some pointers might be NULL. */
4574 template <bool stable>
4575 static int
4576 compare_assert_loc (const void *pa, const void *pb)
4578 assert_locus * const a = *(assert_locus * const *)pa;
4579 assert_locus * const b = *(assert_locus * const *)pb;
4581 /* If stable, some asserts might be optimized away already, sort
4582 them last. */
4583 if (stable)
4585 if (a == NULL)
4586 return b != NULL;
4587 else if (b == NULL)
4588 return -1;
4591 if (a->e == NULL && b->e != NULL)
4592 return 1;
4593 else if (a->e != NULL && b->e == NULL)
4594 return -1;
4596 /* After the above checks, we know that (a->e == NULL) == (b->e == NULL),
4597 no need to test both a->e and b->e. */
4599 /* Sort after destination index. */
4600 if (a->e == NULL)
4602 else if (a->e->dest->index > b->e->dest->index)
4603 return 1;
4604 else if (a->e->dest->index < b->e->dest->index)
4605 return -1;
4607 /* Sort after comp_code. */
4608 if (a->comp_code > b->comp_code)
4609 return 1;
4610 else if (a->comp_code < b->comp_code)
4611 return -1;
4613 hashval_t ha, hb;
4615 /* E.g. if a->val is ADDR_EXPR of a VAR_DECL, iterative_hash_expr
4616 uses DECL_UID of the VAR_DECL, so sorting might differ between
4617 -g and -g0. When doing the removal of redundant assert exprs
4618 and commonization to successors, this does not matter, but for
4619 the final sort needs to be stable. */
4620 if (stable)
4622 ha = 0;
4623 hb = 0;
4625 else
4627 ha = iterative_hash_expr (a->expr, iterative_hash_expr (a->val, 0));
4628 hb = iterative_hash_expr (b->expr, iterative_hash_expr (b->val, 0));
4631 /* Break the tie using hashing and source/bb index. */
4632 if (ha == hb)
4633 return (a->e != NULL
4634 ? a->e->src->index - b->e->src->index
4635 : a->bb->index - b->bb->index);
4636 return ha > hb ? 1 : -1;
4639 /* Process all the insertions registered for every name N_i registered
4640 in NEED_ASSERT_FOR. The list of assertions to be inserted are
4641 found in ASSERTS_FOR[i]. */
4643 static void
4644 process_assert_insertions (void)
4646 unsigned i;
4647 bitmap_iterator bi;
4648 bool update_edges_p = false;
4649 int num_asserts = 0;
4651 if (dump_file && (dump_flags & TDF_DETAILS))
4652 dump_all_asserts (dump_file);
4654 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
4656 assert_locus *loc = asserts_for[i];
4657 gcc_assert (loc);
4659 auto_vec<assert_locus *, 16> asserts;
4660 for (; loc; loc = loc->next)
4661 asserts.safe_push (loc);
4662 asserts.qsort (compare_assert_loc<false>);
4664 /* Push down common asserts to successors and remove redundant ones. */
4665 unsigned ecnt = 0;
4666 assert_locus *common = NULL;
4667 unsigned commonj = 0;
4668 for (unsigned j = 0; j < asserts.length (); ++j)
4670 loc = asserts[j];
4671 if (! loc->e)
4672 common = NULL;
4673 else if (! common
4674 || loc->e->dest != common->e->dest
4675 || loc->comp_code != common->comp_code
4676 || ! operand_equal_p (loc->val, common->val, 0)
4677 || ! operand_equal_p (loc->expr, common->expr, 0))
4679 commonj = j;
4680 common = loc;
4681 ecnt = 1;
4683 else if (loc->e == asserts[j-1]->e)
4685 /* Remove duplicate asserts. */
4686 if (commonj == j - 1)
4688 commonj = j;
4689 common = loc;
4691 free (asserts[j-1]);
4692 asserts[j-1] = NULL;
4694 else
4696 ecnt++;
4697 if (EDGE_COUNT (common->e->dest->preds) == ecnt)
4699 /* We have the same assertion on all incoming edges of a BB.
4700 Insert it at the beginning of that block. */
4701 loc->bb = loc->e->dest;
4702 loc->e = NULL;
4703 loc->si = gsi_none ();
4704 common = NULL;
4705 /* Clear asserts commoned. */
4706 for (; commonj != j; ++commonj)
4707 if (asserts[commonj])
4709 free (asserts[commonj]);
4710 asserts[commonj] = NULL;
4716 /* The asserts vector sorting above might be unstable for
4717 -fcompare-debug, sort again to ensure a stable sort. */
4718 asserts.qsort (compare_assert_loc<true>);
4719 for (unsigned j = 0; j < asserts.length (); ++j)
4721 loc = asserts[j];
4722 if (! loc)
4723 break;
4724 update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
4725 num_asserts++;
4726 free (loc);
4730 if (update_edges_p)
4731 gsi_commit_edge_inserts ();
4733 statistics_counter_event (cfun, "Number of ASSERT_EXPR expressions inserted",
4734 num_asserts);
4738 /* Traverse the flowgraph looking for conditional jumps to insert range
4739 expressions. These range expressions are meant to provide information
4740 to optimizations that need to reason in terms of value ranges. They
4741 will not be expanded into RTL. For instance, given:
4743 x = ...
4744 y = ...
4745 if (x < y)
4746 y = x - 2;
4747 else
4748 x = y + 3;
4750 this pass will transform the code into:
4752 x = ...
4753 y = ...
4754 if (x < y)
4756 x = ASSERT_EXPR <x, x < y>
4757 y = x - 2
4759 else
4761 y = ASSERT_EXPR <y, x >= y>
4762 x = y + 3
4765 The idea is that once copy and constant propagation have run, other
4766 optimizations will be able to determine what ranges of values can 'x'
4767 take in different paths of the code, simply by checking the reaching
4768 definition of 'x'. */
4770 static void
4771 insert_range_assertions (void)
4773 need_assert_for = BITMAP_ALLOC (NULL);
4774 asserts_for = XCNEWVEC (assert_locus *, num_ssa_names);
4776 calculate_dominance_info (CDI_DOMINATORS);
4778 find_assert_locations ();
4779 if (!bitmap_empty_p (need_assert_for))
4781 process_assert_insertions ();
4782 update_ssa (TODO_update_ssa_no_phi);
4785 if (dump_file && (dump_flags & TDF_DETAILS))
4787 fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
4788 dump_function_to_file (current_function_decl, dump_file, dump_flags);
4791 free (asserts_for);
4792 BITMAP_FREE (need_assert_for);
4795 class vrp_prop : public ssa_propagation_engine
4797 public:
4798 enum ssa_prop_result visit_stmt (gimple *, edge *, tree *) FINAL OVERRIDE;
4799 enum ssa_prop_result visit_phi (gphi *) FINAL OVERRIDE;
4801 void vrp_initialize (void);
4802 void vrp_finalize (bool);
4803 void check_all_array_refs (void);
4804 void check_array_ref (location_t, tree, bool);
4805 void search_for_addr_array (tree, location_t);
4807 class vr_values vr_values;
4808 /* Temporary delegator to minimize code churn. */
4809 value_range *get_value_range (const_tree op)
4810 { return vr_values.get_value_range (op); }
4811 void set_defs_to_varying (gimple *stmt)
4812 { return vr_values.set_defs_to_varying (stmt); }
4813 void extract_range_from_stmt (gimple *stmt, edge *taken_edge_p,
4814 tree *output_p, value_range *vr)
4815 { vr_values.extract_range_from_stmt (stmt, taken_edge_p, output_p, vr); }
4816 bool update_value_range (const_tree op, value_range *vr)
4817 { return vr_values.update_value_range (op, vr); }
4818 void extract_range_basic (value_range *vr, gimple *stmt)
4819 { vr_values.extract_range_basic (vr, stmt); }
4820 void extract_range_from_phi_node (gphi *phi, value_range *vr)
4821 { vr_values.extract_range_from_phi_node (phi, vr); }
4823 /* Checks one ARRAY_REF in REF, located at LOCUS. Ignores flexible arrays
4824 and "struct" hacks. If VRP can determine that the
4825 array subscript is a constant, check if it is outside valid
4826 range. If the array subscript is a RANGE, warn if it is
4827 non-overlapping with valid range.
4828 IGNORE_OFF_BY_ONE is true if the ARRAY_REF is inside a ADDR_EXPR. */
4830 void
4831 vrp_prop::check_array_ref (location_t location, tree ref,
4832 bool ignore_off_by_one)
4834 value_range *vr = NULL;
4835 tree low_sub, up_sub;
4836 tree low_bound, up_bound, up_bound_p1;
4838 if (TREE_NO_WARNING (ref))
4839 return;
4841 low_sub = up_sub = TREE_OPERAND (ref, 1);
4842 up_bound = array_ref_up_bound (ref);
4844 if (!up_bound
4845 || TREE_CODE (up_bound) != INTEGER_CST
4846 || (warn_array_bounds < 2
4847 && array_at_struct_end_p (ref)))
4849 /* Accesses to trailing arrays via pointers may access storage
4850 beyond the types array bounds. For such arrays, or for flexible
4851 array members, as well as for other arrays of an unknown size,
4852 replace the upper bound with a more permissive one that assumes
4853 the size of the largest object is PTRDIFF_MAX. */
4854 tree eltsize = array_ref_element_size (ref);
4856 if (TREE_CODE (eltsize) != INTEGER_CST
4857 || integer_zerop (eltsize))
4859 up_bound = NULL_TREE;
4860 up_bound_p1 = NULL_TREE;
4862 else
4864 tree maxbound = TYPE_MAX_VALUE (ptrdiff_type_node);
4865 tree arg = TREE_OPERAND (ref, 0);
4866 poly_int64 off;
4868 if (get_addr_base_and_unit_offset (arg, &off) && known_gt (off, 0))
4869 maxbound = wide_int_to_tree (sizetype,
4870 wi::sub (wi::to_wide (maxbound),
4871 off));
4872 else
4873 maxbound = fold_convert (sizetype, maxbound);
4875 up_bound_p1 = int_const_binop (TRUNC_DIV_EXPR, maxbound, eltsize);
4877 up_bound = int_const_binop (MINUS_EXPR, up_bound_p1,
4878 build_int_cst (ptrdiff_type_node, 1));
4881 else
4882 up_bound_p1 = int_const_binop (PLUS_EXPR, up_bound,
4883 build_int_cst (TREE_TYPE (up_bound), 1));
4885 low_bound = array_ref_low_bound (ref);
4887 tree artype = TREE_TYPE (TREE_OPERAND (ref, 0));
4889 /* Empty array. */
4890 if (up_bound && tree_int_cst_equal (low_bound, up_bound_p1))
4892 warning_at (location, OPT_Warray_bounds,
4893 "array subscript %E is above array bounds of %qT",
4894 low_bound, artype);
4895 TREE_NO_WARNING (ref) = 1;
4898 if (TREE_CODE (low_sub) == SSA_NAME)
4900 vr = get_value_range (low_sub);
4901 if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
4903 low_sub = vr->type == VR_RANGE ? vr->max : vr->min;
4904 up_sub = vr->type == VR_RANGE ? vr->min : vr->max;
4908 if (vr && vr->type == VR_ANTI_RANGE)
4910 if (up_bound
4911 && TREE_CODE (up_sub) == INTEGER_CST
4912 && (ignore_off_by_one
4913 ? tree_int_cst_lt (up_bound, up_sub)
4914 : tree_int_cst_le (up_bound, up_sub))
4915 && TREE_CODE (low_sub) == INTEGER_CST
4916 && tree_int_cst_le (low_sub, low_bound))
4918 warning_at (location, OPT_Warray_bounds,
4919 "array subscript [%E, %E] is outside array bounds of %qT",
4920 low_sub, up_sub, artype);
4921 TREE_NO_WARNING (ref) = 1;
4924 else if (up_bound
4925 && TREE_CODE (up_sub) == INTEGER_CST
4926 && (ignore_off_by_one
4927 ? !tree_int_cst_le (up_sub, up_bound_p1)
4928 : !tree_int_cst_le (up_sub, up_bound)))
4930 if (dump_file && (dump_flags & TDF_DETAILS))
4932 fprintf (dump_file, "Array bound warning for ");
4933 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
4934 fprintf (dump_file, "\n");
4936 warning_at (location, OPT_Warray_bounds,
4937 "array subscript %E is above array bounds of %qT",
4938 up_sub, artype);
4939 TREE_NO_WARNING (ref) = 1;
4941 else if (TREE_CODE (low_sub) == INTEGER_CST
4942 && tree_int_cst_lt (low_sub, low_bound))
4944 if (dump_file && (dump_flags & TDF_DETAILS))
4946 fprintf (dump_file, "Array bound warning for ");
4947 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
4948 fprintf (dump_file, "\n");
4950 warning_at (location, OPT_Warray_bounds,
4951 "array subscript %E is below array bounds of %qT",
4952 low_sub, artype);
4953 TREE_NO_WARNING (ref) = 1;
4957 /* Searches if the expr T, located at LOCATION computes
4958 address of an ARRAY_REF, and call check_array_ref on it. */
4960 void
4961 vrp_prop::search_for_addr_array (tree t, location_t location)
4963 /* Check each ARRAY_REFs in the reference chain. */
4966 if (TREE_CODE (t) == ARRAY_REF)
4967 check_array_ref (location, t, true /*ignore_off_by_one*/);
4969 t = TREE_OPERAND (t, 0);
4971 while (handled_component_p (t));
4973 if (TREE_CODE (t) == MEM_REF
4974 && TREE_CODE (TREE_OPERAND (t, 0)) == ADDR_EXPR
4975 && !TREE_NO_WARNING (t))
4977 tree tem = TREE_OPERAND (TREE_OPERAND (t, 0), 0);
4978 tree low_bound, up_bound, el_sz;
4979 offset_int idx;
4980 if (TREE_CODE (TREE_TYPE (tem)) != ARRAY_TYPE
4981 || TREE_CODE (TREE_TYPE (TREE_TYPE (tem))) == ARRAY_TYPE
4982 || !TYPE_DOMAIN (TREE_TYPE (tem)))
4983 return;
4985 low_bound = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
4986 up_bound = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
4987 el_sz = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (tem)));
4988 if (!low_bound
4989 || TREE_CODE (low_bound) != INTEGER_CST
4990 || !up_bound
4991 || TREE_CODE (up_bound) != INTEGER_CST
4992 || !el_sz
4993 || TREE_CODE (el_sz) != INTEGER_CST)
4994 return;
4996 if (!mem_ref_offset (t).is_constant (&idx))
4997 return;
4999 idx = wi::sdiv_trunc (idx, wi::to_offset (el_sz));
5000 if (idx < 0)
5002 if (dump_file && (dump_flags & TDF_DETAILS))
5004 fprintf (dump_file, "Array bound warning for ");
5005 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
5006 fprintf (dump_file, "\n");
5008 warning_at (location, OPT_Warray_bounds,
5009 "array subscript %wi is below array bounds of %qT",
5010 idx.to_shwi (), TREE_TYPE (tem));
5011 TREE_NO_WARNING (t) = 1;
5013 else if (idx > (wi::to_offset (up_bound)
5014 - wi::to_offset (low_bound) + 1))
5016 if (dump_file && (dump_flags & TDF_DETAILS))
5018 fprintf (dump_file, "Array bound warning for ");
5019 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
5020 fprintf (dump_file, "\n");
5022 warning_at (location, OPT_Warray_bounds,
5023 "array subscript %wu is above array bounds of %qT",
5024 idx.to_uhwi (), TREE_TYPE (tem));
5025 TREE_NO_WARNING (t) = 1;
5030 /* walk_tree() callback that checks if *TP is
5031 an ARRAY_REF inside an ADDR_EXPR (in which an array
5032 subscript one outside the valid range is allowed). Call
5033 check_array_ref for each ARRAY_REF found. The location is
5034 passed in DATA. */
5036 static tree
5037 check_array_bounds (tree *tp, int *walk_subtree, void *data)
5039 tree t = *tp;
5040 struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
5041 location_t location;
5043 if (EXPR_HAS_LOCATION (t))
5044 location = EXPR_LOCATION (t);
5045 else
5046 location = gimple_location (wi->stmt);
5048 *walk_subtree = TRUE;
5050 vrp_prop *vrp_prop = (class vrp_prop *)wi->info;
5051 if (TREE_CODE (t) == ARRAY_REF)
5052 vrp_prop->check_array_ref (location, t, false /*ignore_off_by_one*/);
5054 else if (TREE_CODE (t) == ADDR_EXPR)
5056 vrp_prop->search_for_addr_array (t, location);
5057 *walk_subtree = FALSE;
5060 return NULL_TREE;
5063 /* A dom_walker subclass for use by vrp_prop::check_all_array_refs,
5064 to walk over all statements of all reachable BBs and call
5065 check_array_bounds on them. */
5067 class check_array_bounds_dom_walker : public dom_walker
5069 public:
5070 check_array_bounds_dom_walker (vrp_prop *prop)
5071 : dom_walker (CDI_DOMINATORS,
5072 /* Discover non-executable edges, preserving EDGE_EXECUTABLE
5073 flags, so that we can merge in information on
5074 non-executable edges from vrp_folder . */
5075 REACHABLE_BLOCKS_PRESERVING_FLAGS),
5076 m_prop (prop) {}
5077 ~check_array_bounds_dom_walker () {}
5079 edge before_dom_children (basic_block) FINAL OVERRIDE;
5081 private:
5082 vrp_prop *m_prop;
5085 /* Implementation of dom_walker::before_dom_children.
5087 Walk over all statements of BB and call check_array_bounds on them,
5088 and determine if there's a unique successor edge. */
5090 edge
5091 check_array_bounds_dom_walker::before_dom_children (basic_block bb)
5093 gimple_stmt_iterator si;
5094 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
5096 gimple *stmt = gsi_stmt (si);
5097 struct walk_stmt_info wi;
5098 if (!gimple_has_location (stmt)
5099 || is_gimple_debug (stmt))
5100 continue;
5102 memset (&wi, 0, sizeof (wi));
5104 wi.info = m_prop;
5106 walk_gimple_op (stmt, check_array_bounds, &wi);
5109 /* Determine if there's a unique successor edge, and if so, return
5110 that back to dom_walker, ensuring that we don't visit blocks that
5111 became unreachable during the VRP propagation
5112 (PR tree-optimization/83312). */
5113 return find_taken_edge (bb, NULL_TREE);
5116 /* Walk over all statements of all reachable BBs and call check_array_bounds
5117 on them. */
5119 void
5120 vrp_prop::check_all_array_refs ()
5122 check_array_bounds_dom_walker w (this);
5123 w.walk (ENTRY_BLOCK_PTR_FOR_FN (cfun));
5126 /* Return true if all imm uses of VAR are either in STMT, or
5127 feed (optionally through a chain of single imm uses) GIMPLE_COND
5128 in basic block COND_BB. */
5130 static bool
5131 all_imm_uses_in_stmt_or_feed_cond (tree var, gimple *stmt, basic_block cond_bb)
5133 use_operand_p use_p, use2_p;
5134 imm_use_iterator iter;
5136 FOR_EACH_IMM_USE_FAST (use_p, iter, var)
5137 if (USE_STMT (use_p) != stmt)
5139 gimple *use_stmt = USE_STMT (use_p), *use_stmt2;
5140 if (is_gimple_debug (use_stmt))
5141 continue;
5142 while (is_gimple_assign (use_stmt)
5143 && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
5144 && single_imm_use (gimple_assign_lhs (use_stmt),
5145 &use2_p, &use_stmt2))
5146 use_stmt = use_stmt2;
5147 if (gimple_code (use_stmt) != GIMPLE_COND
5148 || gimple_bb (use_stmt) != cond_bb)
5149 return false;
5151 return true;
5154 /* Handle
5155 _4 = x_3 & 31;
5156 if (_4 != 0)
5157 goto <bb 6>;
5158 else
5159 goto <bb 7>;
5160 <bb 6>:
5161 __builtin_unreachable ();
5162 <bb 7>:
5163 x_5 = ASSERT_EXPR <x_3, ...>;
5164 If x_3 has no other immediate uses (checked by caller),
5165 var is the x_3 var from ASSERT_EXPR, we can clear low 5 bits
5166 from the non-zero bitmask. */
5168 void
5169 maybe_set_nonzero_bits (edge e, tree var)
5171 basic_block cond_bb = e->src;
5172 gimple *stmt = last_stmt (cond_bb);
5173 tree cst;
5175 if (stmt == NULL
5176 || gimple_code (stmt) != GIMPLE_COND
5177 || gimple_cond_code (stmt) != ((e->flags & EDGE_TRUE_VALUE)
5178 ? EQ_EXPR : NE_EXPR)
5179 || TREE_CODE (gimple_cond_lhs (stmt)) != SSA_NAME
5180 || !integer_zerop (gimple_cond_rhs (stmt)))
5181 return;
5183 stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt));
5184 if (!is_gimple_assign (stmt)
5185 || gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
5186 || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
5187 return;
5188 if (gimple_assign_rhs1 (stmt) != var)
5190 gimple *stmt2;
5192 if (TREE_CODE (gimple_assign_rhs1 (stmt)) != SSA_NAME)
5193 return;
5194 stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
5195 if (!gimple_assign_cast_p (stmt2)
5196 || gimple_assign_rhs1 (stmt2) != var
5197 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt2))
5198 || (TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (stmt)))
5199 != TYPE_PRECISION (TREE_TYPE (var))))
5200 return;
5202 cst = gimple_assign_rhs2 (stmt);
5203 set_nonzero_bits (var, wi::bit_and_not (get_nonzero_bits (var),
5204 wi::to_wide (cst)));
5207 /* Convert range assertion expressions into the implied copies and
5208 copy propagate away the copies. Doing the trivial copy propagation
5209 here avoids the need to run the full copy propagation pass after
5210 VRP.
5212 FIXME, this will eventually lead to copy propagation removing the
5213 names that had useful range information attached to them. For
5214 instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
5215 then N_i will have the range [3, +INF].
5217 However, by converting the assertion into the implied copy
5218 operation N_i = N_j, we will then copy-propagate N_j into the uses
5219 of N_i and lose the range information. We may want to hold on to
5220 ASSERT_EXPRs a little while longer as the ranges could be used in
5221 things like jump threading.
5223 The problem with keeping ASSERT_EXPRs around is that passes after
5224 VRP need to handle them appropriately.
5226 Another approach would be to make the range information a first
5227 class property of the SSA_NAME so that it can be queried from
5228 any pass. This is made somewhat more complex by the need for
5229 multiple ranges to be associated with one SSA_NAME. */
5231 static void
5232 remove_range_assertions (void)
5234 basic_block bb;
5235 gimple_stmt_iterator si;
5236 /* 1 if looking at ASSERT_EXPRs immediately at the beginning of
5237 a basic block preceeded by GIMPLE_COND branching to it and
5238 __builtin_trap, -1 if not yet checked, 0 otherwise. */
5239 int is_unreachable;
5241 /* Note that the BSI iterator bump happens at the bottom of the
5242 loop and no bump is necessary if we're removing the statement
5243 referenced by the current BSI. */
5244 FOR_EACH_BB_FN (bb, cfun)
5245 for (si = gsi_after_labels (bb), is_unreachable = -1; !gsi_end_p (si);)
5247 gimple *stmt = gsi_stmt (si);
5249 if (is_gimple_assign (stmt)
5250 && gimple_assign_rhs_code (stmt) == ASSERT_EXPR)
5252 tree lhs = gimple_assign_lhs (stmt);
5253 tree rhs = gimple_assign_rhs1 (stmt);
5254 tree var;
5256 var = ASSERT_EXPR_VAR (rhs);
5258 if (TREE_CODE (var) == SSA_NAME
5259 && !POINTER_TYPE_P (TREE_TYPE (lhs))
5260 && SSA_NAME_RANGE_INFO (lhs))
5262 if (is_unreachable == -1)
5264 is_unreachable = 0;
5265 if (single_pred_p (bb)
5266 && assert_unreachable_fallthru_edge_p
5267 (single_pred_edge (bb)))
5268 is_unreachable = 1;
5270 /* Handle
5271 if (x_7 >= 10 && x_7 < 20)
5272 __builtin_unreachable ();
5273 x_8 = ASSERT_EXPR <x_7, ...>;
5274 if the only uses of x_7 are in the ASSERT_EXPR and
5275 in the condition. In that case, we can copy the
5276 range info from x_8 computed in this pass also
5277 for x_7. */
5278 if (is_unreachable
5279 && all_imm_uses_in_stmt_or_feed_cond (var, stmt,
5280 single_pred (bb)))
5282 set_range_info (var, SSA_NAME_RANGE_TYPE (lhs),
5283 SSA_NAME_RANGE_INFO (lhs)->get_min (),
5284 SSA_NAME_RANGE_INFO (lhs)->get_max ());
5285 maybe_set_nonzero_bits (single_pred_edge (bb), var);
5289 /* Propagate the RHS into every use of the LHS. For SSA names
5290 also propagate abnormals as it merely restores the original
5291 IL in this case (an replace_uses_by would assert). */
5292 if (TREE_CODE (var) == SSA_NAME)
5294 imm_use_iterator iter;
5295 use_operand_p use_p;
5296 gimple *use_stmt;
5297 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
5298 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
5299 SET_USE (use_p, var);
5301 else
5302 replace_uses_by (lhs, var);
5304 /* And finally, remove the copy, it is not needed. */
5305 gsi_remove (&si, true);
5306 release_defs (stmt);
5308 else
5310 if (!is_gimple_debug (gsi_stmt (si)))
5311 is_unreachable = 0;
5312 gsi_next (&si);
5317 /* Return true if STMT is interesting for VRP. */
5319 bool
5320 stmt_interesting_for_vrp (gimple *stmt)
5322 if (gimple_code (stmt) == GIMPLE_PHI)
5324 tree res = gimple_phi_result (stmt);
5325 return (!virtual_operand_p (res)
5326 && (INTEGRAL_TYPE_P (TREE_TYPE (res))
5327 || POINTER_TYPE_P (TREE_TYPE (res))));
5329 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
5331 tree lhs = gimple_get_lhs (stmt);
5333 /* In general, assignments with virtual operands are not useful
5334 for deriving ranges, with the obvious exception of calls to
5335 builtin functions. */
5336 if (lhs && TREE_CODE (lhs) == SSA_NAME
5337 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
5338 || POINTER_TYPE_P (TREE_TYPE (lhs)))
5339 && (is_gimple_call (stmt)
5340 || !gimple_vuse (stmt)))
5341 return true;
5342 else if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
5343 switch (gimple_call_internal_fn (stmt))
5345 case IFN_ADD_OVERFLOW:
5346 case IFN_SUB_OVERFLOW:
5347 case IFN_MUL_OVERFLOW:
5348 case IFN_ATOMIC_COMPARE_EXCHANGE:
5349 /* These internal calls return _Complex integer type,
5350 but are interesting to VRP nevertheless. */
5351 if (lhs && TREE_CODE (lhs) == SSA_NAME)
5352 return true;
5353 break;
5354 default:
5355 break;
5358 else if (gimple_code (stmt) == GIMPLE_COND
5359 || gimple_code (stmt) == GIMPLE_SWITCH)
5360 return true;
5362 return false;
5365 /* Initialization required by ssa_propagate engine. */
5367 void
5368 vrp_prop::vrp_initialize ()
5370 basic_block bb;
5372 FOR_EACH_BB_FN (bb, cfun)
5374 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
5375 gsi_next (&si))
5377 gphi *phi = si.phi ();
5378 if (!stmt_interesting_for_vrp (phi))
5380 tree lhs = PHI_RESULT (phi);
5381 set_value_range_to_varying (get_value_range (lhs));
5382 prop_set_simulate_again (phi, false);
5384 else
5385 prop_set_simulate_again (phi, true);
5388 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
5389 gsi_next (&si))
5391 gimple *stmt = gsi_stmt (si);
5393 /* If the statement is a control insn, then we do not
5394 want to avoid simulating the statement once. Failure
5395 to do so means that those edges will never get added. */
5396 if (stmt_ends_bb_p (stmt))
5397 prop_set_simulate_again (stmt, true);
5398 else if (!stmt_interesting_for_vrp (stmt))
5400 set_defs_to_varying (stmt);
5401 prop_set_simulate_again (stmt, false);
5403 else
5404 prop_set_simulate_again (stmt, true);
5409 /* Searches the case label vector VEC for the index *IDX of the CASE_LABEL
5410 that includes the value VAL. The search is restricted to the range
5411 [START_IDX, n - 1] where n is the size of VEC.
5413 If there is a CASE_LABEL for VAL, its index is placed in IDX and true is
5414 returned.
5416 If there is no CASE_LABEL for VAL and there is one that is larger than VAL,
5417 it is placed in IDX and false is returned.
5419 If VAL is larger than any CASE_LABEL, n is placed on IDX and false is
5420 returned. */
5422 bool
5423 find_case_label_index (gswitch *stmt, size_t start_idx, tree val, size_t *idx)
5425 size_t n = gimple_switch_num_labels (stmt);
5426 size_t low, high;
5428 /* Find case label for minimum of the value range or the next one.
5429 At each iteration we are searching in [low, high - 1]. */
5431 for (low = start_idx, high = n; high != low; )
5433 tree t;
5434 int cmp;
5435 /* Note that i != high, so we never ask for n. */
5436 size_t i = (high + low) / 2;
5437 t = gimple_switch_label (stmt, i);
5439 /* Cache the result of comparing CASE_LOW and val. */
5440 cmp = tree_int_cst_compare (CASE_LOW (t), val);
5442 if (cmp == 0)
5444 /* Ranges cannot be empty. */
5445 *idx = i;
5446 return true;
5448 else if (cmp > 0)
5449 high = i;
5450 else
5452 low = i + 1;
5453 if (CASE_HIGH (t) != NULL
5454 && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
5456 *idx = i;
5457 return true;
5462 *idx = high;
5463 return false;
5466 /* Searches the case label vector VEC for the range of CASE_LABELs that is used
5467 for values between MIN and MAX. The first index is placed in MIN_IDX. The
5468 last index is placed in MAX_IDX. If the range of CASE_LABELs is empty
5469 then MAX_IDX < MIN_IDX.
5470 Returns true if the default label is not needed. */
5472 bool
5473 find_case_label_range (gswitch *stmt, tree min, tree max, size_t *min_idx,
5474 size_t *max_idx)
5476 size_t i, j;
5477 bool min_take_default = !find_case_label_index (stmt, 1, min, &i);
5478 bool max_take_default = !find_case_label_index (stmt, i, max, &j);
5480 if (i == j
5481 && min_take_default
5482 && max_take_default)
5484 /* Only the default case label reached.
5485 Return an empty range. */
5486 *min_idx = 1;
5487 *max_idx = 0;
5488 return false;
5490 else
5492 bool take_default = min_take_default || max_take_default;
5493 tree low, high;
5494 size_t k;
5496 if (max_take_default)
5497 j--;
5499 /* If the case label range is continuous, we do not need
5500 the default case label. Verify that. */
5501 high = CASE_LOW (gimple_switch_label (stmt, i));
5502 if (CASE_HIGH (gimple_switch_label (stmt, i)))
5503 high = CASE_HIGH (gimple_switch_label (stmt, i));
5504 for (k = i + 1; k <= j; ++k)
5506 low = CASE_LOW (gimple_switch_label (stmt, k));
5507 if (!integer_onep (int_const_binop (MINUS_EXPR, low, high)))
5509 take_default = true;
5510 break;
5512 high = low;
5513 if (CASE_HIGH (gimple_switch_label (stmt, k)))
5514 high = CASE_HIGH (gimple_switch_label (stmt, k));
5517 *min_idx = i;
5518 *max_idx = j;
5519 return !take_default;
5523 /* Evaluate statement STMT. If the statement produces a useful range,
5524 return SSA_PROP_INTERESTING and record the SSA name with the
5525 interesting range into *OUTPUT_P.
5527 If STMT is a conditional branch and we can determine its truth
5528 value, the taken edge is recorded in *TAKEN_EDGE_P.
5530 If STMT produces a varying value, return SSA_PROP_VARYING. */
5532 enum ssa_prop_result
5533 vrp_prop::visit_stmt (gimple *stmt, edge *taken_edge_p, tree *output_p)
5535 value_range vr = VR_INITIALIZER;
5536 tree lhs = gimple_get_lhs (stmt);
5537 extract_range_from_stmt (stmt, taken_edge_p, output_p, &vr);
5539 if (*output_p)
5541 if (update_value_range (*output_p, &vr))
5543 if (dump_file && (dump_flags & TDF_DETAILS))
5545 fprintf (dump_file, "Found new range for ");
5546 print_generic_expr (dump_file, *output_p);
5547 fprintf (dump_file, ": ");
5548 dump_value_range (dump_file, &vr);
5549 fprintf (dump_file, "\n");
5552 if (vr.type == VR_VARYING)
5553 return SSA_PROP_VARYING;
5555 return SSA_PROP_INTERESTING;
5557 return SSA_PROP_NOT_INTERESTING;
5560 if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
5561 switch (gimple_call_internal_fn (stmt))
5563 case IFN_ADD_OVERFLOW:
5564 case IFN_SUB_OVERFLOW:
5565 case IFN_MUL_OVERFLOW:
5566 case IFN_ATOMIC_COMPARE_EXCHANGE:
5567 /* These internal calls return _Complex integer type,
5568 which VRP does not track, but the immediate uses
5569 thereof might be interesting. */
5570 if (lhs && TREE_CODE (lhs) == SSA_NAME)
5572 imm_use_iterator iter;
5573 use_operand_p use_p;
5574 enum ssa_prop_result res = SSA_PROP_VARYING;
5576 set_value_range_to_varying (get_value_range (lhs));
5578 FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
5580 gimple *use_stmt = USE_STMT (use_p);
5581 if (!is_gimple_assign (use_stmt))
5582 continue;
5583 enum tree_code rhs_code = gimple_assign_rhs_code (use_stmt);
5584 if (rhs_code != REALPART_EXPR && rhs_code != IMAGPART_EXPR)
5585 continue;
5586 tree rhs1 = gimple_assign_rhs1 (use_stmt);
5587 tree use_lhs = gimple_assign_lhs (use_stmt);
5588 if (TREE_CODE (rhs1) != rhs_code
5589 || TREE_OPERAND (rhs1, 0) != lhs
5590 || TREE_CODE (use_lhs) != SSA_NAME
5591 || !stmt_interesting_for_vrp (use_stmt)
5592 || (!INTEGRAL_TYPE_P (TREE_TYPE (use_lhs))
5593 || !TYPE_MIN_VALUE (TREE_TYPE (use_lhs))
5594 || !TYPE_MAX_VALUE (TREE_TYPE (use_lhs))))
5595 continue;
5597 /* If there is a change in the value range for any of the
5598 REALPART_EXPR/IMAGPART_EXPR immediate uses, return
5599 SSA_PROP_INTERESTING. If there are any REALPART_EXPR
5600 or IMAGPART_EXPR immediate uses, but none of them have
5601 a change in their value ranges, return
5602 SSA_PROP_NOT_INTERESTING. If there are no
5603 {REAL,IMAG}PART_EXPR uses at all,
5604 return SSA_PROP_VARYING. */
5605 value_range new_vr = VR_INITIALIZER;
5606 extract_range_basic (&new_vr, use_stmt);
5607 value_range *old_vr = get_value_range (use_lhs);
5608 if (old_vr->type != new_vr.type
5609 || !vrp_operand_equal_p (old_vr->min, new_vr.min)
5610 || !vrp_operand_equal_p (old_vr->max, new_vr.max)
5611 || !vrp_bitmap_equal_p (old_vr->equiv, new_vr.equiv))
5612 res = SSA_PROP_INTERESTING;
5613 else
5614 res = SSA_PROP_NOT_INTERESTING;
5615 BITMAP_FREE (new_vr.equiv);
5616 if (res == SSA_PROP_INTERESTING)
5618 *output_p = lhs;
5619 return res;
5623 return res;
5625 break;
5626 default:
5627 break;
5630 /* All other statements produce nothing of interest for VRP, so mark
5631 their outputs varying and prevent further simulation. */
5632 set_defs_to_varying (stmt);
5634 return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
5637 /* Union the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
5638 { VR1TYPE, VR0MIN, VR0MAX } and store the result
5639 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
5640 possible such range. The resulting range is not canonicalized. */
5642 static void
5643 union_ranges (enum value_range_type *vr0type,
5644 tree *vr0min, tree *vr0max,
5645 enum value_range_type vr1type,
5646 tree vr1min, tree vr1max)
5648 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
5649 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
5651 /* [] is vr0, () is vr1 in the following classification comments. */
5652 if (mineq && maxeq)
5654 /* [( )] */
5655 if (*vr0type == vr1type)
5656 /* Nothing to do for equal ranges. */
5658 else if ((*vr0type == VR_RANGE
5659 && vr1type == VR_ANTI_RANGE)
5660 || (*vr0type == VR_ANTI_RANGE
5661 && vr1type == VR_RANGE))
5663 /* For anti-range with range union the result is varying. */
5664 goto give_up;
5666 else
5667 gcc_unreachable ();
5669 else if (operand_less_p (*vr0max, vr1min) == 1
5670 || operand_less_p (vr1max, *vr0min) == 1)
5672 /* [ ] ( ) or ( ) [ ]
5673 If the ranges have an empty intersection, result of the union
5674 operation is the anti-range or if both are anti-ranges
5675 it covers all. */
5676 if (*vr0type == VR_ANTI_RANGE
5677 && vr1type == VR_ANTI_RANGE)
5678 goto give_up;
5679 else if (*vr0type == VR_ANTI_RANGE
5680 && vr1type == VR_RANGE)
5682 else if (*vr0type == VR_RANGE
5683 && vr1type == VR_ANTI_RANGE)
5685 *vr0type = vr1type;
5686 *vr0min = vr1min;
5687 *vr0max = vr1max;
5689 else if (*vr0type == VR_RANGE
5690 && vr1type == VR_RANGE)
5692 /* The result is the convex hull of both ranges. */
5693 if (operand_less_p (*vr0max, vr1min) == 1)
5695 /* If the result can be an anti-range, create one. */
5696 if (TREE_CODE (*vr0max) == INTEGER_CST
5697 && TREE_CODE (vr1min) == INTEGER_CST
5698 && vrp_val_is_min (*vr0min)
5699 && vrp_val_is_max (vr1max))
5701 tree min = int_const_binop (PLUS_EXPR,
5702 *vr0max,
5703 build_int_cst (TREE_TYPE (*vr0max), 1));
5704 tree max = int_const_binop (MINUS_EXPR,
5705 vr1min,
5706 build_int_cst (TREE_TYPE (vr1min), 1));
5707 if (!operand_less_p (max, min))
5709 *vr0type = VR_ANTI_RANGE;
5710 *vr0min = min;
5711 *vr0max = max;
5713 else
5714 *vr0max = vr1max;
5716 else
5717 *vr0max = vr1max;
5719 else
5721 /* If the result can be an anti-range, create one. */
5722 if (TREE_CODE (vr1max) == INTEGER_CST
5723 && TREE_CODE (*vr0min) == INTEGER_CST
5724 && vrp_val_is_min (vr1min)
5725 && vrp_val_is_max (*vr0max))
5727 tree min = int_const_binop (PLUS_EXPR,
5728 vr1max,
5729 build_int_cst (TREE_TYPE (vr1max), 1));
5730 tree max = int_const_binop (MINUS_EXPR,
5731 *vr0min,
5732 build_int_cst (TREE_TYPE (*vr0min), 1));
5733 if (!operand_less_p (max, min))
5735 *vr0type = VR_ANTI_RANGE;
5736 *vr0min = min;
5737 *vr0max = max;
5739 else
5740 *vr0min = vr1min;
5742 else
5743 *vr0min = vr1min;
5746 else
5747 gcc_unreachable ();
5749 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
5750 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
5752 /* [ ( ) ] or [( ) ] or [ ( )] */
5753 if (*vr0type == VR_RANGE
5754 && vr1type == VR_RANGE)
5756 else if (*vr0type == VR_ANTI_RANGE
5757 && vr1type == VR_ANTI_RANGE)
5759 *vr0type = vr1type;
5760 *vr0min = vr1min;
5761 *vr0max = vr1max;
5763 else if (*vr0type == VR_ANTI_RANGE
5764 && vr1type == VR_RANGE)
5766 /* Arbitrarily choose the right or left gap. */
5767 if (!mineq && TREE_CODE (vr1min) == INTEGER_CST)
5768 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5769 build_int_cst (TREE_TYPE (vr1min), 1));
5770 else if (!maxeq && TREE_CODE (vr1max) == INTEGER_CST)
5771 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5772 build_int_cst (TREE_TYPE (vr1max), 1));
5773 else
5774 goto give_up;
5776 else if (*vr0type == VR_RANGE
5777 && vr1type == VR_ANTI_RANGE)
5778 /* The result covers everything. */
5779 goto give_up;
5780 else
5781 gcc_unreachable ();
5783 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
5784 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
5786 /* ( [ ] ) or ([ ] ) or ( [ ]) */
5787 if (*vr0type == VR_RANGE
5788 && vr1type == VR_RANGE)
5790 *vr0type = vr1type;
5791 *vr0min = vr1min;
5792 *vr0max = vr1max;
5794 else if (*vr0type == VR_ANTI_RANGE
5795 && vr1type == VR_ANTI_RANGE)
5797 else if (*vr0type == VR_RANGE
5798 && vr1type == VR_ANTI_RANGE)
5800 *vr0type = VR_ANTI_RANGE;
5801 if (!mineq && TREE_CODE (*vr0min) == INTEGER_CST)
5803 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5804 build_int_cst (TREE_TYPE (*vr0min), 1));
5805 *vr0min = vr1min;
5807 else if (!maxeq && TREE_CODE (*vr0max) == INTEGER_CST)
5809 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5810 build_int_cst (TREE_TYPE (*vr0max), 1));
5811 *vr0max = vr1max;
5813 else
5814 goto give_up;
5816 else if (*vr0type == VR_ANTI_RANGE
5817 && vr1type == VR_RANGE)
5818 /* The result covers everything. */
5819 goto give_up;
5820 else
5821 gcc_unreachable ();
5823 else if ((operand_less_p (vr1min, *vr0max) == 1
5824 || operand_equal_p (vr1min, *vr0max, 0))
5825 && operand_less_p (*vr0min, vr1min) == 1
5826 && operand_less_p (*vr0max, vr1max) == 1)
5828 /* [ ( ] ) or [ ]( ) */
5829 if (*vr0type == VR_RANGE
5830 && vr1type == VR_RANGE)
5831 *vr0max = vr1max;
5832 else if (*vr0type == VR_ANTI_RANGE
5833 && vr1type == VR_ANTI_RANGE)
5834 *vr0min = vr1min;
5835 else if (*vr0type == VR_ANTI_RANGE
5836 && vr1type == VR_RANGE)
5838 if (TREE_CODE (vr1min) == INTEGER_CST)
5839 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5840 build_int_cst (TREE_TYPE (vr1min), 1));
5841 else
5842 goto give_up;
5844 else if (*vr0type == VR_RANGE
5845 && vr1type == VR_ANTI_RANGE)
5847 if (TREE_CODE (*vr0max) == INTEGER_CST)
5849 *vr0type = vr1type;
5850 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5851 build_int_cst (TREE_TYPE (*vr0max), 1));
5852 *vr0max = vr1max;
5854 else
5855 goto give_up;
5857 else
5858 gcc_unreachable ();
5860 else if ((operand_less_p (*vr0min, vr1max) == 1
5861 || operand_equal_p (*vr0min, vr1max, 0))
5862 && operand_less_p (vr1min, *vr0min) == 1
5863 && operand_less_p (vr1max, *vr0max) == 1)
5865 /* ( [ ) ] or ( )[ ] */
5866 if (*vr0type == VR_RANGE
5867 && vr1type == VR_RANGE)
5868 *vr0min = vr1min;
5869 else if (*vr0type == VR_ANTI_RANGE
5870 && vr1type == VR_ANTI_RANGE)
5871 *vr0max = vr1max;
5872 else if (*vr0type == VR_ANTI_RANGE
5873 && vr1type == VR_RANGE)
5875 if (TREE_CODE (vr1max) == INTEGER_CST)
5876 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5877 build_int_cst (TREE_TYPE (vr1max), 1));
5878 else
5879 goto give_up;
5881 else if (*vr0type == VR_RANGE
5882 && vr1type == VR_ANTI_RANGE)
5884 if (TREE_CODE (*vr0min) == INTEGER_CST)
5886 *vr0type = vr1type;
5887 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5888 build_int_cst (TREE_TYPE (*vr0min), 1));
5889 *vr0min = vr1min;
5891 else
5892 goto give_up;
5894 else
5895 gcc_unreachable ();
5897 else
5898 goto give_up;
5900 return;
5902 give_up:
5903 *vr0type = VR_VARYING;
5904 *vr0min = NULL_TREE;
5905 *vr0max = NULL_TREE;
5908 /* Intersect the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
5909 { VR1TYPE, VR0MIN, VR0MAX } and store the result
5910 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
5911 possible such range. The resulting range is not canonicalized. */
5913 static void
5914 intersect_ranges (enum value_range_type *vr0type,
5915 tree *vr0min, tree *vr0max,
5916 enum value_range_type vr1type,
5917 tree vr1min, tree vr1max)
5919 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
5920 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
5922 /* [] is vr0, () is vr1 in the following classification comments. */
5923 if (mineq && maxeq)
5925 /* [( )] */
5926 if (*vr0type == vr1type)
5927 /* Nothing to do for equal ranges. */
5929 else if ((*vr0type == VR_RANGE
5930 && vr1type == VR_ANTI_RANGE)
5931 || (*vr0type == VR_ANTI_RANGE
5932 && vr1type == VR_RANGE))
5934 /* For anti-range with range intersection the result is empty. */
5935 *vr0type = VR_UNDEFINED;
5936 *vr0min = NULL_TREE;
5937 *vr0max = NULL_TREE;
5939 else
5940 gcc_unreachable ();
5942 else if (operand_less_p (*vr0max, vr1min) == 1
5943 || operand_less_p (vr1max, *vr0min) == 1)
5945 /* [ ] ( ) or ( ) [ ]
5946 If the ranges have an empty intersection, the result of the
5947 intersect operation is the range for intersecting an
5948 anti-range with a range or empty when intersecting two ranges. */
5949 if (*vr0type == VR_RANGE
5950 && vr1type == VR_ANTI_RANGE)
5952 else if (*vr0type == VR_ANTI_RANGE
5953 && vr1type == VR_RANGE)
5955 *vr0type = vr1type;
5956 *vr0min = vr1min;
5957 *vr0max = vr1max;
5959 else if (*vr0type == VR_RANGE
5960 && vr1type == VR_RANGE)
5962 *vr0type = VR_UNDEFINED;
5963 *vr0min = NULL_TREE;
5964 *vr0max = NULL_TREE;
5966 else if (*vr0type == VR_ANTI_RANGE
5967 && vr1type == VR_ANTI_RANGE)
5969 /* If the anti-ranges are adjacent to each other merge them. */
5970 if (TREE_CODE (*vr0max) == INTEGER_CST
5971 && TREE_CODE (vr1min) == INTEGER_CST
5972 && operand_less_p (*vr0max, vr1min) == 1
5973 && integer_onep (int_const_binop (MINUS_EXPR,
5974 vr1min, *vr0max)))
5975 *vr0max = vr1max;
5976 else if (TREE_CODE (vr1max) == INTEGER_CST
5977 && TREE_CODE (*vr0min) == INTEGER_CST
5978 && operand_less_p (vr1max, *vr0min) == 1
5979 && integer_onep (int_const_binop (MINUS_EXPR,
5980 *vr0min, vr1max)))
5981 *vr0min = vr1min;
5982 /* Else arbitrarily take VR0. */
5985 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
5986 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
5988 /* [ ( ) ] or [( ) ] or [ ( )] */
5989 if (*vr0type == VR_RANGE
5990 && vr1type == VR_RANGE)
5992 /* If both are ranges the result is the inner one. */
5993 *vr0type = vr1type;
5994 *vr0min = vr1min;
5995 *vr0max = vr1max;
5997 else if (*vr0type == VR_RANGE
5998 && vr1type == VR_ANTI_RANGE)
6000 /* Choose the right gap if the left one is empty. */
6001 if (mineq)
6003 if (TREE_CODE (vr1max) != INTEGER_CST)
6004 *vr0min = vr1max;
6005 else if (TYPE_PRECISION (TREE_TYPE (vr1max)) == 1
6006 && !TYPE_UNSIGNED (TREE_TYPE (vr1max)))
6007 *vr0min
6008 = int_const_binop (MINUS_EXPR, vr1max,
6009 build_int_cst (TREE_TYPE (vr1max), -1));
6010 else
6011 *vr0min
6012 = int_const_binop (PLUS_EXPR, vr1max,
6013 build_int_cst (TREE_TYPE (vr1max), 1));
6015 /* Choose the left gap if the right one is empty. */
6016 else if (maxeq)
6018 if (TREE_CODE (vr1min) != INTEGER_CST)
6019 *vr0max = vr1min;
6020 else if (TYPE_PRECISION (TREE_TYPE (vr1min)) == 1
6021 && !TYPE_UNSIGNED (TREE_TYPE (vr1min)))
6022 *vr0max
6023 = int_const_binop (PLUS_EXPR, vr1min,
6024 build_int_cst (TREE_TYPE (vr1min), -1));
6025 else
6026 *vr0max
6027 = int_const_binop (MINUS_EXPR, vr1min,
6028 build_int_cst (TREE_TYPE (vr1min), 1));
6030 /* Choose the anti-range if the range is effectively varying. */
6031 else if (vrp_val_is_min (*vr0min)
6032 && vrp_val_is_max (*vr0max))
6034 *vr0type = vr1type;
6035 *vr0min = vr1min;
6036 *vr0max = vr1max;
6038 /* Else choose the range. */
6040 else if (*vr0type == VR_ANTI_RANGE
6041 && vr1type == VR_ANTI_RANGE)
6042 /* If both are anti-ranges the result is the outer one. */
6044 else if (*vr0type == VR_ANTI_RANGE
6045 && vr1type == VR_RANGE)
6047 /* The intersection is empty. */
6048 *vr0type = VR_UNDEFINED;
6049 *vr0min = NULL_TREE;
6050 *vr0max = NULL_TREE;
6052 else
6053 gcc_unreachable ();
6055 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
6056 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
6058 /* ( [ ] ) or ([ ] ) or ( [ ]) */
6059 if (*vr0type == VR_RANGE
6060 && vr1type == VR_RANGE)
6061 /* Choose the inner range. */
6063 else if (*vr0type == VR_ANTI_RANGE
6064 && vr1type == VR_RANGE)
6066 /* Choose the right gap if the left is empty. */
6067 if (mineq)
6069 *vr0type = VR_RANGE;
6070 if (TREE_CODE (*vr0max) != INTEGER_CST)
6071 *vr0min = *vr0max;
6072 else if (TYPE_PRECISION (TREE_TYPE (*vr0max)) == 1
6073 && !TYPE_UNSIGNED (TREE_TYPE (*vr0max)))
6074 *vr0min
6075 = int_const_binop (MINUS_EXPR, *vr0max,
6076 build_int_cst (TREE_TYPE (*vr0max), -1));
6077 else
6078 *vr0min
6079 = int_const_binop (PLUS_EXPR, *vr0max,
6080 build_int_cst (TREE_TYPE (*vr0max), 1));
6081 *vr0max = vr1max;
6083 /* Choose the left gap if the right is empty. */
6084 else if (maxeq)
6086 *vr0type = VR_RANGE;
6087 if (TREE_CODE (*vr0min) != INTEGER_CST)
6088 *vr0max = *vr0min;
6089 else if (TYPE_PRECISION (TREE_TYPE (*vr0min)) == 1
6090 && !TYPE_UNSIGNED (TREE_TYPE (*vr0min)))
6091 *vr0max
6092 = int_const_binop (PLUS_EXPR, *vr0min,
6093 build_int_cst (TREE_TYPE (*vr0min), -1));
6094 else
6095 *vr0max
6096 = int_const_binop (MINUS_EXPR, *vr0min,
6097 build_int_cst (TREE_TYPE (*vr0min), 1));
6098 *vr0min = vr1min;
6100 /* Choose the anti-range if the range is effectively varying. */
6101 else if (vrp_val_is_min (vr1min)
6102 && vrp_val_is_max (vr1max))
6104 /* Choose the anti-range if it is ~[0,0], that range is special
6105 enough to special case when vr1's range is relatively wide.
6106 At least for types bigger than int - this covers pointers
6107 and arguments to functions like ctz. */
6108 else if (*vr0min == *vr0max
6109 && integer_zerop (*vr0min)
6110 && ((TYPE_PRECISION (TREE_TYPE (*vr0min))
6111 >= TYPE_PRECISION (integer_type_node))
6112 || POINTER_TYPE_P (TREE_TYPE (*vr0min)))
6113 && TREE_CODE (vr1max) == INTEGER_CST
6114 && TREE_CODE (vr1min) == INTEGER_CST
6115 && (wi::clz (wi::to_wide (vr1max) - wi::to_wide (vr1min))
6116 < TYPE_PRECISION (TREE_TYPE (*vr0min)) / 2))
6118 /* Else choose the range. */
6119 else
6121 *vr0type = vr1type;
6122 *vr0min = vr1min;
6123 *vr0max = vr1max;
6126 else if (*vr0type == VR_ANTI_RANGE
6127 && vr1type == VR_ANTI_RANGE)
6129 /* If both are anti-ranges the result is the outer one. */
6130 *vr0type = vr1type;
6131 *vr0min = vr1min;
6132 *vr0max = vr1max;
6134 else if (vr1type == VR_ANTI_RANGE
6135 && *vr0type == VR_RANGE)
6137 /* The intersection is empty. */
6138 *vr0type = VR_UNDEFINED;
6139 *vr0min = NULL_TREE;
6140 *vr0max = NULL_TREE;
6142 else
6143 gcc_unreachable ();
6145 else if ((operand_less_p (vr1min, *vr0max) == 1
6146 || operand_equal_p (vr1min, *vr0max, 0))
6147 && operand_less_p (*vr0min, vr1min) == 1)
6149 /* [ ( ] ) or [ ]( ) */
6150 if (*vr0type == VR_ANTI_RANGE
6151 && vr1type == VR_ANTI_RANGE)
6152 *vr0max = vr1max;
6153 else if (*vr0type == VR_RANGE
6154 && vr1type == VR_RANGE)
6155 *vr0min = vr1min;
6156 else if (*vr0type == VR_RANGE
6157 && vr1type == VR_ANTI_RANGE)
6159 if (TREE_CODE (vr1min) == INTEGER_CST)
6160 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
6161 build_int_cst (TREE_TYPE (vr1min), 1));
6162 else
6163 *vr0max = vr1min;
6165 else if (*vr0type == VR_ANTI_RANGE
6166 && vr1type == VR_RANGE)
6168 *vr0type = VR_RANGE;
6169 if (TREE_CODE (*vr0max) == INTEGER_CST)
6170 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
6171 build_int_cst (TREE_TYPE (*vr0max), 1));
6172 else
6173 *vr0min = *vr0max;
6174 *vr0max = vr1max;
6176 else
6177 gcc_unreachable ();
6179 else if ((operand_less_p (*vr0min, vr1max) == 1
6180 || operand_equal_p (*vr0min, vr1max, 0))
6181 && operand_less_p (vr1min, *vr0min) == 1)
6183 /* ( [ ) ] or ( )[ ] */
6184 if (*vr0type == VR_ANTI_RANGE
6185 && vr1type == VR_ANTI_RANGE)
6186 *vr0min = vr1min;
6187 else if (*vr0type == VR_RANGE
6188 && vr1type == VR_RANGE)
6189 *vr0max = vr1max;
6190 else if (*vr0type == VR_RANGE
6191 && vr1type == VR_ANTI_RANGE)
6193 if (TREE_CODE (vr1max) == INTEGER_CST)
6194 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
6195 build_int_cst (TREE_TYPE (vr1max), 1));
6196 else
6197 *vr0min = vr1max;
6199 else if (*vr0type == VR_ANTI_RANGE
6200 && vr1type == VR_RANGE)
6202 *vr0type = VR_RANGE;
6203 if (TREE_CODE (*vr0min) == INTEGER_CST)
6204 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
6205 build_int_cst (TREE_TYPE (*vr0min), 1));
6206 else
6207 *vr0max = *vr0min;
6208 *vr0min = vr1min;
6210 else
6211 gcc_unreachable ();
6214 /* As a fallback simply use { *VRTYPE, *VR0MIN, *VR0MAX } as
6215 result for the intersection. That's always a conservative
6216 correct estimate unless VR1 is a constant singleton range
6217 in which case we choose that. */
6218 if (vr1type == VR_RANGE
6219 && is_gimple_min_invariant (vr1min)
6220 && vrp_operand_equal_p (vr1min, vr1max))
6222 *vr0type = vr1type;
6223 *vr0min = vr1min;
6224 *vr0max = vr1max;
6227 return;
6231 /* Intersect the two value-ranges *VR0 and *VR1 and store the result
6232 in *VR0. This may not be the smallest possible such range. */
6234 static void
6235 vrp_intersect_ranges_1 (value_range *vr0, value_range *vr1)
6237 value_range saved;
6239 /* If either range is VR_VARYING the other one wins. */
6240 if (vr1->type == VR_VARYING)
6241 return;
6242 if (vr0->type == VR_VARYING)
6244 copy_value_range (vr0, vr1);
6245 return;
6248 /* When either range is VR_UNDEFINED the resulting range is
6249 VR_UNDEFINED, too. */
6250 if (vr0->type == VR_UNDEFINED)
6251 return;
6252 if (vr1->type == VR_UNDEFINED)
6254 set_value_range_to_undefined (vr0);
6255 return;
6258 /* Save the original vr0 so we can return it as conservative intersection
6259 result when our worker turns things to varying. */
6260 saved = *vr0;
6261 intersect_ranges (&vr0->type, &vr0->min, &vr0->max,
6262 vr1->type, vr1->min, vr1->max);
6263 /* Make sure to canonicalize the result though as the inversion of a
6264 VR_RANGE can still be a VR_RANGE. */
6265 set_and_canonicalize_value_range (vr0, vr0->type,
6266 vr0->min, vr0->max, vr0->equiv);
6267 /* If that failed, use the saved original VR0. */
6268 if (vr0->type == VR_VARYING)
6270 *vr0 = saved;
6271 return;
6273 /* If the result is VR_UNDEFINED there is no need to mess with
6274 the equivalencies. */
6275 if (vr0->type == VR_UNDEFINED)
6276 return;
6278 /* The resulting set of equivalences for range intersection is the union of
6279 the two sets. */
6280 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
6281 bitmap_ior_into (vr0->equiv, vr1->equiv);
6282 else if (vr1->equiv && !vr0->equiv)
6284 /* All equivalence bitmaps are allocated from the same obstack. So
6285 we can use the obstack associated with VR to allocate vr0->equiv. */
6286 vr0->equiv = BITMAP_ALLOC (vr1->equiv->obstack);
6287 bitmap_copy (vr0->equiv, vr1->equiv);
6291 void
6292 vrp_intersect_ranges (value_range *vr0, value_range *vr1)
6294 if (dump_file && (dump_flags & TDF_DETAILS))
6296 fprintf (dump_file, "Intersecting\n ");
6297 dump_value_range (dump_file, vr0);
6298 fprintf (dump_file, "\nand\n ");
6299 dump_value_range (dump_file, vr1);
6300 fprintf (dump_file, "\n");
6302 vrp_intersect_ranges_1 (vr0, vr1);
6303 if (dump_file && (dump_flags & TDF_DETAILS))
6305 fprintf (dump_file, "to\n ");
6306 dump_value_range (dump_file, vr0);
6307 fprintf (dump_file, "\n");
6311 /* Meet operation for value ranges. Given two value ranges VR0 and
6312 VR1, store in VR0 a range that contains both VR0 and VR1. This
6313 may not be the smallest possible such range. */
6315 static void
6316 vrp_meet_1 (value_range *vr0, const value_range *vr1)
6318 value_range saved;
6320 if (vr0->type == VR_UNDEFINED)
6322 set_value_range (vr0, vr1->type, vr1->min, vr1->max, vr1->equiv);
6323 return;
6326 if (vr1->type == VR_UNDEFINED)
6328 /* VR0 already has the resulting range. */
6329 return;
6332 if (vr0->type == VR_VARYING)
6334 /* Nothing to do. VR0 already has the resulting range. */
6335 return;
6338 if (vr1->type == VR_VARYING)
6340 set_value_range_to_varying (vr0);
6341 return;
6344 saved = *vr0;
6345 union_ranges (&vr0->type, &vr0->min, &vr0->max,
6346 vr1->type, vr1->min, vr1->max);
6347 if (vr0->type == VR_VARYING)
6349 /* Failed to find an efficient meet. Before giving up and setting
6350 the result to VARYING, see if we can at least derive a useful
6351 anti-range. FIXME, all this nonsense about distinguishing
6352 anti-ranges from ranges is necessary because of the odd
6353 semantics of range_includes_zero_p and friends. */
6354 if (((saved.type == VR_RANGE
6355 && range_includes_zero_p (saved.min, saved.max) == 0)
6356 || (saved.type == VR_ANTI_RANGE
6357 && range_includes_zero_p (saved.min, saved.max) == 1))
6358 && ((vr1->type == VR_RANGE
6359 && range_includes_zero_p (vr1->min, vr1->max) == 0)
6360 || (vr1->type == VR_ANTI_RANGE
6361 && range_includes_zero_p (vr1->min, vr1->max) == 1)))
6363 set_value_range_to_nonnull (vr0, TREE_TYPE (saved.min));
6365 /* Since this meet operation did not result from the meeting of
6366 two equivalent names, VR0 cannot have any equivalences. */
6367 if (vr0->equiv)
6368 bitmap_clear (vr0->equiv);
6369 return;
6372 set_value_range_to_varying (vr0);
6373 return;
6375 set_and_canonicalize_value_range (vr0, vr0->type, vr0->min, vr0->max,
6376 vr0->equiv);
6377 if (vr0->type == VR_VARYING)
6378 return;
6380 /* The resulting set of equivalences is always the intersection of
6381 the two sets. */
6382 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
6383 bitmap_and_into (vr0->equiv, vr1->equiv);
6384 else if (vr0->equiv && !vr1->equiv)
6385 bitmap_clear (vr0->equiv);
6388 void
6389 vrp_meet (value_range *vr0, const value_range *vr1)
6391 if (dump_file && (dump_flags & TDF_DETAILS))
6393 fprintf (dump_file, "Meeting\n ");
6394 dump_value_range (dump_file, vr0);
6395 fprintf (dump_file, "\nand\n ");
6396 dump_value_range (dump_file, vr1);
6397 fprintf (dump_file, "\n");
6399 vrp_meet_1 (vr0, vr1);
6400 if (dump_file && (dump_flags & TDF_DETAILS))
6402 fprintf (dump_file, "to\n ");
6403 dump_value_range (dump_file, vr0);
6404 fprintf (dump_file, "\n");
6409 /* Visit all arguments for PHI node PHI that flow through executable
6410 edges. If a valid value range can be derived from all the incoming
6411 value ranges, set a new range for the LHS of PHI. */
6413 enum ssa_prop_result
6414 vrp_prop::visit_phi (gphi *phi)
6416 tree lhs = PHI_RESULT (phi);
6417 value_range vr_result = VR_INITIALIZER;
6418 extract_range_from_phi_node (phi, &vr_result);
6419 if (update_value_range (lhs, &vr_result))
6421 if (dump_file && (dump_flags & TDF_DETAILS))
6423 fprintf (dump_file, "Found new range for ");
6424 print_generic_expr (dump_file, lhs);
6425 fprintf (dump_file, ": ");
6426 dump_value_range (dump_file, &vr_result);
6427 fprintf (dump_file, "\n");
6430 if (vr_result.type == VR_VARYING)
6431 return SSA_PROP_VARYING;
6433 return SSA_PROP_INTERESTING;
6436 /* Nothing changed, don't add outgoing edges. */
6437 return SSA_PROP_NOT_INTERESTING;
6440 class vrp_folder : public substitute_and_fold_engine
6442 public:
6443 tree get_value (tree) FINAL OVERRIDE;
6444 bool fold_stmt (gimple_stmt_iterator *) FINAL OVERRIDE;
6445 bool fold_predicate_in (gimple_stmt_iterator *);
6447 class vr_values *vr_values;
6449 /* Delegators. */
6450 tree vrp_evaluate_conditional (tree_code code, tree op0,
6451 tree op1, gimple *stmt)
6452 { return vr_values->vrp_evaluate_conditional (code, op0, op1, stmt); }
6453 bool simplify_stmt_using_ranges (gimple_stmt_iterator *gsi)
6454 { return vr_values->simplify_stmt_using_ranges (gsi); }
6455 tree op_with_constant_singleton_value_range (tree op)
6456 { return vr_values->op_with_constant_singleton_value_range (op); }
6459 /* If the statement pointed by SI has a predicate whose value can be
6460 computed using the value range information computed by VRP, compute
6461 its value and return true. Otherwise, return false. */
6463 bool
6464 vrp_folder::fold_predicate_in (gimple_stmt_iterator *si)
6466 bool assignment_p = false;
6467 tree val;
6468 gimple *stmt = gsi_stmt (*si);
6470 if (is_gimple_assign (stmt)
6471 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
6473 assignment_p = true;
6474 val = vrp_evaluate_conditional (gimple_assign_rhs_code (stmt),
6475 gimple_assign_rhs1 (stmt),
6476 gimple_assign_rhs2 (stmt),
6477 stmt);
6479 else if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
6480 val = vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
6481 gimple_cond_lhs (cond_stmt),
6482 gimple_cond_rhs (cond_stmt),
6483 stmt);
6484 else
6485 return false;
6487 if (val)
6489 if (assignment_p)
6490 val = fold_convert (gimple_expr_type (stmt), val);
6492 if (dump_file)
6494 fprintf (dump_file, "Folding predicate ");
6495 print_gimple_expr (dump_file, stmt, 0);
6496 fprintf (dump_file, " to ");
6497 print_generic_expr (dump_file, val);
6498 fprintf (dump_file, "\n");
6501 if (is_gimple_assign (stmt))
6502 gimple_assign_set_rhs_from_tree (si, val);
6503 else
6505 gcc_assert (gimple_code (stmt) == GIMPLE_COND);
6506 gcond *cond_stmt = as_a <gcond *> (stmt);
6507 if (integer_zerop (val))
6508 gimple_cond_make_false (cond_stmt);
6509 else if (integer_onep (val))
6510 gimple_cond_make_true (cond_stmt);
6511 else
6512 gcc_unreachable ();
6515 return true;
6518 return false;
6521 /* Callback for substitute_and_fold folding the stmt at *SI. */
6523 bool
6524 vrp_folder::fold_stmt (gimple_stmt_iterator *si)
6526 if (fold_predicate_in (si))
6527 return true;
6529 return simplify_stmt_using_ranges (si);
6532 /* If OP has a value range with a single constant value return that,
6533 otherwise return NULL_TREE. This returns OP itself if OP is a
6534 constant.
6536 Implemented as a pure wrapper right now, but this will change. */
6538 tree
6539 vrp_folder::get_value (tree op)
6541 return op_with_constant_singleton_value_range (op);
6544 /* Return the LHS of any ASSERT_EXPR where OP appears as the first
6545 argument to the ASSERT_EXPR and in which the ASSERT_EXPR dominates
6546 BB. If no such ASSERT_EXPR is found, return OP. */
6548 static tree
6549 lhs_of_dominating_assert (tree op, basic_block bb, gimple *stmt)
6551 imm_use_iterator imm_iter;
6552 gimple *use_stmt;
6553 use_operand_p use_p;
6555 if (TREE_CODE (op) == SSA_NAME)
6557 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, op)
6559 use_stmt = USE_STMT (use_p);
6560 if (use_stmt != stmt
6561 && gimple_assign_single_p (use_stmt)
6562 && TREE_CODE (gimple_assign_rhs1 (use_stmt)) == ASSERT_EXPR
6563 && TREE_OPERAND (gimple_assign_rhs1 (use_stmt), 0) == op
6564 && dominated_by_p (CDI_DOMINATORS, bb, gimple_bb (use_stmt)))
6565 return gimple_assign_lhs (use_stmt);
6568 return op;
6571 /* A hack. */
6572 static class vr_values *x_vr_values;
6574 /* A trivial wrapper so that we can present the generic jump threading
6575 code with a simple API for simplifying statements. STMT is the
6576 statement we want to simplify, WITHIN_STMT provides the location
6577 for any overflow warnings. */
6579 static tree
6580 simplify_stmt_for_jump_threading (gimple *stmt, gimple *within_stmt,
6581 class avail_exprs_stack *avail_exprs_stack ATTRIBUTE_UNUSED,
6582 basic_block bb)
6584 /* First see if the conditional is in the hash table. */
6585 tree cached_lhs = avail_exprs_stack->lookup_avail_expr (stmt, false, true);
6586 if (cached_lhs && is_gimple_min_invariant (cached_lhs))
6587 return cached_lhs;
6589 vr_values *vr_values = x_vr_values;
6590 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
6592 tree op0 = gimple_cond_lhs (cond_stmt);
6593 op0 = lhs_of_dominating_assert (op0, bb, stmt);
6595 tree op1 = gimple_cond_rhs (cond_stmt);
6596 op1 = lhs_of_dominating_assert (op1, bb, stmt);
6598 return vr_values->vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
6599 op0, op1, within_stmt);
6602 /* We simplify a switch statement by trying to determine which case label
6603 will be taken. If we are successful then we return the corresponding
6604 CASE_LABEL_EXPR. */
6605 if (gswitch *switch_stmt = dyn_cast <gswitch *> (stmt))
6607 tree op = gimple_switch_index (switch_stmt);
6608 if (TREE_CODE (op) != SSA_NAME)
6609 return NULL_TREE;
6611 op = lhs_of_dominating_assert (op, bb, stmt);
6613 value_range *vr = vr_values->get_value_range (op);
6614 if ((vr->type != VR_RANGE && vr->type != VR_ANTI_RANGE)
6615 || symbolic_range_p (vr))
6616 return NULL_TREE;
6618 if (vr->type == VR_RANGE)
6620 size_t i, j;
6621 /* Get the range of labels that contain a part of the operand's
6622 value range. */
6623 find_case_label_range (switch_stmt, vr->min, vr->max, &i, &j);
6625 /* Is there only one such label? */
6626 if (i == j)
6628 tree label = gimple_switch_label (switch_stmt, i);
6630 /* The i'th label will be taken only if the value range of the
6631 operand is entirely within the bounds of this label. */
6632 if (CASE_HIGH (label) != NULL_TREE
6633 ? (tree_int_cst_compare (CASE_LOW (label), vr->min) <= 0
6634 && tree_int_cst_compare (CASE_HIGH (label), vr->max) >= 0)
6635 : (tree_int_cst_equal (CASE_LOW (label), vr->min)
6636 && tree_int_cst_equal (vr->min, vr->max)))
6637 return label;
6640 /* If there are no such labels then the default label will be
6641 taken. */
6642 if (i > j)
6643 return gimple_switch_label (switch_stmt, 0);
6646 if (vr->type == VR_ANTI_RANGE)
6648 unsigned n = gimple_switch_num_labels (switch_stmt);
6649 tree min_label = gimple_switch_label (switch_stmt, 1);
6650 tree max_label = gimple_switch_label (switch_stmt, n - 1);
6652 /* The default label will be taken only if the anti-range of the
6653 operand is entirely outside the bounds of all the (non-default)
6654 case labels. */
6655 if (tree_int_cst_compare (vr->min, CASE_LOW (min_label)) <= 0
6656 && (CASE_HIGH (max_label) != NULL_TREE
6657 ? tree_int_cst_compare (vr->max, CASE_HIGH (max_label)) >= 0
6658 : tree_int_cst_compare (vr->max, CASE_LOW (max_label)) >= 0))
6659 return gimple_switch_label (switch_stmt, 0);
6662 return NULL_TREE;
6665 if (gassign *assign_stmt = dyn_cast <gassign *> (stmt))
6667 tree lhs = gimple_assign_lhs (assign_stmt);
6668 if (TREE_CODE (lhs) == SSA_NAME
6669 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
6670 || POINTER_TYPE_P (TREE_TYPE (lhs)))
6671 && stmt_interesting_for_vrp (stmt))
6673 edge dummy_e;
6674 tree dummy_tree;
6675 value_range new_vr = VR_INITIALIZER;
6676 vr_values->extract_range_from_stmt (stmt, &dummy_e,
6677 &dummy_tree, &new_vr);
6678 if (range_int_cst_singleton_p (&new_vr))
6679 return new_vr.min;
6683 return NULL_TREE;
6686 class vrp_dom_walker : public dom_walker
6688 public:
6689 vrp_dom_walker (cdi_direction direction,
6690 class const_and_copies *const_and_copies,
6691 class avail_exprs_stack *avail_exprs_stack)
6692 : dom_walker (direction, REACHABLE_BLOCKS),
6693 m_const_and_copies (const_and_copies),
6694 m_avail_exprs_stack (avail_exprs_stack),
6695 m_dummy_cond (NULL) {}
6697 virtual edge before_dom_children (basic_block);
6698 virtual void after_dom_children (basic_block);
6700 class vr_values *vr_values;
6702 private:
6703 class const_and_copies *m_const_and_copies;
6704 class avail_exprs_stack *m_avail_exprs_stack;
6706 gcond *m_dummy_cond;
6710 /* Called before processing dominator children of BB. We want to look
6711 at ASSERT_EXPRs and record information from them in the appropriate
6712 tables.
6714 We could look at other statements here. It's not seen as likely
6715 to significantly increase the jump threads we discover. */
6717 edge
6718 vrp_dom_walker::before_dom_children (basic_block bb)
6720 gimple_stmt_iterator gsi;
6722 m_avail_exprs_stack->push_marker ();
6723 m_const_and_copies->push_marker ();
6724 for (gsi = gsi_start_nondebug_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
6726 gimple *stmt = gsi_stmt (gsi);
6727 if (gimple_assign_single_p (stmt)
6728 && TREE_CODE (gimple_assign_rhs1 (stmt)) == ASSERT_EXPR)
6730 tree rhs1 = gimple_assign_rhs1 (stmt);
6731 tree cond = TREE_OPERAND (rhs1, 1);
6732 tree inverted = invert_truthvalue (cond);
6733 vec<cond_equivalence> p;
6734 p.create (3);
6735 record_conditions (&p, cond, inverted);
6736 for (unsigned int i = 0; i < p.length (); i++)
6737 m_avail_exprs_stack->record_cond (&p[i]);
6739 tree lhs = gimple_assign_lhs (stmt);
6740 m_const_and_copies->record_const_or_copy (lhs,
6741 TREE_OPERAND (rhs1, 0));
6742 p.release ();
6743 continue;
6745 break;
6747 return NULL;
6750 /* Called after processing dominator children of BB. This is where we
6751 actually call into the threader. */
6752 void
6753 vrp_dom_walker::after_dom_children (basic_block bb)
6755 if (!m_dummy_cond)
6756 m_dummy_cond = gimple_build_cond (NE_EXPR,
6757 integer_zero_node, integer_zero_node,
6758 NULL, NULL);
6760 x_vr_values = vr_values;
6761 thread_outgoing_edges (bb, m_dummy_cond, m_const_and_copies,
6762 m_avail_exprs_stack, NULL,
6763 simplify_stmt_for_jump_threading);
6764 x_vr_values = NULL;
6766 m_avail_exprs_stack->pop_to_marker ();
6767 m_const_and_copies->pop_to_marker ();
6770 /* Blocks which have more than one predecessor and more than
6771 one successor present jump threading opportunities, i.e.,
6772 when the block is reached from a specific predecessor, we
6773 may be able to determine which of the outgoing edges will
6774 be traversed. When this optimization applies, we are able
6775 to avoid conditionals at runtime and we may expose secondary
6776 optimization opportunities.
6778 This routine is effectively a driver for the generic jump
6779 threading code. It basically just presents the generic code
6780 with edges that may be suitable for jump threading.
6782 Unlike DOM, we do not iterate VRP if jump threading was successful.
6783 While iterating may expose new opportunities for VRP, it is expected
6784 those opportunities would be very limited and the compile time cost
6785 to expose those opportunities would be significant.
6787 As jump threading opportunities are discovered, they are registered
6788 for later realization. */
6790 static void
6791 identify_jump_threads (class vr_values *vr_values)
6793 int i;
6794 edge e;
6796 /* Ugh. When substituting values earlier in this pass we can
6797 wipe the dominance information. So rebuild the dominator
6798 information as we need it within the jump threading code. */
6799 calculate_dominance_info (CDI_DOMINATORS);
6801 /* We do not allow VRP information to be used for jump threading
6802 across a back edge in the CFG. Otherwise it becomes too
6803 difficult to avoid eliminating loop exit tests. Of course
6804 EDGE_DFS_BACK is not accurate at this time so we have to
6805 recompute it. */
6806 mark_dfs_back_edges ();
6808 /* Do not thread across edges we are about to remove. Just marking
6809 them as EDGE_IGNORE will do. */
6810 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
6811 e->flags |= EDGE_IGNORE;
6813 /* Allocate our unwinder stack to unwind any temporary equivalences
6814 that might be recorded. */
6815 const_and_copies *equiv_stack = new const_and_copies ();
6817 hash_table<expr_elt_hasher> *avail_exprs
6818 = new hash_table<expr_elt_hasher> (1024);
6819 avail_exprs_stack *avail_exprs_stack
6820 = new class avail_exprs_stack (avail_exprs);
6822 vrp_dom_walker walker (CDI_DOMINATORS, equiv_stack, avail_exprs_stack);
6823 walker.vr_values = vr_values;
6824 walker.walk (cfun->cfg->x_entry_block_ptr);
6826 /* Clear EDGE_IGNORE. */
6827 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
6828 e->flags &= ~EDGE_IGNORE;
6830 /* We do not actually update the CFG or SSA graphs at this point as
6831 ASSERT_EXPRs are still in the IL and cfg cleanup code does not yet
6832 handle ASSERT_EXPRs gracefully. */
6833 delete equiv_stack;
6834 delete avail_exprs;
6835 delete avail_exprs_stack;
6838 /* Traverse all the blocks folding conditionals with known ranges. */
6840 void
6841 vrp_prop::vrp_finalize (bool warn_array_bounds_p)
6843 size_t i;
6845 /* We have completed propagating through the lattice. */
6846 vr_values.set_lattice_propagation_complete ();
6848 if (dump_file)
6850 fprintf (dump_file, "\nValue ranges after VRP:\n\n");
6851 vr_values.dump_all_value_ranges (dump_file);
6852 fprintf (dump_file, "\n");
6855 /* Set value range to non pointer SSA_NAMEs. */
6856 for (i = 0; i < num_ssa_names; i++)
6858 tree name = ssa_name (i);
6859 if (!name)
6860 continue;
6862 value_range *vr = get_value_range (name);
6863 if (!name
6864 || (vr->type == VR_VARYING)
6865 || (vr->type == VR_UNDEFINED)
6866 || (TREE_CODE (vr->min) != INTEGER_CST)
6867 || (TREE_CODE (vr->max) != INTEGER_CST))
6868 continue;
6870 if (POINTER_TYPE_P (TREE_TYPE (name))
6871 && ((vr->type == VR_RANGE
6872 && range_includes_zero_p (vr->min, vr->max) == 0)
6873 || (vr->type == VR_ANTI_RANGE
6874 && range_includes_zero_p (vr->min, vr->max) == 1)))
6875 set_ptr_nonnull (name);
6876 else if (!POINTER_TYPE_P (TREE_TYPE (name)))
6877 set_range_info (name, vr->type,
6878 wi::to_wide (vr->min),
6879 wi::to_wide (vr->max));
6882 /* If we're checking array refs, we want to merge information on
6883 the executability of each edge between vrp_folder and the
6884 check_array_bounds_dom_walker: each can clear the
6885 EDGE_EXECUTABLE flag on edges, in different ways.
6887 Hence, if we're going to call check_all_array_refs, set
6888 the flag on every edge now, rather than in
6889 check_array_bounds_dom_walker's ctor; vrp_folder may clear
6890 it from some edges. */
6891 if (warn_array_bounds && warn_array_bounds_p)
6892 set_all_edges_as_executable (cfun);
6894 class vrp_folder vrp_folder;
6895 vrp_folder.vr_values = &vr_values;
6896 vrp_folder.substitute_and_fold ();
6898 if (warn_array_bounds && warn_array_bounds_p)
6899 check_all_array_refs ();
6902 /* Main entry point to VRP (Value Range Propagation). This pass is
6903 loosely based on J. R. C. Patterson, ``Accurate Static Branch
6904 Prediction by Value Range Propagation,'' in SIGPLAN Conference on
6905 Programming Language Design and Implementation, pp. 67-78, 1995.
6906 Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
6908 This is essentially an SSA-CCP pass modified to deal with ranges
6909 instead of constants.
6911 While propagating ranges, we may find that two or more SSA name
6912 have equivalent, though distinct ranges. For instance,
6914 1 x_9 = p_3->a;
6915 2 p_4 = ASSERT_EXPR <p_3, p_3 != 0>
6916 3 if (p_4 == q_2)
6917 4 p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
6918 5 endif
6919 6 if (q_2)
6921 In the code above, pointer p_5 has range [q_2, q_2], but from the
6922 code we can also determine that p_5 cannot be NULL and, if q_2 had
6923 a non-varying range, p_5's range should also be compatible with it.
6925 These equivalences are created by two expressions: ASSERT_EXPR and
6926 copy operations. Since p_5 is an assertion on p_4, and p_4 was the
6927 result of another assertion, then we can use the fact that p_5 and
6928 p_4 are equivalent when evaluating p_5's range.
6930 Together with value ranges, we also propagate these equivalences
6931 between names so that we can take advantage of information from
6932 multiple ranges when doing final replacement. Note that this
6933 equivalency relation is transitive but not symmetric.
6935 In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
6936 cannot assert that q_2 is equivalent to p_5 because q_2 may be used
6937 in contexts where that assertion does not hold (e.g., in line 6).
6939 TODO, the main difference between this pass and Patterson's is that
6940 we do not propagate edge probabilities. We only compute whether
6941 edges can be taken or not. That is, instead of having a spectrum
6942 of jump probabilities between 0 and 1, we only deal with 0, 1 and
6943 DON'T KNOW. In the future, it may be worthwhile to propagate
6944 probabilities to aid branch prediction. */
6946 static unsigned int
6947 execute_vrp (bool warn_array_bounds_p)
6949 int i;
6950 edge e;
6951 switch_update *su;
6953 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
6954 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
6955 scev_initialize ();
6957 /* ??? This ends up using stale EDGE_DFS_BACK for liveness computation.
6958 Inserting assertions may split edges which will invalidate
6959 EDGE_DFS_BACK. */
6960 insert_range_assertions ();
6962 to_remove_edges.create (10);
6963 to_update_switch_stmts.create (5);
6964 threadedge_initialize_values ();
6966 /* For visiting PHI nodes we need EDGE_DFS_BACK computed. */
6967 mark_dfs_back_edges ();
6969 class vrp_prop vrp_prop;
6970 vrp_prop.vrp_initialize ();
6971 vrp_prop.ssa_propagate ();
6972 vrp_prop.vrp_finalize (warn_array_bounds_p);
6974 /* We must identify jump threading opportunities before we release
6975 the datastructures built by VRP. */
6976 identify_jump_threads (&vrp_prop.vr_values);
6978 /* A comparison of an SSA_NAME against a constant where the SSA_NAME
6979 was set by a type conversion can often be rewritten to use the
6980 RHS of the type conversion.
6982 However, doing so inhibits jump threading through the comparison.
6983 So that transformation is not performed until after jump threading
6984 is complete. */
6985 basic_block bb;
6986 FOR_EACH_BB_FN (bb, cfun)
6988 gimple *last = last_stmt (bb);
6989 if (last && gimple_code (last) == GIMPLE_COND)
6990 vrp_prop.vr_values.simplify_cond_using_ranges_2 (as_a <gcond *> (last));
6993 free_numbers_of_iterations_estimates (cfun);
6995 /* ASSERT_EXPRs must be removed before finalizing jump threads
6996 as finalizing jump threads calls the CFG cleanup code which
6997 does not properly handle ASSERT_EXPRs. */
6998 remove_range_assertions ();
7000 /* If we exposed any new variables, go ahead and put them into
7001 SSA form now, before we handle jump threading. This simplifies
7002 interactions between rewriting of _DECL nodes into SSA form
7003 and rewriting SSA_NAME nodes into SSA form after block
7004 duplication and CFG manipulation. */
7005 update_ssa (TODO_update_ssa);
7007 /* We identified all the jump threading opportunities earlier, but could
7008 not transform the CFG at that time. This routine transforms the
7009 CFG and arranges for the dominator tree to be rebuilt if necessary.
7011 Note the SSA graph update will occur during the normal TODO
7012 processing by the pass manager. */
7013 thread_through_all_blocks (false);
7015 /* Remove dead edges from SWITCH_EXPR optimization. This leaves the
7016 CFG in a broken state and requires a cfg_cleanup run. */
7017 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
7018 remove_edge (e);
7019 /* Update SWITCH_EXPR case label vector. */
7020 FOR_EACH_VEC_ELT (to_update_switch_stmts, i, su)
7022 size_t j;
7023 size_t n = TREE_VEC_LENGTH (su->vec);
7024 tree label;
7025 gimple_switch_set_num_labels (su->stmt, n);
7026 for (j = 0; j < n; j++)
7027 gimple_switch_set_label (su->stmt, j, TREE_VEC_ELT (su->vec, j));
7028 /* As we may have replaced the default label with a regular one
7029 make sure to make it a real default label again. This ensures
7030 optimal expansion. */
7031 label = gimple_switch_label (su->stmt, 0);
7032 CASE_LOW (label) = NULL_TREE;
7033 CASE_HIGH (label) = NULL_TREE;
7036 if (to_remove_edges.length () > 0)
7038 free_dominance_info (CDI_DOMINATORS);
7039 loops_state_set (LOOPS_NEED_FIXUP);
7042 to_remove_edges.release ();
7043 to_update_switch_stmts.release ();
7044 threadedge_finalize_values ();
7046 scev_finalize ();
7047 loop_optimizer_finalize ();
7048 return 0;
7051 namespace {
7053 const pass_data pass_data_vrp =
7055 GIMPLE_PASS, /* type */
7056 "vrp", /* name */
7057 OPTGROUP_NONE, /* optinfo_flags */
7058 TV_TREE_VRP, /* tv_id */
7059 PROP_ssa, /* properties_required */
7060 0, /* properties_provided */
7061 0, /* properties_destroyed */
7062 0, /* todo_flags_start */
7063 ( TODO_cleanup_cfg | TODO_update_ssa ), /* todo_flags_finish */
7066 class pass_vrp : public gimple_opt_pass
7068 public:
7069 pass_vrp (gcc::context *ctxt)
7070 : gimple_opt_pass (pass_data_vrp, ctxt), warn_array_bounds_p (false)
7073 /* opt_pass methods: */
7074 opt_pass * clone () { return new pass_vrp (m_ctxt); }
7075 void set_pass_param (unsigned int n, bool param)
7077 gcc_assert (n == 0);
7078 warn_array_bounds_p = param;
7080 virtual bool gate (function *) { return flag_tree_vrp != 0; }
7081 virtual unsigned int execute (function *)
7082 { return execute_vrp (warn_array_bounds_p); }
7084 private:
7085 bool warn_array_bounds_p;
7086 }; // class pass_vrp
7088 } // anon namespace
7090 gimple_opt_pass *
7091 make_pass_vrp (gcc::context *ctxt)
7093 return new pass_vrp (ctxt);
7097 /* Worker for determine_value_range. */
7099 static void
7100 determine_value_range_1 (value_range *vr, tree expr)
7102 if (BINARY_CLASS_P (expr))
7104 value_range vr0 = VR_INITIALIZER, vr1 = VR_INITIALIZER;
7105 determine_value_range_1 (&vr0, TREE_OPERAND (expr, 0));
7106 determine_value_range_1 (&vr1, TREE_OPERAND (expr, 1));
7107 extract_range_from_binary_expr_1 (vr, TREE_CODE (expr), TREE_TYPE (expr),
7108 &vr0, &vr1);
7110 else if (UNARY_CLASS_P (expr))
7112 value_range vr0 = VR_INITIALIZER;
7113 determine_value_range_1 (&vr0, TREE_OPERAND (expr, 0));
7114 extract_range_from_unary_expr (vr, TREE_CODE (expr), TREE_TYPE (expr),
7115 &vr0, TREE_TYPE (TREE_OPERAND (expr, 0)));
7117 else if (TREE_CODE (expr) == INTEGER_CST)
7118 set_value_range_to_value (vr, expr, NULL);
7119 else
7121 value_range_type kind;
7122 wide_int min, max;
7123 /* For SSA names try to extract range info computed by VRP. Otherwise
7124 fall back to varying. */
7125 if (TREE_CODE (expr) == SSA_NAME
7126 && INTEGRAL_TYPE_P (TREE_TYPE (expr))
7127 && (kind = get_range_info (expr, &min, &max)) != VR_VARYING)
7128 set_value_range (vr, kind, wide_int_to_tree (TREE_TYPE (expr), min),
7129 wide_int_to_tree (TREE_TYPE (expr), max), NULL);
7130 else
7131 set_value_range_to_varying (vr);
7135 /* Compute a value-range for EXPR and set it in *MIN and *MAX. Return
7136 the determined range type. */
7138 value_range_type
7139 determine_value_range (tree expr, wide_int *min, wide_int *max)
7141 value_range vr = VR_INITIALIZER;
7142 determine_value_range_1 (&vr, expr);
7143 if ((vr.type == VR_RANGE
7144 || vr.type == VR_ANTI_RANGE)
7145 && !symbolic_range_p (&vr))
7147 *min = wi::to_wide (vr.min);
7148 *max = wi::to_wide (vr.max);
7149 return vr.type;
7152 return VR_VARYING;