* lto.c (do_stream_out): Add PART parameter; open dump file.
[official-gcc.git] / gcc / tree-vrp.c
bloba7453abba7ffcd692f9dfea9f87282c4d3a7fb6e
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 wi::overflow_type overflow = wi::OVF_NONE;
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, wi::overflow_type &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)
1340 wi = wi::sub (wi::to_wide (op0), wi::to_wide (op1), sgn, &ovf);
1341 else
1342 wi = wi::add (wi::to_wide (op0), wi::to_wide (op1), sgn, &ovf);
1344 else if (op0)
1345 wi = wi::to_wide (op0);
1346 else if (op1)
1348 if (minus_p)
1349 wi = wi::neg (wi::to_wide (op1), &ovf);
1350 else
1351 wi = wi::to_wide (op1);
1353 else
1354 wi = wi::shwi (0, prec);
1357 /* Given a range in [WMIN, WMAX], adjust it for possible overflow and
1358 put the result in VR.
1360 TYPE is the type of the range.
1362 MIN_OVF and MAX_OVF indicate what type of overflow, if any,
1363 occurred while originally calculating WMIN or WMAX. -1 indicates
1364 underflow. +1 indicates overflow. 0 indicates neither. */
1366 static void
1367 set_value_range_with_overflow (value_range &vr,
1368 tree type,
1369 const wide_int &wmin, const wide_int &wmax,
1370 wi::overflow_type min_ovf,
1371 wi::overflow_type max_ovf)
1373 const signop sgn = TYPE_SIGN (type);
1374 const unsigned int prec = TYPE_PRECISION (type);
1375 vr.type = VR_RANGE;
1376 vr.equiv = NULL;
1377 if (TYPE_OVERFLOW_WRAPS (type))
1379 /* If overflow wraps, truncate the values and adjust the
1380 range kind and bounds appropriately. */
1381 wide_int tmin = wide_int::from (wmin, prec, sgn);
1382 wide_int tmax = wide_int::from (wmax, prec, sgn);
1383 if ((min_ovf != wi::OVF_NONE) == (max_ovf != wi::OVF_NONE))
1385 /* No overflow or both overflow or underflow. The
1386 range kind stays VR_RANGE. */
1387 vr.min = wide_int_to_tree (type, tmin);
1388 vr.max = wide_int_to_tree (type, tmax);
1390 else if ((min_ovf == wi::OVF_UNDERFLOW && max_ovf == wi::OVF_NONE)
1391 || (max_ovf == wi::OVF_OVERFLOW && min_ovf == wi::OVF_NONE))
1393 /* Min underflow or max overflow. The range kind
1394 changes to VR_ANTI_RANGE. */
1395 bool covers = false;
1396 wide_int tem = tmin;
1397 vr.type = VR_ANTI_RANGE;
1398 tmin = tmax + 1;
1399 if (wi::cmp (tmin, tmax, sgn) < 0)
1400 covers = true;
1401 tmax = tem - 1;
1402 if (wi::cmp (tmax, tem, sgn) > 0)
1403 covers = true;
1404 /* If the anti-range would cover nothing, drop to varying.
1405 Likewise if the anti-range bounds are outside of the
1406 types values. */
1407 if (covers || wi::cmp (tmin, tmax, sgn) > 0)
1409 set_value_range_to_varying (&vr);
1410 return;
1412 vr.min = wide_int_to_tree (type, tmin);
1413 vr.max = wide_int_to_tree (type, tmax);
1415 else
1417 /* Other underflow and/or overflow, drop to VR_VARYING. */
1418 set_value_range_to_varying (&vr);
1419 return;
1422 else
1424 /* If overflow does not wrap, saturate to the types min/max
1425 value. */
1426 wide_int type_min = wi::min_value (prec, sgn);
1427 wide_int type_max = wi::max_value (prec, sgn);
1428 if (min_ovf == wi::OVF_UNDERFLOW)
1429 vr.min = wide_int_to_tree (type, type_min);
1430 else if (min_ovf == wi::OVF_OVERFLOW)
1431 vr.min = wide_int_to_tree (type, type_max);
1432 else
1433 vr.min = wide_int_to_tree (type, wmin);
1435 if (max_ovf == wi::OVF_UNDERFLOW)
1436 vr.max = wide_int_to_tree (type, type_min);
1437 else if (max_ovf == wi::OVF_OVERFLOW)
1438 vr.max = wide_int_to_tree (type, type_max);
1439 else
1440 vr.max = wide_int_to_tree (type, wmax);
1444 /* Extract range information from a binary operation CODE based on
1445 the ranges of each of its operands *VR0 and *VR1 with resulting
1446 type EXPR_TYPE. The resulting range is stored in *VR. */
1448 void
1449 extract_range_from_binary_expr_1 (value_range *vr,
1450 enum tree_code code, tree expr_type,
1451 value_range *vr0_, value_range *vr1_)
1453 value_range vr0 = *vr0_, vr1 = *vr1_;
1454 value_range vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
1455 enum value_range_type type;
1456 tree min = NULL_TREE, max = NULL_TREE;
1457 int cmp;
1459 if (!INTEGRAL_TYPE_P (expr_type)
1460 && !POINTER_TYPE_P (expr_type))
1462 set_value_range_to_varying (vr);
1463 return;
1466 /* Not all binary expressions can be applied to ranges in a
1467 meaningful way. Handle only arithmetic operations. */
1468 if (code != PLUS_EXPR
1469 && code != MINUS_EXPR
1470 && code != POINTER_PLUS_EXPR
1471 && code != MULT_EXPR
1472 && code != TRUNC_DIV_EXPR
1473 && code != FLOOR_DIV_EXPR
1474 && code != CEIL_DIV_EXPR
1475 && code != EXACT_DIV_EXPR
1476 && code != ROUND_DIV_EXPR
1477 && code != TRUNC_MOD_EXPR
1478 && code != RSHIFT_EXPR
1479 && code != LSHIFT_EXPR
1480 && code != MIN_EXPR
1481 && code != MAX_EXPR
1482 && code != BIT_AND_EXPR
1483 && code != BIT_IOR_EXPR
1484 && code != BIT_XOR_EXPR)
1486 set_value_range_to_varying (vr);
1487 return;
1490 /* If both ranges are UNDEFINED, so is the result. */
1491 if (vr0.type == VR_UNDEFINED && vr1.type == VR_UNDEFINED)
1493 set_value_range_to_undefined (vr);
1494 return;
1496 /* If one of the ranges is UNDEFINED drop it to VARYING for the following
1497 code. At some point we may want to special-case operations that
1498 have UNDEFINED result for all or some value-ranges of the not UNDEFINED
1499 operand. */
1500 else if (vr0.type == VR_UNDEFINED)
1501 set_value_range_to_varying (&vr0);
1502 else if (vr1.type == VR_UNDEFINED)
1503 set_value_range_to_varying (&vr1);
1505 /* We get imprecise results from ranges_from_anti_range when
1506 code is EXACT_DIV_EXPR. We could mask out bits in the resulting
1507 range, but then we also need to hack up vrp_meet. It's just
1508 easier to special case when vr0 is ~[0,0] for EXACT_DIV_EXPR. */
1509 if (code == EXACT_DIV_EXPR
1510 && vr0.type == VR_ANTI_RANGE
1511 && vr0.min == vr0.max
1512 && integer_zerop (vr0.min))
1514 set_value_range_to_nonnull (vr, expr_type);
1515 return;
1518 /* Now canonicalize anti-ranges to ranges when they are not symbolic
1519 and express ~[] op X as ([]' op X) U ([]'' op X). */
1520 if (vr0.type == VR_ANTI_RANGE
1521 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
1523 extract_range_from_binary_expr_1 (vr, code, expr_type, &vrtem0, vr1_);
1524 if (vrtem1.type != VR_UNDEFINED)
1526 value_range vrres = VR_INITIALIZER;
1527 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
1528 &vrtem1, vr1_);
1529 vrp_meet (vr, &vrres);
1531 return;
1533 /* Likewise for X op ~[]. */
1534 if (vr1.type == VR_ANTI_RANGE
1535 && ranges_from_anti_range (&vr1, &vrtem0, &vrtem1))
1537 extract_range_from_binary_expr_1 (vr, code, expr_type, vr0_, &vrtem0);
1538 if (vrtem1.type != VR_UNDEFINED)
1540 value_range vrres = VR_INITIALIZER;
1541 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
1542 vr0_, &vrtem1);
1543 vrp_meet (vr, &vrres);
1545 return;
1548 /* The type of the resulting value range defaults to VR0.TYPE. */
1549 type = vr0.type;
1551 /* Refuse to operate on VARYING ranges, ranges of different kinds
1552 and symbolic ranges. As an exception, we allow BIT_{AND,IOR}
1553 because we may be able to derive a useful range even if one of
1554 the operands is VR_VARYING or symbolic range. Similarly for
1555 divisions, MIN/MAX and PLUS/MINUS.
1557 TODO, we may be able to derive anti-ranges in some cases. */
1558 if (code != BIT_AND_EXPR
1559 && code != BIT_IOR_EXPR
1560 && code != TRUNC_DIV_EXPR
1561 && code != FLOOR_DIV_EXPR
1562 && code != CEIL_DIV_EXPR
1563 && code != EXACT_DIV_EXPR
1564 && code != ROUND_DIV_EXPR
1565 && code != TRUNC_MOD_EXPR
1566 && code != MIN_EXPR
1567 && code != MAX_EXPR
1568 && code != PLUS_EXPR
1569 && code != MINUS_EXPR
1570 && code != RSHIFT_EXPR
1571 && (vr0.type == VR_VARYING
1572 || vr1.type == VR_VARYING
1573 || vr0.type != vr1.type
1574 || symbolic_range_p (&vr0)
1575 || symbolic_range_p (&vr1)))
1577 set_value_range_to_varying (vr);
1578 return;
1581 /* Now evaluate the expression to determine the new range. */
1582 if (POINTER_TYPE_P (expr_type))
1584 if (code == MIN_EXPR || code == MAX_EXPR)
1586 /* For MIN/MAX expressions with pointers, we only care about
1587 nullness, if both are non null, then the result is nonnull.
1588 If both are null, then the result is null. Otherwise they
1589 are varying. */
1590 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
1591 set_value_range_to_nonnull (vr, expr_type);
1592 else if (range_is_null (&vr0) && range_is_null (&vr1))
1593 set_value_range_to_null (vr, expr_type);
1594 else
1595 set_value_range_to_varying (vr);
1597 else if (code == POINTER_PLUS_EXPR)
1599 /* For pointer types, we are really only interested in asserting
1600 whether the expression evaluates to non-NULL. */
1601 if (range_is_nonnull (&vr0) || range_is_nonnull (&vr1))
1602 set_value_range_to_nonnull (vr, expr_type);
1603 else if (range_is_null (&vr0) && range_is_null (&vr1))
1604 set_value_range_to_null (vr, expr_type);
1605 else
1606 set_value_range_to_varying (vr);
1608 else if (code == BIT_AND_EXPR)
1610 /* For pointer types, we are really only interested in asserting
1611 whether the expression evaluates to non-NULL. */
1612 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
1613 set_value_range_to_nonnull (vr, expr_type);
1614 else if (range_is_null (&vr0) || range_is_null (&vr1))
1615 set_value_range_to_null (vr, expr_type);
1616 else
1617 set_value_range_to_varying (vr);
1619 else
1620 set_value_range_to_varying (vr);
1622 return;
1625 /* For integer ranges, apply the operation to each end of the
1626 range and see what we end up with. */
1627 if (code == PLUS_EXPR || code == MINUS_EXPR)
1629 const bool minus_p = (code == MINUS_EXPR);
1630 tree min_op0 = vr0.min;
1631 tree min_op1 = minus_p ? vr1.max : vr1.min;
1632 tree max_op0 = vr0.max;
1633 tree max_op1 = minus_p ? vr1.min : vr1.max;
1634 tree sym_min_op0 = NULL_TREE;
1635 tree sym_min_op1 = NULL_TREE;
1636 tree sym_max_op0 = NULL_TREE;
1637 tree sym_max_op1 = NULL_TREE;
1638 bool neg_min_op0, neg_min_op1, neg_max_op0, neg_max_op1;
1640 neg_min_op0 = neg_min_op1 = neg_max_op0 = neg_max_op1 = false;
1642 /* If we have a PLUS or MINUS with two VR_RANGEs, either constant or
1643 single-symbolic ranges, try to compute the precise resulting range,
1644 but only if we know that this resulting range will also be constant
1645 or single-symbolic. */
1646 if (vr0.type == VR_RANGE && vr1.type == VR_RANGE
1647 && (TREE_CODE (min_op0) == INTEGER_CST
1648 || (sym_min_op0
1649 = get_single_symbol (min_op0, &neg_min_op0, &min_op0)))
1650 && (TREE_CODE (min_op1) == INTEGER_CST
1651 || (sym_min_op1
1652 = get_single_symbol (min_op1, &neg_min_op1, &min_op1)))
1653 && (!(sym_min_op0 && sym_min_op1)
1654 || (sym_min_op0 == sym_min_op1
1655 && neg_min_op0 == (minus_p ? neg_min_op1 : !neg_min_op1)))
1656 && (TREE_CODE (max_op0) == INTEGER_CST
1657 || (sym_max_op0
1658 = get_single_symbol (max_op0, &neg_max_op0, &max_op0)))
1659 && (TREE_CODE (max_op1) == INTEGER_CST
1660 || (sym_max_op1
1661 = get_single_symbol (max_op1, &neg_max_op1, &max_op1)))
1662 && (!(sym_max_op0 && sym_max_op1)
1663 || (sym_max_op0 == sym_max_op1
1664 && neg_max_op0 == (minus_p ? neg_max_op1 : !neg_max_op1))))
1666 wide_int wmin, wmax;
1667 wi::overflow_type min_ovf = wi::OVF_NONE;
1668 wi::overflow_type max_ovf = wi::OVF_NONE;
1670 /* Build the bounds. */
1671 combine_bound (code, wmin, min_ovf, expr_type, min_op0, min_op1);
1672 combine_bound (code, wmax, max_ovf, expr_type, max_op0, max_op1);
1674 /* If we have overflow for the constant part and the resulting
1675 range will be symbolic, drop to VR_VARYING. */
1676 if (((bool)min_ovf && sym_min_op0 != sym_min_op1)
1677 || ((bool)max_ovf && sym_max_op0 != sym_max_op1))
1679 set_value_range_to_varying (vr);
1680 return;
1683 /* Adjust the range for possible overflow. */
1684 set_value_range_with_overflow (*vr, expr_type,
1685 wmin, wmax, min_ovf, max_ovf);
1686 if (vr->type == VR_VARYING)
1687 return;
1689 /* Build the symbolic bounds if needed. */
1690 adjust_symbolic_bound (vr->min, code, expr_type,
1691 sym_min_op0, sym_min_op1,
1692 neg_min_op0, neg_min_op1);
1693 adjust_symbolic_bound (vr->max, code, expr_type,
1694 sym_max_op0, sym_max_op1,
1695 neg_max_op0, neg_max_op1);
1696 /* ?? It would probably be cleaner to eliminate min/max/type
1697 entirely and hold these values in VR directly. */
1698 min = vr->min;
1699 max = vr->max;
1700 type = vr->type;
1702 else
1704 /* For other cases, for example if we have a PLUS_EXPR with two
1705 VR_ANTI_RANGEs, drop to VR_VARYING. It would take more effort
1706 to compute a precise range for such a case.
1707 ??? General even mixed range kind operations can be expressed
1708 by for example transforming ~[3, 5] + [1, 2] to range-only
1709 operations and a union primitive:
1710 [-INF, 2] + [1, 2] U [5, +INF] + [1, 2]
1711 [-INF+1, 4] U [6, +INF(OVF)]
1712 though usually the union is not exactly representable with
1713 a single range or anti-range as the above is
1714 [-INF+1, +INF(OVF)] intersected with ~[5, 5]
1715 but one could use a scheme similar to equivalences for this. */
1716 set_value_range_to_varying (vr);
1717 return;
1720 else if (code == MIN_EXPR
1721 || code == MAX_EXPR)
1723 if (vr0.type == VR_RANGE
1724 && !symbolic_range_p (&vr0))
1726 type = VR_RANGE;
1727 if (vr1.type == VR_RANGE
1728 && !symbolic_range_p (&vr1))
1730 /* For operations that make the resulting range directly
1731 proportional to the original ranges, apply the operation to
1732 the same end of each range. */
1733 min = int_const_binop (code, vr0.min, vr1.min);
1734 max = int_const_binop (code, vr0.max, vr1.max);
1736 else if (code == MIN_EXPR)
1738 min = vrp_val_min (expr_type);
1739 max = vr0.max;
1741 else if (code == MAX_EXPR)
1743 min = vr0.min;
1744 max = vrp_val_max (expr_type);
1747 else if (vr1.type == VR_RANGE
1748 && !symbolic_range_p (&vr1))
1750 type = VR_RANGE;
1751 if (code == MIN_EXPR)
1753 min = vrp_val_min (expr_type);
1754 max = vr1.max;
1756 else if (code == MAX_EXPR)
1758 min = vr1.min;
1759 max = vrp_val_max (expr_type);
1762 else
1764 set_value_range_to_varying (vr);
1765 return;
1768 else if (code == MULT_EXPR)
1770 /* Fancy code so that with unsigned, [-3,-1]*[-3,-1] does not
1771 drop to varying. This test requires 2*prec bits if both
1772 operands are signed and 2*prec + 2 bits if either is not. */
1774 signop sign = TYPE_SIGN (expr_type);
1775 unsigned int prec = TYPE_PRECISION (expr_type);
1777 if (!range_int_cst_p (&vr0)
1778 || !range_int_cst_p (&vr1))
1780 set_value_range_to_varying (vr);
1781 return;
1784 if (TYPE_OVERFLOW_WRAPS (expr_type))
1786 typedef FIXED_WIDE_INT (WIDE_INT_MAX_PRECISION * 2) vrp_int;
1787 typedef generic_wide_int
1788 <wi::extended_tree <WIDE_INT_MAX_PRECISION * 2> > vrp_int_cst;
1789 vrp_int sizem1 = wi::mask <vrp_int> (prec, false);
1790 vrp_int size = sizem1 + 1;
1792 /* Extend the values using the sign of the result to PREC2.
1793 From here on out, everthing is just signed math no matter
1794 what the input types were. */
1795 vrp_int min0 = vrp_int_cst (vr0.min);
1796 vrp_int max0 = vrp_int_cst (vr0.max);
1797 vrp_int min1 = vrp_int_cst (vr1.min);
1798 vrp_int max1 = vrp_int_cst (vr1.max);
1799 /* Canonicalize the intervals. */
1800 if (sign == UNSIGNED)
1802 if (wi::ltu_p (size, min0 + max0))
1804 min0 -= size;
1805 max0 -= size;
1808 if (wi::ltu_p (size, min1 + max1))
1810 min1 -= size;
1811 max1 -= size;
1815 vrp_int prod0 = min0 * min1;
1816 vrp_int prod1 = min0 * max1;
1817 vrp_int prod2 = max0 * min1;
1818 vrp_int prod3 = max0 * max1;
1820 /* Sort the 4 products so that min is in prod0 and max is in
1821 prod3. */
1822 /* min0min1 > max0max1 */
1823 if (prod0 > prod3)
1824 std::swap (prod0, prod3);
1826 /* min0max1 > max0min1 */
1827 if (prod1 > prod2)
1828 std::swap (prod1, prod2);
1830 if (prod0 > prod1)
1831 std::swap (prod0, prod1);
1833 if (prod2 > prod3)
1834 std::swap (prod2, prod3);
1836 /* diff = max - min. */
1837 prod2 = prod3 - prod0;
1838 if (wi::geu_p (prod2, sizem1))
1840 /* the range covers all values. */
1841 set_value_range_to_varying (vr);
1842 return;
1845 /* The following should handle the wrapping and selecting
1846 VR_ANTI_RANGE for us. */
1847 min = wide_int_to_tree (expr_type, prod0);
1848 max = wide_int_to_tree (expr_type, prod3);
1849 set_and_canonicalize_value_range (vr, VR_RANGE, min, max, NULL);
1850 return;
1853 /* If we have an unsigned MULT_EXPR with two VR_ANTI_RANGEs,
1854 drop to VR_VARYING. It would take more effort to compute a
1855 precise range for such a case. For example, if we have
1856 op0 == 65536 and op1 == 65536 with their ranges both being
1857 ~[0,0] on a 32-bit machine, we would have op0 * op1 == 0, so
1858 we cannot claim that the product is in ~[0,0]. Note that we
1859 are guaranteed to have vr0.type == vr1.type at this
1860 point. */
1861 if (vr0.type == VR_ANTI_RANGE
1862 && !TYPE_OVERFLOW_UNDEFINED (expr_type))
1864 set_value_range_to_varying (vr);
1865 return;
1868 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
1869 return;
1871 else if (code == RSHIFT_EXPR
1872 || code == LSHIFT_EXPR)
1874 /* If we have a RSHIFT_EXPR with any shift values outside [0..prec-1],
1875 then drop to VR_VARYING. Outside of this range we get undefined
1876 behavior from the shift operation. We cannot even trust
1877 SHIFT_COUNT_TRUNCATED at this stage, because that applies to rtl
1878 shifts, and the operation at the tree level may be widened. */
1879 if (range_int_cst_p (&vr1)
1880 && compare_tree_int (vr1.min, 0) >= 0
1881 && compare_tree_int (vr1.max, TYPE_PRECISION (expr_type)) == -1)
1883 if (code == RSHIFT_EXPR)
1885 /* Even if vr0 is VARYING or otherwise not usable, we can derive
1886 useful ranges just from the shift count. E.g.
1887 x >> 63 for signed 64-bit x is always [-1, 0]. */
1888 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
1890 vr0.type = type = VR_RANGE;
1891 vr0.min = vrp_val_min (expr_type);
1892 vr0.max = vrp_val_max (expr_type);
1894 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
1895 return;
1897 /* We can map lshifts by constants to MULT_EXPR handling. */
1898 else if (code == LSHIFT_EXPR
1899 && range_int_cst_singleton_p (&vr1))
1901 bool saved_flag_wrapv;
1902 value_range vr1p = VR_INITIALIZER;
1903 vr1p.type = VR_RANGE;
1904 vr1p.min = (wide_int_to_tree
1905 (expr_type,
1906 wi::set_bit_in_zero (tree_to_shwi (vr1.min),
1907 TYPE_PRECISION (expr_type))));
1908 vr1p.max = vr1p.min;
1909 /* We have to use a wrapping multiply though as signed overflow
1910 on lshifts is implementation defined in C89. */
1911 saved_flag_wrapv = flag_wrapv;
1912 flag_wrapv = 1;
1913 extract_range_from_binary_expr_1 (vr, MULT_EXPR, expr_type,
1914 &vr0, &vr1p);
1915 flag_wrapv = saved_flag_wrapv;
1916 return;
1918 else if (code == LSHIFT_EXPR
1919 && range_int_cst_p (&vr0))
1921 int prec = TYPE_PRECISION (expr_type);
1922 int overflow_pos = prec;
1923 int bound_shift;
1924 wide_int low_bound, high_bound;
1925 bool uns = TYPE_UNSIGNED (expr_type);
1926 bool in_bounds = false;
1928 if (!uns)
1929 overflow_pos -= 1;
1931 bound_shift = overflow_pos - tree_to_shwi (vr1.max);
1932 /* If bound_shift == HOST_BITS_PER_WIDE_INT, the llshift can
1933 overflow. However, for that to happen, vr1.max needs to be
1934 zero, which means vr1 is a singleton range of zero, which
1935 means it should be handled by the previous LSHIFT_EXPR
1936 if-clause. */
1937 wide_int bound = wi::set_bit_in_zero (bound_shift, prec);
1938 wide_int complement = ~(bound - 1);
1940 if (uns)
1942 low_bound = bound;
1943 high_bound = complement;
1944 if (wi::ltu_p (wi::to_wide (vr0.max), low_bound))
1946 /* [5, 6] << [1, 2] == [10, 24]. */
1947 /* We're shifting out only zeroes, the value increases
1948 monotonically. */
1949 in_bounds = true;
1951 else if (wi::ltu_p (high_bound, wi::to_wide (vr0.min)))
1953 /* [0xffffff00, 0xffffffff] << [1, 2]
1954 == [0xfffffc00, 0xfffffffe]. */
1955 /* We're shifting out only ones, the value decreases
1956 monotonically. */
1957 in_bounds = true;
1960 else
1962 /* [-1, 1] << [1, 2] == [-4, 4]. */
1963 low_bound = complement;
1964 high_bound = bound;
1965 if (wi::lts_p (wi::to_wide (vr0.max), high_bound)
1966 && wi::lts_p (low_bound, wi::to_wide (vr0.min)))
1968 /* For non-negative numbers, we're shifting out only
1969 zeroes, the value increases monotonically.
1970 For negative numbers, we're shifting out only ones, the
1971 value decreases monotomically. */
1972 in_bounds = true;
1976 if (in_bounds)
1978 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
1979 return;
1983 set_value_range_to_varying (vr);
1984 return;
1986 else if (code == TRUNC_DIV_EXPR
1987 || code == FLOOR_DIV_EXPR
1988 || code == CEIL_DIV_EXPR
1989 || code == EXACT_DIV_EXPR
1990 || code == ROUND_DIV_EXPR)
1992 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
1994 /* For division, if op1 has VR_RANGE but op0 does not, something
1995 can be deduced just from that range. Say [min, max] / [4, max]
1996 gives [min / 4, max / 4] range. */
1997 if (vr1.type == VR_RANGE
1998 && !symbolic_range_p (&vr1)
1999 && range_includes_zero_p (vr1.min, vr1.max) == 0)
2001 vr0.type = type = VR_RANGE;
2002 vr0.min = vrp_val_min (expr_type);
2003 vr0.max = vrp_val_max (expr_type);
2005 else
2007 set_value_range_to_varying (vr);
2008 return;
2012 /* For divisions, if flag_non_call_exceptions is true, we must
2013 not eliminate a division by zero. */
2014 if (cfun->can_throw_non_call_exceptions
2015 && (vr1.type != VR_RANGE
2016 || range_includes_zero_p (vr1.min, vr1.max) != 0))
2018 set_value_range_to_varying (vr);
2019 return;
2022 /* For divisions, if op0 is VR_RANGE, we can deduce a range
2023 even if op1 is VR_VARYING, VR_ANTI_RANGE, symbolic or can
2024 include 0. */
2025 if (vr0.type == VR_RANGE
2026 && (vr1.type != VR_RANGE
2027 || range_includes_zero_p (vr1.min, vr1.max) != 0))
2029 tree zero = build_int_cst (TREE_TYPE (vr0.min), 0);
2030 int cmp;
2032 min = NULL_TREE;
2033 max = NULL_TREE;
2034 if (TYPE_UNSIGNED (expr_type)
2035 || value_range_nonnegative_p (&vr1))
2037 /* For unsigned division or when divisor is known
2038 to be non-negative, the range has to cover
2039 all numbers from 0 to max for positive max
2040 and all numbers from min to 0 for negative min. */
2041 cmp = compare_values (vr0.max, zero);
2042 if (cmp == -1)
2044 /* When vr0.max < 0, vr1.min != 0 and value
2045 ranges for dividend and divisor are available. */
2046 if (vr1.type == VR_RANGE
2047 && !symbolic_range_p (&vr0)
2048 && !symbolic_range_p (&vr1)
2049 && compare_values (vr1.min, zero) != 0)
2050 max = int_const_binop (code, vr0.max, vr1.min);
2051 else
2052 max = zero;
2054 else if (cmp == 0 || cmp == 1)
2055 max = vr0.max;
2056 else
2057 type = VR_VARYING;
2058 cmp = compare_values (vr0.min, zero);
2059 if (cmp == 1)
2061 /* For unsigned division when value ranges for dividend
2062 and divisor are available. */
2063 if (vr1.type == VR_RANGE
2064 && !symbolic_range_p (&vr0)
2065 && !symbolic_range_p (&vr1)
2066 && compare_values (vr1.max, zero) != 0)
2067 min = int_const_binop (code, vr0.min, vr1.max);
2068 else
2069 min = zero;
2071 else if (cmp == 0 || cmp == -1)
2072 min = vr0.min;
2073 else
2074 type = VR_VARYING;
2076 else
2078 /* Otherwise the range is -max .. max or min .. -min
2079 depending on which bound is bigger in absolute value,
2080 as the division can change the sign. */
2081 abs_extent_range (vr, vr0.min, vr0.max);
2082 return;
2084 if (type == VR_VARYING)
2086 set_value_range_to_varying (vr);
2087 return;
2090 else if (range_int_cst_p (&vr0) && range_int_cst_p (&vr1))
2092 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2093 return;
2096 else if (code == TRUNC_MOD_EXPR)
2098 if (range_is_null (&vr1))
2100 set_value_range_to_undefined (vr);
2101 return;
2103 /* ABS (A % B) < ABS (B) and either
2104 0 <= A % B <= A or A <= A % B <= 0. */
2105 type = VR_RANGE;
2106 signop sgn = TYPE_SIGN (expr_type);
2107 unsigned int prec = TYPE_PRECISION (expr_type);
2108 wide_int wmin, wmax, tmp;
2109 if (vr1.type == VR_RANGE && !symbolic_range_p (&vr1))
2111 wmax = wi::to_wide (vr1.max) - 1;
2112 if (sgn == SIGNED)
2114 tmp = -1 - wi::to_wide (vr1.min);
2115 wmax = wi::smax (wmax, tmp);
2118 else
2120 wmax = wi::max_value (prec, sgn);
2121 /* X % INT_MIN may be INT_MAX. */
2122 if (sgn == UNSIGNED)
2123 wmax = wmax - 1;
2126 if (sgn == UNSIGNED)
2127 wmin = wi::zero (prec);
2128 else
2130 wmin = -wmax;
2131 if (vr0.type == VR_RANGE && TREE_CODE (vr0.min) == INTEGER_CST)
2133 tmp = wi::to_wide (vr0.min);
2134 if (wi::gts_p (tmp, 0))
2135 tmp = wi::zero (prec);
2136 wmin = wi::smax (wmin, tmp);
2140 if (vr0.type == VR_RANGE && TREE_CODE (vr0.max) == INTEGER_CST)
2142 tmp = wi::to_wide (vr0.max);
2143 if (sgn == SIGNED && wi::neg_p (tmp))
2144 tmp = wi::zero (prec);
2145 wmax = wi::min (wmax, tmp, sgn);
2148 min = wide_int_to_tree (expr_type, wmin);
2149 max = wide_int_to_tree (expr_type, wmax);
2151 else if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR || code == BIT_XOR_EXPR)
2153 bool int_cst_range0, int_cst_range1;
2154 wide_int may_be_nonzero0, may_be_nonzero1;
2155 wide_int must_be_nonzero0, must_be_nonzero1;
2157 int_cst_range0 = zero_nonzero_bits_from_vr (expr_type, &vr0,
2158 &may_be_nonzero0,
2159 &must_be_nonzero0);
2160 int_cst_range1 = zero_nonzero_bits_from_vr (expr_type, &vr1,
2161 &may_be_nonzero1,
2162 &must_be_nonzero1);
2164 if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR)
2166 value_range *vr0p = NULL, *vr1p = NULL;
2167 if (range_int_cst_singleton_p (&vr1))
2169 vr0p = &vr0;
2170 vr1p = &vr1;
2172 else if (range_int_cst_singleton_p (&vr0))
2174 vr0p = &vr1;
2175 vr1p = &vr0;
2177 /* For op & or | attempt to optimize:
2178 [x, y] op z into [x op z, y op z]
2179 if z is a constant which (for op | its bitwise not) has n
2180 consecutive least significant bits cleared followed by m 1
2181 consecutive bits set immediately above it and either
2182 m + n == precision, or (x >> (m + n)) == (y >> (m + n)).
2183 The least significant n bits of all the values in the range are
2184 cleared or set, the m bits above it are preserved and any bits
2185 above these are required to be the same for all values in the
2186 range. */
2187 if (vr0p && range_int_cst_p (vr0p))
2189 wide_int w = wi::to_wide (vr1p->min);
2190 int m = 0, n = 0;
2191 if (code == BIT_IOR_EXPR)
2192 w = ~w;
2193 if (wi::eq_p (w, 0))
2194 n = TYPE_PRECISION (expr_type);
2195 else
2197 n = wi::ctz (w);
2198 w = ~(w | wi::mask (n, false, w.get_precision ()));
2199 if (wi::eq_p (w, 0))
2200 m = TYPE_PRECISION (expr_type) - n;
2201 else
2202 m = wi::ctz (w) - n;
2204 wide_int mask = wi::mask (m + n, true, w.get_precision ());
2205 if ((mask & wi::to_wide (vr0p->min))
2206 == (mask & wi::to_wide (vr0p->max)))
2208 min = int_const_binop (code, vr0p->min, vr1p->min);
2209 max = int_const_binop (code, vr0p->max, vr1p->min);
2214 type = VR_RANGE;
2215 if (min && max)
2216 /* Optimized above already. */;
2217 else if (code == BIT_AND_EXPR)
2219 min = wide_int_to_tree (expr_type,
2220 must_be_nonzero0 & must_be_nonzero1);
2221 wide_int wmax = may_be_nonzero0 & may_be_nonzero1;
2222 /* If both input ranges contain only negative values we can
2223 truncate the result range maximum to the minimum of the
2224 input range maxima. */
2225 if (int_cst_range0 && int_cst_range1
2226 && tree_int_cst_sgn (vr0.max) < 0
2227 && tree_int_cst_sgn (vr1.max) < 0)
2229 wmax = wi::min (wmax, wi::to_wide (vr0.max),
2230 TYPE_SIGN (expr_type));
2231 wmax = wi::min (wmax, wi::to_wide (vr1.max),
2232 TYPE_SIGN (expr_type));
2234 /* If either input range contains only non-negative values
2235 we can truncate the result range maximum to the respective
2236 maximum of the input range. */
2237 if (int_cst_range0 && tree_int_cst_sgn (vr0.min) >= 0)
2238 wmax = wi::min (wmax, wi::to_wide (vr0.max),
2239 TYPE_SIGN (expr_type));
2240 if (int_cst_range1 && tree_int_cst_sgn (vr1.min) >= 0)
2241 wmax = wi::min (wmax, wi::to_wide (vr1.max),
2242 TYPE_SIGN (expr_type));
2243 max = wide_int_to_tree (expr_type, wmax);
2244 cmp = compare_values (min, max);
2245 /* PR68217: In case of signed & sign-bit-CST should
2246 result in [-INF, 0] instead of [-INF, INF]. */
2247 if (cmp == -2 || cmp == 1)
2249 wide_int sign_bit
2250 = wi::set_bit_in_zero (TYPE_PRECISION (expr_type) - 1,
2251 TYPE_PRECISION (expr_type));
2252 if (!TYPE_UNSIGNED (expr_type)
2253 && ((int_cst_range0
2254 && value_range_constant_singleton (&vr0)
2255 && !wi::cmps (wi::to_wide (vr0.min), sign_bit))
2256 || (int_cst_range1
2257 && value_range_constant_singleton (&vr1)
2258 && !wi::cmps (wi::to_wide (vr1.min), sign_bit))))
2260 min = TYPE_MIN_VALUE (expr_type);
2261 max = build_int_cst (expr_type, 0);
2265 else if (code == BIT_IOR_EXPR)
2267 max = wide_int_to_tree (expr_type,
2268 may_be_nonzero0 | may_be_nonzero1);
2269 wide_int wmin = must_be_nonzero0 | must_be_nonzero1;
2270 /* If the input ranges contain only positive values we can
2271 truncate the minimum of the result range to the maximum
2272 of the input range minima. */
2273 if (int_cst_range0 && int_cst_range1
2274 && tree_int_cst_sgn (vr0.min) >= 0
2275 && tree_int_cst_sgn (vr1.min) >= 0)
2277 wmin = wi::max (wmin, wi::to_wide (vr0.min),
2278 TYPE_SIGN (expr_type));
2279 wmin = wi::max (wmin, wi::to_wide (vr1.min),
2280 TYPE_SIGN (expr_type));
2282 /* If either input range contains only negative values
2283 we can truncate the minimum of the result range to the
2284 respective minimum range. */
2285 if (int_cst_range0 && tree_int_cst_sgn (vr0.max) < 0)
2286 wmin = wi::max (wmin, wi::to_wide (vr0.min),
2287 TYPE_SIGN (expr_type));
2288 if (int_cst_range1 && tree_int_cst_sgn (vr1.max) < 0)
2289 wmin = wi::max (wmin, wi::to_wide (vr1.min),
2290 TYPE_SIGN (expr_type));
2291 min = wide_int_to_tree (expr_type, wmin);
2293 else if (code == BIT_XOR_EXPR)
2295 wide_int result_zero_bits = ((must_be_nonzero0 & must_be_nonzero1)
2296 | ~(may_be_nonzero0 | may_be_nonzero1));
2297 wide_int result_one_bits
2298 = (wi::bit_and_not (must_be_nonzero0, may_be_nonzero1)
2299 | wi::bit_and_not (must_be_nonzero1, may_be_nonzero0));
2300 max = wide_int_to_tree (expr_type, ~result_zero_bits);
2301 min = wide_int_to_tree (expr_type, result_one_bits);
2302 /* If the range has all positive or all negative values the
2303 result is better than VARYING. */
2304 if (tree_int_cst_sgn (min) < 0
2305 || tree_int_cst_sgn (max) >= 0)
2307 else
2308 max = min = NULL_TREE;
2311 else
2312 gcc_unreachable ();
2314 /* If either MIN or MAX overflowed, then set the resulting range to
2315 VARYING. */
2316 if (min == NULL_TREE
2317 || TREE_OVERFLOW_P (min)
2318 || max == NULL_TREE
2319 || TREE_OVERFLOW_P (max))
2321 set_value_range_to_varying (vr);
2322 return;
2325 /* We punt for [-INF, +INF].
2326 We learn nothing when we have INF on both sides.
2327 Note that we do accept [-INF, -INF] and [+INF, +INF]. */
2328 if (vrp_val_is_min (min) && vrp_val_is_max (max))
2330 set_value_range_to_varying (vr);
2331 return;
2334 cmp = compare_values (min, max);
2335 if (cmp == -2 || cmp == 1)
2337 /* If the new range has its limits swapped around (MIN > MAX),
2338 then the operation caused one of them to wrap around, mark
2339 the new range VARYING. */
2340 set_value_range_to_varying (vr);
2342 else
2343 set_value_range (vr, type, min, max, NULL);
2346 /* Calculates the absolute value of a range and puts the result in VR.
2347 VR0 is the input range. TYPE is the type of the resulting
2348 range. */
2350 static void
2351 extract_range_from_abs_expr (value_range &vr, tree type, value_range &vr0)
2353 /* Pass through vr0 in the easy cases. */
2354 if (TYPE_UNSIGNED (type)
2355 || value_range_nonnegative_p (&vr0))
2357 copy_value_range (&vr, &vr0);
2358 return;
2361 /* For the remaining varying or symbolic ranges we can't do anything
2362 useful. */
2363 if (vr0.type == VR_VARYING
2364 || symbolic_range_p (&vr0))
2366 set_value_range_to_varying (&vr);
2367 return;
2370 /* -TYPE_MIN_VALUE = TYPE_MIN_VALUE with flag_wrapv so we can't get a
2371 useful range. */
2372 if (!TYPE_OVERFLOW_UNDEFINED (type)
2373 && ((vr0.type == VR_RANGE
2374 && vrp_val_is_min (vr0.min))
2375 || (vr0.type == VR_ANTI_RANGE
2376 && !vrp_val_is_min (vr0.min))))
2378 set_value_range_to_varying (&vr);
2379 return;
2382 /* ABS_EXPR may flip the range around, if the original range
2383 included negative values. */
2384 tree min, max;
2385 if (!vrp_val_is_min (vr0.min))
2386 min = fold_unary_to_constant (ABS_EXPR, type, vr0.min);
2387 else
2388 min = TYPE_MAX_VALUE (type);
2390 if (!vrp_val_is_min (vr0.max))
2391 max = fold_unary_to_constant (ABS_EXPR, type, vr0.max);
2392 else
2393 max = TYPE_MAX_VALUE (type);
2395 int cmp = compare_values (min, max);
2396 gcc_assert (vr0.type != VR_ANTI_RANGE);
2398 /* If the range contains zero then we know that the minimum value in the
2399 range will be zero. */
2400 if (range_includes_zero_p (vr0.min, vr0.max) == 1)
2402 if (cmp == 1)
2403 max = min;
2404 min = build_int_cst (type, 0);
2406 else
2408 /* If the range was reversed, swap MIN and MAX. */
2409 if (cmp == 1)
2410 std::swap (min, max);
2413 cmp = compare_values (min, max);
2414 if (cmp == -2 || cmp == 1)
2416 /* If the new range has its limits swapped around (MIN > MAX),
2417 then the operation caused one of them to wrap around, mark
2418 the new range VARYING. */
2419 set_value_range_to_varying (&vr);
2421 else
2422 set_value_range (&vr, vr0.type, min, max, NULL);
2425 /* Extract range information from a unary operation CODE based on
2426 the range of its operand *VR0 with type OP0_TYPE with resulting type TYPE.
2427 The resulting range is stored in *VR. */
2429 void
2430 extract_range_from_unary_expr (value_range *vr,
2431 enum tree_code code, tree type,
2432 value_range *vr0_, tree op0_type)
2434 value_range vr0 = *vr0_, vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
2436 /* VRP only operates on integral and pointer types. */
2437 if (!(INTEGRAL_TYPE_P (op0_type)
2438 || POINTER_TYPE_P (op0_type))
2439 || !(INTEGRAL_TYPE_P (type)
2440 || POINTER_TYPE_P (type)))
2442 set_value_range_to_varying (vr);
2443 return;
2446 /* If VR0 is UNDEFINED, so is the result. */
2447 if (vr0.type == VR_UNDEFINED)
2449 set_value_range_to_undefined (vr);
2450 return;
2453 /* Handle operations that we express in terms of others. */
2454 if (code == PAREN_EXPR || code == OBJ_TYPE_REF)
2456 /* PAREN_EXPR and OBJ_TYPE_REF are simple copies. */
2457 copy_value_range (vr, &vr0);
2458 return;
2460 else if (code == NEGATE_EXPR)
2462 /* -X is simply 0 - X, so re-use existing code that also handles
2463 anti-ranges fine. */
2464 value_range zero = VR_INITIALIZER;
2465 set_value_range_to_value (&zero, build_int_cst (type, 0), NULL);
2466 extract_range_from_binary_expr_1 (vr, MINUS_EXPR, type, &zero, &vr0);
2467 return;
2469 else if (code == BIT_NOT_EXPR)
2471 /* ~X is simply -1 - X, so re-use existing code that also handles
2472 anti-ranges fine. */
2473 value_range minusone = VR_INITIALIZER;
2474 set_value_range_to_value (&minusone, build_int_cst (type, -1), NULL);
2475 extract_range_from_binary_expr_1 (vr, MINUS_EXPR,
2476 type, &minusone, &vr0);
2477 return;
2480 /* Now canonicalize anti-ranges to ranges when they are not symbolic
2481 and express op ~[] as (op []') U (op []''). */
2482 if (vr0.type == VR_ANTI_RANGE
2483 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
2485 extract_range_from_unary_expr (vr, code, type, &vrtem0, op0_type);
2486 if (vrtem1.type != VR_UNDEFINED)
2488 value_range vrres = VR_INITIALIZER;
2489 extract_range_from_unary_expr (&vrres, code, type,
2490 &vrtem1, op0_type);
2491 vrp_meet (vr, &vrres);
2493 return;
2496 if (CONVERT_EXPR_CODE_P (code))
2498 tree inner_type = op0_type;
2499 tree outer_type = type;
2501 /* If the expression evaluates to a pointer, we are only interested in
2502 determining if it evaluates to NULL [0, 0] or non-NULL (~[0, 0]). */
2503 if (POINTER_TYPE_P (type))
2505 if (range_is_nonnull (&vr0))
2506 set_value_range_to_nonnull (vr, type);
2507 else if (range_is_null (&vr0))
2508 set_value_range_to_null (vr, type);
2509 else
2510 set_value_range_to_varying (vr);
2511 return;
2514 /* If VR0 is varying and we increase the type precision, assume
2515 a full range for the following transformation. */
2516 if (vr0.type == VR_VARYING
2517 && INTEGRAL_TYPE_P (inner_type)
2518 && TYPE_PRECISION (inner_type) < TYPE_PRECISION (outer_type))
2520 vr0.type = VR_RANGE;
2521 vr0.min = TYPE_MIN_VALUE (inner_type);
2522 vr0.max = TYPE_MAX_VALUE (inner_type);
2525 /* If VR0 is a constant range or anti-range and the conversion is
2526 not truncating we can convert the min and max values and
2527 canonicalize the resulting range. Otherwise we can do the
2528 conversion if the size of the range is less than what the
2529 precision of the target type can represent and the range is
2530 not an anti-range. */
2531 if ((vr0.type == VR_RANGE
2532 || vr0.type == VR_ANTI_RANGE)
2533 && TREE_CODE (vr0.min) == INTEGER_CST
2534 && TREE_CODE (vr0.max) == INTEGER_CST
2535 && (TYPE_PRECISION (outer_type) >= TYPE_PRECISION (inner_type)
2536 || (vr0.type == VR_RANGE
2537 && integer_zerop (int_const_binop (RSHIFT_EXPR,
2538 int_const_binop (MINUS_EXPR, vr0.max, vr0.min),
2539 size_int (TYPE_PRECISION (outer_type)))))))
2541 tree new_min, new_max;
2542 new_min = force_fit_type (outer_type, wi::to_widest (vr0.min),
2543 0, false);
2544 new_max = force_fit_type (outer_type, wi::to_widest (vr0.max),
2545 0, false);
2546 set_and_canonicalize_value_range (vr, vr0.type,
2547 new_min, new_max, NULL);
2548 return;
2551 set_value_range_to_varying (vr);
2552 return;
2554 else if (code == ABS_EXPR)
2555 return extract_range_from_abs_expr (*vr, type, vr0);
2557 /* For unhandled operations fall back to varying. */
2558 set_value_range_to_varying (vr);
2559 return;
2562 /* Debugging dumps. */
2564 void dump_value_range (FILE *, const value_range *);
2565 void debug_value_range (value_range *);
2566 void dump_all_value_ranges (FILE *);
2567 void dump_vr_equiv (FILE *, bitmap);
2568 void debug_vr_equiv (bitmap);
2571 /* Dump value range VR to FILE. */
2573 void
2574 dump_value_range (FILE *file, const value_range *vr)
2576 if (vr == NULL)
2577 fprintf (file, "[]");
2578 else if (vr->type == VR_UNDEFINED)
2579 fprintf (file, "UNDEFINED");
2580 else if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
2582 tree type = TREE_TYPE (vr->min);
2584 fprintf (file, "%s[", (vr->type == VR_ANTI_RANGE) ? "~" : "");
2586 if (INTEGRAL_TYPE_P (type)
2587 && !TYPE_UNSIGNED (type)
2588 && vrp_val_is_min (vr->min))
2589 fprintf (file, "-INF");
2590 else
2591 print_generic_expr (file, vr->min);
2593 fprintf (file, ", ");
2595 if (INTEGRAL_TYPE_P (type)
2596 && vrp_val_is_max (vr->max))
2597 fprintf (file, "+INF");
2598 else
2599 print_generic_expr (file, vr->max);
2601 fprintf (file, "]");
2603 if (vr->equiv)
2605 bitmap_iterator bi;
2606 unsigned i, c = 0;
2608 fprintf (file, " EQUIVALENCES: { ");
2610 EXECUTE_IF_SET_IN_BITMAP (vr->equiv, 0, i, bi)
2612 print_generic_expr (file, ssa_name (i));
2613 fprintf (file, " ");
2614 c++;
2617 fprintf (file, "} (%u elements)", c);
2620 else if (vr->type == VR_VARYING)
2621 fprintf (file, "VARYING");
2622 else
2623 fprintf (file, "INVALID RANGE");
2627 /* Dump value range VR to stderr. */
2629 DEBUG_FUNCTION void
2630 debug_value_range (value_range *vr)
2632 dump_value_range (stderr, vr);
2633 fprintf (stderr, "\n");
2637 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
2638 create a new SSA name N and return the assertion assignment
2639 'N = ASSERT_EXPR <V, V OP W>'. */
2641 static gimple *
2642 build_assert_expr_for (tree cond, tree v)
2644 tree a;
2645 gassign *assertion;
2647 gcc_assert (TREE_CODE (v) == SSA_NAME
2648 && COMPARISON_CLASS_P (cond));
2650 a = build2 (ASSERT_EXPR, TREE_TYPE (v), v, cond);
2651 assertion = gimple_build_assign (NULL_TREE, a);
2653 /* The new ASSERT_EXPR, creates a new SSA name that replaces the
2654 operand of the ASSERT_EXPR. Create it so the new name and the old one
2655 are registered in the replacement table so that we can fix the SSA web
2656 after adding all the ASSERT_EXPRs. */
2657 tree new_def = create_new_def_for (v, assertion, NULL);
2658 /* Make sure we preserve abnormalness throughout an ASSERT_EXPR chain
2659 given we have to be able to fully propagate those out to re-create
2660 valid SSA when removing the asserts. */
2661 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (v))
2662 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_def) = 1;
2664 return assertion;
2668 /* Return false if EXPR is a predicate expression involving floating
2669 point values. */
2671 static inline bool
2672 fp_predicate (gimple *stmt)
2674 GIMPLE_CHECK (stmt, GIMPLE_COND);
2676 return FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)));
2679 /* If the range of values taken by OP can be inferred after STMT executes,
2680 return the comparison code (COMP_CODE_P) and value (VAL_P) that
2681 describes the inferred range. Return true if a range could be
2682 inferred. */
2684 bool
2685 infer_value_range (gimple *stmt, tree op, tree_code *comp_code_p, tree *val_p)
2687 *val_p = NULL_TREE;
2688 *comp_code_p = ERROR_MARK;
2690 /* Do not attempt to infer anything in names that flow through
2691 abnormal edges. */
2692 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
2693 return false;
2695 /* If STMT is the last statement of a basic block with no normal
2696 successors, there is no point inferring anything about any of its
2697 operands. We would not be able to find a proper insertion point
2698 for the assertion, anyway. */
2699 if (stmt_ends_bb_p (stmt))
2701 edge_iterator ei;
2702 edge e;
2704 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
2705 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
2706 break;
2707 if (e == NULL)
2708 return false;
2711 if (infer_nonnull_range (stmt, op))
2713 *val_p = build_int_cst (TREE_TYPE (op), 0);
2714 *comp_code_p = NE_EXPR;
2715 return true;
2718 return false;
2722 void dump_asserts_for (FILE *, tree);
2723 void debug_asserts_for (tree);
2724 void dump_all_asserts (FILE *);
2725 void debug_all_asserts (void);
2727 /* Dump all the registered assertions for NAME to FILE. */
2729 void
2730 dump_asserts_for (FILE *file, tree name)
2732 assert_locus *loc;
2734 fprintf (file, "Assertions to be inserted for ");
2735 print_generic_expr (file, name);
2736 fprintf (file, "\n");
2738 loc = asserts_for[SSA_NAME_VERSION (name)];
2739 while (loc)
2741 fprintf (file, "\t");
2742 print_gimple_stmt (file, gsi_stmt (loc->si), 0);
2743 fprintf (file, "\n\tBB #%d", loc->bb->index);
2744 if (loc->e)
2746 fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
2747 loc->e->dest->index);
2748 dump_edge_info (file, loc->e, dump_flags, 0);
2750 fprintf (file, "\n\tPREDICATE: ");
2751 print_generic_expr (file, loc->expr);
2752 fprintf (file, " %s ", get_tree_code_name (loc->comp_code));
2753 print_generic_expr (file, loc->val);
2754 fprintf (file, "\n\n");
2755 loc = loc->next;
2758 fprintf (file, "\n");
2762 /* Dump all the registered assertions for NAME to stderr. */
2764 DEBUG_FUNCTION void
2765 debug_asserts_for (tree name)
2767 dump_asserts_for (stderr, name);
2771 /* Dump all the registered assertions for all the names to FILE. */
2773 void
2774 dump_all_asserts (FILE *file)
2776 unsigned i;
2777 bitmap_iterator bi;
2779 fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
2780 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
2781 dump_asserts_for (file, ssa_name (i));
2782 fprintf (file, "\n");
2786 /* Dump all the registered assertions for all the names to stderr. */
2788 DEBUG_FUNCTION void
2789 debug_all_asserts (void)
2791 dump_all_asserts (stderr);
2794 /* Push the assert info for NAME, EXPR, COMP_CODE and VAL to ASSERTS. */
2796 static void
2797 add_assert_info (vec<assert_info> &asserts,
2798 tree name, tree expr, enum tree_code comp_code, tree val)
2800 assert_info info;
2801 info.comp_code = comp_code;
2802 info.name = name;
2803 if (TREE_OVERFLOW_P (val))
2804 val = drop_tree_overflow (val);
2805 info.val = val;
2806 info.expr = expr;
2807 asserts.safe_push (info);
2810 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
2811 'EXPR COMP_CODE VAL' at a location that dominates block BB or
2812 E->DEST, then register this location as a possible insertion point
2813 for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
2815 BB, E and SI provide the exact insertion point for the new
2816 ASSERT_EXPR. If BB is NULL, then the ASSERT_EXPR is to be inserted
2817 on edge E. Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
2818 BB. If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
2819 must not be NULL. */
2821 static void
2822 register_new_assert_for (tree name, tree expr,
2823 enum tree_code comp_code,
2824 tree val,
2825 basic_block bb,
2826 edge e,
2827 gimple_stmt_iterator si)
2829 assert_locus *n, *loc, *last_loc;
2830 basic_block dest_bb;
2832 gcc_checking_assert (bb == NULL || e == NULL);
2834 if (e == NULL)
2835 gcc_checking_assert (gimple_code (gsi_stmt (si)) != GIMPLE_COND
2836 && gimple_code (gsi_stmt (si)) != GIMPLE_SWITCH);
2838 /* Never build an assert comparing against an integer constant with
2839 TREE_OVERFLOW set. This confuses our undefined overflow warning
2840 machinery. */
2841 if (TREE_OVERFLOW_P (val))
2842 val = drop_tree_overflow (val);
2844 /* The new assertion A will be inserted at BB or E. We need to
2845 determine if the new location is dominated by a previously
2846 registered location for A. If we are doing an edge insertion,
2847 assume that A will be inserted at E->DEST. Note that this is not
2848 necessarily true.
2850 If E is a critical edge, it will be split. But even if E is
2851 split, the new block will dominate the same set of blocks that
2852 E->DEST dominates.
2854 The reverse, however, is not true, blocks dominated by E->DEST
2855 will not be dominated by the new block created to split E. So,
2856 if the insertion location is on a critical edge, we will not use
2857 the new location to move another assertion previously registered
2858 at a block dominated by E->DEST. */
2859 dest_bb = (bb) ? bb : e->dest;
2861 /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
2862 VAL at a block dominating DEST_BB, then we don't need to insert a new
2863 one. Similarly, if the same assertion already exists at a block
2864 dominated by DEST_BB and the new location is not on a critical
2865 edge, then update the existing location for the assertion (i.e.,
2866 move the assertion up in the dominance tree).
2868 Note, this is implemented as a simple linked list because there
2869 should not be more than a handful of assertions registered per
2870 name. If this becomes a performance problem, a table hashed by
2871 COMP_CODE and VAL could be implemented. */
2872 loc = asserts_for[SSA_NAME_VERSION (name)];
2873 last_loc = loc;
2874 while (loc)
2876 if (loc->comp_code == comp_code
2877 && (loc->val == val
2878 || operand_equal_p (loc->val, val, 0))
2879 && (loc->expr == expr
2880 || operand_equal_p (loc->expr, expr, 0)))
2882 /* If E is not a critical edge and DEST_BB
2883 dominates the existing location for the assertion, move
2884 the assertion up in the dominance tree by updating its
2885 location information. */
2886 if ((e == NULL || !EDGE_CRITICAL_P (e))
2887 && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
2889 loc->bb = dest_bb;
2890 loc->e = e;
2891 loc->si = si;
2892 return;
2896 /* Update the last node of the list and move to the next one. */
2897 last_loc = loc;
2898 loc = loc->next;
2901 /* If we didn't find an assertion already registered for
2902 NAME COMP_CODE VAL, add a new one at the end of the list of
2903 assertions associated with NAME. */
2904 n = XNEW (struct assert_locus);
2905 n->bb = dest_bb;
2906 n->e = e;
2907 n->si = si;
2908 n->comp_code = comp_code;
2909 n->val = val;
2910 n->expr = expr;
2911 n->next = NULL;
2913 if (last_loc)
2914 last_loc->next = n;
2915 else
2916 asserts_for[SSA_NAME_VERSION (name)] = n;
2918 bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
2921 /* (COND_OP0 COND_CODE COND_OP1) is a predicate which uses NAME.
2922 Extract a suitable test code and value and store them into *CODE_P and
2923 *VAL_P so the predicate is normalized to NAME *CODE_P *VAL_P.
2925 If no extraction was possible, return FALSE, otherwise return TRUE.
2927 If INVERT is true, then we invert the result stored into *CODE_P. */
2929 static bool
2930 extract_code_and_val_from_cond_with_ops (tree name, enum tree_code cond_code,
2931 tree cond_op0, tree cond_op1,
2932 bool invert, enum tree_code *code_p,
2933 tree *val_p)
2935 enum tree_code comp_code;
2936 tree val;
2938 /* Otherwise, we have a comparison of the form NAME COMP VAL
2939 or VAL COMP NAME. */
2940 if (name == cond_op1)
2942 /* If the predicate is of the form VAL COMP NAME, flip
2943 COMP around because we need to register NAME as the
2944 first operand in the predicate. */
2945 comp_code = swap_tree_comparison (cond_code);
2946 val = cond_op0;
2948 else if (name == cond_op0)
2950 /* The comparison is of the form NAME COMP VAL, so the
2951 comparison code remains unchanged. */
2952 comp_code = cond_code;
2953 val = cond_op1;
2955 else
2956 gcc_unreachable ();
2958 /* Invert the comparison code as necessary. */
2959 if (invert)
2960 comp_code = invert_tree_comparison (comp_code, 0);
2962 /* VRP only handles integral and pointer types. */
2963 if (! INTEGRAL_TYPE_P (TREE_TYPE (val))
2964 && ! POINTER_TYPE_P (TREE_TYPE (val)))
2965 return false;
2967 /* Do not register always-false predicates.
2968 FIXME: this works around a limitation in fold() when dealing with
2969 enumerations. Given 'enum { N1, N2 } x;', fold will not
2970 fold 'if (x > N2)' to 'if (0)'. */
2971 if ((comp_code == GT_EXPR || comp_code == LT_EXPR)
2972 && INTEGRAL_TYPE_P (TREE_TYPE (val)))
2974 tree min = TYPE_MIN_VALUE (TREE_TYPE (val));
2975 tree max = TYPE_MAX_VALUE (TREE_TYPE (val));
2977 if (comp_code == GT_EXPR
2978 && (!max
2979 || compare_values (val, max) == 0))
2980 return false;
2982 if (comp_code == LT_EXPR
2983 && (!min
2984 || compare_values (val, min) == 0))
2985 return false;
2987 *code_p = comp_code;
2988 *val_p = val;
2989 return true;
2992 /* Find out smallest RES where RES > VAL && (RES & MASK) == RES, if any
2993 (otherwise return VAL). VAL and MASK must be zero-extended for
2994 precision PREC. If SGNBIT is non-zero, first xor VAL with SGNBIT
2995 (to transform signed values into unsigned) and at the end xor
2996 SGNBIT back. */
2998 static wide_int
2999 masked_increment (const wide_int &val_in, const wide_int &mask,
3000 const wide_int &sgnbit, unsigned int prec)
3002 wide_int bit = wi::one (prec), res;
3003 unsigned int i;
3005 wide_int val = val_in ^ sgnbit;
3006 for (i = 0; i < prec; i++, bit += bit)
3008 res = mask;
3009 if ((res & bit) == 0)
3010 continue;
3011 res = bit - 1;
3012 res = wi::bit_and_not (val + bit, res);
3013 res &= mask;
3014 if (wi::gtu_p (res, val))
3015 return res ^ sgnbit;
3017 return val ^ sgnbit;
3020 /* Helper for overflow_comparison_p
3022 OP0 CODE OP1 is a comparison. Examine the comparison and potentially
3023 OP1's defining statement to see if it ultimately has the form
3024 OP0 CODE (OP0 PLUS INTEGER_CST)
3026 If so, return TRUE indicating this is an overflow test and store into
3027 *NEW_CST an updated constant that can be used in a narrowed range test.
3029 REVERSED indicates if the comparison was originally:
3031 OP1 CODE' OP0.
3033 This affects how we build the updated constant. */
3035 static bool
3036 overflow_comparison_p_1 (enum tree_code code, tree op0, tree op1,
3037 bool follow_assert_exprs, bool reversed, tree *new_cst)
3039 /* See if this is a relational operation between two SSA_NAMES with
3040 unsigned, overflow wrapping values. If so, check it more deeply. */
3041 if ((code == LT_EXPR || code == LE_EXPR
3042 || code == GE_EXPR || code == GT_EXPR)
3043 && TREE_CODE (op0) == SSA_NAME
3044 && TREE_CODE (op1) == SSA_NAME
3045 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
3046 && TYPE_UNSIGNED (TREE_TYPE (op0))
3047 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0)))
3049 gimple *op1_def = SSA_NAME_DEF_STMT (op1);
3051 /* If requested, follow any ASSERT_EXPRs backwards for OP1. */
3052 if (follow_assert_exprs)
3054 while (gimple_assign_single_p (op1_def)
3055 && TREE_CODE (gimple_assign_rhs1 (op1_def)) == ASSERT_EXPR)
3057 op1 = TREE_OPERAND (gimple_assign_rhs1 (op1_def), 0);
3058 if (TREE_CODE (op1) != SSA_NAME)
3059 break;
3060 op1_def = SSA_NAME_DEF_STMT (op1);
3064 /* Now look at the defining statement of OP1 to see if it adds
3065 or subtracts a nonzero constant from another operand. */
3066 if (op1_def
3067 && is_gimple_assign (op1_def)
3068 && gimple_assign_rhs_code (op1_def) == PLUS_EXPR
3069 && TREE_CODE (gimple_assign_rhs2 (op1_def)) == INTEGER_CST
3070 && !integer_zerop (gimple_assign_rhs2 (op1_def)))
3072 tree target = gimple_assign_rhs1 (op1_def);
3074 /* If requested, follow ASSERT_EXPRs backwards for op0 looking
3075 for one where TARGET appears on the RHS. */
3076 if (follow_assert_exprs)
3078 /* Now see if that "other operand" is op0, following the chain
3079 of ASSERT_EXPRs if necessary. */
3080 gimple *op0_def = SSA_NAME_DEF_STMT (op0);
3081 while (op0 != target
3082 && gimple_assign_single_p (op0_def)
3083 && TREE_CODE (gimple_assign_rhs1 (op0_def)) == ASSERT_EXPR)
3085 op0 = TREE_OPERAND (gimple_assign_rhs1 (op0_def), 0);
3086 if (TREE_CODE (op0) != SSA_NAME)
3087 break;
3088 op0_def = SSA_NAME_DEF_STMT (op0);
3092 /* If we did not find our target SSA_NAME, then this is not
3093 an overflow test. */
3094 if (op0 != target)
3095 return false;
3097 tree type = TREE_TYPE (op0);
3098 wide_int max = wi::max_value (TYPE_PRECISION (type), UNSIGNED);
3099 tree inc = gimple_assign_rhs2 (op1_def);
3100 if (reversed)
3101 *new_cst = wide_int_to_tree (type, max + wi::to_wide (inc));
3102 else
3103 *new_cst = wide_int_to_tree (type, max - wi::to_wide (inc));
3104 return true;
3107 return false;
3110 /* OP0 CODE OP1 is a comparison. Examine the comparison and potentially
3111 OP1's defining statement to see if it ultimately has the form
3112 OP0 CODE (OP0 PLUS INTEGER_CST)
3114 If so, return TRUE indicating this is an overflow test and store into
3115 *NEW_CST an updated constant that can be used in a narrowed range test.
3117 These statements are left as-is in the IL to facilitate discovery of
3118 {ADD,SUB}_OVERFLOW sequences later in the optimizer pipeline. But
3119 the alternate range representation is often useful within VRP. */
3121 bool
3122 overflow_comparison_p (tree_code code, tree name, tree val,
3123 bool use_equiv_p, tree *new_cst)
3125 if (overflow_comparison_p_1 (code, name, val, use_equiv_p, false, new_cst))
3126 return true;
3127 return overflow_comparison_p_1 (swap_tree_comparison (code), val, name,
3128 use_equiv_p, true, new_cst);
3132 /* Try to register an edge assertion for SSA name NAME on edge E for
3133 the condition COND contributing to the conditional jump pointed to by BSI.
3134 Invert the condition COND if INVERT is true. */
3136 static void
3137 register_edge_assert_for_2 (tree name, edge e,
3138 enum tree_code cond_code,
3139 tree cond_op0, tree cond_op1, bool invert,
3140 vec<assert_info> &asserts)
3142 tree val;
3143 enum tree_code comp_code;
3145 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
3146 cond_op0,
3147 cond_op1,
3148 invert, &comp_code, &val))
3149 return;
3151 /* Queue the assert. */
3152 tree x;
3153 if (overflow_comparison_p (comp_code, name, val, false, &x))
3155 enum tree_code new_code = ((comp_code == GT_EXPR || comp_code == GE_EXPR)
3156 ? GT_EXPR : LE_EXPR);
3157 add_assert_info (asserts, name, name, new_code, x);
3159 add_assert_info (asserts, name, name, comp_code, val);
3161 /* In the case of NAME <= CST and NAME being defined as
3162 NAME = (unsigned) NAME2 + CST2 we can assert NAME2 >= -CST2
3163 and NAME2 <= CST - CST2. We can do the same for NAME > CST.
3164 This catches range and anti-range tests. */
3165 if ((comp_code == LE_EXPR
3166 || comp_code == GT_EXPR)
3167 && TREE_CODE (val) == INTEGER_CST
3168 && TYPE_UNSIGNED (TREE_TYPE (val)))
3170 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3171 tree cst2 = NULL_TREE, name2 = NULL_TREE, name3 = NULL_TREE;
3173 /* Extract CST2 from the (optional) addition. */
3174 if (is_gimple_assign (def_stmt)
3175 && gimple_assign_rhs_code (def_stmt) == PLUS_EXPR)
3177 name2 = gimple_assign_rhs1 (def_stmt);
3178 cst2 = gimple_assign_rhs2 (def_stmt);
3179 if (TREE_CODE (name2) == SSA_NAME
3180 && TREE_CODE (cst2) == INTEGER_CST)
3181 def_stmt = SSA_NAME_DEF_STMT (name2);
3184 /* Extract NAME2 from the (optional) sign-changing cast. */
3185 if (gimple_assign_cast_p (def_stmt))
3187 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt))
3188 && ! TYPE_UNSIGNED (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
3189 && (TYPE_PRECISION (gimple_expr_type (def_stmt))
3190 == TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))))
3191 name3 = gimple_assign_rhs1 (def_stmt);
3194 /* If name3 is used later, create an ASSERT_EXPR for it. */
3195 if (name3 != NULL_TREE
3196 && TREE_CODE (name3) == SSA_NAME
3197 && (cst2 == NULL_TREE
3198 || TREE_CODE (cst2) == INTEGER_CST)
3199 && INTEGRAL_TYPE_P (TREE_TYPE (name3)))
3201 tree tmp;
3203 /* Build an expression for the range test. */
3204 tmp = build1 (NOP_EXPR, TREE_TYPE (name), name3);
3205 if (cst2 != NULL_TREE)
3206 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
3208 if (dump_file)
3210 fprintf (dump_file, "Adding assert for ");
3211 print_generic_expr (dump_file, name3);
3212 fprintf (dump_file, " from ");
3213 print_generic_expr (dump_file, tmp);
3214 fprintf (dump_file, "\n");
3217 add_assert_info (asserts, name3, tmp, comp_code, val);
3220 /* If name2 is used later, create an ASSERT_EXPR for it. */
3221 if (name2 != NULL_TREE
3222 && TREE_CODE (name2) == SSA_NAME
3223 && TREE_CODE (cst2) == INTEGER_CST
3224 && INTEGRAL_TYPE_P (TREE_TYPE (name2)))
3226 tree tmp;
3228 /* Build an expression for the range test. */
3229 tmp = name2;
3230 if (TREE_TYPE (name) != TREE_TYPE (name2))
3231 tmp = build1 (NOP_EXPR, TREE_TYPE (name), tmp);
3232 if (cst2 != NULL_TREE)
3233 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
3235 if (dump_file)
3237 fprintf (dump_file, "Adding assert for ");
3238 print_generic_expr (dump_file, name2);
3239 fprintf (dump_file, " from ");
3240 print_generic_expr (dump_file, tmp);
3241 fprintf (dump_file, "\n");
3244 add_assert_info (asserts, name2, tmp, comp_code, val);
3248 /* In the case of post-in/decrement tests like if (i++) ... and uses
3249 of the in/decremented value on the edge the extra name we want to
3250 assert for is not on the def chain of the name compared. Instead
3251 it is in the set of use stmts.
3252 Similar cases happen for conversions that were simplified through
3253 fold_{sign_changed,widened}_comparison. */
3254 if ((comp_code == NE_EXPR
3255 || comp_code == EQ_EXPR)
3256 && TREE_CODE (val) == INTEGER_CST)
3258 imm_use_iterator ui;
3259 gimple *use_stmt;
3260 FOR_EACH_IMM_USE_STMT (use_stmt, ui, name)
3262 if (!is_gimple_assign (use_stmt))
3263 continue;
3265 /* Cut off to use-stmts that are dominating the predecessor. */
3266 if (!dominated_by_p (CDI_DOMINATORS, e->src, gimple_bb (use_stmt)))
3267 continue;
3269 tree name2 = gimple_assign_lhs (use_stmt);
3270 if (TREE_CODE (name2) != SSA_NAME)
3271 continue;
3273 enum tree_code code = gimple_assign_rhs_code (use_stmt);
3274 tree cst;
3275 if (code == PLUS_EXPR
3276 || code == MINUS_EXPR)
3278 cst = gimple_assign_rhs2 (use_stmt);
3279 if (TREE_CODE (cst) != INTEGER_CST)
3280 continue;
3281 cst = int_const_binop (code, val, cst);
3283 else if (CONVERT_EXPR_CODE_P (code))
3285 /* For truncating conversions we cannot record
3286 an inequality. */
3287 if (comp_code == NE_EXPR
3288 && (TYPE_PRECISION (TREE_TYPE (name2))
3289 < TYPE_PRECISION (TREE_TYPE (name))))
3290 continue;
3291 cst = fold_convert (TREE_TYPE (name2), val);
3293 else
3294 continue;
3296 if (TREE_OVERFLOW_P (cst))
3297 cst = drop_tree_overflow (cst);
3298 add_assert_info (asserts, name2, name2, comp_code, cst);
3302 if (TREE_CODE_CLASS (comp_code) == tcc_comparison
3303 && TREE_CODE (val) == INTEGER_CST)
3305 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3306 tree name2 = NULL_TREE, names[2], cst2 = NULL_TREE;
3307 tree val2 = NULL_TREE;
3308 unsigned int prec = TYPE_PRECISION (TREE_TYPE (val));
3309 wide_int mask = wi::zero (prec);
3310 unsigned int nprec = prec;
3311 enum tree_code rhs_code = ERROR_MARK;
3313 if (is_gimple_assign (def_stmt))
3314 rhs_code = gimple_assign_rhs_code (def_stmt);
3316 /* In the case of NAME != CST1 where NAME = A +- CST2 we can
3317 assert that A != CST1 -+ CST2. */
3318 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
3319 && (rhs_code == PLUS_EXPR || rhs_code == MINUS_EXPR))
3321 tree op0 = gimple_assign_rhs1 (def_stmt);
3322 tree op1 = gimple_assign_rhs2 (def_stmt);
3323 if (TREE_CODE (op0) == SSA_NAME
3324 && TREE_CODE (op1) == INTEGER_CST)
3326 enum tree_code reverse_op = (rhs_code == PLUS_EXPR
3327 ? MINUS_EXPR : PLUS_EXPR);
3328 op1 = int_const_binop (reverse_op, val, op1);
3329 if (TREE_OVERFLOW (op1))
3330 op1 = drop_tree_overflow (op1);
3331 add_assert_info (asserts, op0, op0, comp_code, op1);
3335 /* Add asserts for NAME cmp CST and NAME being defined
3336 as NAME = (int) NAME2. */
3337 if (!TYPE_UNSIGNED (TREE_TYPE (val))
3338 && (comp_code == LE_EXPR || comp_code == LT_EXPR
3339 || comp_code == GT_EXPR || comp_code == GE_EXPR)
3340 && gimple_assign_cast_p (def_stmt))
3342 name2 = gimple_assign_rhs1 (def_stmt);
3343 if (CONVERT_EXPR_CODE_P (rhs_code)
3344 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
3345 && TYPE_UNSIGNED (TREE_TYPE (name2))
3346 && prec == TYPE_PRECISION (TREE_TYPE (name2))
3347 && (comp_code == LE_EXPR || comp_code == GT_EXPR
3348 || !tree_int_cst_equal (val,
3349 TYPE_MIN_VALUE (TREE_TYPE (val)))))
3351 tree tmp, cst;
3352 enum tree_code new_comp_code = comp_code;
3354 cst = fold_convert (TREE_TYPE (name2),
3355 TYPE_MIN_VALUE (TREE_TYPE (val)));
3356 /* Build an expression for the range test. */
3357 tmp = build2 (PLUS_EXPR, TREE_TYPE (name2), name2, cst);
3358 cst = fold_build2 (PLUS_EXPR, TREE_TYPE (name2), cst,
3359 fold_convert (TREE_TYPE (name2), val));
3360 if (comp_code == LT_EXPR || comp_code == GE_EXPR)
3362 new_comp_code = comp_code == LT_EXPR ? LE_EXPR : GT_EXPR;
3363 cst = fold_build2 (MINUS_EXPR, TREE_TYPE (name2), cst,
3364 build_int_cst (TREE_TYPE (name2), 1));
3367 if (dump_file)
3369 fprintf (dump_file, "Adding assert for ");
3370 print_generic_expr (dump_file, name2);
3371 fprintf (dump_file, " from ");
3372 print_generic_expr (dump_file, tmp);
3373 fprintf (dump_file, "\n");
3376 add_assert_info (asserts, name2, tmp, new_comp_code, cst);
3380 /* Add asserts for NAME cmp CST and NAME being defined as
3381 NAME = NAME2 >> CST2.
3383 Extract CST2 from the right shift. */
3384 if (rhs_code == RSHIFT_EXPR)
3386 name2 = gimple_assign_rhs1 (def_stmt);
3387 cst2 = gimple_assign_rhs2 (def_stmt);
3388 if (TREE_CODE (name2) == SSA_NAME
3389 && tree_fits_uhwi_p (cst2)
3390 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
3391 && IN_RANGE (tree_to_uhwi (cst2), 1, prec - 1)
3392 && type_has_mode_precision_p (TREE_TYPE (val)))
3394 mask = wi::mask (tree_to_uhwi (cst2), false, prec);
3395 val2 = fold_binary (LSHIFT_EXPR, TREE_TYPE (val), val, cst2);
3398 if (val2 != NULL_TREE
3399 && TREE_CODE (val2) == INTEGER_CST
3400 && simple_cst_equal (fold_build2 (RSHIFT_EXPR,
3401 TREE_TYPE (val),
3402 val2, cst2), val))
3404 enum tree_code new_comp_code = comp_code;
3405 tree tmp, new_val;
3407 tmp = name2;
3408 if (comp_code == EQ_EXPR || comp_code == NE_EXPR)
3410 if (!TYPE_UNSIGNED (TREE_TYPE (val)))
3412 tree type = build_nonstandard_integer_type (prec, 1);
3413 tmp = build1 (NOP_EXPR, type, name2);
3414 val2 = fold_convert (type, val2);
3416 tmp = fold_build2 (MINUS_EXPR, TREE_TYPE (tmp), tmp, val2);
3417 new_val = wide_int_to_tree (TREE_TYPE (tmp), mask);
3418 new_comp_code = comp_code == EQ_EXPR ? LE_EXPR : GT_EXPR;
3420 else if (comp_code == LT_EXPR || comp_code == GE_EXPR)
3422 wide_int minval
3423 = wi::min_value (prec, TYPE_SIGN (TREE_TYPE (val)));
3424 new_val = val2;
3425 if (minval == wi::to_wide (new_val))
3426 new_val = NULL_TREE;
3428 else
3430 wide_int maxval
3431 = wi::max_value (prec, TYPE_SIGN (TREE_TYPE (val)));
3432 mask |= wi::to_wide (val2);
3433 if (wi::eq_p (mask, maxval))
3434 new_val = NULL_TREE;
3435 else
3436 new_val = wide_int_to_tree (TREE_TYPE (val2), mask);
3439 if (new_val)
3441 if (dump_file)
3443 fprintf (dump_file, "Adding assert for ");
3444 print_generic_expr (dump_file, name2);
3445 fprintf (dump_file, " from ");
3446 print_generic_expr (dump_file, tmp);
3447 fprintf (dump_file, "\n");
3450 add_assert_info (asserts, name2, tmp, new_comp_code, new_val);
3454 /* Add asserts for NAME cmp CST and NAME being defined as
3455 NAME = NAME2 & CST2.
3457 Extract CST2 from the and.
3459 Also handle
3460 NAME = (unsigned) NAME2;
3461 casts where NAME's type is unsigned and has smaller precision
3462 than NAME2's type as if it was NAME = NAME2 & MASK. */
3463 names[0] = NULL_TREE;
3464 names[1] = NULL_TREE;
3465 cst2 = NULL_TREE;
3466 if (rhs_code == BIT_AND_EXPR
3467 || (CONVERT_EXPR_CODE_P (rhs_code)
3468 && INTEGRAL_TYPE_P (TREE_TYPE (val))
3469 && TYPE_UNSIGNED (TREE_TYPE (val))
3470 && TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
3471 > prec))
3473 name2 = gimple_assign_rhs1 (def_stmt);
3474 if (rhs_code == BIT_AND_EXPR)
3475 cst2 = gimple_assign_rhs2 (def_stmt);
3476 else
3478 cst2 = TYPE_MAX_VALUE (TREE_TYPE (val));
3479 nprec = TYPE_PRECISION (TREE_TYPE (name2));
3481 if (TREE_CODE (name2) == SSA_NAME
3482 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
3483 && TREE_CODE (cst2) == INTEGER_CST
3484 && !integer_zerop (cst2)
3485 && (nprec > 1
3486 || TYPE_UNSIGNED (TREE_TYPE (val))))
3488 gimple *def_stmt2 = SSA_NAME_DEF_STMT (name2);
3489 if (gimple_assign_cast_p (def_stmt2))
3491 names[1] = gimple_assign_rhs1 (def_stmt2);
3492 if (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt2))
3493 || !INTEGRAL_TYPE_P (TREE_TYPE (names[1]))
3494 || (TYPE_PRECISION (TREE_TYPE (name2))
3495 != TYPE_PRECISION (TREE_TYPE (names[1]))))
3496 names[1] = NULL_TREE;
3498 names[0] = name2;
3501 if (names[0] || names[1])
3503 wide_int minv, maxv, valv, cst2v;
3504 wide_int tem, sgnbit;
3505 bool valid_p = false, valn, cst2n;
3506 enum tree_code ccode = comp_code;
3508 valv = wide_int::from (wi::to_wide (val), nprec, UNSIGNED);
3509 cst2v = wide_int::from (wi::to_wide (cst2), nprec, UNSIGNED);
3510 valn = wi::neg_p (valv, TYPE_SIGN (TREE_TYPE (val)));
3511 cst2n = wi::neg_p (cst2v, TYPE_SIGN (TREE_TYPE (val)));
3512 /* If CST2 doesn't have most significant bit set,
3513 but VAL is negative, we have comparison like
3514 if ((x & 0x123) > -4) (always true). Just give up. */
3515 if (!cst2n && valn)
3516 ccode = ERROR_MARK;
3517 if (cst2n)
3518 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
3519 else
3520 sgnbit = wi::zero (nprec);
3521 minv = valv & cst2v;
3522 switch (ccode)
3524 case EQ_EXPR:
3525 /* Minimum unsigned value for equality is VAL & CST2
3526 (should be equal to VAL, otherwise we probably should
3527 have folded the comparison into false) and
3528 maximum unsigned value is VAL | ~CST2. */
3529 maxv = valv | ~cst2v;
3530 valid_p = true;
3531 break;
3533 case NE_EXPR:
3534 tem = valv | ~cst2v;
3535 /* If VAL is 0, handle (X & CST2) != 0 as (X & CST2) > 0U. */
3536 if (valv == 0)
3538 cst2n = false;
3539 sgnbit = wi::zero (nprec);
3540 goto gt_expr;
3542 /* If (VAL | ~CST2) is all ones, handle it as
3543 (X & CST2) < VAL. */
3544 if (tem == -1)
3546 cst2n = false;
3547 valn = false;
3548 sgnbit = wi::zero (nprec);
3549 goto lt_expr;
3551 if (!cst2n && wi::neg_p (cst2v))
3552 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
3553 if (sgnbit != 0)
3555 if (valv == sgnbit)
3557 cst2n = true;
3558 valn = true;
3559 goto gt_expr;
3561 if (tem == wi::mask (nprec - 1, false, nprec))
3563 cst2n = true;
3564 goto lt_expr;
3566 if (!cst2n)
3567 sgnbit = wi::zero (nprec);
3569 break;
3571 case GE_EXPR:
3572 /* Minimum unsigned value for >= if (VAL & CST2) == VAL
3573 is VAL and maximum unsigned value is ~0. For signed
3574 comparison, if CST2 doesn't have most significant bit
3575 set, handle it similarly. If CST2 has MSB set,
3576 the minimum is the same, and maximum is ~0U/2. */
3577 if (minv != valv)
3579 /* If (VAL & CST2) != VAL, X & CST2 can't be equal to
3580 VAL. */
3581 minv = masked_increment (valv, cst2v, sgnbit, nprec);
3582 if (minv == valv)
3583 break;
3585 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
3586 valid_p = true;
3587 break;
3589 case GT_EXPR:
3590 gt_expr:
3591 /* Find out smallest MINV where MINV > VAL
3592 && (MINV & CST2) == MINV, if any. If VAL is signed and
3593 CST2 has MSB set, compute it biased by 1 << (nprec - 1). */
3594 minv = masked_increment (valv, cst2v, sgnbit, nprec);
3595 if (minv == valv)
3596 break;
3597 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
3598 valid_p = true;
3599 break;
3601 case LE_EXPR:
3602 /* Minimum unsigned value for <= is 0 and maximum
3603 unsigned value is VAL | ~CST2 if (VAL & CST2) == VAL.
3604 Otherwise, find smallest VAL2 where VAL2 > VAL
3605 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
3606 as maximum.
3607 For signed comparison, if CST2 doesn't have most
3608 significant bit set, handle it similarly. If CST2 has
3609 MSB set, the maximum is the same and minimum is INT_MIN. */
3610 if (minv == valv)
3611 maxv = valv;
3612 else
3614 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
3615 if (maxv == valv)
3616 break;
3617 maxv -= 1;
3619 maxv |= ~cst2v;
3620 minv = sgnbit;
3621 valid_p = true;
3622 break;
3624 case LT_EXPR:
3625 lt_expr:
3626 /* Minimum unsigned value for < is 0 and maximum
3627 unsigned value is (VAL-1) | ~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)
3636 if (valv == sgnbit)
3637 break;
3638 maxv = valv;
3640 else
3642 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
3643 if (maxv == valv)
3644 break;
3646 maxv -= 1;
3647 maxv |= ~cst2v;
3648 minv = sgnbit;
3649 valid_p = true;
3650 break;
3652 default:
3653 break;
3655 if (valid_p
3656 && (maxv - minv) != -1)
3658 tree tmp, new_val, type;
3659 int i;
3661 for (i = 0; i < 2; i++)
3662 if (names[i])
3664 wide_int maxv2 = maxv;
3665 tmp = names[i];
3666 type = TREE_TYPE (names[i]);
3667 if (!TYPE_UNSIGNED (type))
3669 type = build_nonstandard_integer_type (nprec, 1);
3670 tmp = build1 (NOP_EXPR, type, names[i]);
3672 if (minv != 0)
3674 tmp = build2 (PLUS_EXPR, type, tmp,
3675 wide_int_to_tree (type, -minv));
3676 maxv2 = maxv - minv;
3678 new_val = wide_int_to_tree (type, maxv2);
3680 if (dump_file)
3682 fprintf (dump_file, "Adding assert for ");
3683 print_generic_expr (dump_file, names[i]);
3684 fprintf (dump_file, " from ");
3685 print_generic_expr (dump_file, tmp);
3686 fprintf (dump_file, "\n");
3689 add_assert_info (asserts, names[i], tmp, LE_EXPR, new_val);
3696 /* OP is an operand of a truth value expression which is known to have
3697 a particular value. Register any asserts for OP and for any
3698 operands in OP's defining statement.
3700 If CODE is EQ_EXPR, then we want to register OP is zero (false),
3701 if CODE is NE_EXPR, then we want to register OP is nonzero (true). */
3703 static void
3704 register_edge_assert_for_1 (tree op, enum tree_code code,
3705 edge e, vec<assert_info> &asserts)
3707 gimple *op_def;
3708 tree val;
3709 enum tree_code rhs_code;
3711 /* We only care about SSA_NAMEs. */
3712 if (TREE_CODE (op) != SSA_NAME)
3713 return;
3715 /* We know that OP will have a zero or nonzero value. */
3716 val = build_int_cst (TREE_TYPE (op), 0);
3717 add_assert_info (asserts, op, op, code, val);
3719 /* Now look at how OP is set. If it's set from a comparison,
3720 a truth operation or some bit operations, then we may be able
3721 to register information about the operands of that assignment. */
3722 op_def = SSA_NAME_DEF_STMT (op);
3723 if (gimple_code (op_def) != GIMPLE_ASSIGN)
3724 return;
3726 rhs_code = gimple_assign_rhs_code (op_def);
3728 if (TREE_CODE_CLASS (rhs_code) == tcc_comparison)
3730 bool invert = (code == EQ_EXPR ? true : false);
3731 tree op0 = gimple_assign_rhs1 (op_def);
3732 tree op1 = gimple_assign_rhs2 (op_def);
3734 if (TREE_CODE (op0) == SSA_NAME)
3735 register_edge_assert_for_2 (op0, e, rhs_code, op0, op1, invert, asserts);
3736 if (TREE_CODE (op1) == SSA_NAME)
3737 register_edge_assert_for_2 (op1, e, rhs_code, op0, op1, invert, asserts);
3739 else if ((code == NE_EXPR
3740 && gimple_assign_rhs_code (op_def) == BIT_AND_EXPR)
3741 || (code == EQ_EXPR
3742 && gimple_assign_rhs_code (op_def) == BIT_IOR_EXPR))
3744 /* Recurse on each operand. */
3745 tree op0 = gimple_assign_rhs1 (op_def);
3746 tree op1 = gimple_assign_rhs2 (op_def);
3747 if (TREE_CODE (op0) == SSA_NAME
3748 && has_single_use (op0))
3749 register_edge_assert_for_1 (op0, code, e, asserts);
3750 if (TREE_CODE (op1) == SSA_NAME
3751 && has_single_use (op1))
3752 register_edge_assert_for_1 (op1, code, e, asserts);
3754 else if (gimple_assign_rhs_code (op_def) == BIT_NOT_EXPR
3755 && TYPE_PRECISION (TREE_TYPE (gimple_assign_lhs (op_def))) == 1)
3757 /* Recurse, flipping CODE. */
3758 code = invert_tree_comparison (code, false);
3759 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
3761 else if (gimple_assign_rhs_code (op_def) == SSA_NAME)
3763 /* Recurse through the copy. */
3764 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
3766 else if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (op_def)))
3768 /* Recurse through the type conversion, unless it is a narrowing
3769 conversion or conversion from non-integral type. */
3770 tree rhs = gimple_assign_rhs1 (op_def);
3771 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs))
3772 && (TYPE_PRECISION (TREE_TYPE (rhs))
3773 <= TYPE_PRECISION (TREE_TYPE (op))))
3774 register_edge_assert_for_1 (rhs, code, e, asserts);
3778 /* Check if comparison
3779 NAME COND_OP INTEGER_CST
3780 has a form of
3781 (X & 11...100..0) COND_OP XX...X00...0
3782 Such comparison can yield assertions like
3783 X >= XX...X00...0
3784 X <= XX...X11...1
3785 in case of COND_OP being EQ_EXPR or
3786 X < XX...X00...0
3787 X > XX...X11...1
3788 in case of NE_EXPR. */
3790 static bool
3791 is_masked_range_test (tree name, tree valt, enum tree_code cond_code,
3792 tree *new_name, tree *low, enum tree_code *low_code,
3793 tree *high, enum tree_code *high_code)
3795 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3797 if (!is_gimple_assign (def_stmt)
3798 || gimple_assign_rhs_code (def_stmt) != BIT_AND_EXPR)
3799 return false;
3801 tree t = gimple_assign_rhs1 (def_stmt);
3802 tree maskt = gimple_assign_rhs2 (def_stmt);
3803 if (TREE_CODE (t) != SSA_NAME || TREE_CODE (maskt) != INTEGER_CST)
3804 return false;
3806 wi::tree_to_wide_ref mask = wi::to_wide (maskt);
3807 wide_int inv_mask = ~mask;
3808 /* Must have been removed by now so don't bother optimizing. */
3809 if (mask == 0 || inv_mask == 0)
3810 return false;
3812 /* Assume VALT is INTEGER_CST. */
3813 wi::tree_to_wide_ref val = wi::to_wide (valt);
3815 if ((inv_mask & (inv_mask + 1)) != 0
3816 || (val & mask) != val)
3817 return false;
3819 bool is_range = cond_code == EQ_EXPR;
3821 tree type = TREE_TYPE (t);
3822 wide_int min = wi::min_value (type),
3823 max = wi::max_value (type);
3825 if (is_range)
3827 *low_code = val == min ? ERROR_MARK : GE_EXPR;
3828 *high_code = val == max ? ERROR_MARK : LE_EXPR;
3830 else
3832 /* We can still generate assertion if one of alternatives
3833 is known to always be false. */
3834 if (val == min)
3836 *low_code = (enum tree_code) 0;
3837 *high_code = GT_EXPR;
3839 else if ((val | inv_mask) == max)
3841 *low_code = LT_EXPR;
3842 *high_code = (enum tree_code) 0;
3844 else
3845 return false;
3848 *new_name = t;
3849 *low = wide_int_to_tree (type, val);
3850 *high = wide_int_to_tree (type, val | inv_mask);
3852 return true;
3855 /* Try to register an edge assertion for SSA name NAME on edge E for
3856 the condition COND contributing to the conditional jump pointed to by
3857 SI. */
3859 void
3860 register_edge_assert_for (tree name, edge e,
3861 enum tree_code cond_code, tree cond_op0,
3862 tree cond_op1, vec<assert_info> &asserts)
3864 tree val;
3865 enum tree_code comp_code;
3866 bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
3868 /* Do not attempt to infer anything in names that flow through
3869 abnormal edges. */
3870 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
3871 return;
3873 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
3874 cond_op0, cond_op1,
3875 is_else_edge,
3876 &comp_code, &val))
3877 return;
3879 /* Register ASSERT_EXPRs for name. */
3880 register_edge_assert_for_2 (name, e, cond_code, cond_op0,
3881 cond_op1, is_else_edge, asserts);
3884 /* If COND is effectively an equality test of an SSA_NAME against
3885 the value zero or one, then we may be able to assert values
3886 for SSA_NAMEs which flow into COND. */
3888 /* In the case of NAME == 1 or NAME != 0, for BIT_AND_EXPR defining
3889 statement of NAME we can assert both operands of the BIT_AND_EXPR
3890 have nonzero value. */
3891 if (((comp_code == EQ_EXPR && integer_onep (val))
3892 || (comp_code == NE_EXPR && integer_zerop (val))))
3894 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3896 if (is_gimple_assign (def_stmt)
3897 && gimple_assign_rhs_code (def_stmt) == BIT_AND_EXPR)
3899 tree op0 = gimple_assign_rhs1 (def_stmt);
3900 tree op1 = gimple_assign_rhs2 (def_stmt);
3901 register_edge_assert_for_1 (op0, NE_EXPR, e, asserts);
3902 register_edge_assert_for_1 (op1, NE_EXPR, e, asserts);
3906 /* In the case of NAME == 0 or NAME != 1, for BIT_IOR_EXPR defining
3907 statement of NAME we can assert both operands of the BIT_IOR_EXPR
3908 have zero value. */
3909 if (((comp_code == EQ_EXPR && integer_zerop (val))
3910 || (comp_code == NE_EXPR && integer_onep (val))))
3912 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3914 /* For BIT_IOR_EXPR only if NAME == 0 both operands have
3915 necessarily zero value, or if type-precision is one. */
3916 if (is_gimple_assign (def_stmt)
3917 && (gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR
3918 && (TYPE_PRECISION (TREE_TYPE (name)) == 1
3919 || comp_code == EQ_EXPR)))
3921 tree op0 = gimple_assign_rhs1 (def_stmt);
3922 tree op1 = gimple_assign_rhs2 (def_stmt);
3923 register_edge_assert_for_1 (op0, EQ_EXPR, e, asserts);
3924 register_edge_assert_for_1 (op1, EQ_EXPR, e, asserts);
3928 /* Sometimes we can infer ranges from (NAME & MASK) == VALUE. */
3929 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
3930 && TREE_CODE (val) == INTEGER_CST)
3932 enum tree_code low_code, high_code;
3933 tree low, high;
3934 if (is_masked_range_test (name, val, comp_code, &name, &low,
3935 &low_code, &high, &high_code))
3937 if (low_code != ERROR_MARK)
3938 register_edge_assert_for_2 (name, e, low_code, name,
3939 low, /*invert*/false, asserts);
3940 if (high_code != ERROR_MARK)
3941 register_edge_assert_for_2 (name, e, high_code, name,
3942 high, /*invert*/false, asserts);
3947 /* Finish found ASSERTS for E and register them at GSI. */
3949 static void
3950 finish_register_edge_assert_for (edge e, gimple_stmt_iterator gsi,
3951 vec<assert_info> &asserts)
3953 for (unsigned i = 0; i < asserts.length (); ++i)
3954 /* Only register an ASSERT_EXPR if NAME was found in the sub-graph
3955 reachable from E. */
3956 if (live_on_edge (e, asserts[i].name))
3957 register_new_assert_for (asserts[i].name, asserts[i].expr,
3958 asserts[i].comp_code, asserts[i].val,
3959 NULL, e, gsi);
3964 /* Determine whether the outgoing edges of BB should receive an
3965 ASSERT_EXPR for each of the operands of BB's LAST statement.
3966 The last statement of BB must be a COND_EXPR.
3968 If any of the sub-graphs rooted at BB have an interesting use of
3969 the predicate operands, an assert location node is added to the
3970 list of assertions for the corresponding operands. */
3972 static void
3973 find_conditional_asserts (basic_block bb, gcond *last)
3975 gimple_stmt_iterator bsi;
3976 tree op;
3977 edge_iterator ei;
3978 edge e;
3979 ssa_op_iter iter;
3981 bsi = gsi_for_stmt (last);
3983 /* Look for uses of the operands in each of the sub-graphs
3984 rooted at BB. We need to check each of the outgoing edges
3985 separately, so that we know what kind of ASSERT_EXPR to
3986 insert. */
3987 FOR_EACH_EDGE (e, ei, bb->succs)
3989 if (e->dest == bb)
3990 continue;
3992 /* Register the necessary assertions for each operand in the
3993 conditional predicate. */
3994 auto_vec<assert_info, 8> asserts;
3995 FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
3996 register_edge_assert_for (op, e,
3997 gimple_cond_code (last),
3998 gimple_cond_lhs (last),
3999 gimple_cond_rhs (last), asserts);
4000 finish_register_edge_assert_for (e, bsi, asserts);
4004 struct case_info
4006 tree expr;
4007 basic_block bb;
4010 /* Compare two case labels sorting first by the destination bb index
4011 and then by the case value. */
4013 static int
4014 compare_case_labels (const void *p1, const void *p2)
4016 const struct case_info *ci1 = (const struct case_info *) p1;
4017 const struct case_info *ci2 = (const struct case_info *) p2;
4018 int idx1 = ci1->bb->index;
4019 int idx2 = ci2->bb->index;
4021 if (idx1 < idx2)
4022 return -1;
4023 else if (idx1 == idx2)
4025 /* Make sure the default label is first in a group. */
4026 if (!CASE_LOW (ci1->expr))
4027 return -1;
4028 else if (!CASE_LOW (ci2->expr))
4029 return 1;
4030 else
4031 return tree_int_cst_compare (CASE_LOW (ci1->expr),
4032 CASE_LOW (ci2->expr));
4034 else
4035 return 1;
4038 /* Determine whether the outgoing edges of BB should receive an
4039 ASSERT_EXPR for each of the operands of BB's LAST statement.
4040 The last statement of BB must be a SWITCH_EXPR.
4042 If any of the sub-graphs rooted at BB have an interesting use of
4043 the predicate operands, an assert location node is added to the
4044 list of assertions for the corresponding operands. */
4046 static void
4047 find_switch_asserts (basic_block bb, gswitch *last)
4049 gimple_stmt_iterator bsi;
4050 tree op;
4051 edge e;
4052 struct case_info *ci;
4053 size_t n = gimple_switch_num_labels (last);
4054 #if GCC_VERSION >= 4000
4055 unsigned int idx;
4056 #else
4057 /* Work around GCC 3.4 bug (PR 37086). */
4058 volatile unsigned int idx;
4059 #endif
4061 bsi = gsi_for_stmt (last);
4062 op = gimple_switch_index (last);
4063 if (TREE_CODE (op) != SSA_NAME)
4064 return;
4066 /* Build a vector of case labels sorted by destination label. */
4067 ci = XNEWVEC (struct case_info, n);
4068 for (idx = 0; idx < n; ++idx)
4070 ci[idx].expr = gimple_switch_label (last, idx);
4071 ci[idx].bb = label_to_block (CASE_LABEL (ci[idx].expr));
4073 edge default_edge = find_edge (bb, ci[0].bb);
4074 qsort (ci, n, sizeof (struct case_info), compare_case_labels);
4076 for (idx = 0; idx < n; ++idx)
4078 tree min, max;
4079 tree cl = ci[idx].expr;
4080 basic_block cbb = ci[idx].bb;
4082 min = CASE_LOW (cl);
4083 max = CASE_HIGH (cl);
4085 /* If there are multiple case labels with the same destination
4086 we need to combine them to a single value range for the edge. */
4087 if (idx + 1 < n && cbb == ci[idx + 1].bb)
4089 /* Skip labels until the last of the group. */
4090 do {
4091 ++idx;
4092 } while (idx < n && cbb == ci[idx].bb);
4093 --idx;
4095 /* Pick up the maximum of the case label range. */
4096 if (CASE_HIGH (ci[idx].expr))
4097 max = CASE_HIGH (ci[idx].expr);
4098 else
4099 max = CASE_LOW (ci[idx].expr);
4102 /* Can't extract a useful assertion out of a range that includes the
4103 default label. */
4104 if (min == NULL_TREE)
4105 continue;
4107 /* Find the edge to register the assert expr on. */
4108 e = find_edge (bb, cbb);
4110 /* Register the necessary assertions for the operand in the
4111 SWITCH_EXPR. */
4112 auto_vec<assert_info, 8> asserts;
4113 register_edge_assert_for (op, e,
4114 max ? GE_EXPR : EQ_EXPR,
4115 op, fold_convert (TREE_TYPE (op), min),
4116 asserts);
4117 if (max)
4118 register_edge_assert_for (op, e, LE_EXPR, op,
4119 fold_convert (TREE_TYPE (op), max),
4120 asserts);
4121 finish_register_edge_assert_for (e, bsi, asserts);
4124 XDELETEVEC (ci);
4126 if (!live_on_edge (default_edge, op))
4127 return;
4129 /* Now register along the default label assertions that correspond to the
4130 anti-range of each label. */
4131 int insertion_limit = PARAM_VALUE (PARAM_MAX_VRP_SWITCH_ASSERTIONS);
4132 if (insertion_limit == 0)
4133 return;
4135 /* We can't do this if the default case shares a label with another case. */
4136 tree default_cl = gimple_switch_default_label (last);
4137 for (idx = 1; idx < n; idx++)
4139 tree min, max;
4140 tree cl = gimple_switch_label (last, idx);
4141 if (CASE_LABEL (cl) == CASE_LABEL (default_cl))
4142 continue;
4144 min = CASE_LOW (cl);
4145 max = CASE_HIGH (cl);
4147 /* Combine contiguous case ranges to reduce the number of assertions
4148 to insert. */
4149 for (idx = idx + 1; idx < n; idx++)
4151 tree next_min, next_max;
4152 tree next_cl = gimple_switch_label (last, idx);
4153 if (CASE_LABEL (next_cl) == CASE_LABEL (default_cl))
4154 break;
4156 next_min = CASE_LOW (next_cl);
4157 next_max = CASE_HIGH (next_cl);
4159 wide_int difference = (wi::to_wide (next_min)
4160 - wi::to_wide (max ? max : min));
4161 if (wi::eq_p (difference, 1))
4162 max = next_max ? next_max : next_min;
4163 else
4164 break;
4166 idx--;
4168 if (max == NULL_TREE)
4170 /* Register the assertion OP != MIN. */
4171 auto_vec<assert_info, 8> asserts;
4172 min = fold_convert (TREE_TYPE (op), min);
4173 register_edge_assert_for (op, default_edge, NE_EXPR, op, min,
4174 asserts);
4175 finish_register_edge_assert_for (default_edge, bsi, asserts);
4177 else
4179 /* Register the assertion (unsigned)OP - MIN > (MAX - MIN),
4180 which will give OP the anti-range ~[MIN,MAX]. */
4181 tree uop = fold_convert (unsigned_type_for (TREE_TYPE (op)), op);
4182 min = fold_convert (TREE_TYPE (uop), min);
4183 max = fold_convert (TREE_TYPE (uop), max);
4185 tree lhs = fold_build2 (MINUS_EXPR, TREE_TYPE (uop), uop, min);
4186 tree rhs = int_const_binop (MINUS_EXPR, max, min);
4187 register_new_assert_for (op, lhs, GT_EXPR, rhs,
4188 NULL, default_edge, bsi);
4191 if (--insertion_limit == 0)
4192 break;
4197 /* Traverse all the statements in block BB looking for statements that
4198 may generate useful assertions for the SSA names in their operand.
4199 If a statement produces a useful assertion A for name N_i, then the
4200 list of assertions already generated for N_i is scanned to
4201 determine if A is actually needed.
4203 If N_i already had the assertion A at a location dominating the
4204 current location, then nothing needs to be done. Otherwise, the
4205 new location for A is recorded instead.
4207 1- For every statement S in BB, all the variables used by S are
4208 added to bitmap FOUND_IN_SUBGRAPH.
4210 2- If statement S uses an operand N in a way that exposes a known
4211 value range for N, then if N was not already generated by an
4212 ASSERT_EXPR, create a new assert location for N. For instance,
4213 if N is a pointer and the statement dereferences it, we can
4214 assume that N is not NULL.
4216 3- COND_EXPRs are a special case of #2. We can derive range
4217 information from the predicate but need to insert different
4218 ASSERT_EXPRs for each of the sub-graphs rooted at the
4219 conditional block. If the last statement of BB is a conditional
4220 expression of the form 'X op Y', then
4222 a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
4224 b) If the conditional is the only entry point to the sub-graph
4225 corresponding to the THEN_CLAUSE, recurse into it. On
4226 return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
4227 an ASSERT_EXPR is added for the corresponding variable.
4229 c) Repeat step (b) on the ELSE_CLAUSE.
4231 d) Mark X and Y in FOUND_IN_SUBGRAPH.
4233 For instance,
4235 if (a == 9)
4236 b = a;
4237 else
4238 b = c + 1;
4240 In this case, an assertion on the THEN clause is useful to
4241 determine that 'a' is always 9 on that edge. However, an assertion
4242 on the ELSE clause would be unnecessary.
4244 4- If BB does not end in a conditional expression, then we recurse
4245 into BB's dominator children.
4247 At the end of the recursive traversal, every SSA name will have a
4248 list of locations where ASSERT_EXPRs should be added. When a new
4249 location for name N is found, it is registered by calling
4250 register_new_assert_for. That function keeps track of all the
4251 registered assertions to prevent adding unnecessary assertions.
4252 For instance, if a pointer P_4 is dereferenced more than once in a
4253 dominator tree, only the location dominating all the dereference of
4254 P_4 will receive an ASSERT_EXPR. */
4256 static void
4257 find_assert_locations_1 (basic_block bb, sbitmap live)
4259 gimple *last;
4261 last = last_stmt (bb);
4263 /* If BB's last statement is a conditional statement involving integer
4264 operands, determine if we need to add ASSERT_EXPRs. */
4265 if (last
4266 && gimple_code (last) == GIMPLE_COND
4267 && !fp_predicate (last)
4268 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
4269 find_conditional_asserts (bb, as_a <gcond *> (last));
4271 /* If BB's last statement is a switch statement involving integer
4272 operands, determine if we need to add ASSERT_EXPRs. */
4273 if (last
4274 && gimple_code (last) == GIMPLE_SWITCH
4275 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
4276 find_switch_asserts (bb, as_a <gswitch *> (last));
4278 /* Traverse all the statements in BB marking used names and looking
4279 for statements that may infer assertions for their used operands. */
4280 for (gimple_stmt_iterator si = gsi_last_bb (bb); !gsi_end_p (si);
4281 gsi_prev (&si))
4283 gimple *stmt;
4284 tree op;
4285 ssa_op_iter i;
4287 stmt = gsi_stmt (si);
4289 if (is_gimple_debug (stmt))
4290 continue;
4292 /* See if we can derive an assertion for any of STMT's operands. */
4293 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
4295 tree value;
4296 enum tree_code comp_code;
4298 /* If op is not live beyond this stmt, do not bother to insert
4299 asserts for it. */
4300 if (!bitmap_bit_p (live, SSA_NAME_VERSION (op)))
4301 continue;
4303 /* If OP is used in such a way that we can infer a value
4304 range for it, and we don't find a previous assertion for
4305 it, create a new assertion location node for OP. */
4306 if (infer_value_range (stmt, op, &comp_code, &value))
4308 /* If we are able to infer a nonzero value range for OP,
4309 then walk backwards through the use-def chain to see if OP
4310 was set via a typecast.
4312 If so, then we can also infer a nonzero value range
4313 for the operand of the NOP_EXPR. */
4314 if (comp_code == NE_EXPR && integer_zerop (value))
4316 tree t = op;
4317 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
4319 while (is_gimple_assign (def_stmt)
4320 && CONVERT_EXPR_CODE_P
4321 (gimple_assign_rhs_code (def_stmt))
4322 && TREE_CODE
4323 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
4324 && POINTER_TYPE_P
4325 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
4327 t = gimple_assign_rhs1 (def_stmt);
4328 def_stmt = SSA_NAME_DEF_STMT (t);
4330 /* Note we want to register the assert for the
4331 operand of the NOP_EXPR after SI, not after the
4332 conversion. */
4333 if (bitmap_bit_p (live, SSA_NAME_VERSION (t)))
4334 register_new_assert_for (t, t, comp_code, value,
4335 bb, NULL, si);
4339 register_new_assert_for (op, op, comp_code, value, bb, NULL, si);
4343 /* Update live. */
4344 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
4345 bitmap_set_bit (live, SSA_NAME_VERSION (op));
4346 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_DEF)
4347 bitmap_clear_bit (live, SSA_NAME_VERSION (op));
4350 /* Traverse all PHI nodes in BB, updating live. */
4351 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
4352 gsi_next (&si))
4354 use_operand_p arg_p;
4355 ssa_op_iter i;
4356 gphi *phi = si.phi ();
4357 tree res = gimple_phi_result (phi);
4359 if (virtual_operand_p (res))
4360 continue;
4362 FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
4364 tree arg = USE_FROM_PTR (arg_p);
4365 if (TREE_CODE (arg) == SSA_NAME)
4366 bitmap_set_bit (live, SSA_NAME_VERSION (arg));
4369 bitmap_clear_bit (live, SSA_NAME_VERSION (res));
4373 /* Do an RPO walk over the function computing SSA name liveness
4374 on-the-fly and deciding on assert expressions to insert. */
4376 static void
4377 find_assert_locations (void)
4379 int *rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
4380 int *bb_rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
4381 int *last_rpo = XCNEWVEC (int, last_basic_block_for_fn (cfun));
4382 int rpo_cnt, i;
4384 live = XCNEWVEC (sbitmap, last_basic_block_for_fn (cfun));
4385 rpo_cnt = pre_and_rev_post_order_compute (NULL, rpo, false);
4386 for (i = 0; i < rpo_cnt; ++i)
4387 bb_rpo[rpo[i]] = i;
4389 /* Pre-seed loop latch liveness from loop header PHI nodes. Due to
4390 the order we compute liveness and insert asserts we otherwise
4391 fail to insert asserts into the loop latch. */
4392 loop_p loop;
4393 FOR_EACH_LOOP (loop, 0)
4395 i = loop->latch->index;
4396 unsigned int j = single_succ_edge (loop->latch)->dest_idx;
4397 for (gphi_iterator gsi = gsi_start_phis (loop->header);
4398 !gsi_end_p (gsi); gsi_next (&gsi))
4400 gphi *phi = gsi.phi ();
4401 if (virtual_operand_p (gimple_phi_result (phi)))
4402 continue;
4403 tree arg = gimple_phi_arg_def (phi, j);
4404 if (TREE_CODE (arg) == SSA_NAME)
4406 if (live[i] == NULL)
4408 live[i] = sbitmap_alloc (num_ssa_names);
4409 bitmap_clear (live[i]);
4411 bitmap_set_bit (live[i], SSA_NAME_VERSION (arg));
4416 for (i = rpo_cnt - 1; i >= 0; --i)
4418 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, rpo[i]);
4419 edge e;
4420 edge_iterator ei;
4422 if (!live[rpo[i]])
4424 live[rpo[i]] = sbitmap_alloc (num_ssa_names);
4425 bitmap_clear (live[rpo[i]]);
4428 /* Process BB and update the live information with uses in
4429 this block. */
4430 find_assert_locations_1 (bb, live[rpo[i]]);
4432 /* Merge liveness into the predecessor blocks and free it. */
4433 if (!bitmap_empty_p (live[rpo[i]]))
4435 int pred_rpo = i;
4436 FOR_EACH_EDGE (e, ei, bb->preds)
4438 int pred = e->src->index;
4439 if ((e->flags & EDGE_DFS_BACK) || pred == ENTRY_BLOCK)
4440 continue;
4442 if (!live[pred])
4444 live[pred] = sbitmap_alloc (num_ssa_names);
4445 bitmap_clear (live[pred]);
4447 bitmap_ior (live[pred], live[pred], live[rpo[i]]);
4449 if (bb_rpo[pred] < pred_rpo)
4450 pred_rpo = bb_rpo[pred];
4453 /* Record the RPO number of the last visited block that needs
4454 live information from this block. */
4455 last_rpo[rpo[i]] = pred_rpo;
4457 else
4459 sbitmap_free (live[rpo[i]]);
4460 live[rpo[i]] = NULL;
4463 /* We can free all successors live bitmaps if all their
4464 predecessors have been visited already. */
4465 FOR_EACH_EDGE (e, ei, bb->succs)
4466 if (last_rpo[e->dest->index] == i
4467 && live[e->dest->index])
4469 sbitmap_free (live[e->dest->index]);
4470 live[e->dest->index] = NULL;
4474 XDELETEVEC (rpo);
4475 XDELETEVEC (bb_rpo);
4476 XDELETEVEC (last_rpo);
4477 for (i = 0; i < last_basic_block_for_fn (cfun); ++i)
4478 if (live[i])
4479 sbitmap_free (live[i]);
4480 XDELETEVEC (live);
4483 /* Create an ASSERT_EXPR for NAME and insert it in the location
4484 indicated by LOC. Return true if we made any edge insertions. */
4486 static bool
4487 process_assert_insertions_for (tree name, assert_locus *loc)
4489 /* Build the comparison expression NAME_i COMP_CODE VAL. */
4490 gimple *stmt;
4491 tree cond;
4492 gimple *assert_stmt;
4493 edge_iterator ei;
4494 edge e;
4496 /* If we have X <=> X do not insert an assert expr for that. */
4497 if (loc->expr == loc->val)
4498 return false;
4500 cond = build2 (loc->comp_code, boolean_type_node, loc->expr, loc->val);
4501 assert_stmt = build_assert_expr_for (cond, name);
4502 if (loc->e)
4504 /* We have been asked to insert the assertion on an edge. This
4505 is used only by COND_EXPR and SWITCH_EXPR assertions. */
4506 gcc_checking_assert (gimple_code (gsi_stmt (loc->si)) == GIMPLE_COND
4507 || (gimple_code (gsi_stmt (loc->si))
4508 == GIMPLE_SWITCH));
4510 gsi_insert_on_edge (loc->e, assert_stmt);
4511 return true;
4514 /* If the stmt iterator points at the end then this is an insertion
4515 at the beginning of a block. */
4516 if (gsi_end_p (loc->si))
4518 gimple_stmt_iterator si = gsi_after_labels (loc->bb);
4519 gsi_insert_before (&si, assert_stmt, GSI_SAME_STMT);
4520 return false;
4523 /* Otherwise, we can insert right after LOC->SI iff the
4524 statement must not be the last statement in the block. */
4525 stmt = gsi_stmt (loc->si);
4526 if (!stmt_ends_bb_p (stmt))
4528 gsi_insert_after (&loc->si, assert_stmt, GSI_SAME_STMT);
4529 return false;
4532 /* If STMT must be the last statement in BB, we can only insert new
4533 assertions on the non-abnormal edge out of BB. Note that since
4534 STMT is not control flow, there may only be one non-abnormal/eh edge
4535 out of BB. */
4536 FOR_EACH_EDGE (e, ei, loc->bb->succs)
4537 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
4539 gsi_insert_on_edge (e, assert_stmt);
4540 return true;
4543 gcc_unreachable ();
4546 /* Qsort helper for sorting assert locations. If stable is true, don't
4547 use iterative_hash_expr because it can be unstable for -fcompare-debug,
4548 on the other side some pointers might be NULL. */
4550 template <bool stable>
4551 static int
4552 compare_assert_loc (const void *pa, const void *pb)
4554 assert_locus * const a = *(assert_locus * const *)pa;
4555 assert_locus * const b = *(assert_locus * const *)pb;
4557 /* If stable, some asserts might be optimized away already, sort
4558 them last. */
4559 if (stable)
4561 if (a == NULL)
4562 return b != NULL;
4563 else if (b == NULL)
4564 return -1;
4567 if (a->e == NULL && b->e != NULL)
4568 return 1;
4569 else if (a->e != NULL && b->e == NULL)
4570 return -1;
4572 /* After the above checks, we know that (a->e == NULL) == (b->e == NULL),
4573 no need to test both a->e and b->e. */
4575 /* Sort after destination index. */
4576 if (a->e == NULL)
4578 else if (a->e->dest->index > b->e->dest->index)
4579 return 1;
4580 else if (a->e->dest->index < b->e->dest->index)
4581 return -1;
4583 /* Sort after comp_code. */
4584 if (a->comp_code > b->comp_code)
4585 return 1;
4586 else if (a->comp_code < b->comp_code)
4587 return -1;
4589 hashval_t ha, hb;
4591 /* E.g. if a->val is ADDR_EXPR of a VAR_DECL, iterative_hash_expr
4592 uses DECL_UID of the VAR_DECL, so sorting might differ between
4593 -g and -g0. When doing the removal of redundant assert exprs
4594 and commonization to successors, this does not matter, but for
4595 the final sort needs to be stable. */
4596 if (stable)
4598 ha = 0;
4599 hb = 0;
4601 else
4603 ha = iterative_hash_expr (a->expr, iterative_hash_expr (a->val, 0));
4604 hb = iterative_hash_expr (b->expr, iterative_hash_expr (b->val, 0));
4607 /* Break the tie using hashing and source/bb index. */
4608 if (ha == hb)
4609 return (a->e != NULL
4610 ? a->e->src->index - b->e->src->index
4611 : a->bb->index - b->bb->index);
4612 return ha > hb ? 1 : -1;
4615 /* Process all the insertions registered for every name N_i registered
4616 in NEED_ASSERT_FOR. The list of assertions to be inserted are
4617 found in ASSERTS_FOR[i]. */
4619 static void
4620 process_assert_insertions (void)
4622 unsigned i;
4623 bitmap_iterator bi;
4624 bool update_edges_p = false;
4625 int num_asserts = 0;
4627 if (dump_file && (dump_flags & TDF_DETAILS))
4628 dump_all_asserts (dump_file);
4630 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
4632 assert_locus *loc = asserts_for[i];
4633 gcc_assert (loc);
4635 auto_vec<assert_locus *, 16> asserts;
4636 for (; loc; loc = loc->next)
4637 asserts.safe_push (loc);
4638 asserts.qsort (compare_assert_loc<false>);
4640 /* Push down common asserts to successors and remove redundant ones. */
4641 unsigned ecnt = 0;
4642 assert_locus *common = NULL;
4643 unsigned commonj = 0;
4644 for (unsigned j = 0; j < asserts.length (); ++j)
4646 loc = asserts[j];
4647 if (! loc->e)
4648 common = NULL;
4649 else if (! common
4650 || loc->e->dest != common->e->dest
4651 || loc->comp_code != common->comp_code
4652 || ! operand_equal_p (loc->val, common->val, 0)
4653 || ! operand_equal_p (loc->expr, common->expr, 0))
4655 commonj = j;
4656 common = loc;
4657 ecnt = 1;
4659 else if (loc->e == asserts[j-1]->e)
4661 /* Remove duplicate asserts. */
4662 if (commonj == j - 1)
4664 commonj = j;
4665 common = loc;
4667 free (asserts[j-1]);
4668 asserts[j-1] = NULL;
4670 else
4672 ecnt++;
4673 if (EDGE_COUNT (common->e->dest->preds) == ecnt)
4675 /* We have the same assertion on all incoming edges of a BB.
4676 Insert it at the beginning of that block. */
4677 loc->bb = loc->e->dest;
4678 loc->e = NULL;
4679 loc->si = gsi_none ();
4680 common = NULL;
4681 /* Clear asserts commoned. */
4682 for (; commonj != j; ++commonj)
4683 if (asserts[commonj])
4685 free (asserts[commonj]);
4686 asserts[commonj] = NULL;
4692 /* The asserts vector sorting above might be unstable for
4693 -fcompare-debug, sort again to ensure a stable sort. */
4694 asserts.qsort (compare_assert_loc<true>);
4695 for (unsigned j = 0; j < asserts.length (); ++j)
4697 loc = asserts[j];
4698 if (! loc)
4699 break;
4700 update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
4701 num_asserts++;
4702 free (loc);
4706 if (update_edges_p)
4707 gsi_commit_edge_inserts ();
4709 statistics_counter_event (cfun, "Number of ASSERT_EXPR expressions inserted",
4710 num_asserts);
4714 /* Traverse the flowgraph looking for conditional jumps to insert range
4715 expressions. These range expressions are meant to provide information
4716 to optimizations that need to reason in terms of value ranges. They
4717 will not be expanded into RTL. For instance, given:
4719 x = ...
4720 y = ...
4721 if (x < y)
4722 y = x - 2;
4723 else
4724 x = y + 3;
4726 this pass will transform the code into:
4728 x = ...
4729 y = ...
4730 if (x < y)
4732 x = ASSERT_EXPR <x, x < y>
4733 y = x - 2
4735 else
4737 y = ASSERT_EXPR <y, x >= y>
4738 x = y + 3
4741 The idea is that once copy and constant propagation have run, other
4742 optimizations will be able to determine what ranges of values can 'x'
4743 take in different paths of the code, simply by checking the reaching
4744 definition of 'x'. */
4746 static void
4747 insert_range_assertions (void)
4749 need_assert_for = BITMAP_ALLOC (NULL);
4750 asserts_for = XCNEWVEC (assert_locus *, num_ssa_names);
4752 calculate_dominance_info (CDI_DOMINATORS);
4754 find_assert_locations ();
4755 if (!bitmap_empty_p (need_assert_for))
4757 process_assert_insertions ();
4758 update_ssa (TODO_update_ssa_no_phi);
4761 if (dump_file && (dump_flags & TDF_DETAILS))
4763 fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
4764 dump_function_to_file (current_function_decl, dump_file, dump_flags);
4767 free (asserts_for);
4768 BITMAP_FREE (need_assert_for);
4771 class vrp_prop : public ssa_propagation_engine
4773 public:
4774 enum ssa_prop_result visit_stmt (gimple *, edge *, tree *) FINAL OVERRIDE;
4775 enum ssa_prop_result visit_phi (gphi *) FINAL OVERRIDE;
4777 void vrp_initialize (void);
4778 void vrp_finalize (bool);
4779 void check_all_array_refs (void);
4780 void check_array_ref (location_t, tree, bool);
4781 void search_for_addr_array (tree, location_t);
4783 class vr_values vr_values;
4784 /* Temporary delegator to minimize code churn. */
4785 value_range *get_value_range (const_tree op)
4786 { return vr_values.get_value_range (op); }
4787 void set_defs_to_varying (gimple *stmt)
4788 { return vr_values.set_defs_to_varying (stmt); }
4789 void extract_range_from_stmt (gimple *stmt, edge *taken_edge_p,
4790 tree *output_p, value_range *vr)
4791 { vr_values.extract_range_from_stmt (stmt, taken_edge_p, output_p, vr); }
4792 bool update_value_range (const_tree op, value_range *vr)
4793 { return vr_values.update_value_range (op, vr); }
4794 void extract_range_basic (value_range *vr, gimple *stmt)
4795 { vr_values.extract_range_basic (vr, stmt); }
4796 void extract_range_from_phi_node (gphi *phi, value_range *vr)
4797 { vr_values.extract_range_from_phi_node (phi, vr); }
4799 /* Checks one ARRAY_REF in REF, located at LOCUS. Ignores flexible arrays
4800 and "struct" hacks. If VRP can determine that the
4801 array subscript is a constant, check if it is outside valid
4802 range. If the array subscript is a RANGE, warn if it is
4803 non-overlapping with valid range.
4804 IGNORE_OFF_BY_ONE is true if the ARRAY_REF is inside a ADDR_EXPR. */
4806 void
4807 vrp_prop::check_array_ref (location_t location, tree ref,
4808 bool ignore_off_by_one)
4810 value_range *vr = NULL;
4811 tree low_sub, up_sub;
4812 tree low_bound, up_bound, up_bound_p1;
4814 if (TREE_NO_WARNING (ref))
4815 return;
4817 low_sub = up_sub = TREE_OPERAND (ref, 1);
4818 up_bound = array_ref_up_bound (ref);
4820 if (!up_bound
4821 || TREE_CODE (up_bound) != INTEGER_CST
4822 || (warn_array_bounds < 2
4823 && array_at_struct_end_p (ref)))
4825 /* Accesses to trailing arrays via pointers may access storage
4826 beyond the types array bounds. For such arrays, or for flexible
4827 array members, as well as for other arrays of an unknown size,
4828 replace the upper bound with a more permissive one that assumes
4829 the size of the largest object is PTRDIFF_MAX. */
4830 tree eltsize = array_ref_element_size (ref);
4832 if (TREE_CODE (eltsize) != INTEGER_CST
4833 || integer_zerop (eltsize))
4835 up_bound = NULL_TREE;
4836 up_bound_p1 = NULL_TREE;
4838 else
4840 tree maxbound = TYPE_MAX_VALUE (ptrdiff_type_node);
4841 tree arg = TREE_OPERAND (ref, 0);
4842 poly_int64 off;
4844 if (get_addr_base_and_unit_offset (arg, &off) && known_gt (off, 0))
4845 maxbound = wide_int_to_tree (sizetype,
4846 wi::sub (wi::to_wide (maxbound),
4847 off));
4848 else
4849 maxbound = fold_convert (sizetype, maxbound);
4851 up_bound_p1 = int_const_binop (TRUNC_DIV_EXPR, maxbound, eltsize);
4853 up_bound = int_const_binop (MINUS_EXPR, up_bound_p1,
4854 build_int_cst (ptrdiff_type_node, 1));
4857 else
4858 up_bound_p1 = int_const_binop (PLUS_EXPR, up_bound,
4859 build_int_cst (TREE_TYPE (up_bound), 1));
4861 low_bound = array_ref_low_bound (ref);
4863 tree artype = TREE_TYPE (TREE_OPERAND (ref, 0));
4865 /* Empty array. */
4866 if (up_bound && tree_int_cst_equal (low_bound, up_bound_p1))
4868 warning_at (location, OPT_Warray_bounds,
4869 "array subscript %E is above array bounds of %qT",
4870 low_bound, artype);
4871 TREE_NO_WARNING (ref) = 1;
4874 if (TREE_CODE (low_sub) == SSA_NAME)
4876 vr = get_value_range (low_sub);
4877 if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
4879 low_sub = vr->type == VR_RANGE ? vr->max : vr->min;
4880 up_sub = vr->type == VR_RANGE ? vr->min : vr->max;
4884 if (vr && vr->type == VR_ANTI_RANGE)
4886 if (up_bound
4887 && TREE_CODE (up_sub) == INTEGER_CST
4888 && (ignore_off_by_one
4889 ? tree_int_cst_lt (up_bound, up_sub)
4890 : tree_int_cst_le (up_bound, up_sub))
4891 && TREE_CODE (low_sub) == INTEGER_CST
4892 && tree_int_cst_le (low_sub, low_bound))
4894 warning_at (location, OPT_Warray_bounds,
4895 "array subscript [%E, %E] is outside array bounds of %qT",
4896 low_sub, up_sub, artype);
4897 TREE_NO_WARNING (ref) = 1;
4900 else if (up_bound
4901 && TREE_CODE (up_sub) == INTEGER_CST
4902 && (ignore_off_by_one
4903 ? !tree_int_cst_le (up_sub, up_bound_p1)
4904 : !tree_int_cst_le (up_sub, up_bound)))
4906 if (dump_file && (dump_flags & TDF_DETAILS))
4908 fprintf (dump_file, "Array bound warning for ");
4909 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
4910 fprintf (dump_file, "\n");
4912 warning_at (location, OPT_Warray_bounds,
4913 "array subscript %E is above array bounds of %qT",
4914 up_sub, artype);
4915 TREE_NO_WARNING (ref) = 1;
4917 else if (TREE_CODE (low_sub) == INTEGER_CST
4918 && tree_int_cst_lt (low_sub, low_bound))
4920 if (dump_file && (dump_flags & TDF_DETAILS))
4922 fprintf (dump_file, "Array bound warning for ");
4923 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
4924 fprintf (dump_file, "\n");
4926 warning_at (location, OPT_Warray_bounds,
4927 "array subscript %E is below array bounds of %qT",
4928 low_sub, artype);
4929 TREE_NO_WARNING (ref) = 1;
4933 /* Searches if the expr T, located at LOCATION computes
4934 address of an ARRAY_REF, and call check_array_ref on it. */
4936 void
4937 vrp_prop::search_for_addr_array (tree t, location_t location)
4939 /* Check each ARRAY_REFs in the reference chain. */
4942 if (TREE_CODE (t) == ARRAY_REF)
4943 check_array_ref (location, t, true /*ignore_off_by_one*/);
4945 t = TREE_OPERAND (t, 0);
4947 while (handled_component_p (t));
4949 if (TREE_CODE (t) == MEM_REF
4950 && TREE_CODE (TREE_OPERAND (t, 0)) == ADDR_EXPR
4951 && !TREE_NO_WARNING (t))
4953 tree tem = TREE_OPERAND (TREE_OPERAND (t, 0), 0);
4954 tree low_bound, up_bound, el_sz;
4955 offset_int idx;
4956 if (TREE_CODE (TREE_TYPE (tem)) != ARRAY_TYPE
4957 || TREE_CODE (TREE_TYPE (TREE_TYPE (tem))) == ARRAY_TYPE
4958 || !TYPE_DOMAIN (TREE_TYPE (tem)))
4959 return;
4961 low_bound = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
4962 up_bound = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
4963 el_sz = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (tem)));
4964 if (!low_bound
4965 || TREE_CODE (low_bound) != INTEGER_CST
4966 || !up_bound
4967 || TREE_CODE (up_bound) != INTEGER_CST
4968 || !el_sz
4969 || TREE_CODE (el_sz) != INTEGER_CST)
4970 return;
4972 if (!mem_ref_offset (t).is_constant (&idx))
4973 return;
4975 idx = wi::sdiv_trunc (idx, wi::to_offset (el_sz));
4976 if (idx < 0)
4978 if (dump_file && (dump_flags & TDF_DETAILS))
4980 fprintf (dump_file, "Array bound warning for ");
4981 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
4982 fprintf (dump_file, "\n");
4984 warning_at (location, OPT_Warray_bounds,
4985 "array subscript %wi is below array bounds of %qT",
4986 idx.to_shwi (), TREE_TYPE (tem));
4987 TREE_NO_WARNING (t) = 1;
4989 else if (idx > (wi::to_offset (up_bound)
4990 - wi::to_offset (low_bound) + 1))
4992 if (dump_file && (dump_flags & TDF_DETAILS))
4994 fprintf (dump_file, "Array bound warning for ");
4995 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
4996 fprintf (dump_file, "\n");
4998 warning_at (location, OPT_Warray_bounds,
4999 "array subscript %wu is above array bounds of %qT",
5000 idx.to_uhwi (), TREE_TYPE (tem));
5001 TREE_NO_WARNING (t) = 1;
5006 /* walk_tree() callback that checks if *TP is
5007 an ARRAY_REF inside an ADDR_EXPR (in which an array
5008 subscript one outside the valid range is allowed). Call
5009 check_array_ref for each ARRAY_REF found. The location is
5010 passed in DATA. */
5012 static tree
5013 check_array_bounds (tree *tp, int *walk_subtree, void *data)
5015 tree t = *tp;
5016 struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
5017 location_t location;
5019 if (EXPR_HAS_LOCATION (t))
5020 location = EXPR_LOCATION (t);
5021 else
5022 location = gimple_location (wi->stmt);
5024 *walk_subtree = TRUE;
5026 vrp_prop *vrp_prop = (class vrp_prop *)wi->info;
5027 if (TREE_CODE (t) == ARRAY_REF)
5028 vrp_prop->check_array_ref (location, t, false /*ignore_off_by_one*/);
5030 else if (TREE_CODE (t) == ADDR_EXPR)
5032 vrp_prop->search_for_addr_array (t, location);
5033 *walk_subtree = FALSE;
5036 return NULL_TREE;
5039 /* A dom_walker subclass for use by vrp_prop::check_all_array_refs,
5040 to walk over all statements of all reachable BBs and call
5041 check_array_bounds on them. */
5043 class check_array_bounds_dom_walker : public dom_walker
5045 public:
5046 check_array_bounds_dom_walker (vrp_prop *prop)
5047 : dom_walker (CDI_DOMINATORS,
5048 /* Discover non-executable edges, preserving EDGE_EXECUTABLE
5049 flags, so that we can merge in information on
5050 non-executable edges from vrp_folder . */
5051 REACHABLE_BLOCKS_PRESERVING_FLAGS),
5052 m_prop (prop) {}
5053 ~check_array_bounds_dom_walker () {}
5055 edge before_dom_children (basic_block) FINAL OVERRIDE;
5057 private:
5058 vrp_prop *m_prop;
5061 /* Implementation of dom_walker::before_dom_children.
5063 Walk over all statements of BB and call check_array_bounds on them,
5064 and determine if there's a unique successor edge. */
5066 edge
5067 check_array_bounds_dom_walker::before_dom_children (basic_block bb)
5069 gimple_stmt_iterator si;
5070 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
5072 gimple *stmt = gsi_stmt (si);
5073 struct walk_stmt_info wi;
5074 if (!gimple_has_location (stmt)
5075 || is_gimple_debug (stmt))
5076 continue;
5078 memset (&wi, 0, sizeof (wi));
5080 wi.info = m_prop;
5082 walk_gimple_op (stmt, check_array_bounds, &wi);
5085 /* Determine if there's a unique successor edge, and if so, return
5086 that back to dom_walker, ensuring that we don't visit blocks that
5087 became unreachable during the VRP propagation
5088 (PR tree-optimization/83312). */
5089 return find_taken_edge (bb, NULL_TREE);
5092 /* Walk over all statements of all reachable BBs and call check_array_bounds
5093 on them. */
5095 void
5096 vrp_prop::check_all_array_refs ()
5098 check_array_bounds_dom_walker w (this);
5099 w.walk (ENTRY_BLOCK_PTR_FOR_FN (cfun));
5102 /* Return true if all imm uses of VAR are either in STMT, or
5103 feed (optionally through a chain of single imm uses) GIMPLE_COND
5104 in basic block COND_BB. */
5106 static bool
5107 all_imm_uses_in_stmt_or_feed_cond (tree var, gimple *stmt, basic_block cond_bb)
5109 use_operand_p use_p, use2_p;
5110 imm_use_iterator iter;
5112 FOR_EACH_IMM_USE_FAST (use_p, iter, var)
5113 if (USE_STMT (use_p) != stmt)
5115 gimple *use_stmt = USE_STMT (use_p), *use_stmt2;
5116 if (is_gimple_debug (use_stmt))
5117 continue;
5118 while (is_gimple_assign (use_stmt)
5119 && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
5120 && single_imm_use (gimple_assign_lhs (use_stmt),
5121 &use2_p, &use_stmt2))
5122 use_stmt = use_stmt2;
5123 if (gimple_code (use_stmt) != GIMPLE_COND
5124 || gimple_bb (use_stmt) != cond_bb)
5125 return false;
5127 return true;
5130 /* Handle
5131 _4 = x_3 & 31;
5132 if (_4 != 0)
5133 goto <bb 6>;
5134 else
5135 goto <bb 7>;
5136 <bb 6>:
5137 __builtin_unreachable ();
5138 <bb 7>:
5139 x_5 = ASSERT_EXPR <x_3, ...>;
5140 If x_3 has no other immediate uses (checked by caller),
5141 var is the x_3 var from ASSERT_EXPR, we can clear low 5 bits
5142 from the non-zero bitmask. */
5144 void
5145 maybe_set_nonzero_bits (edge e, tree var)
5147 basic_block cond_bb = e->src;
5148 gimple *stmt = last_stmt (cond_bb);
5149 tree cst;
5151 if (stmt == NULL
5152 || gimple_code (stmt) != GIMPLE_COND
5153 || gimple_cond_code (stmt) != ((e->flags & EDGE_TRUE_VALUE)
5154 ? EQ_EXPR : NE_EXPR)
5155 || TREE_CODE (gimple_cond_lhs (stmt)) != SSA_NAME
5156 || !integer_zerop (gimple_cond_rhs (stmt)))
5157 return;
5159 stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt));
5160 if (!is_gimple_assign (stmt)
5161 || gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
5162 || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
5163 return;
5164 if (gimple_assign_rhs1 (stmt) != var)
5166 gimple *stmt2;
5168 if (TREE_CODE (gimple_assign_rhs1 (stmt)) != SSA_NAME)
5169 return;
5170 stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
5171 if (!gimple_assign_cast_p (stmt2)
5172 || gimple_assign_rhs1 (stmt2) != var
5173 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt2))
5174 || (TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (stmt)))
5175 != TYPE_PRECISION (TREE_TYPE (var))))
5176 return;
5178 cst = gimple_assign_rhs2 (stmt);
5179 set_nonzero_bits (var, wi::bit_and_not (get_nonzero_bits (var),
5180 wi::to_wide (cst)));
5183 /* Convert range assertion expressions into the implied copies and
5184 copy propagate away the copies. Doing the trivial copy propagation
5185 here avoids the need to run the full copy propagation pass after
5186 VRP.
5188 FIXME, this will eventually lead to copy propagation removing the
5189 names that had useful range information attached to them. For
5190 instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
5191 then N_i will have the range [3, +INF].
5193 However, by converting the assertion into the implied copy
5194 operation N_i = N_j, we will then copy-propagate N_j into the uses
5195 of N_i and lose the range information. We may want to hold on to
5196 ASSERT_EXPRs a little while longer as the ranges could be used in
5197 things like jump threading.
5199 The problem with keeping ASSERT_EXPRs around is that passes after
5200 VRP need to handle them appropriately.
5202 Another approach would be to make the range information a first
5203 class property of the SSA_NAME so that it can be queried from
5204 any pass. This is made somewhat more complex by the need for
5205 multiple ranges to be associated with one SSA_NAME. */
5207 static void
5208 remove_range_assertions (void)
5210 basic_block bb;
5211 gimple_stmt_iterator si;
5212 /* 1 if looking at ASSERT_EXPRs immediately at the beginning of
5213 a basic block preceeded by GIMPLE_COND branching to it and
5214 __builtin_trap, -1 if not yet checked, 0 otherwise. */
5215 int is_unreachable;
5217 /* Note that the BSI iterator bump happens at the bottom of the
5218 loop and no bump is necessary if we're removing the statement
5219 referenced by the current BSI. */
5220 FOR_EACH_BB_FN (bb, cfun)
5221 for (si = gsi_after_labels (bb), is_unreachable = -1; !gsi_end_p (si);)
5223 gimple *stmt = gsi_stmt (si);
5225 if (is_gimple_assign (stmt)
5226 && gimple_assign_rhs_code (stmt) == ASSERT_EXPR)
5228 tree lhs = gimple_assign_lhs (stmt);
5229 tree rhs = gimple_assign_rhs1 (stmt);
5230 tree var;
5232 var = ASSERT_EXPR_VAR (rhs);
5234 if (TREE_CODE (var) == SSA_NAME
5235 && !POINTER_TYPE_P (TREE_TYPE (lhs))
5236 && SSA_NAME_RANGE_INFO (lhs))
5238 if (is_unreachable == -1)
5240 is_unreachable = 0;
5241 if (single_pred_p (bb)
5242 && assert_unreachable_fallthru_edge_p
5243 (single_pred_edge (bb)))
5244 is_unreachable = 1;
5246 /* Handle
5247 if (x_7 >= 10 && x_7 < 20)
5248 __builtin_unreachable ();
5249 x_8 = ASSERT_EXPR <x_7, ...>;
5250 if the only uses of x_7 are in the ASSERT_EXPR and
5251 in the condition. In that case, we can copy the
5252 range info from x_8 computed in this pass also
5253 for x_7. */
5254 if (is_unreachable
5255 && all_imm_uses_in_stmt_or_feed_cond (var, stmt,
5256 single_pred (bb)))
5258 set_range_info (var, SSA_NAME_RANGE_TYPE (lhs),
5259 SSA_NAME_RANGE_INFO (lhs)->get_min (),
5260 SSA_NAME_RANGE_INFO (lhs)->get_max ());
5261 maybe_set_nonzero_bits (single_pred_edge (bb), var);
5265 /* Propagate the RHS into every use of the LHS. For SSA names
5266 also propagate abnormals as it merely restores the original
5267 IL in this case (an replace_uses_by would assert). */
5268 if (TREE_CODE (var) == SSA_NAME)
5270 imm_use_iterator iter;
5271 use_operand_p use_p;
5272 gimple *use_stmt;
5273 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
5274 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
5275 SET_USE (use_p, var);
5277 else
5278 replace_uses_by (lhs, var);
5280 /* And finally, remove the copy, it is not needed. */
5281 gsi_remove (&si, true);
5282 release_defs (stmt);
5284 else
5286 if (!is_gimple_debug (gsi_stmt (si)))
5287 is_unreachable = 0;
5288 gsi_next (&si);
5293 /* Return true if STMT is interesting for VRP. */
5295 bool
5296 stmt_interesting_for_vrp (gimple *stmt)
5298 if (gimple_code (stmt) == GIMPLE_PHI)
5300 tree res = gimple_phi_result (stmt);
5301 return (!virtual_operand_p (res)
5302 && (INTEGRAL_TYPE_P (TREE_TYPE (res))
5303 || POINTER_TYPE_P (TREE_TYPE (res))));
5305 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
5307 tree lhs = gimple_get_lhs (stmt);
5309 /* In general, assignments with virtual operands are not useful
5310 for deriving ranges, with the obvious exception of calls to
5311 builtin functions. */
5312 if (lhs && TREE_CODE (lhs) == SSA_NAME
5313 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
5314 || POINTER_TYPE_P (TREE_TYPE (lhs)))
5315 && (is_gimple_call (stmt)
5316 || !gimple_vuse (stmt)))
5317 return true;
5318 else if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
5319 switch (gimple_call_internal_fn (stmt))
5321 case IFN_ADD_OVERFLOW:
5322 case IFN_SUB_OVERFLOW:
5323 case IFN_MUL_OVERFLOW:
5324 case IFN_ATOMIC_COMPARE_EXCHANGE:
5325 /* These internal calls return _Complex integer type,
5326 but are interesting to VRP nevertheless. */
5327 if (lhs && TREE_CODE (lhs) == SSA_NAME)
5328 return true;
5329 break;
5330 default:
5331 break;
5334 else if (gimple_code (stmt) == GIMPLE_COND
5335 || gimple_code (stmt) == GIMPLE_SWITCH)
5336 return true;
5338 return false;
5341 /* Initialization required by ssa_propagate engine. */
5343 void
5344 vrp_prop::vrp_initialize ()
5346 basic_block bb;
5348 FOR_EACH_BB_FN (bb, cfun)
5350 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
5351 gsi_next (&si))
5353 gphi *phi = si.phi ();
5354 if (!stmt_interesting_for_vrp (phi))
5356 tree lhs = PHI_RESULT (phi);
5357 set_value_range_to_varying (get_value_range (lhs));
5358 prop_set_simulate_again (phi, false);
5360 else
5361 prop_set_simulate_again (phi, true);
5364 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
5365 gsi_next (&si))
5367 gimple *stmt = gsi_stmt (si);
5369 /* If the statement is a control insn, then we do not
5370 want to avoid simulating the statement once. Failure
5371 to do so means that those edges will never get added. */
5372 if (stmt_ends_bb_p (stmt))
5373 prop_set_simulate_again (stmt, true);
5374 else if (!stmt_interesting_for_vrp (stmt))
5376 set_defs_to_varying (stmt);
5377 prop_set_simulate_again (stmt, false);
5379 else
5380 prop_set_simulate_again (stmt, true);
5385 /* Searches the case label vector VEC for the index *IDX of the CASE_LABEL
5386 that includes the value VAL. The search is restricted to the range
5387 [START_IDX, n - 1] where n is the size of VEC.
5389 If there is a CASE_LABEL for VAL, its index is placed in IDX and true is
5390 returned.
5392 If there is no CASE_LABEL for VAL and there is one that is larger than VAL,
5393 it is placed in IDX and false is returned.
5395 If VAL is larger than any CASE_LABEL, n is placed on IDX and false is
5396 returned. */
5398 bool
5399 find_case_label_index (gswitch *stmt, size_t start_idx, tree val, size_t *idx)
5401 size_t n = gimple_switch_num_labels (stmt);
5402 size_t low, high;
5404 /* Find case label for minimum of the value range or the next one.
5405 At each iteration we are searching in [low, high - 1]. */
5407 for (low = start_idx, high = n; high != low; )
5409 tree t;
5410 int cmp;
5411 /* Note that i != high, so we never ask for n. */
5412 size_t i = (high + low) / 2;
5413 t = gimple_switch_label (stmt, i);
5415 /* Cache the result of comparing CASE_LOW and val. */
5416 cmp = tree_int_cst_compare (CASE_LOW (t), val);
5418 if (cmp == 0)
5420 /* Ranges cannot be empty. */
5421 *idx = i;
5422 return true;
5424 else if (cmp > 0)
5425 high = i;
5426 else
5428 low = i + 1;
5429 if (CASE_HIGH (t) != NULL
5430 && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
5432 *idx = i;
5433 return true;
5438 *idx = high;
5439 return false;
5442 /* Searches the case label vector VEC for the range of CASE_LABELs that is used
5443 for values between MIN and MAX. The first index is placed in MIN_IDX. The
5444 last index is placed in MAX_IDX. If the range of CASE_LABELs is empty
5445 then MAX_IDX < MIN_IDX.
5446 Returns true if the default label is not needed. */
5448 bool
5449 find_case_label_range (gswitch *stmt, tree min, tree max, size_t *min_idx,
5450 size_t *max_idx)
5452 size_t i, j;
5453 bool min_take_default = !find_case_label_index (stmt, 1, min, &i);
5454 bool max_take_default = !find_case_label_index (stmt, i, max, &j);
5456 if (i == j
5457 && min_take_default
5458 && max_take_default)
5460 /* Only the default case label reached.
5461 Return an empty range. */
5462 *min_idx = 1;
5463 *max_idx = 0;
5464 return false;
5466 else
5468 bool take_default = min_take_default || max_take_default;
5469 tree low, high;
5470 size_t k;
5472 if (max_take_default)
5473 j--;
5475 /* If the case label range is continuous, we do not need
5476 the default case label. Verify that. */
5477 high = CASE_LOW (gimple_switch_label (stmt, i));
5478 if (CASE_HIGH (gimple_switch_label (stmt, i)))
5479 high = CASE_HIGH (gimple_switch_label (stmt, i));
5480 for (k = i + 1; k <= j; ++k)
5482 low = CASE_LOW (gimple_switch_label (stmt, k));
5483 if (!integer_onep (int_const_binop (MINUS_EXPR, low, high)))
5485 take_default = true;
5486 break;
5488 high = low;
5489 if (CASE_HIGH (gimple_switch_label (stmt, k)))
5490 high = CASE_HIGH (gimple_switch_label (stmt, k));
5493 *min_idx = i;
5494 *max_idx = j;
5495 return !take_default;
5499 /* Evaluate statement STMT. If the statement produces a useful range,
5500 return SSA_PROP_INTERESTING and record the SSA name with the
5501 interesting range into *OUTPUT_P.
5503 If STMT is a conditional branch and we can determine its truth
5504 value, the taken edge is recorded in *TAKEN_EDGE_P.
5506 If STMT produces a varying value, return SSA_PROP_VARYING. */
5508 enum ssa_prop_result
5509 vrp_prop::visit_stmt (gimple *stmt, edge *taken_edge_p, tree *output_p)
5511 value_range vr = VR_INITIALIZER;
5512 tree lhs = gimple_get_lhs (stmt);
5513 extract_range_from_stmt (stmt, taken_edge_p, output_p, &vr);
5515 if (*output_p)
5517 if (update_value_range (*output_p, &vr))
5519 if (dump_file && (dump_flags & TDF_DETAILS))
5521 fprintf (dump_file, "Found new range for ");
5522 print_generic_expr (dump_file, *output_p);
5523 fprintf (dump_file, ": ");
5524 dump_value_range (dump_file, &vr);
5525 fprintf (dump_file, "\n");
5528 if (vr.type == VR_VARYING)
5529 return SSA_PROP_VARYING;
5531 return SSA_PROP_INTERESTING;
5533 return SSA_PROP_NOT_INTERESTING;
5536 if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
5537 switch (gimple_call_internal_fn (stmt))
5539 case IFN_ADD_OVERFLOW:
5540 case IFN_SUB_OVERFLOW:
5541 case IFN_MUL_OVERFLOW:
5542 case IFN_ATOMIC_COMPARE_EXCHANGE:
5543 /* These internal calls return _Complex integer type,
5544 which VRP does not track, but the immediate uses
5545 thereof might be interesting. */
5546 if (lhs && TREE_CODE (lhs) == SSA_NAME)
5548 imm_use_iterator iter;
5549 use_operand_p use_p;
5550 enum ssa_prop_result res = SSA_PROP_VARYING;
5552 set_value_range_to_varying (get_value_range (lhs));
5554 FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
5556 gimple *use_stmt = USE_STMT (use_p);
5557 if (!is_gimple_assign (use_stmt))
5558 continue;
5559 enum tree_code rhs_code = gimple_assign_rhs_code (use_stmt);
5560 if (rhs_code != REALPART_EXPR && rhs_code != IMAGPART_EXPR)
5561 continue;
5562 tree rhs1 = gimple_assign_rhs1 (use_stmt);
5563 tree use_lhs = gimple_assign_lhs (use_stmt);
5564 if (TREE_CODE (rhs1) != rhs_code
5565 || TREE_OPERAND (rhs1, 0) != lhs
5566 || TREE_CODE (use_lhs) != SSA_NAME
5567 || !stmt_interesting_for_vrp (use_stmt)
5568 || (!INTEGRAL_TYPE_P (TREE_TYPE (use_lhs))
5569 || !TYPE_MIN_VALUE (TREE_TYPE (use_lhs))
5570 || !TYPE_MAX_VALUE (TREE_TYPE (use_lhs))))
5571 continue;
5573 /* If there is a change in the value range for any of the
5574 REALPART_EXPR/IMAGPART_EXPR immediate uses, return
5575 SSA_PROP_INTERESTING. If there are any REALPART_EXPR
5576 or IMAGPART_EXPR immediate uses, but none of them have
5577 a change in their value ranges, return
5578 SSA_PROP_NOT_INTERESTING. If there are no
5579 {REAL,IMAG}PART_EXPR uses at all,
5580 return SSA_PROP_VARYING. */
5581 value_range new_vr = VR_INITIALIZER;
5582 extract_range_basic (&new_vr, use_stmt);
5583 value_range *old_vr = get_value_range (use_lhs);
5584 if (old_vr->type != new_vr.type
5585 || !vrp_operand_equal_p (old_vr->min, new_vr.min)
5586 || !vrp_operand_equal_p (old_vr->max, new_vr.max)
5587 || !vrp_bitmap_equal_p (old_vr->equiv, new_vr.equiv))
5588 res = SSA_PROP_INTERESTING;
5589 else
5590 res = SSA_PROP_NOT_INTERESTING;
5591 BITMAP_FREE (new_vr.equiv);
5592 if (res == SSA_PROP_INTERESTING)
5594 *output_p = lhs;
5595 return res;
5599 return res;
5601 break;
5602 default:
5603 break;
5606 /* All other statements produce nothing of interest for VRP, so mark
5607 their outputs varying and prevent further simulation. */
5608 set_defs_to_varying (stmt);
5610 return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
5613 /* Union the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
5614 { VR1TYPE, VR0MIN, VR0MAX } and store the result
5615 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
5616 possible such range. The resulting range is not canonicalized. */
5618 static void
5619 union_ranges (enum value_range_type *vr0type,
5620 tree *vr0min, tree *vr0max,
5621 enum value_range_type vr1type,
5622 tree vr1min, tree vr1max)
5624 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
5625 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
5627 /* [] is vr0, () is vr1 in the following classification comments. */
5628 if (mineq && maxeq)
5630 /* [( )] */
5631 if (*vr0type == vr1type)
5632 /* Nothing to do for equal ranges. */
5634 else if ((*vr0type == VR_RANGE
5635 && vr1type == VR_ANTI_RANGE)
5636 || (*vr0type == VR_ANTI_RANGE
5637 && vr1type == VR_RANGE))
5639 /* For anti-range with range union the result is varying. */
5640 goto give_up;
5642 else
5643 gcc_unreachable ();
5645 else if (operand_less_p (*vr0max, vr1min) == 1
5646 || operand_less_p (vr1max, *vr0min) == 1)
5648 /* [ ] ( ) or ( ) [ ]
5649 If the ranges have an empty intersection, result of the union
5650 operation is the anti-range or if both are anti-ranges
5651 it covers all. */
5652 if (*vr0type == VR_ANTI_RANGE
5653 && vr1type == VR_ANTI_RANGE)
5654 goto give_up;
5655 else if (*vr0type == VR_ANTI_RANGE
5656 && vr1type == VR_RANGE)
5658 else if (*vr0type == VR_RANGE
5659 && vr1type == VR_ANTI_RANGE)
5661 *vr0type = vr1type;
5662 *vr0min = vr1min;
5663 *vr0max = vr1max;
5665 else if (*vr0type == VR_RANGE
5666 && vr1type == VR_RANGE)
5668 /* The result is the convex hull of both ranges. */
5669 if (operand_less_p (*vr0max, vr1min) == 1)
5671 /* If the result can be an anti-range, create one. */
5672 if (TREE_CODE (*vr0max) == INTEGER_CST
5673 && TREE_CODE (vr1min) == INTEGER_CST
5674 && vrp_val_is_min (*vr0min)
5675 && vrp_val_is_max (vr1max))
5677 tree min = int_const_binop (PLUS_EXPR,
5678 *vr0max,
5679 build_int_cst (TREE_TYPE (*vr0max), 1));
5680 tree max = int_const_binop (MINUS_EXPR,
5681 vr1min,
5682 build_int_cst (TREE_TYPE (vr1min), 1));
5683 if (!operand_less_p (max, min))
5685 *vr0type = VR_ANTI_RANGE;
5686 *vr0min = min;
5687 *vr0max = max;
5689 else
5690 *vr0max = vr1max;
5692 else
5693 *vr0max = vr1max;
5695 else
5697 /* If the result can be an anti-range, create one. */
5698 if (TREE_CODE (vr1max) == INTEGER_CST
5699 && TREE_CODE (*vr0min) == INTEGER_CST
5700 && vrp_val_is_min (vr1min)
5701 && vrp_val_is_max (*vr0max))
5703 tree min = int_const_binop (PLUS_EXPR,
5704 vr1max,
5705 build_int_cst (TREE_TYPE (vr1max), 1));
5706 tree max = int_const_binop (MINUS_EXPR,
5707 *vr0min,
5708 build_int_cst (TREE_TYPE (*vr0min), 1));
5709 if (!operand_less_p (max, min))
5711 *vr0type = VR_ANTI_RANGE;
5712 *vr0min = min;
5713 *vr0max = max;
5715 else
5716 *vr0min = vr1min;
5718 else
5719 *vr0min = vr1min;
5722 else
5723 gcc_unreachable ();
5725 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
5726 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
5728 /* [ ( ) ] or [( ) ] or [ ( )] */
5729 if (*vr0type == VR_RANGE
5730 && vr1type == VR_RANGE)
5732 else if (*vr0type == VR_ANTI_RANGE
5733 && vr1type == VR_ANTI_RANGE)
5735 *vr0type = vr1type;
5736 *vr0min = vr1min;
5737 *vr0max = vr1max;
5739 else if (*vr0type == VR_ANTI_RANGE
5740 && vr1type == VR_RANGE)
5742 /* Arbitrarily choose the right or left gap. */
5743 if (!mineq && TREE_CODE (vr1min) == INTEGER_CST)
5744 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5745 build_int_cst (TREE_TYPE (vr1min), 1));
5746 else if (!maxeq && TREE_CODE (vr1max) == INTEGER_CST)
5747 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5748 build_int_cst (TREE_TYPE (vr1max), 1));
5749 else
5750 goto give_up;
5752 else if (*vr0type == VR_RANGE
5753 && vr1type == VR_ANTI_RANGE)
5754 /* The result covers everything. */
5755 goto give_up;
5756 else
5757 gcc_unreachable ();
5759 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
5760 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
5762 /* ( [ ] ) or ([ ] ) or ( [ ]) */
5763 if (*vr0type == VR_RANGE
5764 && vr1type == VR_RANGE)
5766 *vr0type = vr1type;
5767 *vr0min = vr1min;
5768 *vr0max = vr1max;
5770 else if (*vr0type == VR_ANTI_RANGE
5771 && vr1type == VR_ANTI_RANGE)
5773 else if (*vr0type == VR_RANGE
5774 && vr1type == VR_ANTI_RANGE)
5776 *vr0type = VR_ANTI_RANGE;
5777 if (!mineq && TREE_CODE (*vr0min) == INTEGER_CST)
5779 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5780 build_int_cst (TREE_TYPE (*vr0min), 1));
5781 *vr0min = vr1min;
5783 else if (!maxeq && TREE_CODE (*vr0max) == INTEGER_CST)
5785 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5786 build_int_cst (TREE_TYPE (*vr0max), 1));
5787 *vr0max = vr1max;
5789 else
5790 goto give_up;
5792 else if (*vr0type == VR_ANTI_RANGE
5793 && vr1type == VR_RANGE)
5794 /* The result covers everything. */
5795 goto give_up;
5796 else
5797 gcc_unreachable ();
5799 else if ((operand_less_p (vr1min, *vr0max) == 1
5800 || operand_equal_p (vr1min, *vr0max, 0))
5801 && operand_less_p (*vr0min, vr1min) == 1
5802 && operand_less_p (*vr0max, vr1max) == 1)
5804 /* [ ( ] ) or [ ]( ) */
5805 if (*vr0type == VR_RANGE
5806 && vr1type == VR_RANGE)
5807 *vr0max = vr1max;
5808 else if (*vr0type == VR_ANTI_RANGE
5809 && vr1type == VR_ANTI_RANGE)
5810 *vr0min = vr1min;
5811 else if (*vr0type == VR_ANTI_RANGE
5812 && vr1type == VR_RANGE)
5814 if (TREE_CODE (vr1min) == INTEGER_CST)
5815 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5816 build_int_cst (TREE_TYPE (vr1min), 1));
5817 else
5818 goto give_up;
5820 else if (*vr0type == VR_RANGE
5821 && vr1type == VR_ANTI_RANGE)
5823 if (TREE_CODE (*vr0max) == INTEGER_CST)
5825 *vr0type = vr1type;
5826 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
5827 build_int_cst (TREE_TYPE (*vr0max), 1));
5828 *vr0max = vr1max;
5830 else
5831 goto give_up;
5833 else
5834 gcc_unreachable ();
5836 else if ((operand_less_p (*vr0min, vr1max) == 1
5837 || operand_equal_p (*vr0min, vr1max, 0))
5838 && operand_less_p (vr1min, *vr0min) == 1
5839 && operand_less_p (vr1max, *vr0max) == 1)
5841 /* ( [ ) ] or ( )[ ] */
5842 if (*vr0type == VR_RANGE
5843 && vr1type == VR_RANGE)
5844 *vr0min = vr1min;
5845 else if (*vr0type == VR_ANTI_RANGE
5846 && vr1type == VR_ANTI_RANGE)
5847 *vr0max = vr1max;
5848 else if (*vr0type == VR_ANTI_RANGE
5849 && vr1type == VR_RANGE)
5851 if (TREE_CODE (vr1max) == INTEGER_CST)
5852 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5853 build_int_cst (TREE_TYPE (vr1max), 1));
5854 else
5855 goto give_up;
5857 else if (*vr0type == VR_RANGE
5858 && vr1type == VR_ANTI_RANGE)
5860 if (TREE_CODE (*vr0min) == INTEGER_CST)
5862 *vr0type = vr1type;
5863 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
5864 build_int_cst (TREE_TYPE (*vr0min), 1));
5865 *vr0min = vr1min;
5867 else
5868 goto give_up;
5870 else
5871 gcc_unreachable ();
5873 else
5874 goto give_up;
5876 return;
5878 give_up:
5879 *vr0type = VR_VARYING;
5880 *vr0min = NULL_TREE;
5881 *vr0max = NULL_TREE;
5884 /* Intersect the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
5885 { VR1TYPE, VR0MIN, VR0MAX } and store the result
5886 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
5887 possible such range. The resulting range is not canonicalized. */
5889 static void
5890 intersect_ranges (enum value_range_type *vr0type,
5891 tree *vr0min, tree *vr0max,
5892 enum value_range_type vr1type,
5893 tree vr1min, tree vr1max)
5895 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
5896 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
5898 /* [] is vr0, () is vr1 in the following classification comments. */
5899 if (mineq && maxeq)
5901 /* [( )] */
5902 if (*vr0type == vr1type)
5903 /* Nothing to do for equal ranges. */
5905 else if ((*vr0type == VR_RANGE
5906 && vr1type == VR_ANTI_RANGE)
5907 || (*vr0type == VR_ANTI_RANGE
5908 && vr1type == VR_RANGE))
5910 /* For anti-range with range intersection the result is empty. */
5911 *vr0type = VR_UNDEFINED;
5912 *vr0min = NULL_TREE;
5913 *vr0max = NULL_TREE;
5915 else
5916 gcc_unreachable ();
5918 else if (operand_less_p (*vr0max, vr1min) == 1
5919 || operand_less_p (vr1max, *vr0min) == 1)
5921 /* [ ] ( ) or ( ) [ ]
5922 If the ranges have an empty intersection, the result of the
5923 intersect operation is the range for intersecting an
5924 anti-range with a range or empty when intersecting two ranges. */
5925 if (*vr0type == VR_RANGE
5926 && vr1type == VR_ANTI_RANGE)
5928 else if (*vr0type == VR_ANTI_RANGE
5929 && vr1type == VR_RANGE)
5931 *vr0type = vr1type;
5932 *vr0min = vr1min;
5933 *vr0max = vr1max;
5935 else if (*vr0type == VR_RANGE
5936 && vr1type == VR_RANGE)
5938 *vr0type = VR_UNDEFINED;
5939 *vr0min = NULL_TREE;
5940 *vr0max = NULL_TREE;
5942 else if (*vr0type == VR_ANTI_RANGE
5943 && vr1type == VR_ANTI_RANGE)
5945 /* If the anti-ranges are adjacent to each other merge them. */
5946 if (TREE_CODE (*vr0max) == INTEGER_CST
5947 && TREE_CODE (vr1min) == INTEGER_CST
5948 && operand_less_p (*vr0max, vr1min) == 1
5949 && integer_onep (int_const_binop (MINUS_EXPR,
5950 vr1min, *vr0max)))
5951 *vr0max = vr1max;
5952 else if (TREE_CODE (vr1max) == INTEGER_CST
5953 && TREE_CODE (*vr0min) == INTEGER_CST
5954 && operand_less_p (vr1max, *vr0min) == 1
5955 && integer_onep (int_const_binop (MINUS_EXPR,
5956 *vr0min, vr1max)))
5957 *vr0min = vr1min;
5958 /* Else arbitrarily take VR0. */
5961 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
5962 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
5964 /* [ ( ) ] or [( ) ] or [ ( )] */
5965 if (*vr0type == VR_RANGE
5966 && vr1type == VR_RANGE)
5968 /* If both are ranges the result is the inner one. */
5969 *vr0type = vr1type;
5970 *vr0min = vr1min;
5971 *vr0max = vr1max;
5973 else if (*vr0type == VR_RANGE
5974 && vr1type == VR_ANTI_RANGE)
5976 /* Choose the right gap if the left one is empty. */
5977 if (mineq)
5979 if (TREE_CODE (vr1max) != INTEGER_CST)
5980 *vr0min = vr1max;
5981 else if (TYPE_PRECISION (TREE_TYPE (vr1max)) == 1
5982 && !TYPE_UNSIGNED (TREE_TYPE (vr1max)))
5983 *vr0min
5984 = int_const_binop (MINUS_EXPR, vr1max,
5985 build_int_cst (TREE_TYPE (vr1max), -1));
5986 else
5987 *vr0min
5988 = int_const_binop (PLUS_EXPR, vr1max,
5989 build_int_cst (TREE_TYPE (vr1max), 1));
5991 /* Choose the left gap if the right one is empty. */
5992 else if (maxeq)
5994 if (TREE_CODE (vr1min) != INTEGER_CST)
5995 *vr0max = vr1min;
5996 else if (TYPE_PRECISION (TREE_TYPE (vr1min)) == 1
5997 && !TYPE_UNSIGNED (TREE_TYPE (vr1min)))
5998 *vr0max
5999 = int_const_binop (PLUS_EXPR, vr1min,
6000 build_int_cst (TREE_TYPE (vr1min), -1));
6001 else
6002 *vr0max
6003 = int_const_binop (MINUS_EXPR, vr1min,
6004 build_int_cst (TREE_TYPE (vr1min), 1));
6006 /* Choose the anti-range if the range is effectively varying. */
6007 else if (vrp_val_is_min (*vr0min)
6008 && vrp_val_is_max (*vr0max))
6010 *vr0type = vr1type;
6011 *vr0min = vr1min;
6012 *vr0max = vr1max;
6014 /* Else choose the range. */
6016 else if (*vr0type == VR_ANTI_RANGE
6017 && vr1type == VR_ANTI_RANGE)
6018 /* If both are anti-ranges the result is the outer one. */
6020 else if (*vr0type == VR_ANTI_RANGE
6021 && vr1type == VR_RANGE)
6023 /* The intersection is empty. */
6024 *vr0type = VR_UNDEFINED;
6025 *vr0min = NULL_TREE;
6026 *vr0max = NULL_TREE;
6028 else
6029 gcc_unreachable ();
6031 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
6032 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
6034 /* ( [ ] ) or ([ ] ) or ( [ ]) */
6035 if (*vr0type == VR_RANGE
6036 && vr1type == VR_RANGE)
6037 /* Choose the inner range. */
6039 else if (*vr0type == VR_ANTI_RANGE
6040 && vr1type == VR_RANGE)
6042 /* Choose the right gap if the left is empty. */
6043 if (mineq)
6045 *vr0type = VR_RANGE;
6046 if (TREE_CODE (*vr0max) != INTEGER_CST)
6047 *vr0min = *vr0max;
6048 else if (TYPE_PRECISION (TREE_TYPE (*vr0max)) == 1
6049 && !TYPE_UNSIGNED (TREE_TYPE (*vr0max)))
6050 *vr0min
6051 = int_const_binop (MINUS_EXPR, *vr0max,
6052 build_int_cst (TREE_TYPE (*vr0max), -1));
6053 else
6054 *vr0min
6055 = int_const_binop (PLUS_EXPR, *vr0max,
6056 build_int_cst (TREE_TYPE (*vr0max), 1));
6057 *vr0max = vr1max;
6059 /* Choose the left gap if the right is empty. */
6060 else if (maxeq)
6062 *vr0type = VR_RANGE;
6063 if (TREE_CODE (*vr0min) != INTEGER_CST)
6064 *vr0max = *vr0min;
6065 else if (TYPE_PRECISION (TREE_TYPE (*vr0min)) == 1
6066 && !TYPE_UNSIGNED (TREE_TYPE (*vr0min)))
6067 *vr0max
6068 = int_const_binop (PLUS_EXPR, *vr0min,
6069 build_int_cst (TREE_TYPE (*vr0min), -1));
6070 else
6071 *vr0max
6072 = int_const_binop (MINUS_EXPR, *vr0min,
6073 build_int_cst (TREE_TYPE (*vr0min), 1));
6074 *vr0min = vr1min;
6076 /* Choose the anti-range if the range is effectively varying. */
6077 else if (vrp_val_is_min (vr1min)
6078 && vrp_val_is_max (vr1max))
6080 /* Choose the anti-range if it is ~[0,0], that range is special
6081 enough to special case when vr1's range is relatively wide.
6082 At least for types bigger than int - this covers pointers
6083 and arguments to functions like ctz. */
6084 else if (*vr0min == *vr0max
6085 && integer_zerop (*vr0min)
6086 && ((TYPE_PRECISION (TREE_TYPE (*vr0min))
6087 >= TYPE_PRECISION (integer_type_node))
6088 || POINTER_TYPE_P (TREE_TYPE (*vr0min)))
6089 && TREE_CODE (vr1max) == INTEGER_CST
6090 && TREE_CODE (vr1min) == INTEGER_CST
6091 && (wi::clz (wi::to_wide (vr1max) - wi::to_wide (vr1min))
6092 < TYPE_PRECISION (TREE_TYPE (*vr0min)) / 2))
6094 /* Else choose the range. */
6095 else
6097 *vr0type = vr1type;
6098 *vr0min = vr1min;
6099 *vr0max = vr1max;
6102 else if (*vr0type == VR_ANTI_RANGE
6103 && vr1type == VR_ANTI_RANGE)
6105 /* If both are anti-ranges the result is the outer one. */
6106 *vr0type = vr1type;
6107 *vr0min = vr1min;
6108 *vr0max = vr1max;
6110 else if (vr1type == VR_ANTI_RANGE
6111 && *vr0type == VR_RANGE)
6113 /* The intersection is empty. */
6114 *vr0type = VR_UNDEFINED;
6115 *vr0min = NULL_TREE;
6116 *vr0max = NULL_TREE;
6118 else
6119 gcc_unreachable ();
6121 else if ((operand_less_p (vr1min, *vr0max) == 1
6122 || operand_equal_p (vr1min, *vr0max, 0))
6123 && operand_less_p (*vr0min, vr1min) == 1)
6125 /* [ ( ] ) or [ ]( ) */
6126 if (*vr0type == VR_ANTI_RANGE
6127 && vr1type == VR_ANTI_RANGE)
6128 *vr0max = vr1max;
6129 else if (*vr0type == VR_RANGE
6130 && vr1type == VR_RANGE)
6131 *vr0min = vr1min;
6132 else if (*vr0type == VR_RANGE
6133 && vr1type == VR_ANTI_RANGE)
6135 if (TREE_CODE (vr1min) == INTEGER_CST)
6136 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
6137 build_int_cst (TREE_TYPE (vr1min), 1));
6138 else
6139 *vr0max = vr1min;
6141 else if (*vr0type == VR_ANTI_RANGE
6142 && vr1type == VR_RANGE)
6144 *vr0type = VR_RANGE;
6145 if (TREE_CODE (*vr0max) == INTEGER_CST)
6146 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
6147 build_int_cst (TREE_TYPE (*vr0max), 1));
6148 else
6149 *vr0min = *vr0max;
6150 *vr0max = vr1max;
6152 else
6153 gcc_unreachable ();
6155 else if ((operand_less_p (*vr0min, vr1max) == 1
6156 || operand_equal_p (*vr0min, vr1max, 0))
6157 && operand_less_p (vr1min, *vr0min) == 1)
6159 /* ( [ ) ] or ( )[ ] */
6160 if (*vr0type == VR_ANTI_RANGE
6161 && vr1type == VR_ANTI_RANGE)
6162 *vr0min = vr1min;
6163 else if (*vr0type == VR_RANGE
6164 && vr1type == VR_RANGE)
6165 *vr0max = vr1max;
6166 else if (*vr0type == VR_RANGE
6167 && vr1type == VR_ANTI_RANGE)
6169 if (TREE_CODE (vr1max) == INTEGER_CST)
6170 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
6171 build_int_cst (TREE_TYPE (vr1max), 1));
6172 else
6173 *vr0min = vr1max;
6175 else if (*vr0type == VR_ANTI_RANGE
6176 && vr1type == VR_RANGE)
6178 *vr0type = VR_RANGE;
6179 if (TREE_CODE (*vr0min) == INTEGER_CST)
6180 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
6181 build_int_cst (TREE_TYPE (*vr0min), 1));
6182 else
6183 *vr0max = *vr0min;
6184 *vr0min = vr1min;
6186 else
6187 gcc_unreachable ();
6190 /* As a fallback simply use { *VRTYPE, *VR0MIN, *VR0MAX } as
6191 result for the intersection. That's always a conservative
6192 correct estimate unless VR1 is a constant singleton range
6193 in which case we choose that. */
6194 if (vr1type == VR_RANGE
6195 && is_gimple_min_invariant (vr1min)
6196 && vrp_operand_equal_p (vr1min, vr1max))
6198 *vr0type = vr1type;
6199 *vr0min = vr1min;
6200 *vr0max = vr1max;
6203 return;
6207 /* Intersect the two value-ranges *VR0 and *VR1 and store the result
6208 in *VR0. This may not be the smallest possible such range. */
6210 static void
6211 vrp_intersect_ranges_1 (value_range *vr0, value_range *vr1)
6213 value_range saved;
6215 /* If either range is VR_VARYING the other one wins. */
6216 if (vr1->type == VR_VARYING)
6217 return;
6218 if (vr0->type == VR_VARYING)
6220 copy_value_range (vr0, vr1);
6221 return;
6224 /* When either range is VR_UNDEFINED the resulting range is
6225 VR_UNDEFINED, too. */
6226 if (vr0->type == VR_UNDEFINED)
6227 return;
6228 if (vr1->type == VR_UNDEFINED)
6230 set_value_range_to_undefined (vr0);
6231 return;
6234 /* Save the original vr0 so we can return it as conservative intersection
6235 result when our worker turns things to varying. */
6236 saved = *vr0;
6237 intersect_ranges (&vr0->type, &vr0->min, &vr0->max,
6238 vr1->type, vr1->min, vr1->max);
6239 /* Make sure to canonicalize the result though as the inversion of a
6240 VR_RANGE can still be a VR_RANGE. */
6241 set_and_canonicalize_value_range (vr0, vr0->type,
6242 vr0->min, vr0->max, vr0->equiv);
6243 /* If that failed, use the saved original VR0. */
6244 if (vr0->type == VR_VARYING)
6246 *vr0 = saved;
6247 return;
6249 /* If the result is VR_UNDEFINED there is no need to mess with
6250 the equivalencies. */
6251 if (vr0->type == VR_UNDEFINED)
6252 return;
6254 /* The resulting set of equivalences for range intersection is the union of
6255 the two sets. */
6256 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
6257 bitmap_ior_into (vr0->equiv, vr1->equiv);
6258 else if (vr1->equiv && !vr0->equiv)
6260 /* All equivalence bitmaps are allocated from the same obstack. So
6261 we can use the obstack associated with VR to allocate vr0->equiv. */
6262 vr0->equiv = BITMAP_ALLOC (vr1->equiv->obstack);
6263 bitmap_copy (vr0->equiv, vr1->equiv);
6267 void
6268 vrp_intersect_ranges (value_range *vr0, value_range *vr1)
6270 if (dump_file && (dump_flags & TDF_DETAILS))
6272 fprintf (dump_file, "Intersecting\n ");
6273 dump_value_range (dump_file, vr0);
6274 fprintf (dump_file, "\nand\n ");
6275 dump_value_range (dump_file, vr1);
6276 fprintf (dump_file, "\n");
6278 vrp_intersect_ranges_1 (vr0, vr1);
6279 if (dump_file && (dump_flags & TDF_DETAILS))
6281 fprintf (dump_file, "to\n ");
6282 dump_value_range (dump_file, vr0);
6283 fprintf (dump_file, "\n");
6287 /* Meet operation for value ranges. Given two value ranges VR0 and
6288 VR1, store in VR0 a range that contains both VR0 and VR1. This
6289 may not be the smallest possible such range. */
6291 static void
6292 vrp_meet_1 (value_range *vr0, const value_range *vr1)
6294 value_range saved;
6296 if (vr0->type == VR_UNDEFINED)
6298 set_value_range (vr0, vr1->type, vr1->min, vr1->max, vr1->equiv);
6299 return;
6302 if (vr1->type == VR_UNDEFINED)
6304 /* VR0 already has the resulting range. */
6305 return;
6308 if (vr0->type == VR_VARYING)
6310 /* Nothing to do. VR0 already has the resulting range. */
6311 return;
6314 if (vr1->type == VR_VARYING)
6316 set_value_range_to_varying (vr0);
6317 return;
6320 saved = *vr0;
6321 union_ranges (&vr0->type, &vr0->min, &vr0->max,
6322 vr1->type, vr1->min, vr1->max);
6323 if (vr0->type == VR_VARYING)
6325 /* Failed to find an efficient meet. Before giving up and setting
6326 the result to VARYING, see if we can at least derive a useful
6327 anti-range. FIXME, all this nonsense about distinguishing
6328 anti-ranges from ranges is necessary because of the odd
6329 semantics of range_includes_zero_p and friends. */
6330 if (((saved.type == VR_RANGE
6331 && range_includes_zero_p (saved.min, saved.max) == 0)
6332 || (saved.type == VR_ANTI_RANGE
6333 && range_includes_zero_p (saved.min, saved.max) == 1))
6334 && ((vr1->type == VR_RANGE
6335 && range_includes_zero_p (vr1->min, vr1->max) == 0)
6336 || (vr1->type == VR_ANTI_RANGE
6337 && range_includes_zero_p (vr1->min, vr1->max) == 1)))
6339 set_value_range_to_nonnull (vr0, TREE_TYPE (saved.min));
6341 /* Since this meet operation did not result from the meeting of
6342 two equivalent names, VR0 cannot have any equivalences. */
6343 if (vr0->equiv)
6344 bitmap_clear (vr0->equiv);
6345 return;
6348 set_value_range_to_varying (vr0);
6349 return;
6351 set_and_canonicalize_value_range (vr0, vr0->type, vr0->min, vr0->max,
6352 vr0->equiv);
6353 if (vr0->type == VR_VARYING)
6354 return;
6356 /* The resulting set of equivalences is always the intersection of
6357 the two sets. */
6358 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
6359 bitmap_and_into (vr0->equiv, vr1->equiv);
6360 else if (vr0->equiv && !vr1->equiv)
6361 bitmap_clear (vr0->equiv);
6364 void
6365 vrp_meet (value_range *vr0, const value_range *vr1)
6367 if (dump_file && (dump_flags & TDF_DETAILS))
6369 fprintf (dump_file, "Meeting\n ");
6370 dump_value_range (dump_file, vr0);
6371 fprintf (dump_file, "\nand\n ");
6372 dump_value_range (dump_file, vr1);
6373 fprintf (dump_file, "\n");
6375 vrp_meet_1 (vr0, vr1);
6376 if (dump_file && (dump_flags & TDF_DETAILS))
6378 fprintf (dump_file, "to\n ");
6379 dump_value_range (dump_file, vr0);
6380 fprintf (dump_file, "\n");
6385 /* Visit all arguments for PHI node PHI that flow through executable
6386 edges. If a valid value range can be derived from all the incoming
6387 value ranges, set a new range for the LHS of PHI. */
6389 enum ssa_prop_result
6390 vrp_prop::visit_phi (gphi *phi)
6392 tree lhs = PHI_RESULT (phi);
6393 value_range vr_result = VR_INITIALIZER;
6394 extract_range_from_phi_node (phi, &vr_result);
6395 if (update_value_range (lhs, &vr_result))
6397 if (dump_file && (dump_flags & TDF_DETAILS))
6399 fprintf (dump_file, "Found new range for ");
6400 print_generic_expr (dump_file, lhs);
6401 fprintf (dump_file, ": ");
6402 dump_value_range (dump_file, &vr_result);
6403 fprintf (dump_file, "\n");
6406 if (vr_result.type == VR_VARYING)
6407 return SSA_PROP_VARYING;
6409 return SSA_PROP_INTERESTING;
6412 /* Nothing changed, don't add outgoing edges. */
6413 return SSA_PROP_NOT_INTERESTING;
6416 class vrp_folder : public substitute_and_fold_engine
6418 public:
6419 tree get_value (tree) FINAL OVERRIDE;
6420 bool fold_stmt (gimple_stmt_iterator *) FINAL OVERRIDE;
6421 bool fold_predicate_in (gimple_stmt_iterator *);
6423 class vr_values *vr_values;
6425 /* Delegators. */
6426 tree vrp_evaluate_conditional (tree_code code, tree op0,
6427 tree op1, gimple *stmt)
6428 { return vr_values->vrp_evaluate_conditional (code, op0, op1, stmt); }
6429 bool simplify_stmt_using_ranges (gimple_stmt_iterator *gsi)
6430 { return vr_values->simplify_stmt_using_ranges (gsi); }
6431 tree op_with_constant_singleton_value_range (tree op)
6432 { return vr_values->op_with_constant_singleton_value_range (op); }
6435 /* If the statement pointed by SI has a predicate whose value can be
6436 computed using the value range information computed by VRP, compute
6437 its value and return true. Otherwise, return false. */
6439 bool
6440 vrp_folder::fold_predicate_in (gimple_stmt_iterator *si)
6442 bool assignment_p = false;
6443 tree val;
6444 gimple *stmt = gsi_stmt (*si);
6446 if (is_gimple_assign (stmt)
6447 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
6449 assignment_p = true;
6450 val = vrp_evaluate_conditional (gimple_assign_rhs_code (stmt),
6451 gimple_assign_rhs1 (stmt),
6452 gimple_assign_rhs2 (stmt),
6453 stmt);
6455 else if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
6456 val = vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
6457 gimple_cond_lhs (cond_stmt),
6458 gimple_cond_rhs (cond_stmt),
6459 stmt);
6460 else
6461 return false;
6463 if (val)
6465 if (assignment_p)
6466 val = fold_convert (gimple_expr_type (stmt), val);
6468 if (dump_file)
6470 fprintf (dump_file, "Folding predicate ");
6471 print_gimple_expr (dump_file, stmt, 0);
6472 fprintf (dump_file, " to ");
6473 print_generic_expr (dump_file, val);
6474 fprintf (dump_file, "\n");
6477 if (is_gimple_assign (stmt))
6478 gimple_assign_set_rhs_from_tree (si, val);
6479 else
6481 gcc_assert (gimple_code (stmt) == GIMPLE_COND);
6482 gcond *cond_stmt = as_a <gcond *> (stmt);
6483 if (integer_zerop (val))
6484 gimple_cond_make_false (cond_stmt);
6485 else if (integer_onep (val))
6486 gimple_cond_make_true (cond_stmt);
6487 else
6488 gcc_unreachable ();
6491 return true;
6494 return false;
6497 /* Callback for substitute_and_fold folding the stmt at *SI. */
6499 bool
6500 vrp_folder::fold_stmt (gimple_stmt_iterator *si)
6502 if (fold_predicate_in (si))
6503 return true;
6505 return simplify_stmt_using_ranges (si);
6508 /* If OP has a value range with a single constant value return that,
6509 otherwise return NULL_TREE. This returns OP itself if OP is a
6510 constant.
6512 Implemented as a pure wrapper right now, but this will change. */
6514 tree
6515 vrp_folder::get_value (tree op)
6517 return op_with_constant_singleton_value_range (op);
6520 /* Return the LHS of any ASSERT_EXPR where OP appears as the first
6521 argument to the ASSERT_EXPR and in which the ASSERT_EXPR dominates
6522 BB. If no such ASSERT_EXPR is found, return OP. */
6524 static tree
6525 lhs_of_dominating_assert (tree op, basic_block bb, gimple *stmt)
6527 imm_use_iterator imm_iter;
6528 gimple *use_stmt;
6529 use_operand_p use_p;
6531 if (TREE_CODE (op) == SSA_NAME)
6533 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, op)
6535 use_stmt = USE_STMT (use_p);
6536 if (use_stmt != stmt
6537 && gimple_assign_single_p (use_stmt)
6538 && TREE_CODE (gimple_assign_rhs1 (use_stmt)) == ASSERT_EXPR
6539 && TREE_OPERAND (gimple_assign_rhs1 (use_stmt), 0) == op
6540 && dominated_by_p (CDI_DOMINATORS, bb, gimple_bb (use_stmt)))
6541 return gimple_assign_lhs (use_stmt);
6544 return op;
6547 /* A hack. */
6548 static class vr_values *x_vr_values;
6550 /* A trivial wrapper so that we can present the generic jump threading
6551 code with a simple API for simplifying statements. STMT is the
6552 statement we want to simplify, WITHIN_STMT provides the location
6553 for any overflow warnings. */
6555 static tree
6556 simplify_stmt_for_jump_threading (gimple *stmt, gimple *within_stmt,
6557 class avail_exprs_stack *avail_exprs_stack ATTRIBUTE_UNUSED,
6558 basic_block bb)
6560 /* First see if the conditional is in the hash table. */
6561 tree cached_lhs = avail_exprs_stack->lookup_avail_expr (stmt, false, true);
6562 if (cached_lhs && is_gimple_min_invariant (cached_lhs))
6563 return cached_lhs;
6565 vr_values *vr_values = x_vr_values;
6566 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
6568 tree op0 = gimple_cond_lhs (cond_stmt);
6569 op0 = lhs_of_dominating_assert (op0, bb, stmt);
6571 tree op1 = gimple_cond_rhs (cond_stmt);
6572 op1 = lhs_of_dominating_assert (op1, bb, stmt);
6574 return vr_values->vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
6575 op0, op1, within_stmt);
6578 /* We simplify a switch statement by trying to determine which case label
6579 will be taken. If we are successful then we return the corresponding
6580 CASE_LABEL_EXPR. */
6581 if (gswitch *switch_stmt = dyn_cast <gswitch *> (stmt))
6583 tree op = gimple_switch_index (switch_stmt);
6584 if (TREE_CODE (op) != SSA_NAME)
6585 return NULL_TREE;
6587 op = lhs_of_dominating_assert (op, bb, stmt);
6589 value_range *vr = vr_values->get_value_range (op);
6590 if ((vr->type != VR_RANGE && vr->type != VR_ANTI_RANGE)
6591 || symbolic_range_p (vr))
6592 return NULL_TREE;
6594 if (vr->type == VR_RANGE)
6596 size_t i, j;
6597 /* Get the range of labels that contain a part of the operand's
6598 value range. */
6599 find_case_label_range (switch_stmt, vr->min, vr->max, &i, &j);
6601 /* Is there only one such label? */
6602 if (i == j)
6604 tree label = gimple_switch_label (switch_stmt, i);
6606 /* The i'th label will be taken only if the value range of the
6607 operand is entirely within the bounds of this label. */
6608 if (CASE_HIGH (label) != NULL_TREE
6609 ? (tree_int_cst_compare (CASE_LOW (label), vr->min) <= 0
6610 && tree_int_cst_compare (CASE_HIGH (label), vr->max) >= 0)
6611 : (tree_int_cst_equal (CASE_LOW (label), vr->min)
6612 && tree_int_cst_equal (vr->min, vr->max)))
6613 return label;
6616 /* If there are no such labels then the default label will be
6617 taken. */
6618 if (i > j)
6619 return gimple_switch_label (switch_stmt, 0);
6622 if (vr->type == VR_ANTI_RANGE)
6624 unsigned n = gimple_switch_num_labels (switch_stmt);
6625 tree min_label = gimple_switch_label (switch_stmt, 1);
6626 tree max_label = gimple_switch_label (switch_stmt, n - 1);
6628 /* The default label will be taken only if the anti-range of the
6629 operand is entirely outside the bounds of all the (non-default)
6630 case labels. */
6631 if (tree_int_cst_compare (vr->min, CASE_LOW (min_label)) <= 0
6632 && (CASE_HIGH (max_label) != NULL_TREE
6633 ? tree_int_cst_compare (vr->max, CASE_HIGH (max_label)) >= 0
6634 : tree_int_cst_compare (vr->max, CASE_LOW (max_label)) >= 0))
6635 return gimple_switch_label (switch_stmt, 0);
6638 return NULL_TREE;
6641 if (gassign *assign_stmt = dyn_cast <gassign *> (stmt))
6643 tree lhs = gimple_assign_lhs (assign_stmt);
6644 if (TREE_CODE (lhs) == SSA_NAME
6645 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
6646 || POINTER_TYPE_P (TREE_TYPE (lhs)))
6647 && stmt_interesting_for_vrp (stmt))
6649 edge dummy_e;
6650 tree dummy_tree;
6651 value_range new_vr = VR_INITIALIZER;
6652 vr_values->extract_range_from_stmt (stmt, &dummy_e,
6653 &dummy_tree, &new_vr);
6654 if (range_int_cst_singleton_p (&new_vr))
6655 return new_vr.min;
6659 return NULL_TREE;
6662 class vrp_dom_walker : public dom_walker
6664 public:
6665 vrp_dom_walker (cdi_direction direction,
6666 class const_and_copies *const_and_copies,
6667 class avail_exprs_stack *avail_exprs_stack)
6668 : dom_walker (direction, REACHABLE_BLOCKS),
6669 m_const_and_copies (const_and_copies),
6670 m_avail_exprs_stack (avail_exprs_stack),
6671 m_dummy_cond (NULL) {}
6673 virtual edge before_dom_children (basic_block);
6674 virtual void after_dom_children (basic_block);
6676 class vr_values *vr_values;
6678 private:
6679 class const_and_copies *m_const_and_copies;
6680 class avail_exprs_stack *m_avail_exprs_stack;
6682 gcond *m_dummy_cond;
6686 /* Called before processing dominator children of BB. We want to look
6687 at ASSERT_EXPRs and record information from them in the appropriate
6688 tables.
6690 We could look at other statements here. It's not seen as likely
6691 to significantly increase the jump threads we discover. */
6693 edge
6694 vrp_dom_walker::before_dom_children (basic_block bb)
6696 gimple_stmt_iterator gsi;
6698 m_avail_exprs_stack->push_marker ();
6699 m_const_and_copies->push_marker ();
6700 for (gsi = gsi_start_nondebug_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
6702 gimple *stmt = gsi_stmt (gsi);
6703 if (gimple_assign_single_p (stmt)
6704 && TREE_CODE (gimple_assign_rhs1 (stmt)) == ASSERT_EXPR)
6706 tree rhs1 = gimple_assign_rhs1 (stmt);
6707 tree cond = TREE_OPERAND (rhs1, 1);
6708 tree inverted = invert_truthvalue (cond);
6709 vec<cond_equivalence> p;
6710 p.create (3);
6711 record_conditions (&p, cond, inverted);
6712 for (unsigned int i = 0; i < p.length (); i++)
6713 m_avail_exprs_stack->record_cond (&p[i]);
6715 tree lhs = gimple_assign_lhs (stmt);
6716 m_const_and_copies->record_const_or_copy (lhs,
6717 TREE_OPERAND (rhs1, 0));
6718 p.release ();
6719 continue;
6721 break;
6723 return NULL;
6726 /* Called after processing dominator children of BB. This is where we
6727 actually call into the threader. */
6728 void
6729 vrp_dom_walker::after_dom_children (basic_block bb)
6731 if (!m_dummy_cond)
6732 m_dummy_cond = gimple_build_cond (NE_EXPR,
6733 integer_zero_node, integer_zero_node,
6734 NULL, NULL);
6736 x_vr_values = vr_values;
6737 thread_outgoing_edges (bb, m_dummy_cond, m_const_and_copies,
6738 m_avail_exprs_stack, NULL,
6739 simplify_stmt_for_jump_threading);
6740 x_vr_values = NULL;
6742 m_avail_exprs_stack->pop_to_marker ();
6743 m_const_and_copies->pop_to_marker ();
6746 /* Blocks which have more than one predecessor and more than
6747 one successor present jump threading opportunities, i.e.,
6748 when the block is reached from a specific predecessor, we
6749 may be able to determine which of the outgoing edges will
6750 be traversed. When this optimization applies, we are able
6751 to avoid conditionals at runtime and we may expose secondary
6752 optimization opportunities.
6754 This routine is effectively a driver for the generic jump
6755 threading code. It basically just presents the generic code
6756 with edges that may be suitable for jump threading.
6758 Unlike DOM, we do not iterate VRP if jump threading was successful.
6759 While iterating may expose new opportunities for VRP, it is expected
6760 those opportunities would be very limited and the compile time cost
6761 to expose those opportunities would be significant.
6763 As jump threading opportunities are discovered, they are registered
6764 for later realization. */
6766 static void
6767 identify_jump_threads (class vr_values *vr_values)
6769 int i;
6770 edge e;
6772 /* Ugh. When substituting values earlier in this pass we can
6773 wipe the dominance information. So rebuild the dominator
6774 information as we need it within the jump threading code. */
6775 calculate_dominance_info (CDI_DOMINATORS);
6777 /* We do not allow VRP information to be used for jump threading
6778 across a back edge in the CFG. Otherwise it becomes too
6779 difficult to avoid eliminating loop exit tests. Of course
6780 EDGE_DFS_BACK is not accurate at this time so we have to
6781 recompute it. */
6782 mark_dfs_back_edges ();
6784 /* Do not thread across edges we are about to remove. Just marking
6785 them as EDGE_IGNORE will do. */
6786 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
6787 e->flags |= EDGE_IGNORE;
6789 /* Allocate our unwinder stack to unwind any temporary equivalences
6790 that might be recorded. */
6791 const_and_copies *equiv_stack = new const_and_copies ();
6793 hash_table<expr_elt_hasher> *avail_exprs
6794 = new hash_table<expr_elt_hasher> (1024);
6795 avail_exprs_stack *avail_exprs_stack
6796 = new class avail_exprs_stack (avail_exprs);
6798 vrp_dom_walker walker (CDI_DOMINATORS, equiv_stack, avail_exprs_stack);
6799 walker.vr_values = vr_values;
6800 walker.walk (cfun->cfg->x_entry_block_ptr);
6802 /* Clear EDGE_IGNORE. */
6803 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
6804 e->flags &= ~EDGE_IGNORE;
6806 /* We do not actually update the CFG or SSA graphs at this point as
6807 ASSERT_EXPRs are still in the IL and cfg cleanup code does not yet
6808 handle ASSERT_EXPRs gracefully. */
6809 delete equiv_stack;
6810 delete avail_exprs;
6811 delete avail_exprs_stack;
6814 /* Traverse all the blocks folding conditionals with known ranges. */
6816 void
6817 vrp_prop::vrp_finalize (bool warn_array_bounds_p)
6819 size_t i;
6821 /* We have completed propagating through the lattice. */
6822 vr_values.set_lattice_propagation_complete ();
6824 if (dump_file)
6826 fprintf (dump_file, "\nValue ranges after VRP:\n\n");
6827 vr_values.dump_all_value_ranges (dump_file);
6828 fprintf (dump_file, "\n");
6831 /* Set value range to non pointer SSA_NAMEs. */
6832 for (i = 0; i < num_ssa_names; i++)
6834 tree name = ssa_name (i);
6835 if (!name)
6836 continue;
6838 value_range *vr = get_value_range (name);
6839 if (!name
6840 || (vr->type == VR_VARYING)
6841 || (vr->type == VR_UNDEFINED)
6842 || (TREE_CODE (vr->min) != INTEGER_CST)
6843 || (TREE_CODE (vr->max) != INTEGER_CST))
6844 continue;
6846 if (POINTER_TYPE_P (TREE_TYPE (name))
6847 && ((vr->type == VR_RANGE
6848 && range_includes_zero_p (vr->min, vr->max) == 0)
6849 || (vr->type == VR_ANTI_RANGE
6850 && range_includes_zero_p (vr->min, vr->max) == 1)))
6851 set_ptr_nonnull (name);
6852 else if (!POINTER_TYPE_P (TREE_TYPE (name)))
6853 set_range_info (name, vr->type,
6854 wi::to_wide (vr->min),
6855 wi::to_wide (vr->max));
6858 /* If we're checking array refs, we want to merge information on
6859 the executability of each edge between vrp_folder and the
6860 check_array_bounds_dom_walker: each can clear the
6861 EDGE_EXECUTABLE flag on edges, in different ways.
6863 Hence, if we're going to call check_all_array_refs, set
6864 the flag on every edge now, rather than in
6865 check_array_bounds_dom_walker's ctor; vrp_folder may clear
6866 it from some edges. */
6867 if (warn_array_bounds && warn_array_bounds_p)
6868 set_all_edges_as_executable (cfun);
6870 class vrp_folder vrp_folder;
6871 vrp_folder.vr_values = &vr_values;
6872 vrp_folder.substitute_and_fold ();
6874 if (warn_array_bounds && warn_array_bounds_p)
6875 check_all_array_refs ();
6878 /* Main entry point to VRP (Value Range Propagation). This pass is
6879 loosely based on J. R. C. Patterson, ``Accurate Static Branch
6880 Prediction by Value Range Propagation,'' in SIGPLAN Conference on
6881 Programming Language Design and Implementation, pp. 67-78, 1995.
6882 Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
6884 This is essentially an SSA-CCP pass modified to deal with ranges
6885 instead of constants.
6887 While propagating ranges, we may find that two or more SSA name
6888 have equivalent, though distinct ranges. For instance,
6890 1 x_9 = p_3->a;
6891 2 p_4 = ASSERT_EXPR <p_3, p_3 != 0>
6892 3 if (p_4 == q_2)
6893 4 p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
6894 5 endif
6895 6 if (q_2)
6897 In the code above, pointer p_5 has range [q_2, q_2], but from the
6898 code we can also determine that p_5 cannot be NULL and, if q_2 had
6899 a non-varying range, p_5's range should also be compatible with it.
6901 These equivalences are created by two expressions: ASSERT_EXPR and
6902 copy operations. Since p_5 is an assertion on p_4, and p_4 was the
6903 result of another assertion, then we can use the fact that p_5 and
6904 p_4 are equivalent when evaluating p_5's range.
6906 Together with value ranges, we also propagate these equivalences
6907 between names so that we can take advantage of information from
6908 multiple ranges when doing final replacement. Note that this
6909 equivalency relation is transitive but not symmetric.
6911 In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
6912 cannot assert that q_2 is equivalent to p_5 because q_2 may be used
6913 in contexts where that assertion does not hold (e.g., in line 6).
6915 TODO, the main difference between this pass and Patterson's is that
6916 we do not propagate edge probabilities. We only compute whether
6917 edges can be taken or not. That is, instead of having a spectrum
6918 of jump probabilities between 0 and 1, we only deal with 0, 1 and
6919 DON'T KNOW. In the future, it may be worthwhile to propagate
6920 probabilities to aid branch prediction. */
6922 static unsigned int
6923 execute_vrp (bool warn_array_bounds_p)
6925 int i;
6926 edge e;
6927 switch_update *su;
6929 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
6930 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
6931 scev_initialize ();
6933 /* ??? This ends up using stale EDGE_DFS_BACK for liveness computation.
6934 Inserting assertions may split edges which will invalidate
6935 EDGE_DFS_BACK. */
6936 insert_range_assertions ();
6938 to_remove_edges.create (10);
6939 to_update_switch_stmts.create (5);
6940 threadedge_initialize_values ();
6942 /* For visiting PHI nodes we need EDGE_DFS_BACK computed. */
6943 mark_dfs_back_edges ();
6945 class vrp_prop vrp_prop;
6946 vrp_prop.vrp_initialize ();
6947 vrp_prop.ssa_propagate ();
6948 vrp_prop.vrp_finalize (warn_array_bounds_p);
6950 /* We must identify jump threading opportunities before we release
6951 the datastructures built by VRP. */
6952 identify_jump_threads (&vrp_prop.vr_values);
6954 /* A comparison of an SSA_NAME against a constant where the SSA_NAME
6955 was set by a type conversion can often be rewritten to use the
6956 RHS of the type conversion.
6958 However, doing so inhibits jump threading through the comparison.
6959 So that transformation is not performed until after jump threading
6960 is complete. */
6961 basic_block bb;
6962 FOR_EACH_BB_FN (bb, cfun)
6964 gimple *last = last_stmt (bb);
6965 if (last && gimple_code (last) == GIMPLE_COND)
6966 vrp_prop.vr_values.simplify_cond_using_ranges_2 (as_a <gcond *> (last));
6969 free_numbers_of_iterations_estimates (cfun);
6971 /* ASSERT_EXPRs must be removed before finalizing jump threads
6972 as finalizing jump threads calls the CFG cleanup code which
6973 does not properly handle ASSERT_EXPRs. */
6974 remove_range_assertions ();
6976 /* If we exposed any new variables, go ahead and put them into
6977 SSA form now, before we handle jump threading. This simplifies
6978 interactions between rewriting of _DECL nodes into SSA form
6979 and rewriting SSA_NAME nodes into SSA form after block
6980 duplication and CFG manipulation. */
6981 update_ssa (TODO_update_ssa);
6983 /* We identified all the jump threading opportunities earlier, but could
6984 not transform the CFG at that time. This routine transforms the
6985 CFG and arranges for the dominator tree to be rebuilt if necessary.
6987 Note the SSA graph update will occur during the normal TODO
6988 processing by the pass manager. */
6989 thread_through_all_blocks (false);
6991 /* Remove dead edges from SWITCH_EXPR optimization. This leaves the
6992 CFG in a broken state and requires a cfg_cleanup run. */
6993 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
6994 remove_edge (e);
6995 /* Update SWITCH_EXPR case label vector. */
6996 FOR_EACH_VEC_ELT (to_update_switch_stmts, i, su)
6998 size_t j;
6999 size_t n = TREE_VEC_LENGTH (su->vec);
7000 tree label;
7001 gimple_switch_set_num_labels (su->stmt, n);
7002 for (j = 0; j < n; j++)
7003 gimple_switch_set_label (su->stmt, j, TREE_VEC_ELT (su->vec, j));
7004 /* As we may have replaced the default label with a regular one
7005 make sure to make it a real default label again. This ensures
7006 optimal expansion. */
7007 label = gimple_switch_label (su->stmt, 0);
7008 CASE_LOW (label) = NULL_TREE;
7009 CASE_HIGH (label) = NULL_TREE;
7012 if (to_remove_edges.length () > 0)
7014 free_dominance_info (CDI_DOMINATORS);
7015 loops_state_set (LOOPS_NEED_FIXUP);
7018 to_remove_edges.release ();
7019 to_update_switch_stmts.release ();
7020 threadedge_finalize_values ();
7022 scev_finalize ();
7023 loop_optimizer_finalize ();
7024 return 0;
7027 namespace {
7029 const pass_data pass_data_vrp =
7031 GIMPLE_PASS, /* type */
7032 "vrp", /* name */
7033 OPTGROUP_NONE, /* optinfo_flags */
7034 TV_TREE_VRP, /* tv_id */
7035 PROP_ssa, /* properties_required */
7036 0, /* properties_provided */
7037 0, /* properties_destroyed */
7038 0, /* todo_flags_start */
7039 ( TODO_cleanup_cfg | TODO_update_ssa ), /* todo_flags_finish */
7042 class pass_vrp : public gimple_opt_pass
7044 public:
7045 pass_vrp (gcc::context *ctxt)
7046 : gimple_opt_pass (pass_data_vrp, ctxt), warn_array_bounds_p (false)
7049 /* opt_pass methods: */
7050 opt_pass * clone () { return new pass_vrp (m_ctxt); }
7051 void set_pass_param (unsigned int n, bool param)
7053 gcc_assert (n == 0);
7054 warn_array_bounds_p = param;
7056 virtual bool gate (function *) { return flag_tree_vrp != 0; }
7057 virtual unsigned int execute (function *)
7058 { return execute_vrp (warn_array_bounds_p); }
7060 private:
7061 bool warn_array_bounds_p;
7062 }; // class pass_vrp
7064 } // anon namespace
7066 gimple_opt_pass *
7067 make_pass_vrp (gcc::context *ctxt)
7069 return new pass_vrp (ctxt);
7073 /* Worker for determine_value_range. */
7075 static void
7076 determine_value_range_1 (value_range *vr, tree expr)
7078 if (BINARY_CLASS_P (expr))
7080 value_range vr0 = VR_INITIALIZER, vr1 = VR_INITIALIZER;
7081 determine_value_range_1 (&vr0, TREE_OPERAND (expr, 0));
7082 determine_value_range_1 (&vr1, TREE_OPERAND (expr, 1));
7083 extract_range_from_binary_expr_1 (vr, TREE_CODE (expr), TREE_TYPE (expr),
7084 &vr0, &vr1);
7086 else if (UNARY_CLASS_P (expr))
7088 value_range vr0 = VR_INITIALIZER;
7089 determine_value_range_1 (&vr0, TREE_OPERAND (expr, 0));
7090 extract_range_from_unary_expr (vr, TREE_CODE (expr), TREE_TYPE (expr),
7091 &vr0, TREE_TYPE (TREE_OPERAND (expr, 0)));
7093 else if (TREE_CODE (expr) == INTEGER_CST)
7094 set_value_range_to_value (vr, expr, NULL);
7095 else
7097 value_range_type kind;
7098 wide_int min, max;
7099 /* For SSA names try to extract range info computed by VRP. Otherwise
7100 fall back to varying. */
7101 if (TREE_CODE (expr) == SSA_NAME
7102 && INTEGRAL_TYPE_P (TREE_TYPE (expr))
7103 && (kind = get_range_info (expr, &min, &max)) != VR_VARYING)
7104 set_value_range (vr, kind, wide_int_to_tree (TREE_TYPE (expr), min),
7105 wide_int_to_tree (TREE_TYPE (expr), max), NULL);
7106 else
7107 set_value_range_to_varying (vr);
7111 /* Compute a value-range for EXPR and set it in *MIN and *MAX. Return
7112 the determined range type. */
7114 value_range_type
7115 determine_value_range (tree expr, wide_int *min, wide_int *max)
7117 value_range vr = VR_INITIALIZER;
7118 determine_value_range_1 (&vr, expr);
7119 if ((vr.type == VR_RANGE
7120 || vr.type == VR_ANTI_RANGE)
7121 && !symbolic_range_p (&vr))
7123 *min = wi::to_wide (vr.min);
7124 *max = wi::to_wide (vr.max);
7125 return vr.type;
7128 return VR_VARYING;