[42/46] Add vec_info::replace_stmt
[official-gcc.git] / gcc / tree-vrp.c
blob7ab8898b4534a1ef003a8d0ff1e98c6752deadd3
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 wide_int_binop that adjusts for overflow.
961 Return true if we can compute the result; i.e. if the operation
962 doesn't overflow or if the overflow is undefined. In the latter
963 case (if the operation overflows and overflow is undefined), then
964 adjust the result to be -INF or +INF depending on CODE, VAL1 and
965 VAL2. Return the value in *RES.
967 Return false for division by zero, for which the result is
968 indeterminate. */
970 static bool
971 wide_int_binop_overflow (wide_int &res,
972 enum tree_code code,
973 const wide_int &w0, const wide_int &w1,
974 signop sign, bool overflow_undefined)
976 wi::overflow_type overflow;
977 if (!wide_int_binop (res, code, w0, w1, sign, &overflow))
978 return false;
980 /* If the operation overflowed return -INF or +INF depending on the
981 operation and the combination of signs of the operands. */
982 if (overflow && overflow_undefined)
984 switch (code)
986 case MULT_EXPR:
987 /* For multiplication, the sign of the overflow is given
988 by the comparison of the signs of the operands. */
989 if (sign == UNSIGNED || w0.sign_mask () == w1.sign_mask ())
990 res = wi::max_value (w0.get_precision (), sign);
991 else
992 res = wi::min_value (w0.get_precision (), sign);
993 return true;
995 case TRUNC_DIV_EXPR:
996 case FLOOR_DIV_EXPR:
997 case CEIL_DIV_EXPR:
998 case EXACT_DIV_EXPR:
999 case ROUND_DIV_EXPR:
1000 /* For division, the only case is -INF / -1 = +INF. */
1001 res = wi::max_value (w0.get_precision (), sign);
1002 return true;
1004 default:
1005 gcc_unreachable ();
1008 return !overflow;
1011 /* For range [LB, UB] compute two wide_int bitmasks. In *MAY_BE_NONZERO
1012 bitmask, if some bit is unset, it means for all numbers in the range
1013 the bit is 0, otherwise it might be 0 or 1. In *MUST_BE_NONZERO
1014 bitmask, if some bit is set, it means for all numbers in the range
1015 the bit is 1, otherwise it might be 0 or 1. */
1017 void
1018 zero_nonzero_bits_from_bounds (signop sign,
1019 const wide_int &lb, const wide_int &ub,
1020 wide_int *may_be_nonzero,
1021 wide_int *must_be_nonzero)
1023 *may_be_nonzero = wi::minus_one (lb.get_precision ());
1024 *must_be_nonzero = wi::zero (lb.get_precision ());
1026 if (wi::eq_p (lb, ub))
1028 *may_be_nonzero = lb;
1029 *must_be_nonzero = *may_be_nonzero;
1031 else if (wi::ge_p (lb, 0, sign) || wi::lt_p (ub, 0, sign))
1033 wide_int xor_mask = lb ^ ub;
1034 *may_be_nonzero = lb | ub;
1035 *must_be_nonzero = lb & ub;
1036 if (xor_mask != 0)
1038 wide_int mask = wi::mask (wi::floor_log2 (xor_mask), false,
1039 may_be_nonzero->get_precision ());
1040 *may_be_nonzero = *may_be_nonzero | mask;
1041 *must_be_nonzero = wi::bit_and_not (*must_be_nonzero, mask);
1046 /* Like zero_nonzero_bits_from_bounds, but use the range in value_range VR. */
1048 bool
1049 zero_nonzero_bits_from_vr (const tree expr_type,
1050 value_range *vr,
1051 wide_int *may_be_nonzero,
1052 wide_int *must_be_nonzero)
1054 if (!range_int_cst_p (vr))
1056 *may_be_nonzero = wi::minus_one (TYPE_PRECISION (expr_type));
1057 *must_be_nonzero = wi::zero (TYPE_PRECISION (expr_type));
1058 return false;
1061 zero_nonzero_bits_from_bounds (TYPE_SIGN (expr_type),
1062 wi::to_wide (vr->min), wi::to_wide (vr->max),
1063 may_be_nonzero, must_be_nonzero);
1064 return true;
1067 /* Create two value-ranges in *VR0 and *VR1 from the anti-range *AR
1068 so that *VR0 U *VR1 == *AR. Returns true if that is possible,
1069 false otherwise. If *AR can be represented with a single range
1070 *VR1 will be VR_UNDEFINED. */
1072 static bool
1073 ranges_from_anti_range (value_range *ar,
1074 value_range *vr0, value_range *vr1)
1076 tree type = TREE_TYPE (ar->min);
1078 vr0->type = VR_UNDEFINED;
1079 vr1->type = VR_UNDEFINED;
1081 if (ar->type != VR_ANTI_RANGE
1082 || TREE_CODE (ar->min) != INTEGER_CST
1083 || TREE_CODE (ar->max) != INTEGER_CST
1084 || !vrp_val_min (type)
1085 || !vrp_val_max (type))
1086 return false;
1088 if (!vrp_val_is_min (ar->min))
1090 vr0->type = VR_RANGE;
1091 vr0->min = vrp_val_min (type);
1092 vr0->max = wide_int_to_tree (type, wi::to_wide (ar->min) - 1);
1094 if (!vrp_val_is_max (ar->max))
1096 vr1->type = VR_RANGE;
1097 vr1->min = wide_int_to_tree (type, wi::to_wide (ar->max) + 1);
1098 vr1->max = vrp_val_max (type);
1100 if (vr0->type == VR_UNDEFINED)
1102 *vr0 = *vr1;
1103 vr1->type = VR_UNDEFINED;
1106 return vr0->type != VR_UNDEFINED;
1109 /* Order 2 sets of wide int ranges (w0/w1, w2/w3) and set MIN/MAX
1110 accordingly. */
1112 static void
1113 wide_int_range_min_max (wide_int &min, wide_int &max,
1114 wide_int &w0, wide_int &w1, wide_int &w2, wide_int &w3,
1115 signop sign)
1117 /* Order pairs w0,w1 and w2,w3. */
1118 if (wi::gt_p (w0, w1, sign))
1119 std::swap (w0, w1);
1120 if (wi::gt_p (w2, w3, sign))
1121 std::swap (w2, w3);
1123 /* Choose min and max from the ordered pairs. */
1124 min = wi::min (w0, w2, sign);
1125 max = wi::max (w1, w3, sign);
1128 /* Calculate the cross product of two sets of ranges (VR0 and VR1) and
1129 store the result in [RES_LB, RES_UB].
1131 CODE is the operation to perform with sign SIGN.
1133 OVERFLOW_UNDEFINED is set if overflow is undefined for the operation type.
1135 Return TRUE if we were able to calculate the cross product. */
1137 bool
1138 wide_int_range_cross_product (wide_int &res_lb, wide_int &res_ub,
1139 enum tree_code code, signop sign,
1140 const wide_int &vr0_lb, const wide_int &vr0_ub,
1141 const wide_int &vr1_lb, const wide_int &vr1_ub,
1142 bool overflow_undefined)
1144 wide_int cp1, cp2, cp3, cp4;
1146 /* Compute the 4 cross operations, bailing if we get an overflow we
1147 can't handle. */
1149 if (!wide_int_binop_overflow (cp1, code, vr0_lb, vr1_lb, sign,
1150 overflow_undefined))
1151 return false;
1153 if (wi::eq_p (vr0_lb, vr0_ub))
1154 cp3 = cp1;
1155 else if (!wide_int_binop_overflow (cp3, code, vr0_ub, vr1_lb, sign,
1156 overflow_undefined))
1157 return false;
1159 if (wi::eq_p (vr1_lb, vr1_ub))
1160 cp2 = cp1;
1161 else if (!wide_int_binop_overflow (cp2, code, vr0_lb, vr1_ub, sign,
1162 overflow_undefined))
1163 return false;
1165 if (wi::eq_p (vr0_lb, vr0_ub))
1166 cp4 = cp2;
1167 else if (!wide_int_binop_overflow (cp4, code, vr0_ub, vr1_ub, sign,
1168 overflow_undefined))
1169 return false;
1171 wide_int_range_min_max (res_lb, res_ub, cp1, cp2, cp3, cp4, sign);
1172 return true;
1175 /* Multiply two ranges when TYPE_OVERFLOW_WRAPS:
1177 [RES_LB, RES_UB] = [MIN0, MAX0] * [MIN1, MAX1]
1179 This is basically fancy code so we don't drop to varying with an
1180 unsigned [-3,-1]*[-3,-1]. */
1182 bool
1183 wide_int_range_mult_wrapping (wide_int &res_lb,
1184 wide_int &res_ub,
1185 signop sign,
1186 unsigned prec,
1187 const wide_int &min0_,
1188 const wide_int &max0_,
1189 const wide_int &min1_,
1190 const wide_int &max1_)
1192 /* This test requires 2*prec bits if both operands are signed and
1193 2*prec + 2 bits if either is not. Therefore, extend the values
1194 using the sign of the result to PREC2. From here on out,
1195 everthing is just signed math no matter what the input types
1196 were. */
1197 widest2_int min0 = widest2_int::from (min0_, sign);
1198 widest2_int max0 = widest2_int::from (max0_, sign);
1199 widest2_int min1 = widest2_int::from (min1_, sign);
1200 widest2_int max1 = widest2_int::from (max1_, sign);
1201 widest2_int sizem1 = wi::mask <widest2_int> (prec, false);
1202 widest2_int size = sizem1 + 1;
1204 /* Canonicalize the intervals. */
1205 if (sign == UNSIGNED)
1207 if (wi::ltu_p (size, min0 + max0))
1209 min0 -= size;
1210 max0 -= size;
1213 if (wi::ltu_p (size, min1 + max1))
1215 min1 -= size;
1216 max1 -= size;
1220 widest2_int prod0 = min0 * min1;
1221 widest2_int prod1 = min0 * max1;
1222 widest2_int prod2 = max0 * min1;
1223 widest2_int prod3 = max0 * max1;
1225 /* Sort the 4 products so that min is in prod0 and max is in
1226 prod3. */
1227 /* min0min1 > max0max1 */
1228 if (prod0 > prod3)
1229 std::swap (prod0, prod3);
1231 /* min0max1 > max0min1 */
1232 if (prod1 > prod2)
1233 std::swap (prod1, prod2);
1235 if (prod0 > prod1)
1236 std::swap (prod0, prod1);
1238 if (prod2 > prod3)
1239 std::swap (prod2, prod3);
1241 /* diff = max - min. */
1242 prod2 = prod3 - prod0;
1243 if (wi::geu_p (prod2, sizem1))
1244 /* The range covers all values. */
1245 return false;
1247 res_lb = wide_int::from (prod0, prec, sign);
1248 res_ub = wide_int::from (prod3, prec, sign);
1249 return true;
1252 /* Helper to extract a value-range *VR for a multiplicative operation
1253 *VR0 CODE *VR1. */
1255 static void
1256 extract_range_from_multiplicative_op_1 (value_range *vr,
1257 enum tree_code code,
1258 value_range *vr0, value_range *vr1)
1260 /* Multiplications, divisions and shifts are a bit tricky to handle,
1261 depending on the mix of signs we have in the two ranges, we
1262 need to operate on different values to get the minimum and
1263 maximum values for the new range. One approach is to figure
1264 out all the variations of range combinations and do the
1265 operations.
1267 However, this involves several calls to compare_values and it
1268 is pretty convoluted. It's simpler to do the 4 operations
1269 (MIN0 OP MIN1, MIN0 OP MAX1, MAX0 OP MIN1 and MAX0 OP MAX0 OP
1270 MAX1) and then figure the smallest and largest values to form
1271 the new range. */
1272 gcc_assert (code == MULT_EXPR
1273 || code == TRUNC_DIV_EXPR
1274 || code == FLOOR_DIV_EXPR
1275 || code == CEIL_DIV_EXPR
1276 || code == EXACT_DIV_EXPR
1277 || code == ROUND_DIV_EXPR
1278 || code == RSHIFT_EXPR
1279 || code == LSHIFT_EXPR);
1280 gcc_assert (vr0->type == VR_RANGE
1281 && vr0->type == vr1->type);
1283 tree type = TREE_TYPE (vr0->min);
1284 wide_int res_lb, res_ub;
1285 wide_int vr0_lb = wi::to_wide (vr0->min);
1286 wide_int vr0_ub = wi::to_wide (vr0->max);
1287 wide_int vr1_lb = wi::to_wide (vr1->min);
1288 wide_int vr1_ub = wi::to_wide (vr1->max);
1289 bool overflow_undefined = TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (vr0->min));
1291 if (!wide_int_range_cross_product (res_lb, res_ub,
1292 code, TYPE_SIGN (type),
1293 vr0_lb, vr0_ub, vr1_lb, vr1_ub,
1294 overflow_undefined))
1296 set_value_range_to_varying (vr);
1297 return;
1299 set_value_range (vr, VR_RANGE,
1300 wide_int_to_tree (type, res_lb),
1301 wide_int_to_tree (type, res_ub), NULL);
1304 /* For op & or | attempt to optimize:
1306 [LB, UB] op Z
1307 into:
1308 [LB op Z, UB op Z]
1310 if Z is a constant which (for op | its bitwise not) has n
1311 consecutive least significant bits cleared followed by m 1
1312 consecutive bits set immediately above it and either
1313 m + n == precision, or (x >> (m + n)) == (y >> (m + n)).
1315 The least significant n bits of all the values in the range are
1316 cleared or set, the m bits above it are preserved and any bits
1317 above these are required to be the same for all values in the
1318 range.
1320 Return TRUE if the min and max can simply be folded. */
1322 bool
1323 range_easy_mask_min_max (tree_code code,
1324 const wide_int &lb, const wide_int &ub,
1325 const wide_int &mask)
1328 wide_int w = mask;
1329 int m = 0, n = 0;
1330 if (code == BIT_IOR_EXPR)
1331 w = ~w;
1332 if (wi::eq_p (w, 0))
1333 n = w.get_precision ();
1334 else
1336 n = wi::ctz (w);
1337 w = ~(w | wi::mask (n, false, w.get_precision ()));
1338 if (wi::eq_p (w, 0))
1339 m = w.get_precision () - n;
1340 else
1341 m = wi::ctz (w) - n;
1343 wide_int new_mask = wi::mask (m + n, true, w.get_precision ());
1344 if ((new_mask & lb) == (new_mask & ub))
1345 return true;
1347 return false;
1350 /* If BOUND will include a symbolic bound, adjust it accordingly,
1351 otherwise leave it as is.
1353 CODE is the original operation that combined the bounds (PLUS_EXPR
1354 or MINUS_EXPR).
1356 TYPE is the type of the original operation.
1358 SYM_OPn is the symbolic for OPn if it has a symbolic.
1360 NEG_OPn is TRUE if the OPn was negated. */
1362 static void
1363 adjust_symbolic_bound (tree &bound, enum tree_code code, tree type,
1364 tree sym_op0, tree sym_op1,
1365 bool neg_op0, bool neg_op1)
1367 bool minus_p = (code == MINUS_EXPR);
1368 /* If the result bound is constant, we're done; otherwise, build the
1369 symbolic lower bound. */
1370 if (sym_op0 == sym_op1)
1372 else if (sym_op0)
1373 bound = build_symbolic_expr (type, sym_op0,
1374 neg_op0, bound);
1375 else if (sym_op1)
1377 /* We may not negate if that might introduce
1378 undefined overflow. */
1379 if (!minus_p
1380 || neg_op1
1381 || TYPE_OVERFLOW_WRAPS (type))
1382 bound = build_symbolic_expr (type, sym_op1,
1383 neg_op1 ^ minus_p, bound);
1384 else
1385 bound = NULL_TREE;
1389 /* Combine OP1 and OP1, which are two parts of a bound, into one wide
1390 int bound according to CODE. CODE is the operation combining the
1391 bound (either a PLUS_EXPR or a MINUS_EXPR).
1393 TYPE is the type of the combine operation.
1395 WI is the wide int to store the result.
1397 OVF is -1 if an underflow occurred, +1 if an overflow occurred or 0
1398 if over/underflow occurred. */
1400 static void
1401 combine_bound (enum tree_code code, wide_int &wi, wi::overflow_type &ovf,
1402 tree type, tree op0, tree op1)
1404 bool minus_p = (code == MINUS_EXPR);
1405 const signop sgn = TYPE_SIGN (type);
1406 const unsigned int prec = TYPE_PRECISION (type);
1408 /* Combine the bounds, if any. */
1409 if (op0 && op1)
1411 if (minus_p)
1412 wi = wi::sub (wi::to_wide (op0), wi::to_wide (op1), sgn, &ovf);
1413 else
1414 wi = wi::add (wi::to_wide (op0), wi::to_wide (op1), sgn, &ovf);
1416 else if (op0)
1417 wi = wi::to_wide (op0);
1418 else if (op1)
1420 if (minus_p)
1421 wi = wi::neg (wi::to_wide (op1), &ovf);
1422 else
1423 wi = wi::to_wide (op1);
1425 else
1426 wi = wi::shwi (0, prec);
1429 /* Given a range in [WMIN, WMAX], adjust it for possible overflow and
1430 put the result in VR.
1432 TYPE is the type of the range.
1434 MIN_OVF and MAX_OVF indicate what type of overflow, if any,
1435 occurred while originally calculating WMIN or WMAX. -1 indicates
1436 underflow. +1 indicates overflow. 0 indicates neither. */
1438 static void
1439 set_value_range_with_overflow (value_range &vr,
1440 tree type,
1441 const wide_int &wmin, const wide_int &wmax,
1442 wi::overflow_type min_ovf,
1443 wi::overflow_type max_ovf)
1445 const signop sgn = TYPE_SIGN (type);
1446 const unsigned int prec = TYPE_PRECISION (type);
1447 vr.type = VR_RANGE;
1448 vr.equiv = NULL;
1449 if (TYPE_OVERFLOW_WRAPS (type))
1451 /* If overflow wraps, truncate the values and adjust the
1452 range kind and bounds appropriately. */
1453 wide_int tmin = wide_int::from (wmin, prec, sgn);
1454 wide_int tmax = wide_int::from (wmax, prec, sgn);
1455 if ((min_ovf != wi::OVF_NONE) == (max_ovf != wi::OVF_NONE))
1457 /* No overflow or both overflow or underflow. The
1458 range kind stays VR_RANGE. */
1459 vr.min = wide_int_to_tree (type, tmin);
1460 vr.max = wide_int_to_tree (type, tmax);
1462 else if ((min_ovf == wi::OVF_UNDERFLOW && max_ovf == wi::OVF_NONE)
1463 || (max_ovf == wi::OVF_OVERFLOW && min_ovf == wi::OVF_NONE))
1465 /* Min underflow or max overflow. The range kind
1466 changes to VR_ANTI_RANGE. */
1467 bool covers = false;
1468 wide_int tem = tmin;
1469 vr.type = VR_ANTI_RANGE;
1470 tmin = tmax + 1;
1471 if (wi::cmp (tmin, tmax, sgn) < 0)
1472 covers = true;
1473 tmax = tem - 1;
1474 if (wi::cmp (tmax, tem, sgn) > 0)
1475 covers = true;
1476 /* If the anti-range would cover nothing, drop to varying.
1477 Likewise if the anti-range bounds are outside of the
1478 types values. */
1479 if (covers || wi::cmp (tmin, tmax, sgn) > 0)
1481 set_value_range_to_varying (&vr);
1482 return;
1484 vr.min = wide_int_to_tree (type, tmin);
1485 vr.max = wide_int_to_tree (type, tmax);
1487 else
1489 /* Other underflow and/or overflow, drop to VR_VARYING. */
1490 set_value_range_to_varying (&vr);
1491 return;
1494 else
1496 /* If overflow does not wrap, saturate to the types min/max
1497 value. */
1498 wide_int type_min = wi::min_value (prec, sgn);
1499 wide_int type_max = wi::max_value (prec, sgn);
1500 if (min_ovf == wi::OVF_UNDERFLOW)
1501 vr.min = wide_int_to_tree (type, type_min);
1502 else if (min_ovf == wi::OVF_OVERFLOW)
1503 vr.min = wide_int_to_tree (type, type_max);
1504 else
1505 vr.min = wide_int_to_tree (type, wmin);
1507 if (max_ovf == wi::OVF_UNDERFLOW)
1508 vr.max = wide_int_to_tree (type, type_min);
1509 else if (max_ovf == wi::OVF_OVERFLOW)
1510 vr.max = wide_int_to_tree (type, type_max);
1511 else
1512 vr.max = wide_int_to_tree (type, wmax);
1516 /* Extract range information from a binary operation CODE based on
1517 the ranges of each of its operands *VR0 and *VR1 with resulting
1518 type EXPR_TYPE. The resulting range is stored in *VR. */
1520 void
1521 extract_range_from_binary_expr_1 (value_range *vr,
1522 enum tree_code code, tree expr_type,
1523 value_range *vr0_, value_range *vr1_)
1525 value_range vr0 = *vr0_, vr1 = *vr1_;
1526 value_range vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
1527 enum value_range_type type;
1528 tree min = NULL_TREE, max = NULL_TREE;
1529 int cmp;
1531 if (!INTEGRAL_TYPE_P (expr_type)
1532 && !POINTER_TYPE_P (expr_type))
1534 set_value_range_to_varying (vr);
1535 return;
1538 /* Not all binary expressions can be applied to ranges in a
1539 meaningful way. Handle only arithmetic operations. */
1540 if (code != PLUS_EXPR
1541 && code != MINUS_EXPR
1542 && code != POINTER_PLUS_EXPR
1543 && code != MULT_EXPR
1544 && code != TRUNC_DIV_EXPR
1545 && code != FLOOR_DIV_EXPR
1546 && code != CEIL_DIV_EXPR
1547 && code != EXACT_DIV_EXPR
1548 && code != ROUND_DIV_EXPR
1549 && code != TRUNC_MOD_EXPR
1550 && code != RSHIFT_EXPR
1551 && code != LSHIFT_EXPR
1552 && code != MIN_EXPR
1553 && code != MAX_EXPR
1554 && code != BIT_AND_EXPR
1555 && code != BIT_IOR_EXPR
1556 && code != BIT_XOR_EXPR)
1558 set_value_range_to_varying (vr);
1559 return;
1562 /* If both ranges are UNDEFINED, so is the result. */
1563 if (vr0.type == VR_UNDEFINED && vr1.type == VR_UNDEFINED)
1565 set_value_range_to_undefined (vr);
1566 return;
1568 /* If one of the ranges is UNDEFINED drop it to VARYING for the following
1569 code. At some point we may want to special-case operations that
1570 have UNDEFINED result for all or some value-ranges of the not UNDEFINED
1571 operand. */
1572 else if (vr0.type == VR_UNDEFINED)
1573 set_value_range_to_varying (&vr0);
1574 else if (vr1.type == VR_UNDEFINED)
1575 set_value_range_to_varying (&vr1);
1577 /* We get imprecise results from ranges_from_anti_range when
1578 code is EXACT_DIV_EXPR. We could mask out bits in the resulting
1579 range, but then we also need to hack up vrp_meet. It's just
1580 easier to special case when vr0 is ~[0,0] for EXACT_DIV_EXPR. */
1581 if (code == EXACT_DIV_EXPR
1582 && vr0.type == VR_ANTI_RANGE
1583 && vr0.min == vr0.max
1584 && integer_zerop (vr0.min))
1586 set_value_range_to_nonnull (vr, expr_type);
1587 return;
1590 /* Now canonicalize anti-ranges to ranges when they are not symbolic
1591 and express ~[] op X as ([]' op X) U ([]'' op X). */
1592 if (vr0.type == VR_ANTI_RANGE
1593 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
1595 extract_range_from_binary_expr_1 (vr, code, expr_type, &vrtem0, vr1_);
1596 if (vrtem1.type != VR_UNDEFINED)
1598 value_range vrres = VR_INITIALIZER;
1599 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
1600 &vrtem1, vr1_);
1601 vrp_meet (vr, &vrres);
1603 return;
1605 /* Likewise for X op ~[]. */
1606 if (vr1.type == VR_ANTI_RANGE
1607 && ranges_from_anti_range (&vr1, &vrtem0, &vrtem1))
1609 extract_range_from_binary_expr_1 (vr, code, expr_type, vr0_, &vrtem0);
1610 if (vrtem1.type != VR_UNDEFINED)
1612 value_range vrres = VR_INITIALIZER;
1613 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
1614 vr0_, &vrtem1);
1615 vrp_meet (vr, &vrres);
1617 return;
1620 /* The type of the resulting value range defaults to VR0.TYPE. */
1621 type = vr0.type;
1623 /* Refuse to operate on VARYING ranges, ranges of different kinds
1624 and symbolic ranges. As an exception, we allow BIT_{AND,IOR}
1625 because we may be able to derive a useful range even if one of
1626 the operands is VR_VARYING or symbolic range. Similarly for
1627 divisions, MIN/MAX and PLUS/MINUS.
1629 TODO, we may be able to derive anti-ranges in some cases. */
1630 if (code != BIT_AND_EXPR
1631 && code != BIT_IOR_EXPR
1632 && code != TRUNC_DIV_EXPR
1633 && code != FLOOR_DIV_EXPR
1634 && code != CEIL_DIV_EXPR
1635 && code != EXACT_DIV_EXPR
1636 && code != ROUND_DIV_EXPR
1637 && code != TRUNC_MOD_EXPR
1638 && code != MIN_EXPR
1639 && code != MAX_EXPR
1640 && code != PLUS_EXPR
1641 && code != MINUS_EXPR
1642 && code != RSHIFT_EXPR
1643 && (vr0.type == VR_VARYING
1644 || vr1.type == VR_VARYING
1645 || vr0.type != vr1.type
1646 || symbolic_range_p (&vr0)
1647 || symbolic_range_p (&vr1)))
1649 set_value_range_to_varying (vr);
1650 return;
1653 /* Now evaluate the expression to determine the new range. */
1654 if (POINTER_TYPE_P (expr_type))
1656 if (code == MIN_EXPR || code == MAX_EXPR)
1658 /* For MIN/MAX expressions with pointers, we only care about
1659 nullness, if both are non null, then the result is nonnull.
1660 If both are null, then the result is null. Otherwise they
1661 are varying. */
1662 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
1663 set_value_range_to_nonnull (vr, expr_type);
1664 else if (range_is_null (&vr0) && range_is_null (&vr1))
1665 set_value_range_to_null (vr, expr_type);
1666 else
1667 set_value_range_to_varying (vr);
1669 else if (code == POINTER_PLUS_EXPR)
1671 /* For pointer types, we are really only interested in asserting
1672 whether the expression evaluates to non-NULL. */
1673 if (range_is_nonnull (&vr0) || range_is_nonnull (&vr1))
1674 set_value_range_to_nonnull (vr, expr_type);
1675 else if (range_is_null (&vr0) && range_is_null (&vr1))
1676 set_value_range_to_null (vr, expr_type);
1677 else
1678 set_value_range_to_varying (vr);
1680 else if (code == BIT_AND_EXPR)
1682 /* For pointer types, we are really only interested in asserting
1683 whether the expression evaluates to non-NULL. */
1684 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
1685 set_value_range_to_nonnull (vr, expr_type);
1686 else if (range_is_null (&vr0) || range_is_null (&vr1))
1687 set_value_range_to_null (vr, expr_type);
1688 else
1689 set_value_range_to_varying (vr);
1691 else
1692 set_value_range_to_varying (vr);
1694 return;
1697 /* For integer ranges, apply the operation to each end of the
1698 range and see what we end up with. */
1699 if (code == PLUS_EXPR || code == MINUS_EXPR)
1701 const bool minus_p = (code == MINUS_EXPR);
1702 tree min_op0 = vr0.min;
1703 tree min_op1 = minus_p ? vr1.max : vr1.min;
1704 tree max_op0 = vr0.max;
1705 tree max_op1 = minus_p ? vr1.min : vr1.max;
1706 tree sym_min_op0 = NULL_TREE;
1707 tree sym_min_op1 = NULL_TREE;
1708 tree sym_max_op0 = NULL_TREE;
1709 tree sym_max_op1 = NULL_TREE;
1710 bool neg_min_op0, neg_min_op1, neg_max_op0, neg_max_op1;
1712 neg_min_op0 = neg_min_op1 = neg_max_op0 = neg_max_op1 = false;
1714 /* If we have a PLUS or MINUS with two VR_RANGEs, either constant or
1715 single-symbolic ranges, try to compute the precise resulting range,
1716 but only if we know that this resulting range will also be constant
1717 or single-symbolic. */
1718 if (vr0.type == VR_RANGE && vr1.type == VR_RANGE
1719 && (TREE_CODE (min_op0) == INTEGER_CST
1720 || (sym_min_op0
1721 = get_single_symbol (min_op0, &neg_min_op0, &min_op0)))
1722 && (TREE_CODE (min_op1) == INTEGER_CST
1723 || (sym_min_op1
1724 = get_single_symbol (min_op1, &neg_min_op1, &min_op1)))
1725 && (!(sym_min_op0 && sym_min_op1)
1726 || (sym_min_op0 == sym_min_op1
1727 && neg_min_op0 == (minus_p ? neg_min_op1 : !neg_min_op1)))
1728 && (TREE_CODE (max_op0) == INTEGER_CST
1729 || (sym_max_op0
1730 = get_single_symbol (max_op0, &neg_max_op0, &max_op0)))
1731 && (TREE_CODE (max_op1) == INTEGER_CST
1732 || (sym_max_op1
1733 = get_single_symbol (max_op1, &neg_max_op1, &max_op1)))
1734 && (!(sym_max_op0 && sym_max_op1)
1735 || (sym_max_op0 == sym_max_op1
1736 && neg_max_op0 == (minus_p ? neg_max_op1 : !neg_max_op1))))
1738 wide_int wmin, wmax;
1739 wi::overflow_type min_ovf = wi::OVF_NONE;
1740 wi::overflow_type max_ovf = wi::OVF_NONE;
1742 /* Build the bounds. */
1743 combine_bound (code, wmin, min_ovf, expr_type, min_op0, min_op1);
1744 combine_bound (code, wmax, max_ovf, expr_type, max_op0, max_op1);
1746 /* If we have overflow for the constant part and the resulting
1747 range will be symbolic, drop to VR_VARYING. */
1748 if (((bool)min_ovf && sym_min_op0 != sym_min_op1)
1749 || ((bool)max_ovf && sym_max_op0 != sym_max_op1))
1751 set_value_range_to_varying (vr);
1752 return;
1755 /* Adjust the range for possible overflow. */
1756 set_value_range_with_overflow (*vr, expr_type,
1757 wmin, wmax, min_ovf, max_ovf);
1758 if (vr->type == VR_VARYING)
1759 return;
1761 /* Build the symbolic bounds if needed. */
1762 adjust_symbolic_bound (vr->min, code, expr_type,
1763 sym_min_op0, sym_min_op1,
1764 neg_min_op0, neg_min_op1);
1765 adjust_symbolic_bound (vr->max, code, expr_type,
1766 sym_max_op0, sym_max_op1,
1767 neg_max_op0, neg_max_op1);
1768 /* ?? It would probably be cleaner to eliminate min/max/type
1769 entirely and hold these values in VR directly. */
1770 min = vr->min;
1771 max = vr->max;
1772 type = vr->type;
1774 else
1776 /* For other cases, for example if we have a PLUS_EXPR with two
1777 VR_ANTI_RANGEs, drop to VR_VARYING. It would take more effort
1778 to compute a precise range for such a case.
1779 ??? General even mixed range kind operations can be expressed
1780 by for example transforming ~[3, 5] + [1, 2] to range-only
1781 operations and a union primitive:
1782 [-INF, 2] + [1, 2] U [5, +INF] + [1, 2]
1783 [-INF+1, 4] U [6, +INF(OVF)]
1784 though usually the union is not exactly representable with
1785 a single range or anti-range as the above is
1786 [-INF+1, +INF(OVF)] intersected with ~[5, 5]
1787 but one could use a scheme similar to equivalences for this. */
1788 set_value_range_to_varying (vr);
1789 return;
1792 else if (code == MIN_EXPR
1793 || code == MAX_EXPR)
1795 if (vr0.type == VR_RANGE
1796 && !symbolic_range_p (&vr0))
1798 type = VR_RANGE;
1799 if (vr1.type == VR_RANGE
1800 && !symbolic_range_p (&vr1))
1802 /* For operations that make the resulting range directly
1803 proportional to the original ranges, apply the operation to
1804 the same end of each range. */
1805 min = int_const_binop (code, vr0.min, vr1.min);
1806 max = int_const_binop (code, vr0.max, vr1.max);
1808 else if (code == MIN_EXPR)
1810 min = vrp_val_min (expr_type);
1811 max = vr0.max;
1813 else if (code == MAX_EXPR)
1815 min = vr0.min;
1816 max = vrp_val_max (expr_type);
1819 else if (vr1.type == VR_RANGE
1820 && !symbolic_range_p (&vr1))
1822 type = VR_RANGE;
1823 if (code == MIN_EXPR)
1825 min = vrp_val_min (expr_type);
1826 max = vr1.max;
1828 else if (code == MAX_EXPR)
1830 min = vr1.min;
1831 max = vrp_val_max (expr_type);
1834 else
1836 set_value_range_to_varying (vr);
1837 return;
1840 else if (code == MULT_EXPR)
1842 if (!range_int_cst_p (&vr0)
1843 || !range_int_cst_p (&vr1))
1845 set_value_range_to_varying (vr);
1846 return;
1848 if (TYPE_OVERFLOW_WRAPS (expr_type))
1850 signop sign = TYPE_SIGN (expr_type);
1851 unsigned int prec = TYPE_PRECISION (expr_type);
1852 wide_int res_lb, res_ub;
1853 if (!wide_int_range_mult_wrapping (res_lb, res_ub,
1854 sign, prec,
1855 wi::to_wide (vr0.min),
1856 wi::to_wide (vr0.max),
1857 wi::to_wide (vr1.min),
1858 wi::to_wide (vr1.max)))
1860 set_value_range_to_varying (vr);
1861 return;
1863 min = wide_int_to_tree (expr_type, res_lb);
1864 max = wide_int_to_tree (expr_type, res_ub);
1865 set_and_canonicalize_value_range (vr, VR_RANGE, min, max, NULL);
1866 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 (vr0p && range_int_cst_p (vr0p)
2180 && range_easy_mask_min_max (code, wi::to_wide (vr0p->min),
2181 wi::to_wide (vr0p->max),
2182 wi::to_wide (vr1p->min)))
2184 min = int_const_binop (code, vr0p->min, vr1p->min);
2185 max = int_const_binop (code, vr0p->max, vr1p->min);
2189 type = VR_RANGE;
2190 if (min && max)
2191 /* Optimized above already. */;
2192 else if (code == BIT_AND_EXPR)
2194 min = wide_int_to_tree (expr_type,
2195 must_be_nonzero0 & must_be_nonzero1);
2196 wide_int wmax = may_be_nonzero0 & may_be_nonzero1;
2197 /* If both input ranges contain only negative values we can
2198 truncate the result range maximum to the minimum of the
2199 input range maxima. */
2200 if (int_cst_range0 && int_cst_range1
2201 && tree_int_cst_sgn (vr0.max) < 0
2202 && tree_int_cst_sgn (vr1.max) < 0)
2204 wmax = wi::min (wmax, wi::to_wide (vr0.max),
2205 TYPE_SIGN (expr_type));
2206 wmax = wi::min (wmax, wi::to_wide (vr1.max),
2207 TYPE_SIGN (expr_type));
2209 /* If either input range contains only non-negative values
2210 we can truncate the result range maximum to the respective
2211 maximum of the input range. */
2212 if (int_cst_range0 && tree_int_cst_sgn (vr0.min) >= 0)
2213 wmax = wi::min (wmax, wi::to_wide (vr0.max),
2214 TYPE_SIGN (expr_type));
2215 if (int_cst_range1 && tree_int_cst_sgn (vr1.min) >= 0)
2216 wmax = wi::min (wmax, wi::to_wide (vr1.max),
2217 TYPE_SIGN (expr_type));
2218 max = wide_int_to_tree (expr_type, wmax);
2219 cmp = compare_values (min, max);
2220 /* PR68217: In case of signed & sign-bit-CST should
2221 result in [-INF, 0] instead of [-INF, INF]. */
2222 if (cmp == -2 || cmp == 1)
2224 wide_int sign_bit
2225 = wi::set_bit_in_zero (TYPE_PRECISION (expr_type) - 1,
2226 TYPE_PRECISION (expr_type));
2227 if (!TYPE_UNSIGNED (expr_type)
2228 && ((int_cst_range0
2229 && value_range_constant_singleton (&vr0)
2230 && !wi::cmps (wi::to_wide (vr0.min), sign_bit))
2231 || (int_cst_range1
2232 && value_range_constant_singleton (&vr1)
2233 && !wi::cmps (wi::to_wide (vr1.min), sign_bit))))
2235 min = TYPE_MIN_VALUE (expr_type);
2236 max = build_int_cst (expr_type, 0);
2240 else if (code == BIT_IOR_EXPR)
2242 max = wide_int_to_tree (expr_type,
2243 may_be_nonzero0 | may_be_nonzero1);
2244 wide_int wmin = must_be_nonzero0 | must_be_nonzero1;
2245 /* If the input ranges contain only positive values we can
2246 truncate the minimum of the result range to the maximum
2247 of the input range minima. */
2248 if (int_cst_range0 && int_cst_range1
2249 && tree_int_cst_sgn (vr0.min) >= 0
2250 && tree_int_cst_sgn (vr1.min) >= 0)
2252 wmin = wi::max (wmin, wi::to_wide (vr0.min),
2253 TYPE_SIGN (expr_type));
2254 wmin = wi::max (wmin, wi::to_wide (vr1.min),
2255 TYPE_SIGN (expr_type));
2257 /* If either input range contains only negative values
2258 we can truncate the minimum of the result range to the
2259 respective minimum range. */
2260 if (int_cst_range0 && tree_int_cst_sgn (vr0.max) < 0)
2261 wmin = wi::max (wmin, wi::to_wide (vr0.min),
2262 TYPE_SIGN (expr_type));
2263 if (int_cst_range1 && tree_int_cst_sgn (vr1.max) < 0)
2264 wmin = wi::max (wmin, wi::to_wide (vr1.min),
2265 TYPE_SIGN (expr_type));
2266 min = wide_int_to_tree (expr_type, wmin);
2268 else if (code == BIT_XOR_EXPR)
2270 wide_int result_zero_bits = ((must_be_nonzero0 & must_be_nonzero1)
2271 | ~(may_be_nonzero0 | may_be_nonzero1));
2272 wide_int result_one_bits
2273 = (wi::bit_and_not (must_be_nonzero0, may_be_nonzero1)
2274 | wi::bit_and_not (must_be_nonzero1, may_be_nonzero0));
2275 max = wide_int_to_tree (expr_type, ~result_zero_bits);
2276 min = wide_int_to_tree (expr_type, result_one_bits);
2277 /* If the range has all positive or all negative values the
2278 result is better than VARYING. */
2279 if (tree_int_cst_sgn (min) < 0
2280 || tree_int_cst_sgn (max) >= 0)
2282 else
2283 max = min = NULL_TREE;
2286 else
2287 gcc_unreachable ();
2289 /* If either MIN or MAX overflowed, then set the resulting range to
2290 VARYING. */
2291 if (min == NULL_TREE
2292 || TREE_OVERFLOW_P (min)
2293 || max == NULL_TREE
2294 || TREE_OVERFLOW_P (max))
2296 set_value_range_to_varying (vr);
2297 return;
2300 /* We punt for [-INF, +INF].
2301 We learn nothing when we have INF on both sides.
2302 Note that we do accept [-INF, -INF] and [+INF, +INF]. */
2303 if (vrp_val_is_min (min) && vrp_val_is_max (max))
2305 set_value_range_to_varying (vr);
2306 return;
2309 cmp = compare_values (min, max);
2310 if (cmp == -2 || cmp == 1)
2312 /* If the new range has its limits swapped around (MIN > MAX),
2313 then the operation caused one of them to wrap around, mark
2314 the new range VARYING. */
2315 set_value_range_to_varying (vr);
2317 else
2318 set_value_range (vr, type, min, max, NULL);
2321 /* Calculates the absolute value of a range and puts the result in VR.
2322 VR0 is the input range. TYPE is the type of the resulting
2323 range. */
2325 static void
2326 extract_range_from_abs_expr (value_range &vr, tree type, value_range &vr0)
2328 /* Pass through vr0 in the easy cases. */
2329 if (TYPE_UNSIGNED (type)
2330 || value_range_nonnegative_p (&vr0))
2332 copy_value_range (&vr, &vr0);
2333 return;
2336 /* For the remaining varying or symbolic ranges we can't do anything
2337 useful. */
2338 if (vr0.type == VR_VARYING
2339 || symbolic_range_p (&vr0))
2341 set_value_range_to_varying (&vr);
2342 return;
2345 /* -TYPE_MIN_VALUE = TYPE_MIN_VALUE with flag_wrapv so we can't get a
2346 useful range. */
2347 if (!TYPE_OVERFLOW_UNDEFINED (type)
2348 && ((vr0.type == VR_RANGE
2349 && vrp_val_is_min (vr0.min))
2350 || (vr0.type == VR_ANTI_RANGE
2351 && !vrp_val_is_min (vr0.min))))
2353 set_value_range_to_varying (&vr);
2354 return;
2357 /* ABS_EXPR may flip the range around, if the original range
2358 included negative values. */
2359 tree min, max;
2360 if (!vrp_val_is_min (vr0.min))
2361 min = fold_unary_to_constant (ABS_EXPR, type, vr0.min);
2362 else
2363 min = TYPE_MAX_VALUE (type);
2365 if (!vrp_val_is_min (vr0.max))
2366 max = fold_unary_to_constant (ABS_EXPR, type, vr0.max);
2367 else
2368 max = TYPE_MAX_VALUE (type);
2370 int cmp = compare_values (min, max);
2371 gcc_assert (vr0.type != VR_ANTI_RANGE);
2373 /* If the range contains zero then we know that the minimum value in the
2374 range will be zero. */
2375 if (range_includes_zero_p (vr0.min, vr0.max) == 1)
2377 if (cmp == 1)
2378 max = min;
2379 min = build_int_cst (type, 0);
2381 else
2383 /* If the range was reversed, swap MIN and MAX. */
2384 if (cmp == 1)
2385 std::swap (min, max);
2388 cmp = compare_values (min, max);
2389 if (cmp == -2 || cmp == 1)
2391 /* If the new range has its limits swapped around (MIN > MAX),
2392 then the operation caused one of them to wrap around, mark
2393 the new range VARYING. */
2394 set_value_range_to_varying (&vr);
2396 else
2397 set_value_range (&vr, vr0.type, min, max, NULL);
2400 /* Extract range information from a unary operation CODE based on
2401 the range of its operand *VR0 with type OP0_TYPE with resulting type TYPE.
2402 The resulting range is stored in *VR. */
2404 void
2405 extract_range_from_unary_expr (value_range *vr,
2406 enum tree_code code, tree type,
2407 value_range *vr0_, tree op0_type)
2409 value_range vr0 = *vr0_, vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
2411 /* VRP only operates on integral and pointer types. */
2412 if (!(INTEGRAL_TYPE_P (op0_type)
2413 || POINTER_TYPE_P (op0_type))
2414 || !(INTEGRAL_TYPE_P (type)
2415 || POINTER_TYPE_P (type)))
2417 set_value_range_to_varying (vr);
2418 return;
2421 /* If VR0 is UNDEFINED, so is the result. */
2422 if (vr0.type == VR_UNDEFINED)
2424 set_value_range_to_undefined (vr);
2425 return;
2428 /* Handle operations that we express in terms of others. */
2429 if (code == PAREN_EXPR || code == OBJ_TYPE_REF)
2431 /* PAREN_EXPR and OBJ_TYPE_REF are simple copies. */
2432 copy_value_range (vr, &vr0);
2433 return;
2435 else if (code == NEGATE_EXPR)
2437 /* -X is simply 0 - X, so re-use existing code that also handles
2438 anti-ranges fine. */
2439 value_range zero = VR_INITIALIZER;
2440 set_value_range_to_value (&zero, build_int_cst (type, 0), NULL);
2441 extract_range_from_binary_expr_1 (vr, MINUS_EXPR, type, &zero, &vr0);
2442 return;
2444 else if (code == BIT_NOT_EXPR)
2446 /* ~X is simply -1 - X, so re-use existing code that also handles
2447 anti-ranges fine. */
2448 value_range minusone = VR_INITIALIZER;
2449 set_value_range_to_value (&minusone, build_int_cst (type, -1), NULL);
2450 extract_range_from_binary_expr_1 (vr, MINUS_EXPR,
2451 type, &minusone, &vr0);
2452 return;
2455 /* Now canonicalize anti-ranges to ranges when they are not symbolic
2456 and express op ~[] as (op []') U (op []''). */
2457 if (vr0.type == VR_ANTI_RANGE
2458 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
2460 extract_range_from_unary_expr (vr, code, type, &vrtem0, op0_type);
2461 if (vrtem1.type != VR_UNDEFINED)
2463 value_range vrres = VR_INITIALIZER;
2464 extract_range_from_unary_expr (&vrres, code, type,
2465 &vrtem1, op0_type);
2466 vrp_meet (vr, &vrres);
2468 return;
2471 if (CONVERT_EXPR_CODE_P (code))
2473 tree inner_type = op0_type;
2474 tree outer_type = type;
2476 /* If the expression evaluates to a pointer, we are only interested in
2477 determining if it evaluates to NULL [0, 0] or non-NULL (~[0, 0]). */
2478 if (POINTER_TYPE_P (type))
2480 if (range_is_nonnull (&vr0))
2481 set_value_range_to_nonnull (vr, type);
2482 else if (range_is_null (&vr0))
2483 set_value_range_to_null (vr, type);
2484 else
2485 set_value_range_to_varying (vr);
2486 return;
2489 /* If VR0 is varying and we increase the type precision, assume
2490 a full range for the following transformation. */
2491 if (vr0.type == VR_VARYING
2492 && INTEGRAL_TYPE_P (inner_type)
2493 && TYPE_PRECISION (inner_type) < TYPE_PRECISION (outer_type))
2495 vr0.type = VR_RANGE;
2496 vr0.min = TYPE_MIN_VALUE (inner_type);
2497 vr0.max = TYPE_MAX_VALUE (inner_type);
2500 /* If VR0 is a constant range or anti-range and the conversion is
2501 not truncating we can convert the min and max values and
2502 canonicalize the resulting range. Otherwise we can do the
2503 conversion if the size of the range is less than what the
2504 precision of the target type can represent and the range is
2505 not an anti-range. */
2506 if ((vr0.type == VR_RANGE
2507 || vr0.type == VR_ANTI_RANGE)
2508 && TREE_CODE (vr0.min) == INTEGER_CST
2509 && TREE_CODE (vr0.max) == INTEGER_CST
2510 && (TYPE_PRECISION (outer_type) >= TYPE_PRECISION (inner_type)
2511 || (vr0.type == VR_RANGE
2512 && integer_zerop (int_const_binop (RSHIFT_EXPR,
2513 int_const_binop (MINUS_EXPR, vr0.max, vr0.min),
2514 size_int (TYPE_PRECISION (outer_type)))))))
2516 tree new_min, new_max;
2517 new_min = force_fit_type (outer_type, wi::to_widest (vr0.min),
2518 0, false);
2519 new_max = force_fit_type (outer_type, wi::to_widest (vr0.max),
2520 0, false);
2521 set_and_canonicalize_value_range (vr, vr0.type,
2522 new_min, new_max, NULL);
2523 return;
2526 set_value_range_to_varying (vr);
2527 return;
2529 else if (code == ABS_EXPR)
2530 return extract_range_from_abs_expr (*vr, type, vr0);
2532 /* For unhandled operations fall back to varying. */
2533 set_value_range_to_varying (vr);
2534 return;
2537 /* Debugging dumps. */
2539 void dump_value_range (FILE *, const value_range *);
2540 void debug_value_range (value_range *);
2541 void dump_all_value_ranges (FILE *);
2542 void dump_vr_equiv (FILE *, bitmap);
2543 void debug_vr_equiv (bitmap);
2546 /* Dump value range VR to FILE. */
2548 void
2549 dump_value_range (FILE *file, const value_range *vr)
2551 if (vr == NULL)
2552 fprintf (file, "[]");
2553 else if (vr->type == VR_UNDEFINED)
2554 fprintf (file, "UNDEFINED");
2555 else if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
2557 tree type = TREE_TYPE (vr->min);
2559 fprintf (file, "%s[", (vr->type == VR_ANTI_RANGE) ? "~" : "");
2561 if (INTEGRAL_TYPE_P (type)
2562 && !TYPE_UNSIGNED (type)
2563 && vrp_val_is_min (vr->min))
2564 fprintf (file, "-INF");
2565 else
2566 print_generic_expr (file, vr->min);
2568 fprintf (file, ", ");
2570 if (INTEGRAL_TYPE_P (type)
2571 && vrp_val_is_max (vr->max))
2572 fprintf (file, "+INF");
2573 else
2574 print_generic_expr (file, vr->max);
2576 fprintf (file, "]");
2578 if (vr->equiv)
2580 bitmap_iterator bi;
2581 unsigned i, c = 0;
2583 fprintf (file, " EQUIVALENCES: { ");
2585 EXECUTE_IF_SET_IN_BITMAP (vr->equiv, 0, i, bi)
2587 print_generic_expr (file, ssa_name (i));
2588 fprintf (file, " ");
2589 c++;
2592 fprintf (file, "} (%u elements)", c);
2595 else if (vr->type == VR_VARYING)
2596 fprintf (file, "VARYING");
2597 else
2598 fprintf (file, "INVALID RANGE");
2602 /* Dump value range VR to stderr. */
2604 DEBUG_FUNCTION void
2605 debug_value_range (value_range *vr)
2607 dump_value_range (stderr, vr);
2608 fprintf (stderr, "\n");
2612 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
2613 create a new SSA name N and return the assertion assignment
2614 'N = ASSERT_EXPR <V, V OP W>'. */
2616 static gimple *
2617 build_assert_expr_for (tree cond, tree v)
2619 tree a;
2620 gassign *assertion;
2622 gcc_assert (TREE_CODE (v) == SSA_NAME
2623 && COMPARISON_CLASS_P (cond));
2625 a = build2 (ASSERT_EXPR, TREE_TYPE (v), v, cond);
2626 assertion = gimple_build_assign (NULL_TREE, a);
2628 /* The new ASSERT_EXPR, creates a new SSA name that replaces the
2629 operand of the ASSERT_EXPR. Create it so the new name and the old one
2630 are registered in the replacement table so that we can fix the SSA web
2631 after adding all the ASSERT_EXPRs. */
2632 tree new_def = create_new_def_for (v, assertion, NULL);
2633 /* Make sure we preserve abnormalness throughout an ASSERT_EXPR chain
2634 given we have to be able to fully propagate those out to re-create
2635 valid SSA when removing the asserts. */
2636 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (v))
2637 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_def) = 1;
2639 return assertion;
2643 /* Return false if EXPR is a predicate expression involving floating
2644 point values. */
2646 static inline bool
2647 fp_predicate (gimple *stmt)
2649 GIMPLE_CHECK (stmt, GIMPLE_COND);
2651 return FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)));
2654 /* If the range of values taken by OP can be inferred after STMT executes,
2655 return the comparison code (COMP_CODE_P) and value (VAL_P) that
2656 describes the inferred range. Return true if a range could be
2657 inferred. */
2659 bool
2660 infer_value_range (gimple *stmt, tree op, tree_code *comp_code_p, tree *val_p)
2662 *val_p = NULL_TREE;
2663 *comp_code_p = ERROR_MARK;
2665 /* Do not attempt to infer anything in names that flow through
2666 abnormal edges. */
2667 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
2668 return false;
2670 /* If STMT is the last statement of a basic block with no normal
2671 successors, there is no point inferring anything about any of its
2672 operands. We would not be able to find a proper insertion point
2673 for the assertion, anyway. */
2674 if (stmt_ends_bb_p (stmt))
2676 edge_iterator ei;
2677 edge e;
2679 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
2680 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
2681 break;
2682 if (e == NULL)
2683 return false;
2686 if (infer_nonnull_range (stmt, op))
2688 *val_p = build_int_cst (TREE_TYPE (op), 0);
2689 *comp_code_p = NE_EXPR;
2690 return true;
2693 return false;
2697 void dump_asserts_for (FILE *, tree);
2698 void debug_asserts_for (tree);
2699 void dump_all_asserts (FILE *);
2700 void debug_all_asserts (void);
2702 /* Dump all the registered assertions for NAME to FILE. */
2704 void
2705 dump_asserts_for (FILE *file, tree name)
2707 assert_locus *loc;
2709 fprintf (file, "Assertions to be inserted for ");
2710 print_generic_expr (file, name);
2711 fprintf (file, "\n");
2713 loc = asserts_for[SSA_NAME_VERSION (name)];
2714 while (loc)
2716 fprintf (file, "\t");
2717 print_gimple_stmt (file, gsi_stmt (loc->si), 0);
2718 fprintf (file, "\n\tBB #%d", loc->bb->index);
2719 if (loc->e)
2721 fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
2722 loc->e->dest->index);
2723 dump_edge_info (file, loc->e, dump_flags, 0);
2725 fprintf (file, "\n\tPREDICATE: ");
2726 print_generic_expr (file, loc->expr);
2727 fprintf (file, " %s ", get_tree_code_name (loc->comp_code));
2728 print_generic_expr (file, loc->val);
2729 fprintf (file, "\n\n");
2730 loc = loc->next;
2733 fprintf (file, "\n");
2737 /* Dump all the registered assertions for NAME to stderr. */
2739 DEBUG_FUNCTION void
2740 debug_asserts_for (tree name)
2742 dump_asserts_for (stderr, name);
2746 /* Dump all the registered assertions for all the names to FILE. */
2748 void
2749 dump_all_asserts (FILE *file)
2751 unsigned i;
2752 bitmap_iterator bi;
2754 fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
2755 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
2756 dump_asserts_for (file, ssa_name (i));
2757 fprintf (file, "\n");
2761 /* Dump all the registered assertions for all the names to stderr. */
2763 DEBUG_FUNCTION void
2764 debug_all_asserts (void)
2766 dump_all_asserts (stderr);
2769 /* Push the assert info for NAME, EXPR, COMP_CODE and VAL to ASSERTS. */
2771 static void
2772 add_assert_info (vec<assert_info> &asserts,
2773 tree name, tree expr, enum tree_code comp_code, tree val)
2775 assert_info info;
2776 info.comp_code = comp_code;
2777 info.name = name;
2778 if (TREE_OVERFLOW_P (val))
2779 val = drop_tree_overflow (val);
2780 info.val = val;
2781 info.expr = expr;
2782 asserts.safe_push (info);
2785 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
2786 'EXPR COMP_CODE VAL' at a location that dominates block BB or
2787 E->DEST, then register this location as a possible insertion point
2788 for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
2790 BB, E and SI provide the exact insertion point for the new
2791 ASSERT_EXPR. If BB is NULL, then the ASSERT_EXPR is to be inserted
2792 on edge E. Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
2793 BB. If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
2794 must not be NULL. */
2796 static void
2797 register_new_assert_for (tree name, tree expr,
2798 enum tree_code comp_code,
2799 tree val,
2800 basic_block bb,
2801 edge e,
2802 gimple_stmt_iterator si)
2804 assert_locus *n, *loc, *last_loc;
2805 basic_block dest_bb;
2807 gcc_checking_assert (bb == NULL || e == NULL);
2809 if (e == NULL)
2810 gcc_checking_assert (gimple_code (gsi_stmt (si)) != GIMPLE_COND
2811 && gimple_code (gsi_stmt (si)) != GIMPLE_SWITCH);
2813 /* Never build an assert comparing against an integer constant with
2814 TREE_OVERFLOW set. This confuses our undefined overflow warning
2815 machinery. */
2816 if (TREE_OVERFLOW_P (val))
2817 val = drop_tree_overflow (val);
2819 /* The new assertion A will be inserted at BB or E. We need to
2820 determine if the new location is dominated by a previously
2821 registered location for A. If we are doing an edge insertion,
2822 assume that A will be inserted at E->DEST. Note that this is not
2823 necessarily true.
2825 If E is a critical edge, it will be split. But even if E is
2826 split, the new block will dominate the same set of blocks that
2827 E->DEST dominates.
2829 The reverse, however, is not true, blocks dominated by E->DEST
2830 will not be dominated by the new block created to split E. So,
2831 if the insertion location is on a critical edge, we will not use
2832 the new location to move another assertion previously registered
2833 at a block dominated by E->DEST. */
2834 dest_bb = (bb) ? bb : e->dest;
2836 /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
2837 VAL at a block dominating DEST_BB, then we don't need to insert a new
2838 one. Similarly, if the same assertion already exists at a block
2839 dominated by DEST_BB and the new location is not on a critical
2840 edge, then update the existing location for the assertion (i.e.,
2841 move the assertion up in the dominance tree).
2843 Note, this is implemented as a simple linked list because there
2844 should not be more than a handful of assertions registered per
2845 name. If this becomes a performance problem, a table hashed by
2846 COMP_CODE and VAL could be implemented. */
2847 loc = asserts_for[SSA_NAME_VERSION (name)];
2848 last_loc = loc;
2849 while (loc)
2851 if (loc->comp_code == comp_code
2852 && (loc->val == val
2853 || operand_equal_p (loc->val, val, 0))
2854 && (loc->expr == expr
2855 || operand_equal_p (loc->expr, expr, 0)))
2857 /* If E is not a critical edge and DEST_BB
2858 dominates the existing location for the assertion, move
2859 the assertion up in the dominance tree by updating its
2860 location information. */
2861 if ((e == NULL || !EDGE_CRITICAL_P (e))
2862 && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
2864 loc->bb = dest_bb;
2865 loc->e = e;
2866 loc->si = si;
2867 return;
2871 /* Update the last node of the list and move to the next one. */
2872 last_loc = loc;
2873 loc = loc->next;
2876 /* If we didn't find an assertion already registered for
2877 NAME COMP_CODE VAL, add a new one at the end of the list of
2878 assertions associated with NAME. */
2879 n = XNEW (struct assert_locus);
2880 n->bb = dest_bb;
2881 n->e = e;
2882 n->si = si;
2883 n->comp_code = comp_code;
2884 n->val = val;
2885 n->expr = expr;
2886 n->next = NULL;
2888 if (last_loc)
2889 last_loc->next = n;
2890 else
2891 asserts_for[SSA_NAME_VERSION (name)] = n;
2893 bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
2896 /* (COND_OP0 COND_CODE COND_OP1) is a predicate which uses NAME.
2897 Extract a suitable test code and value and store them into *CODE_P and
2898 *VAL_P so the predicate is normalized to NAME *CODE_P *VAL_P.
2900 If no extraction was possible, return FALSE, otherwise return TRUE.
2902 If INVERT is true, then we invert the result stored into *CODE_P. */
2904 static bool
2905 extract_code_and_val_from_cond_with_ops (tree name, enum tree_code cond_code,
2906 tree cond_op0, tree cond_op1,
2907 bool invert, enum tree_code *code_p,
2908 tree *val_p)
2910 enum tree_code comp_code;
2911 tree val;
2913 /* Otherwise, we have a comparison of the form NAME COMP VAL
2914 or VAL COMP NAME. */
2915 if (name == cond_op1)
2917 /* If the predicate is of the form VAL COMP NAME, flip
2918 COMP around because we need to register NAME as the
2919 first operand in the predicate. */
2920 comp_code = swap_tree_comparison (cond_code);
2921 val = cond_op0;
2923 else if (name == cond_op0)
2925 /* The comparison is of the form NAME COMP VAL, so the
2926 comparison code remains unchanged. */
2927 comp_code = cond_code;
2928 val = cond_op1;
2930 else
2931 gcc_unreachable ();
2933 /* Invert the comparison code as necessary. */
2934 if (invert)
2935 comp_code = invert_tree_comparison (comp_code, 0);
2937 /* VRP only handles integral and pointer types. */
2938 if (! INTEGRAL_TYPE_P (TREE_TYPE (val))
2939 && ! POINTER_TYPE_P (TREE_TYPE (val)))
2940 return false;
2942 /* Do not register always-false predicates.
2943 FIXME: this works around a limitation in fold() when dealing with
2944 enumerations. Given 'enum { N1, N2 } x;', fold will not
2945 fold 'if (x > N2)' to 'if (0)'. */
2946 if ((comp_code == GT_EXPR || comp_code == LT_EXPR)
2947 && INTEGRAL_TYPE_P (TREE_TYPE (val)))
2949 tree min = TYPE_MIN_VALUE (TREE_TYPE (val));
2950 tree max = TYPE_MAX_VALUE (TREE_TYPE (val));
2952 if (comp_code == GT_EXPR
2953 && (!max
2954 || compare_values (val, max) == 0))
2955 return false;
2957 if (comp_code == LT_EXPR
2958 && (!min
2959 || compare_values (val, min) == 0))
2960 return false;
2962 *code_p = comp_code;
2963 *val_p = val;
2964 return true;
2967 /* Find out smallest RES where RES > VAL && (RES & MASK) == RES, if any
2968 (otherwise return VAL). VAL and MASK must be zero-extended for
2969 precision PREC. If SGNBIT is non-zero, first xor VAL with SGNBIT
2970 (to transform signed values into unsigned) and at the end xor
2971 SGNBIT back. */
2973 static wide_int
2974 masked_increment (const wide_int &val_in, const wide_int &mask,
2975 const wide_int &sgnbit, unsigned int prec)
2977 wide_int bit = wi::one (prec), res;
2978 unsigned int i;
2980 wide_int val = val_in ^ sgnbit;
2981 for (i = 0; i < prec; i++, bit += bit)
2983 res = mask;
2984 if ((res & bit) == 0)
2985 continue;
2986 res = bit - 1;
2987 res = wi::bit_and_not (val + bit, res);
2988 res &= mask;
2989 if (wi::gtu_p (res, val))
2990 return res ^ sgnbit;
2992 return val ^ sgnbit;
2995 /* Helper for overflow_comparison_p
2997 OP0 CODE OP1 is a comparison. Examine the comparison and potentially
2998 OP1's defining statement to see if it ultimately has the form
2999 OP0 CODE (OP0 PLUS INTEGER_CST)
3001 If so, return TRUE indicating this is an overflow test and store into
3002 *NEW_CST an updated constant that can be used in a narrowed range test.
3004 REVERSED indicates if the comparison was originally:
3006 OP1 CODE' OP0.
3008 This affects how we build the updated constant. */
3010 static bool
3011 overflow_comparison_p_1 (enum tree_code code, tree op0, tree op1,
3012 bool follow_assert_exprs, bool reversed, tree *new_cst)
3014 /* See if this is a relational operation between two SSA_NAMES with
3015 unsigned, overflow wrapping values. If so, check it more deeply. */
3016 if ((code == LT_EXPR || code == LE_EXPR
3017 || code == GE_EXPR || code == GT_EXPR)
3018 && TREE_CODE (op0) == SSA_NAME
3019 && TREE_CODE (op1) == SSA_NAME
3020 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
3021 && TYPE_UNSIGNED (TREE_TYPE (op0))
3022 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0)))
3024 gimple *op1_def = SSA_NAME_DEF_STMT (op1);
3026 /* If requested, follow any ASSERT_EXPRs backwards for OP1. */
3027 if (follow_assert_exprs)
3029 while (gimple_assign_single_p (op1_def)
3030 && TREE_CODE (gimple_assign_rhs1 (op1_def)) == ASSERT_EXPR)
3032 op1 = TREE_OPERAND (gimple_assign_rhs1 (op1_def), 0);
3033 if (TREE_CODE (op1) != SSA_NAME)
3034 break;
3035 op1_def = SSA_NAME_DEF_STMT (op1);
3039 /* Now look at the defining statement of OP1 to see if it adds
3040 or subtracts a nonzero constant from another operand. */
3041 if (op1_def
3042 && is_gimple_assign (op1_def)
3043 && gimple_assign_rhs_code (op1_def) == PLUS_EXPR
3044 && TREE_CODE (gimple_assign_rhs2 (op1_def)) == INTEGER_CST
3045 && !integer_zerop (gimple_assign_rhs2 (op1_def)))
3047 tree target = gimple_assign_rhs1 (op1_def);
3049 /* If requested, follow ASSERT_EXPRs backwards for op0 looking
3050 for one where TARGET appears on the RHS. */
3051 if (follow_assert_exprs)
3053 /* Now see if that "other operand" is op0, following the chain
3054 of ASSERT_EXPRs if necessary. */
3055 gimple *op0_def = SSA_NAME_DEF_STMT (op0);
3056 while (op0 != target
3057 && gimple_assign_single_p (op0_def)
3058 && TREE_CODE (gimple_assign_rhs1 (op0_def)) == ASSERT_EXPR)
3060 op0 = TREE_OPERAND (gimple_assign_rhs1 (op0_def), 0);
3061 if (TREE_CODE (op0) != SSA_NAME)
3062 break;
3063 op0_def = SSA_NAME_DEF_STMT (op0);
3067 /* If we did not find our target SSA_NAME, then this is not
3068 an overflow test. */
3069 if (op0 != target)
3070 return false;
3072 tree type = TREE_TYPE (op0);
3073 wide_int max = wi::max_value (TYPE_PRECISION (type), UNSIGNED);
3074 tree inc = gimple_assign_rhs2 (op1_def);
3075 if (reversed)
3076 *new_cst = wide_int_to_tree (type, max + wi::to_wide (inc));
3077 else
3078 *new_cst = wide_int_to_tree (type, max - wi::to_wide (inc));
3079 return true;
3082 return false;
3085 /* OP0 CODE OP1 is a comparison. Examine the comparison and potentially
3086 OP1's defining statement to see if it ultimately has the form
3087 OP0 CODE (OP0 PLUS INTEGER_CST)
3089 If so, return TRUE indicating this is an overflow test and store into
3090 *NEW_CST an updated constant that can be used in a narrowed range test.
3092 These statements are left as-is in the IL to facilitate discovery of
3093 {ADD,SUB}_OVERFLOW sequences later in the optimizer pipeline. But
3094 the alternate range representation is often useful within VRP. */
3096 bool
3097 overflow_comparison_p (tree_code code, tree name, tree val,
3098 bool use_equiv_p, tree *new_cst)
3100 if (overflow_comparison_p_1 (code, name, val, use_equiv_p, false, new_cst))
3101 return true;
3102 return overflow_comparison_p_1 (swap_tree_comparison (code), val, name,
3103 use_equiv_p, true, new_cst);
3107 /* Try to register an edge assertion for SSA name NAME on edge E for
3108 the condition COND contributing to the conditional jump pointed to by BSI.
3109 Invert the condition COND if INVERT is true. */
3111 static void
3112 register_edge_assert_for_2 (tree name, edge e,
3113 enum tree_code cond_code,
3114 tree cond_op0, tree cond_op1, bool invert,
3115 vec<assert_info> &asserts)
3117 tree val;
3118 enum tree_code comp_code;
3120 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
3121 cond_op0,
3122 cond_op1,
3123 invert, &comp_code, &val))
3124 return;
3126 /* Queue the assert. */
3127 tree x;
3128 if (overflow_comparison_p (comp_code, name, val, false, &x))
3130 enum tree_code new_code = ((comp_code == GT_EXPR || comp_code == GE_EXPR)
3131 ? GT_EXPR : LE_EXPR);
3132 add_assert_info (asserts, name, name, new_code, x);
3134 add_assert_info (asserts, name, name, comp_code, val);
3136 /* In the case of NAME <= CST and NAME being defined as
3137 NAME = (unsigned) NAME2 + CST2 we can assert NAME2 >= -CST2
3138 and NAME2 <= CST - CST2. We can do the same for NAME > CST.
3139 This catches range and anti-range tests. */
3140 if ((comp_code == LE_EXPR
3141 || comp_code == GT_EXPR)
3142 && TREE_CODE (val) == INTEGER_CST
3143 && TYPE_UNSIGNED (TREE_TYPE (val)))
3145 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3146 tree cst2 = NULL_TREE, name2 = NULL_TREE, name3 = NULL_TREE;
3148 /* Extract CST2 from the (optional) addition. */
3149 if (is_gimple_assign (def_stmt)
3150 && gimple_assign_rhs_code (def_stmt) == PLUS_EXPR)
3152 name2 = gimple_assign_rhs1 (def_stmt);
3153 cst2 = gimple_assign_rhs2 (def_stmt);
3154 if (TREE_CODE (name2) == SSA_NAME
3155 && TREE_CODE (cst2) == INTEGER_CST)
3156 def_stmt = SSA_NAME_DEF_STMT (name2);
3159 /* Extract NAME2 from the (optional) sign-changing cast. */
3160 if (gimple_assign_cast_p (def_stmt))
3162 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt))
3163 && ! TYPE_UNSIGNED (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
3164 && (TYPE_PRECISION (gimple_expr_type (def_stmt))
3165 == TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))))
3166 name3 = gimple_assign_rhs1 (def_stmt);
3169 /* If name3 is used later, create an ASSERT_EXPR for it. */
3170 if (name3 != NULL_TREE
3171 && TREE_CODE (name3) == SSA_NAME
3172 && (cst2 == NULL_TREE
3173 || TREE_CODE (cst2) == INTEGER_CST)
3174 && INTEGRAL_TYPE_P (TREE_TYPE (name3)))
3176 tree tmp;
3178 /* Build an expression for the range test. */
3179 tmp = build1 (NOP_EXPR, TREE_TYPE (name), name3);
3180 if (cst2 != NULL_TREE)
3181 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
3183 if (dump_file)
3185 fprintf (dump_file, "Adding assert for ");
3186 print_generic_expr (dump_file, name3);
3187 fprintf (dump_file, " from ");
3188 print_generic_expr (dump_file, tmp);
3189 fprintf (dump_file, "\n");
3192 add_assert_info (asserts, name3, tmp, comp_code, val);
3195 /* If name2 is used later, create an ASSERT_EXPR for it. */
3196 if (name2 != NULL_TREE
3197 && TREE_CODE (name2) == SSA_NAME
3198 && TREE_CODE (cst2) == INTEGER_CST
3199 && INTEGRAL_TYPE_P (TREE_TYPE (name2)))
3201 tree tmp;
3203 /* Build an expression for the range test. */
3204 tmp = name2;
3205 if (TREE_TYPE (name) != TREE_TYPE (name2))
3206 tmp = build1 (NOP_EXPR, TREE_TYPE (name), tmp);
3207 if (cst2 != NULL_TREE)
3208 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
3210 if (dump_file)
3212 fprintf (dump_file, "Adding assert for ");
3213 print_generic_expr (dump_file, name2);
3214 fprintf (dump_file, " from ");
3215 print_generic_expr (dump_file, tmp);
3216 fprintf (dump_file, "\n");
3219 add_assert_info (asserts, name2, tmp, comp_code, val);
3223 /* In the case of post-in/decrement tests like if (i++) ... and uses
3224 of the in/decremented value on the edge the extra name we want to
3225 assert for is not on the def chain of the name compared. Instead
3226 it is in the set of use stmts.
3227 Similar cases happen for conversions that were simplified through
3228 fold_{sign_changed,widened}_comparison. */
3229 if ((comp_code == NE_EXPR
3230 || comp_code == EQ_EXPR)
3231 && TREE_CODE (val) == INTEGER_CST)
3233 imm_use_iterator ui;
3234 gimple *use_stmt;
3235 FOR_EACH_IMM_USE_STMT (use_stmt, ui, name)
3237 if (!is_gimple_assign (use_stmt))
3238 continue;
3240 /* Cut off to use-stmts that are dominating the predecessor. */
3241 if (!dominated_by_p (CDI_DOMINATORS, e->src, gimple_bb (use_stmt)))
3242 continue;
3244 tree name2 = gimple_assign_lhs (use_stmt);
3245 if (TREE_CODE (name2) != SSA_NAME)
3246 continue;
3248 enum tree_code code = gimple_assign_rhs_code (use_stmt);
3249 tree cst;
3250 if (code == PLUS_EXPR
3251 || code == MINUS_EXPR)
3253 cst = gimple_assign_rhs2 (use_stmt);
3254 if (TREE_CODE (cst) != INTEGER_CST)
3255 continue;
3256 cst = int_const_binop (code, val, cst);
3258 else if (CONVERT_EXPR_CODE_P (code))
3260 /* For truncating conversions we cannot record
3261 an inequality. */
3262 if (comp_code == NE_EXPR
3263 && (TYPE_PRECISION (TREE_TYPE (name2))
3264 < TYPE_PRECISION (TREE_TYPE (name))))
3265 continue;
3266 cst = fold_convert (TREE_TYPE (name2), val);
3268 else
3269 continue;
3271 if (TREE_OVERFLOW_P (cst))
3272 cst = drop_tree_overflow (cst);
3273 add_assert_info (asserts, name2, name2, comp_code, cst);
3277 if (TREE_CODE_CLASS (comp_code) == tcc_comparison
3278 && TREE_CODE (val) == INTEGER_CST)
3280 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3281 tree name2 = NULL_TREE, names[2], cst2 = NULL_TREE;
3282 tree val2 = NULL_TREE;
3283 unsigned int prec = TYPE_PRECISION (TREE_TYPE (val));
3284 wide_int mask = wi::zero (prec);
3285 unsigned int nprec = prec;
3286 enum tree_code rhs_code = ERROR_MARK;
3288 if (is_gimple_assign (def_stmt))
3289 rhs_code = gimple_assign_rhs_code (def_stmt);
3291 /* In the case of NAME != CST1 where NAME = A +- CST2 we can
3292 assert that A != CST1 -+ CST2. */
3293 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
3294 && (rhs_code == PLUS_EXPR || rhs_code == MINUS_EXPR))
3296 tree op0 = gimple_assign_rhs1 (def_stmt);
3297 tree op1 = gimple_assign_rhs2 (def_stmt);
3298 if (TREE_CODE (op0) == SSA_NAME
3299 && TREE_CODE (op1) == INTEGER_CST)
3301 enum tree_code reverse_op = (rhs_code == PLUS_EXPR
3302 ? MINUS_EXPR : PLUS_EXPR);
3303 op1 = int_const_binop (reverse_op, val, op1);
3304 if (TREE_OVERFLOW (op1))
3305 op1 = drop_tree_overflow (op1);
3306 add_assert_info (asserts, op0, op0, comp_code, op1);
3310 /* Add asserts for NAME cmp CST and NAME being defined
3311 as NAME = (int) NAME2. */
3312 if (!TYPE_UNSIGNED (TREE_TYPE (val))
3313 && (comp_code == LE_EXPR || comp_code == LT_EXPR
3314 || comp_code == GT_EXPR || comp_code == GE_EXPR)
3315 && gimple_assign_cast_p (def_stmt))
3317 name2 = gimple_assign_rhs1 (def_stmt);
3318 if (CONVERT_EXPR_CODE_P (rhs_code)
3319 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
3320 && TYPE_UNSIGNED (TREE_TYPE (name2))
3321 && prec == TYPE_PRECISION (TREE_TYPE (name2))
3322 && (comp_code == LE_EXPR || comp_code == GT_EXPR
3323 || !tree_int_cst_equal (val,
3324 TYPE_MIN_VALUE (TREE_TYPE (val)))))
3326 tree tmp, cst;
3327 enum tree_code new_comp_code = comp_code;
3329 cst = fold_convert (TREE_TYPE (name2),
3330 TYPE_MIN_VALUE (TREE_TYPE (val)));
3331 /* Build an expression for the range test. */
3332 tmp = build2 (PLUS_EXPR, TREE_TYPE (name2), name2, cst);
3333 cst = fold_build2 (PLUS_EXPR, TREE_TYPE (name2), cst,
3334 fold_convert (TREE_TYPE (name2), val));
3335 if (comp_code == LT_EXPR || comp_code == GE_EXPR)
3337 new_comp_code = comp_code == LT_EXPR ? LE_EXPR : GT_EXPR;
3338 cst = fold_build2 (MINUS_EXPR, TREE_TYPE (name2), cst,
3339 build_int_cst (TREE_TYPE (name2), 1));
3342 if (dump_file)
3344 fprintf (dump_file, "Adding assert for ");
3345 print_generic_expr (dump_file, name2);
3346 fprintf (dump_file, " from ");
3347 print_generic_expr (dump_file, tmp);
3348 fprintf (dump_file, "\n");
3351 add_assert_info (asserts, name2, tmp, new_comp_code, cst);
3355 /* Add asserts for NAME cmp CST and NAME being defined as
3356 NAME = NAME2 >> CST2.
3358 Extract CST2 from the right shift. */
3359 if (rhs_code == RSHIFT_EXPR)
3361 name2 = gimple_assign_rhs1 (def_stmt);
3362 cst2 = gimple_assign_rhs2 (def_stmt);
3363 if (TREE_CODE (name2) == SSA_NAME
3364 && tree_fits_uhwi_p (cst2)
3365 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
3366 && IN_RANGE (tree_to_uhwi (cst2), 1, prec - 1)
3367 && type_has_mode_precision_p (TREE_TYPE (val)))
3369 mask = wi::mask (tree_to_uhwi (cst2), false, prec);
3370 val2 = fold_binary (LSHIFT_EXPR, TREE_TYPE (val), val, cst2);
3373 if (val2 != NULL_TREE
3374 && TREE_CODE (val2) == INTEGER_CST
3375 && simple_cst_equal (fold_build2 (RSHIFT_EXPR,
3376 TREE_TYPE (val),
3377 val2, cst2), val))
3379 enum tree_code new_comp_code = comp_code;
3380 tree tmp, new_val;
3382 tmp = name2;
3383 if (comp_code == EQ_EXPR || comp_code == NE_EXPR)
3385 if (!TYPE_UNSIGNED (TREE_TYPE (val)))
3387 tree type = build_nonstandard_integer_type (prec, 1);
3388 tmp = build1 (NOP_EXPR, type, name2);
3389 val2 = fold_convert (type, val2);
3391 tmp = fold_build2 (MINUS_EXPR, TREE_TYPE (tmp), tmp, val2);
3392 new_val = wide_int_to_tree (TREE_TYPE (tmp), mask);
3393 new_comp_code = comp_code == EQ_EXPR ? LE_EXPR : GT_EXPR;
3395 else if (comp_code == LT_EXPR || comp_code == GE_EXPR)
3397 wide_int minval
3398 = wi::min_value (prec, TYPE_SIGN (TREE_TYPE (val)));
3399 new_val = val2;
3400 if (minval == wi::to_wide (new_val))
3401 new_val = NULL_TREE;
3403 else
3405 wide_int maxval
3406 = wi::max_value (prec, TYPE_SIGN (TREE_TYPE (val)));
3407 mask |= wi::to_wide (val2);
3408 if (wi::eq_p (mask, maxval))
3409 new_val = NULL_TREE;
3410 else
3411 new_val = wide_int_to_tree (TREE_TYPE (val2), mask);
3414 if (new_val)
3416 if (dump_file)
3418 fprintf (dump_file, "Adding assert for ");
3419 print_generic_expr (dump_file, name2);
3420 fprintf (dump_file, " from ");
3421 print_generic_expr (dump_file, tmp);
3422 fprintf (dump_file, "\n");
3425 add_assert_info (asserts, name2, tmp, new_comp_code, new_val);
3429 /* Add asserts for NAME cmp CST and NAME being defined as
3430 NAME = NAME2 & CST2.
3432 Extract CST2 from the and.
3434 Also handle
3435 NAME = (unsigned) NAME2;
3436 casts where NAME's type is unsigned and has smaller precision
3437 than NAME2's type as if it was NAME = NAME2 & MASK. */
3438 names[0] = NULL_TREE;
3439 names[1] = NULL_TREE;
3440 cst2 = NULL_TREE;
3441 if (rhs_code == BIT_AND_EXPR
3442 || (CONVERT_EXPR_CODE_P (rhs_code)
3443 && INTEGRAL_TYPE_P (TREE_TYPE (val))
3444 && TYPE_UNSIGNED (TREE_TYPE (val))
3445 && TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
3446 > prec))
3448 name2 = gimple_assign_rhs1 (def_stmt);
3449 if (rhs_code == BIT_AND_EXPR)
3450 cst2 = gimple_assign_rhs2 (def_stmt);
3451 else
3453 cst2 = TYPE_MAX_VALUE (TREE_TYPE (val));
3454 nprec = TYPE_PRECISION (TREE_TYPE (name2));
3456 if (TREE_CODE (name2) == SSA_NAME
3457 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
3458 && TREE_CODE (cst2) == INTEGER_CST
3459 && !integer_zerop (cst2)
3460 && (nprec > 1
3461 || TYPE_UNSIGNED (TREE_TYPE (val))))
3463 gimple *def_stmt2 = SSA_NAME_DEF_STMT (name2);
3464 if (gimple_assign_cast_p (def_stmt2))
3466 names[1] = gimple_assign_rhs1 (def_stmt2);
3467 if (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt2))
3468 || !INTEGRAL_TYPE_P (TREE_TYPE (names[1]))
3469 || (TYPE_PRECISION (TREE_TYPE (name2))
3470 != TYPE_PRECISION (TREE_TYPE (names[1]))))
3471 names[1] = NULL_TREE;
3473 names[0] = name2;
3476 if (names[0] || names[1])
3478 wide_int minv, maxv, valv, cst2v;
3479 wide_int tem, sgnbit;
3480 bool valid_p = false, valn, cst2n;
3481 enum tree_code ccode = comp_code;
3483 valv = wide_int::from (wi::to_wide (val), nprec, UNSIGNED);
3484 cst2v = wide_int::from (wi::to_wide (cst2), nprec, UNSIGNED);
3485 valn = wi::neg_p (valv, TYPE_SIGN (TREE_TYPE (val)));
3486 cst2n = wi::neg_p (cst2v, TYPE_SIGN (TREE_TYPE (val)));
3487 /* If CST2 doesn't have most significant bit set,
3488 but VAL is negative, we have comparison like
3489 if ((x & 0x123) > -4) (always true). Just give up. */
3490 if (!cst2n && valn)
3491 ccode = ERROR_MARK;
3492 if (cst2n)
3493 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
3494 else
3495 sgnbit = wi::zero (nprec);
3496 minv = valv & cst2v;
3497 switch (ccode)
3499 case EQ_EXPR:
3500 /* Minimum unsigned value for equality is VAL & CST2
3501 (should be equal to VAL, otherwise we probably should
3502 have folded the comparison into false) and
3503 maximum unsigned value is VAL | ~CST2. */
3504 maxv = valv | ~cst2v;
3505 valid_p = true;
3506 break;
3508 case NE_EXPR:
3509 tem = valv | ~cst2v;
3510 /* If VAL is 0, handle (X & CST2) != 0 as (X & CST2) > 0U. */
3511 if (valv == 0)
3513 cst2n = false;
3514 sgnbit = wi::zero (nprec);
3515 goto gt_expr;
3517 /* If (VAL | ~CST2) is all ones, handle it as
3518 (X & CST2) < VAL. */
3519 if (tem == -1)
3521 cst2n = false;
3522 valn = false;
3523 sgnbit = wi::zero (nprec);
3524 goto lt_expr;
3526 if (!cst2n && wi::neg_p (cst2v))
3527 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
3528 if (sgnbit != 0)
3530 if (valv == sgnbit)
3532 cst2n = true;
3533 valn = true;
3534 goto gt_expr;
3536 if (tem == wi::mask (nprec - 1, false, nprec))
3538 cst2n = true;
3539 goto lt_expr;
3541 if (!cst2n)
3542 sgnbit = wi::zero (nprec);
3544 break;
3546 case GE_EXPR:
3547 /* Minimum unsigned value for >= if (VAL & CST2) == VAL
3548 is VAL and maximum unsigned value is ~0. For signed
3549 comparison, if CST2 doesn't have most significant bit
3550 set, handle it similarly. If CST2 has MSB set,
3551 the minimum is the same, and maximum is ~0U/2. */
3552 if (minv != valv)
3554 /* If (VAL & CST2) != VAL, X & CST2 can't be equal to
3555 VAL. */
3556 minv = masked_increment (valv, cst2v, sgnbit, nprec);
3557 if (minv == valv)
3558 break;
3560 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
3561 valid_p = true;
3562 break;
3564 case GT_EXPR:
3565 gt_expr:
3566 /* Find out smallest MINV where MINV > VAL
3567 && (MINV & CST2) == MINV, if any. If VAL is signed and
3568 CST2 has MSB set, compute it biased by 1 << (nprec - 1). */
3569 minv = masked_increment (valv, cst2v, sgnbit, nprec);
3570 if (minv == valv)
3571 break;
3572 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
3573 valid_p = true;
3574 break;
3576 case LE_EXPR:
3577 /* Minimum unsigned value for <= is 0 and maximum
3578 unsigned value is VAL | ~CST2 if (VAL & CST2) == VAL.
3579 Otherwise, find smallest VAL2 where VAL2 > VAL
3580 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
3581 as maximum.
3582 For signed comparison, if CST2 doesn't have most
3583 significant bit set, handle it similarly. If CST2 has
3584 MSB set, the maximum is the same and minimum is INT_MIN. */
3585 if (minv == valv)
3586 maxv = valv;
3587 else
3589 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
3590 if (maxv == valv)
3591 break;
3592 maxv -= 1;
3594 maxv |= ~cst2v;
3595 minv = sgnbit;
3596 valid_p = true;
3597 break;
3599 case LT_EXPR:
3600 lt_expr:
3601 /* Minimum unsigned value for < is 0 and maximum
3602 unsigned value is (VAL-1) | ~CST2 if (VAL & CST2) == VAL.
3603 Otherwise, find smallest VAL2 where VAL2 > VAL
3604 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
3605 as maximum.
3606 For signed comparison, if CST2 doesn't have most
3607 significant bit set, handle it similarly. If CST2 has
3608 MSB set, the maximum is the same and minimum is INT_MIN. */
3609 if (minv == valv)
3611 if (valv == sgnbit)
3612 break;
3613 maxv = valv;
3615 else
3617 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
3618 if (maxv == valv)
3619 break;
3621 maxv -= 1;
3622 maxv |= ~cst2v;
3623 minv = sgnbit;
3624 valid_p = true;
3625 break;
3627 default:
3628 break;
3630 if (valid_p
3631 && (maxv - minv) != -1)
3633 tree tmp, new_val, type;
3634 int i;
3636 for (i = 0; i < 2; i++)
3637 if (names[i])
3639 wide_int maxv2 = maxv;
3640 tmp = names[i];
3641 type = TREE_TYPE (names[i]);
3642 if (!TYPE_UNSIGNED (type))
3644 type = build_nonstandard_integer_type (nprec, 1);
3645 tmp = build1 (NOP_EXPR, type, names[i]);
3647 if (minv != 0)
3649 tmp = build2 (PLUS_EXPR, type, tmp,
3650 wide_int_to_tree (type, -minv));
3651 maxv2 = maxv - minv;
3653 new_val = wide_int_to_tree (type, maxv2);
3655 if (dump_file)
3657 fprintf (dump_file, "Adding assert for ");
3658 print_generic_expr (dump_file, names[i]);
3659 fprintf (dump_file, " from ");
3660 print_generic_expr (dump_file, tmp);
3661 fprintf (dump_file, "\n");
3664 add_assert_info (asserts, names[i], tmp, LE_EXPR, new_val);
3671 /* OP is an operand of a truth value expression which is known to have
3672 a particular value. Register any asserts for OP and for any
3673 operands in OP's defining statement.
3675 If CODE is EQ_EXPR, then we want to register OP is zero (false),
3676 if CODE is NE_EXPR, then we want to register OP is nonzero (true). */
3678 static void
3679 register_edge_assert_for_1 (tree op, enum tree_code code,
3680 edge e, vec<assert_info> &asserts)
3682 gimple *op_def;
3683 tree val;
3684 enum tree_code rhs_code;
3686 /* We only care about SSA_NAMEs. */
3687 if (TREE_CODE (op) != SSA_NAME)
3688 return;
3690 /* We know that OP will have a zero or nonzero value. */
3691 val = build_int_cst (TREE_TYPE (op), 0);
3692 add_assert_info (asserts, op, op, code, val);
3694 /* Now look at how OP is set. If it's set from a comparison,
3695 a truth operation or some bit operations, then we may be able
3696 to register information about the operands of that assignment. */
3697 op_def = SSA_NAME_DEF_STMT (op);
3698 if (gimple_code (op_def) != GIMPLE_ASSIGN)
3699 return;
3701 rhs_code = gimple_assign_rhs_code (op_def);
3703 if (TREE_CODE_CLASS (rhs_code) == tcc_comparison)
3705 bool invert = (code == EQ_EXPR ? true : false);
3706 tree op0 = gimple_assign_rhs1 (op_def);
3707 tree op1 = gimple_assign_rhs2 (op_def);
3709 if (TREE_CODE (op0) == SSA_NAME)
3710 register_edge_assert_for_2 (op0, e, rhs_code, op0, op1, invert, asserts);
3711 if (TREE_CODE (op1) == SSA_NAME)
3712 register_edge_assert_for_2 (op1, e, rhs_code, op0, op1, invert, asserts);
3714 else if ((code == NE_EXPR
3715 && gimple_assign_rhs_code (op_def) == BIT_AND_EXPR)
3716 || (code == EQ_EXPR
3717 && gimple_assign_rhs_code (op_def) == BIT_IOR_EXPR))
3719 /* Recurse on each operand. */
3720 tree op0 = gimple_assign_rhs1 (op_def);
3721 tree op1 = gimple_assign_rhs2 (op_def);
3722 if (TREE_CODE (op0) == SSA_NAME
3723 && has_single_use (op0))
3724 register_edge_assert_for_1 (op0, code, e, asserts);
3725 if (TREE_CODE (op1) == SSA_NAME
3726 && has_single_use (op1))
3727 register_edge_assert_for_1 (op1, code, e, asserts);
3729 else if (gimple_assign_rhs_code (op_def) == BIT_NOT_EXPR
3730 && TYPE_PRECISION (TREE_TYPE (gimple_assign_lhs (op_def))) == 1)
3732 /* Recurse, flipping CODE. */
3733 code = invert_tree_comparison (code, false);
3734 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
3736 else if (gimple_assign_rhs_code (op_def) == SSA_NAME)
3738 /* Recurse through the copy. */
3739 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
3741 else if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (op_def)))
3743 /* Recurse through the type conversion, unless it is a narrowing
3744 conversion or conversion from non-integral type. */
3745 tree rhs = gimple_assign_rhs1 (op_def);
3746 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs))
3747 && (TYPE_PRECISION (TREE_TYPE (rhs))
3748 <= TYPE_PRECISION (TREE_TYPE (op))))
3749 register_edge_assert_for_1 (rhs, code, e, asserts);
3753 /* Check if comparison
3754 NAME COND_OP INTEGER_CST
3755 has a form of
3756 (X & 11...100..0) COND_OP XX...X00...0
3757 Such comparison can yield assertions like
3758 X >= XX...X00...0
3759 X <= XX...X11...1
3760 in case of COND_OP being EQ_EXPR or
3761 X < XX...X00...0
3762 X > XX...X11...1
3763 in case of NE_EXPR. */
3765 static bool
3766 is_masked_range_test (tree name, tree valt, enum tree_code cond_code,
3767 tree *new_name, tree *low, enum tree_code *low_code,
3768 tree *high, enum tree_code *high_code)
3770 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3772 if (!is_gimple_assign (def_stmt)
3773 || gimple_assign_rhs_code (def_stmt) != BIT_AND_EXPR)
3774 return false;
3776 tree t = gimple_assign_rhs1 (def_stmt);
3777 tree maskt = gimple_assign_rhs2 (def_stmt);
3778 if (TREE_CODE (t) != SSA_NAME || TREE_CODE (maskt) != INTEGER_CST)
3779 return false;
3781 wi::tree_to_wide_ref mask = wi::to_wide (maskt);
3782 wide_int inv_mask = ~mask;
3783 /* Must have been removed by now so don't bother optimizing. */
3784 if (mask == 0 || inv_mask == 0)
3785 return false;
3787 /* Assume VALT is INTEGER_CST. */
3788 wi::tree_to_wide_ref val = wi::to_wide (valt);
3790 if ((inv_mask & (inv_mask + 1)) != 0
3791 || (val & mask) != val)
3792 return false;
3794 bool is_range = cond_code == EQ_EXPR;
3796 tree type = TREE_TYPE (t);
3797 wide_int min = wi::min_value (type),
3798 max = wi::max_value (type);
3800 if (is_range)
3802 *low_code = val == min ? ERROR_MARK : GE_EXPR;
3803 *high_code = val == max ? ERROR_MARK : LE_EXPR;
3805 else
3807 /* We can still generate assertion if one of alternatives
3808 is known to always be false. */
3809 if (val == min)
3811 *low_code = (enum tree_code) 0;
3812 *high_code = GT_EXPR;
3814 else if ((val | inv_mask) == max)
3816 *low_code = LT_EXPR;
3817 *high_code = (enum tree_code) 0;
3819 else
3820 return false;
3823 *new_name = t;
3824 *low = wide_int_to_tree (type, val);
3825 *high = wide_int_to_tree (type, val | inv_mask);
3827 return true;
3830 /* Try to register an edge assertion for SSA name NAME on edge E for
3831 the condition COND contributing to the conditional jump pointed to by
3832 SI. */
3834 void
3835 register_edge_assert_for (tree name, edge e,
3836 enum tree_code cond_code, tree cond_op0,
3837 tree cond_op1, vec<assert_info> &asserts)
3839 tree val;
3840 enum tree_code comp_code;
3841 bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
3843 /* Do not attempt to infer anything in names that flow through
3844 abnormal edges. */
3845 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
3846 return;
3848 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
3849 cond_op0, cond_op1,
3850 is_else_edge,
3851 &comp_code, &val))
3852 return;
3854 /* Register ASSERT_EXPRs for name. */
3855 register_edge_assert_for_2 (name, e, cond_code, cond_op0,
3856 cond_op1, is_else_edge, asserts);
3859 /* If COND is effectively an equality test of an SSA_NAME against
3860 the value zero or one, then we may be able to assert values
3861 for SSA_NAMEs which flow into COND. */
3863 /* In the case of NAME == 1 or NAME != 0, for BIT_AND_EXPR defining
3864 statement of NAME we can assert both operands of the BIT_AND_EXPR
3865 have nonzero value. */
3866 if (((comp_code == EQ_EXPR && integer_onep (val))
3867 || (comp_code == NE_EXPR && integer_zerop (val))))
3869 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3871 if (is_gimple_assign (def_stmt)
3872 && gimple_assign_rhs_code (def_stmt) == BIT_AND_EXPR)
3874 tree op0 = gimple_assign_rhs1 (def_stmt);
3875 tree op1 = gimple_assign_rhs2 (def_stmt);
3876 register_edge_assert_for_1 (op0, NE_EXPR, e, asserts);
3877 register_edge_assert_for_1 (op1, NE_EXPR, e, asserts);
3881 /* In the case of NAME == 0 or NAME != 1, for BIT_IOR_EXPR defining
3882 statement of NAME we can assert both operands of the BIT_IOR_EXPR
3883 have zero value. */
3884 if (((comp_code == EQ_EXPR && integer_zerop (val))
3885 || (comp_code == NE_EXPR && integer_onep (val))))
3887 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
3889 /* For BIT_IOR_EXPR only if NAME == 0 both operands have
3890 necessarily zero value, or if type-precision is one. */
3891 if (is_gimple_assign (def_stmt)
3892 && (gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR
3893 && (TYPE_PRECISION (TREE_TYPE (name)) == 1
3894 || comp_code == EQ_EXPR)))
3896 tree op0 = gimple_assign_rhs1 (def_stmt);
3897 tree op1 = gimple_assign_rhs2 (def_stmt);
3898 register_edge_assert_for_1 (op0, EQ_EXPR, e, asserts);
3899 register_edge_assert_for_1 (op1, EQ_EXPR, e, asserts);
3903 /* Sometimes we can infer ranges from (NAME & MASK) == VALUE. */
3904 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
3905 && TREE_CODE (val) == INTEGER_CST)
3907 enum tree_code low_code, high_code;
3908 tree low, high;
3909 if (is_masked_range_test (name, val, comp_code, &name, &low,
3910 &low_code, &high, &high_code))
3912 if (low_code != ERROR_MARK)
3913 register_edge_assert_for_2 (name, e, low_code, name,
3914 low, /*invert*/false, asserts);
3915 if (high_code != ERROR_MARK)
3916 register_edge_assert_for_2 (name, e, high_code, name,
3917 high, /*invert*/false, asserts);
3922 /* Finish found ASSERTS for E and register them at GSI. */
3924 static void
3925 finish_register_edge_assert_for (edge e, gimple_stmt_iterator gsi,
3926 vec<assert_info> &asserts)
3928 for (unsigned i = 0; i < asserts.length (); ++i)
3929 /* Only register an ASSERT_EXPR if NAME was found in the sub-graph
3930 reachable from E. */
3931 if (live_on_edge (e, asserts[i].name))
3932 register_new_assert_for (asserts[i].name, asserts[i].expr,
3933 asserts[i].comp_code, asserts[i].val,
3934 NULL, e, gsi);
3939 /* Determine whether the outgoing edges of BB should receive an
3940 ASSERT_EXPR for each of the operands of BB's LAST statement.
3941 The last statement of BB must be a COND_EXPR.
3943 If any of the sub-graphs rooted at BB have an interesting use of
3944 the predicate operands, an assert location node is added to the
3945 list of assertions for the corresponding operands. */
3947 static void
3948 find_conditional_asserts (basic_block bb, gcond *last)
3950 gimple_stmt_iterator bsi;
3951 tree op;
3952 edge_iterator ei;
3953 edge e;
3954 ssa_op_iter iter;
3956 bsi = gsi_for_stmt (last);
3958 /* Look for uses of the operands in each of the sub-graphs
3959 rooted at BB. We need to check each of the outgoing edges
3960 separately, so that we know what kind of ASSERT_EXPR to
3961 insert. */
3962 FOR_EACH_EDGE (e, ei, bb->succs)
3964 if (e->dest == bb)
3965 continue;
3967 /* Register the necessary assertions for each operand in the
3968 conditional predicate. */
3969 auto_vec<assert_info, 8> asserts;
3970 FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
3971 register_edge_assert_for (op, e,
3972 gimple_cond_code (last),
3973 gimple_cond_lhs (last),
3974 gimple_cond_rhs (last), asserts);
3975 finish_register_edge_assert_for (e, bsi, asserts);
3979 struct case_info
3981 tree expr;
3982 basic_block bb;
3985 /* Compare two case labels sorting first by the destination bb index
3986 and then by the case value. */
3988 static int
3989 compare_case_labels (const void *p1, const void *p2)
3991 const struct case_info *ci1 = (const struct case_info *) p1;
3992 const struct case_info *ci2 = (const struct case_info *) p2;
3993 int idx1 = ci1->bb->index;
3994 int idx2 = ci2->bb->index;
3996 if (idx1 < idx2)
3997 return -1;
3998 else if (idx1 == idx2)
4000 /* Make sure the default label is first in a group. */
4001 if (!CASE_LOW (ci1->expr))
4002 return -1;
4003 else if (!CASE_LOW (ci2->expr))
4004 return 1;
4005 else
4006 return tree_int_cst_compare (CASE_LOW (ci1->expr),
4007 CASE_LOW (ci2->expr));
4009 else
4010 return 1;
4013 /* Determine whether the outgoing edges of BB should receive an
4014 ASSERT_EXPR for each of the operands of BB's LAST statement.
4015 The last statement of BB must be a SWITCH_EXPR.
4017 If any of the sub-graphs rooted at BB have an interesting use of
4018 the predicate operands, an assert location node is added to the
4019 list of assertions for the corresponding operands. */
4021 static void
4022 find_switch_asserts (basic_block bb, gswitch *last)
4024 gimple_stmt_iterator bsi;
4025 tree op;
4026 edge e;
4027 struct case_info *ci;
4028 size_t n = gimple_switch_num_labels (last);
4029 #if GCC_VERSION >= 4000
4030 unsigned int idx;
4031 #else
4032 /* Work around GCC 3.4 bug (PR 37086). */
4033 volatile unsigned int idx;
4034 #endif
4036 bsi = gsi_for_stmt (last);
4037 op = gimple_switch_index (last);
4038 if (TREE_CODE (op) != SSA_NAME)
4039 return;
4041 /* Build a vector of case labels sorted by destination label. */
4042 ci = XNEWVEC (struct case_info, n);
4043 for (idx = 0; idx < n; ++idx)
4045 ci[idx].expr = gimple_switch_label (last, idx);
4046 ci[idx].bb = label_to_block (CASE_LABEL (ci[idx].expr));
4048 edge default_edge = find_edge (bb, ci[0].bb);
4049 qsort (ci, n, sizeof (struct case_info), compare_case_labels);
4051 for (idx = 0; idx < n; ++idx)
4053 tree min, max;
4054 tree cl = ci[idx].expr;
4055 basic_block cbb = ci[idx].bb;
4057 min = CASE_LOW (cl);
4058 max = CASE_HIGH (cl);
4060 /* If there are multiple case labels with the same destination
4061 we need to combine them to a single value range for the edge. */
4062 if (idx + 1 < n && cbb == ci[idx + 1].bb)
4064 /* Skip labels until the last of the group. */
4065 do {
4066 ++idx;
4067 } while (idx < n && cbb == ci[idx].bb);
4068 --idx;
4070 /* Pick up the maximum of the case label range. */
4071 if (CASE_HIGH (ci[idx].expr))
4072 max = CASE_HIGH (ci[idx].expr);
4073 else
4074 max = CASE_LOW (ci[idx].expr);
4077 /* Can't extract a useful assertion out of a range that includes the
4078 default label. */
4079 if (min == NULL_TREE)
4080 continue;
4082 /* Find the edge to register the assert expr on. */
4083 e = find_edge (bb, cbb);
4085 /* Register the necessary assertions for the operand in the
4086 SWITCH_EXPR. */
4087 auto_vec<assert_info, 8> asserts;
4088 register_edge_assert_for (op, e,
4089 max ? GE_EXPR : EQ_EXPR,
4090 op, fold_convert (TREE_TYPE (op), min),
4091 asserts);
4092 if (max)
4093 register_edge_assert_for (op, e, LE_EXPR, op,
4094 fold_convert (TREE_TYPE (op), max),
4095 asserts);
4096 finish_register_edge_assert_for (e, bsi, asserts);
4099 XDELETEVEC (ci);
4101 if (!live_on_edge (default_edge, op))
4102 return;
4104 /* Now register along the default label assertions that correspond to the
4105 anti-range of each label. */
4106 int insertion_limit = PARAM_VALUE (PARAM_MAX_VRP_SWITCH_ASSERTIONS);
4107 if (insertion_limit == 0)
4108 return;
4110 /* We can't do this if the default case shares a label with another case. */
4111 tree default_cl = gimple_switch_default_label (last);
4112 for (idx = 1; idx < n; idx++)
4114 tree min, max;
4115 tree cl = gimple_switch_label (last, idx);
4116 if (CASE_LABEL (cl) == CASE_LABEL (default_cl))
4117 continue;
4119 min = CASE_LOW (cl);
4120 max = CASE_HIGH (cl);
4122 /* Combine contiguous case ranges to reduce the number of assertions
4123 to insert. */
4124 for (idx = idx + 1; idx < n; idx++)
4126 tree next_min, next_max;
4127 tree next_cl = gimple_switch_label (last, idx);
4128 if (CASE_LABEL (next_cl) == CASE_LABEL (default_cl))
4129 break;
4131 next_min = CASE_LOW (next_cl);
4132 next_max = CASE_HIGH (next_cl);
4134 wide_int difference = (wi::to_wide (next_min)
4135 - wi::to_wide (max ? max : min));
4136 if (wi::eq_p (difference, 1))
4137 max = next_max ? next_max : next_min;
4138 else
4139 break;
4141 idx--;
4143 if (max == NULL_TREE)
4145 /* Register the assertion OP != MIN. */
4146 auto_vec<assert_info, 8> asserts;
4147 min = fold_convert (TREE_TYPE (op), min);
4148 register_edge_assert_for (op, default_edge, NE_EXPR, op, min,
4149 asserts);
4150 finish_register_edge_assert_for (default_edge, bsi, asserts);
4152 else
4154 /* Register the assertion (unsigned)OP - MIN > (MAX - MIN),
4155 which will give OP the anti-range ~[MIN,MAX]. */
4156 tree uop = fold_convert (unsigned_type_for (TREE_TYPE (op)), op);
4157 min = fold_convert (TREE_TYPE (uop), min);
4158 max = fold_convert (TREE_TYPE (uop), max);
4160 tree lhs = fold_build2 (MINUS_EXPR, TREE_TYPE (uop), uop, min);
4161 tree rhs = int_const_binop (MINUS_EXPR, max, min);
4162 register_new_assert_for (op, lhs, GT_EXPR, rhs,
4163 NULL, default_edge, bsi);
4166 if (--insertion_limit == 0)
4167 break;
4172 /* Traverse all the statements in block BB looking for statements that
4173 may generate useful assertions for the SSA names in their operand.
4174 If a statement produces a useful assertion A for name N_i, then the
4175 list of assertions already generated for N_i is scanned to
4176 determine if A is actually needed.
4178 If N_i already had the assertion A at a location dominating the
4179 current location, then nothing needs to be done. Otherwise, the
4180 new location for A is recorded instead.
4182 1- For every statement S in BB, all the variables used by S are
4183 added to bitmap FOUND_IN_SUBGRAPH.
4185 2- If statement S uses an operand N in a way that exposes a known
4186 value range for N, then if N was not already generated by an
4187 ASSERT_EXPR, create a new assert location for N. For instance,
4188 if N is a pointer and the statement dereferences it, we can
4189 assume that N is not NULL.
4191 3- COND_EXPRs are a special case of #2. We can derive range
4192 information from the predicate but need to insert different
4193 ASSERT_EXPRs for each of the sub-graphs rooted at the
4194 conditional block. If the last statement of BB is a conditional
4195 expression of the form 'X op Y', then
4197 a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
4199 b) If the conditional is the only entry point to the sub-graph
4200 corresponding to the THEN_CLAUSE, recurse into it. On
4201 return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
4202 an ASSERT_EXPR is added for the corresponding variable.
4204 c) Repeat step (b) on the ELSE_CLAUSE.
4206 d) Mark X and Y in FOUND_IN_SUBGRAPH.
4208 For instance,
4210 if (a == 9)
4211 b = a;
4212 else
4213 b = c + 1;
4215 In this case, an assertion on the THEN clause is useful to
4216 determine that 'a' is always 9 on that edge. However, an assertion
4217 on the ELSE clause would be unnecessary.
4219 4- If BB does not end in a conditional expression, then we recurse
4220 into BB's dominator children.
4222 At the end of the recursive traversal, every SSA name will have a
4223 list of locations where ASSERT_EXPRs should be added. When a new
4224 location for name N is found, it is registered by calling
4225 register_new_assert_for. That function keeps track of all the
4226 registered assertions to prevent adding unnecessary assertions.
4227 For instance, if a pointer P_4 is dereferenced more than once in a
4228 dominator tree, only the location dominating all the dereference of
4229 P_4 will receive an ASSERT_EXPR. */
4231 static void
4232 find_assert_locations_1 (basic_block bb, sbitmap live)
4234 gimple *last;
4236 last = last_stmt (bb);
4238 /* If BB's last statement is a conditional statement involving integer
4239 operands, determine if we need to add ASSERT_EXPRs. */
4240 if (last
4241 && gimple_code (last) == GIMPLE_COND
4242 && !fp_predicate (last)
4243 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
4244 find_conditional_asserts (bb, as_a <gcond *> (last));
4246 /* If BB's last statement is a switch statement involving integer
4247 operands, determine if we need to add ASSERT_EXPRs. */
4248 if (last
4249 && gimple_code (last) == GIMPLE_SWITCH
4250 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
4251 find_switch_asserts (bb, as_a <gswitch *> (last));
4253 /* Traverse all the statements in BB marking used names and looking
4254 for statements that may infer assertions for their used operands. */
4255 for (gimple_stmt_iterator si = gsi_last_bb (bb); !gsi_end_p (si);
4256 gsi_prev (&si))
4258 gimple *stmt;
4259 tree op;
4260 ssa_op_iter i;
4262 stmt = gsi_stmt (si);
4264 if (is_gimple_debug (stmt))
4265 continue;
4267 /* See if we can derive an assertion for any of STMT's operands. */
4268 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
4270 tree value;
4271 enum tree_code comp_code;
4273 /* If op is not live beyond this stmt, do not bother to insert
4274 asserts for it. */
4275 if (!bitmap_bit_p (live, SSA_NAME_VERSION (op)))
4276 continue;
4278 /* If OP is used in such a way that we can infer a value
4279 range for it, and we don't find a previous assertion for
4280 it, create a new assertion location node for OP. */
4281 if (infer_value_range (stmt, op, &comp_code, &value))
4283 /* If we are able to infer a nonzero value range for OP,
4284 then walk backwards through the use-def chain to see if OP
4285 was set via a typecast.
4287 If so, then we can also infer a nonzero value range
4288 for the operand of the NOP_EXPR. */
4289 if (comp_code == NE_EXPR && integer_zerop (value))
4291 tree t = op;
4292 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
4294 while (is_gimple_assign (def_stmt)
4295 && CONVERT_EXPR_CODE_P
4296 (gimple_assign_rhs_code (def_stmt))
4297 && TREE_CODE
4298 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
4299 && POINTER_TYPE_P
4300 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
4302 t = gimple_assign_rhs1 (def_stmt);
4303 def_stmt = SSA_NAME_DEF_STMT (t);
4305 /* Note we want to register the assert for the
4306 operand of the NOP_EXPR after SI, not after the
4307 conversion. */
4308 if (bitmap_bit_p (live, SSA_NAME_VERSION (t)))
4309 register_new_assert_for (t, t, comp_code, value,
4310 bb, NULL, si);
4314 register_new_assert_for (op, op, comp_code, value, bb, NULL, si);
4318 /* Update live. */
4319 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
4320 bitmap_set_bit (live, SSA_NAME_VERSION (op));
4321 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_DEF)
4322 bitmap_clear_bit (live, SSA_NAME_VERSION (op));
4325 /* Traverse all PHI nodes in BB, updating live. */
4326 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
4327 gsi_next (&si))
4329 use_operand_p arg_p;
4330 ssa_op_iter i;
4331 gphi *phi = si.phi ();
4332 tree res = gimple_phi_result (phi);
4334 if (virtual_operand_p (res))
4335 continue;
4337 FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
4339 tree arg = USE_FROM_PTR (arg_p);
4340 if (TREE_CODE (arg) == SSA_NAME)
4341 bitmap_set_bit (live, SSA_NAME_VERSION (arg));
4344 bitmap_clear_bit (live, SSA_NAME_VERSION (res));
4348 /* Do an RPO walk over the function computing SSA name liveness
4349 on-the-fly and deciding on assert expressions to insert. */
4351 static void
4352 find_assert_locations (void)
4354 int *rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
4355 int *bb_rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
4356 int *last_rpo = XCNEWVEC (int, last_basic_block_for_fn (cfun));
4357 int rpo_cnt, i;
4359 live = XCNEWVEC (sbitmap, last_basic_block_for_fn (cfun));
4360 rpo_cnt = pre_and_rev_post_order_compute (NULL, rpo, false);
4361 for (i = 0; i < rpo_cnt; ++i)
4362 bb_rpo[rpo[i]] = i;
4364 /* Pre-seed loop latch liveness from loop header PHI nodes. Due to
4365 the order we compute liveness and insert asserts we otherwise
4366 fail to insert asserts into the loop latch. */
4367 loop_p loop;
4368 FOR_EACH_LOOP (loop, 0)
4370 i = loop->latch->index;
4371 unsigned int j = single_succ_edge (loop->latch)->dest_idx;
4372 for (gphi_iterator gsi = gsi_start_phis (loop->header);
4373 !gsi_end_p (gsi); gsi_next (&gsi))
4375 gphi *phi = gsi.phi ();
4376 if (virtual_operand_p (gimple_phi_result (phi)))
4377 continue;
4378 tree arg = gimple_phi_arg_def (phi, j);
4379 if (TREE_CODE (arg) == SSA_NAME)
4381 if (live[i] == NULL)
4383 live[i] = sbitmap_alloc (num_ssa_names);
4384 bitmap_clear (live[i]);
4386 bitmap_set_bit (live[i], SSA_NAME_VERSION (arg));
4391 for (i = rpo_cnt - 1; i >= 0; --i)
4393 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, rpo[i]);
4394 edge e;
4395 edge_iterator ei;
4397 if (!live[rpo[i]])
4399 live[rpo[i]] = sbitmap_alloc (num_ssa_names);
4400 bitmap_clear (live[rpo[i]]);
4403 /* Process BB and update the live information with uses in
4404 this block. */
4405 find_assert_locations_1 (bb, live[rpo[i]]);
4407 /* Merge liveness into the predecessor blocks and free it. */
4408 if (!bitmap_empty_p (live[rpo[i]]))
4410 int pred_rpo = i;
4411 FOR_EACH_EDGE (e, ei, bb->preds)
4413 int pred = e->src->index;
4414 if ((e->flags & EDGE_DFS_BACK) || pred == ENTRY_BLOCK)
4415 continue;
4417 if (!live[pred])
4419 live[pred] = sbitmap_alloc (num_ssa_names);
4420 bitmap_clear (live[pred]);
4422 bitmap_ior (live[pred], live[pred], live[rpo[i]]);
4424 if (bb_rpo[pred] < pred_rpo)
4425 pred_rpo = bb_rpo[pred];
4428 /* Record the RPO number of the last visited block that needs
4429 live information from this block. */
4430 last_rpo[rpo[i]] = pred_rpo;
4432 else
4434 sbitmap_free (live[rpo[i]]);
4435 live[rpo[i]] = NULL;
4438 /* We can free all successors live bitmaps if all their
4439 predecessors have been visited already. */
4440 FOR_EACH_EDGE (e, ei, bb->succs)
4441 if (last_rpo[e->dest->index] == i
4442 && live[e->dest->index])
4444 sbitmap_free (live[e->dest->index]);
4445 live[e->dest->index] = NULL;
4449 XDELETEVEC (rpo);
4450 XDELETEVEC (bb_rpo);
4451 XDELETEVEC (last_rpo);
4452 for (i = 0; i < last_basic_block_for_fn (cfun); ++i)
4453 if (live[i])
4454 sbitmap_free (live[i]);
4455 XDELETEVEC (live);
4458 /* Create an ASSERT_EXPR for NAME and insert it in the location
4459 indicated by LOC. Return true if we made any edge insertions. */
4461 static bool
4462 process_assert_insertions_for (tree name, assert_locus *loc)
4464 /* Build the comparison expression NAME_i COMP_CODE VAL. */
4465 gimple *stmt;
4466 tree cond;
4467 gimple *assert_stmt;
4468 edge_iterator ei;
4469 edge e;
4471 /* If we have X <=> X do not insert an assert expr for that. */
4472 if (loc->expr == loc->val)
4473 return false;
4475 cond = build2 (loc->comp_code, boolean_type_node, loc->expr, loc->val);
4476 assert_stmt = build_assert_expr_for (cond, name);
4477 if (loc->e)
4479 /* We have been asked to insert the assertion on an edge. This
4480 is used only by COND_EXPR and SWITCH_EXPR assertions. */
4481 gcc_checking_assert (gimple_code (gsi_stmt (loc->si)) == GIMPLE_COND
4482 || (gimple_code (gsi_stmt (loc->si))
4483 == GIMPLE_SWITCH));
4485 gsi_insert_on_edge (loc->e, assert_stmt);
4486 return true;
4489 /* If the stmt iterator points at the end then this is an insertion
4490 at the beginning of a block. */
4491 if (gsi_end_p (loc->si))
4493 gimple_stmt_iterator si = gsi_after_labels (loc->bb);
4494 gsi_insert_before (&si, assert_stmt, GSI_SAME_STMT);
4495 return false;
4498 /* Otherwise, we can insert right after LOC->SI iff the
4499 statement must not be the last statement in the block. */
4500 stmt = gsi_stmt (loc->si);
4501 if (!stmt_ends_bb_p (stmt))
4503 gsi_insert_after (&loc->si, assert_stmt, GSI_SAME_STMT);
4504 return false;
4507 /* If STMT must be the last statement in BB, we can only insert new
4508 assertions on the non-abnormal edge out of BB. Note that since
4509 STMT is not control flow, there may only be one non-abnormal/eh edge
4510 out of BB. */
4511 FOR_EACH_EDGE (e, ei, loc->bb->succs)
4512 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
4514 gsi_insert_on_edge (e, assert_stmt);
4515 return true;
4518 gcc_unreachable ();
4521 /* Qsort helper for sorting assert locations. If stable is true, don't
4522 use iterative_hash_expr because it can be unstable for -fcompare-debug,
4523 on the other side some pointers might be NULL. */
4525 template <bool stable>
4526 static int
4527 compare_assert_loc (const void *pa, const void *pb)
4529 assert_locus * const a = *(assert_locus * const *)pa;
4530 assert_locus * const b = *(assert_locus * const *)pb;
4532 /* If stable, some asserts might be optimized away already, sort
4533 them last. */
4534 if (stable)
4536 if (a == NULL)
4537 return b != NULL;
4538 else if (b == NULL)
4539 return -1;
4542 if (a->e == NULL && b->e != NULL)
4543 return 1;
4544 else if (a->e != NULL && b->e == NULL)
4545 return -1;
4547 /* After the above checks, we know that (a->e == NULL) == (b->e == NULL),
4548 no need to test both a->e and b->e. */
4550 /* Sort after destination index. */
4551 if (a->e == NULL)
4553 else if (a->e->dest->index > b->e->dest->index)
4554 return 1;
4555 else if (a->e->dest->index < b->e->dest->index)
4556 return -1;
4558 /* Sort after comp_code. */
4559 if (a->comp_code > b->comp_code)
4560 return 1;
4561 else if (a->comp_code < b->comp_code)
4562 return -1;
4564 hashval_t ha, hb;
4566 /* E.g. if a->val is ADDR_EXPR of a VAR_DECL, iterative_hash_expr
4567 uses DECL_UID of the VAR_DECL, so sorting might differ between
4568 -g and -g0. When doing the removal of redundant assert exprs
4569 and commonization to successors, this does not matter, but for
4570 the final sort needs to be stable. */
4571 if (stable)
4573 ha = 0;
4574 hb = 0;
4576 else
4578 ha = iterative_hash_expr (a->expr, iterative_hash_expr (a->val, 0));
4579 hb = iterative_hash_expr (b->expr, iterative_hash_expr (b->val, 0));
4582 /* Break the tie using hashing and source/bb index. */
4583 if (ha == hb)
4584 return (a->e != NULL
4585 ? a->e->src->index - b->e->src->index
4586 : a->bb->index - b->bb->index);
4587 return ha > hb ? 1 : -1;
4590 /* Process all the insertions registered for every name N_i registered
4591 in NEED_ASSERT_FOR. The list of assertions to be inserted are
4592 found in ASSERTS_FOR[i]. */
4594 static void
4595 process_assert_insertions (void)
4597 unsigned i;
4598 bitmap_iterator bi;
4599 bool update_edges_p = false;
4600 int num_asserts = 0;
4602 if (dump_file && (dump_flags & TDF_DETAILS))
4603 dump_all_asserts (dump_file);
4605 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
4607 assert_locus *loc = asserts_for[i];
4608 gcc_assert (loc);
4610 auto_vec<assert_locus *, 16> asserts;
4611 for (; loc; loc = loc->next)
4612 asserts.safe_push (loc);
4613 asserts.qsort (compare_assert_loc<false>);
4615 /* Push down common asserts to successors and remove redundant ones. */
4616 unsigned ecnt = 0;
4617 assert_locus *common = NULL;
4618 unsigned commonj = 0;
4619 for (unsigned j = 0; j < asserts.length (); ++j)
4621 loc = asserts[j];
4622 if (! loc->e)
4623 common = NULL;
4624 else if (! common
4625 || loc->e->dest != common->e->dest
4626 || loc->comp_code != common->comp_code
4627 || ! operand_equal_p (loc->val, common->val, 0)
4628 || ! operand_equal_p (loc->expr, common->expr, 0))
4630 commonj = j;
4631 common = loc;
4632 ecnt = 1;
4634 else if (loc->e == asserts[j-1]->e)
4636 /* Remove duplicate asserts. */
4637 if (commonj == j - 1)
4639 commonj = j;
4640 common = loc;
4642 free (asserts[j-1]);
4643 asserts[j-1] = NULL;
4645 else
4647 ecnt++;
4648 if (EDGE_COUNT (common->e->dest->preds) == ecnt)
4650 /* We have the same assertion on all incoming edges of a BB.
4651 Insert it at the beginning of that block. */
4652 loc->bb = loc->e->dest;
4653 loc->e = NULL;
4654 loc->si = gsi_none ();
4655 common = NULL;
4656 /* Clear asserts commoned. */
4657 for (; commonj != j; ++commonj)
4658 if (asserts[commonj])
4660 free (asserts[commonj]);
4661 asserts[commonj] = NULL;
4667 /* The asserts vector sorting above might be unstable for
4668 -fcompare-debug, sort again to ensure a stable sort. */
4669 asserts.qsort (compare_assert_loc<true>);
4670 for (unsigned j = 0; j < asserts.length (); ++j)
4672 loc = asserts[j];
4673 if (! loc)
4674 break;
4675 update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
4676 num_asserts++;
4677 free (loc);
4681 if (update_edges_p)
4682 gsi_commit_edge_inserts ();
4684 statistics_counter_event (cfun, "Number of ASSERT_EXPR expressions inserted",
4685 num_asserts);
4689 /* Traverse the flowgraph looking for conditional jumps to insert range
4690 expressions. These range expressions are meant to provide information
4691 to optimizations that need to reason in terms of value ranges. They
4692 will not be expanded into RTL. For instance, given:
4694 x = ...
4695 y = ...
4696 if (x < y)
4697 y = x - 2;
4698 else
4699 x = y + 3;
4701 this pass will transform the code into:
4703 x = ...
4704 y = ...
4705 if (x < y)
4707 x = ASSERT_EXPR <x, x < y>
4708 y = x - 2
4710 else
4712 y = ASSERT_EXPR <y, x >= y>
4713 x = y + 3
4716 The idea is that once copy and constant propagation have run, other
4717 optimizations will be able to determine what ranges of values can 'x'
4718 take in different paths of the code, simply by checking the reaching
4719 definition of 'x'. */
4721 static void
4722 insert_range_assertions (void)
4724 need_assert_for = BITMAP_ALLOC (NULL);
4725 asserts_for = XCNEWVEC (assert_locus *, num_ssa_names);
4727 calculate_dominance_info (CDI_DOMINATORS);
4729 find_assert_locations ();
4730 if (!bitmap_empty_p (need_assert_for))
4732 process_assert_insertions ();
4733 update_ssa (TODO_update_ssa_no_phi);
4736 if (dump_file && (dump_flags & TDF_DETAILS))
4738 fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
4739 dump_function_to_file (current_function_decl, dump_file, dump_flags);
4742 free (asserts_for);
4743 BITMAP_FREE (need_assert_for);
4746 class vrp_prop : public ssa_propagation_engine
4748 public:
4749 enum ssa_prop_result visit_stmt (gimple *, edge *, tree *) FINAL OVERRIDE;
4750 enum ssa_prop_result visit_phi (gphi *) FINAL OVERRIDE;
4752 void vrp_initialize (void);
4753 void vrp_finalize (bool);
4754 void check_all_array_refs (void);
4755 void check_array_ref (location_t, tree, bool);
4756 void check_mem_ref (location_t, tree, bool);
4757 void search_for_addr_array (tree, location_t);
4759 class vr_values vr_values;
4760 /* Temporary delegator to minimize code churn. */
4761 value_range *get_value_range (const_tree op)
4762 { return vr_values.get_value_range (op); }
4763 void set_defs_to_varying (gimple *stmt)
4764 { return vr_values.set_defs_to_varying (stmt); }
4765 void extract_range_from_stmt (gimple *stmt, edge *taken_edge_p,
4766 tree *output_p, value_range *vr)
4767 { vr_values.extract_range_from_stmt (stmt, taken_edge_p, output_p, vr); }
4768 bool update_value_range (const_tree op, value_range *vr)
4769 { return vr_values.update_value_range (op, vr); }
4770 void extract_range_basic (value_range *vr, gimple *stmt)
4771 { vr_values.extract_range_basic (vr, stmt); }
4772 void extract_range_from_phi_node (gphi *phi, value_range *vr)
4773 { vr_values.extract_range_from_phi_node (phi, vr); }
4775 /* Checks one ARRAY_REF in REF, located at LOCUS. Ignores flexible arrays
4776 and "struct" hacks. If VRP can determine that the
4777 array subscript is a constant, check if it is outside valid
4778 range. If the array subscript is a RANGE, warn if it is
4779 non-overlapping with valid range.
4780 IGNORE_OFF_BY_ONE is true if the ARRAY_REF is inside a ADDR_EXPR. */
4782 void
4783 vrp_prop::check_array_ref (location_t location, tree ref,
4784 bool ignore_off_by_one)
4786 value_range *vr = NULL;
4787 tree low_sub, up_sub;
4788 tree low_bound, up_bound, up_bound_p1;
4790 if (TREE_NO_WARNING (ref))
4791 return;
4793 low_sub = up_sub = TREE_OPERAND (ref, 1);
4794 up_bound = array_ref_up_bound (ref);
4796 if (!up_bound
4797 || TREE_CODE (up_bound) != INTEGER_CST
4798 || (warn_array_bounds < 2
4799 && array_at_struct_end_p (ref)))
4801 /* Accesses to trailing arrays via pointers may access storage
4802 beyond the types array bounds. For such arrays, or for flexible
4803 array members, as well as for other arrays of an unknown size,
4804 replace the upper bound with a more permissive one that assumes
4805 the size of the largest object is PTRDIFF_MAX. */
4806 tree eltsize = array_ref_element_size (ref);
4808 if (TREE_CODE (eltsize) != INTEGER_CST
4809 || integer_zerop (eltsize))
4811 up_bound = NULL_TREE;
4812 up_bound_p1 = NULL_TREE;
4814 else
4816 tree maxbound = TYPE_MAX_VALUE (ptrdiff_type_node);
4817 tree arg = TREE_OPERAND (ref, 0);
4818 poly_int64 off;
4820 if (get_addr_base_and_unit_offset (arg, &off) && known_gt (off, 0))
4821 maxbound = wide_int_to_tree (sizetype,
4822 wi::sub (wi::to_wide (maxbound),
4823 off));
4824 else
4825 maxbound = fold_convert (sizetype, maxbound);
4827 up_bound_p1 = int_const_binop (TRUNC_DIV_EXPR, maxbound, eltsize);
4829 up_bound = int_const_binop (MINUS_EXPR, up_bound_p1,
4830 build_int_cst (ptrdiff_type_node, 1));
4833 else
4834 up_bound_p1 = int_const_binop (PLUS_EXPR, up_bound,
4835 build_int_cst (TREE_TYPE (up_bound), 1));
4837 low_bound = array_ref_low_bound (ref);
4839 tree artype = TREE_TYPE (TREE_OPERAND (ref, 0));
4841 /* Empty array. */
4842 if (up_bound && tree_int_cst_equal (low_bound, up_bound_p1))
4844 warning_at (location, OPT_Warray_bounds,
4845 "array subscript %E is above array bounds of %qT",
4846 low_bound, artype);
4847 TREE_NO_WARNING (ref) = 1;
4850 if (TREE_CODE (low_sub) == SSA_NAME)
4852 vr = get_value_range (low_sub);
4853 if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
4855 low_sub = vr->type == VR_RANGE ? vr->max : vr->min;
4856 up_sub = vr->type == VR_RANGE ? vr->min : vr->max;
4860 if (vr && vr->type == VR_ANTI_RANGE)
4862 if (up_bound
4863 && TREE_CODE (up_sub) == INTEGER_CST
4864 && (ignore_off_by_one
4865 ? tree_int_cst_lt (up_bound, up_sub)
4866 : tree_int_cst_le (up_bound, up_sub))
4867 && TREE_CODE (low_sub) == INTEGER_CST
4868 && tree_int_cst_le (low_sub, low_bound))
4870 warning_at (location, OPT_Warray_bounds,
4871 "array subscript [%E, %E] is outside array bounds of %qT",
4872 low_sub, up_sub, artype);
4873 TREE_NO_WARNING (ref) = 1;
4876 else if (up_bound
4877 && TREE_CODE (up_sub) == INTEGER_CST
4878 && (ignore_off_by_one
4879 ? !tree_int_cst_le (up_sub, up_bound_p1)
4880 : !tree_int_cst_le (up_sub, up_bound)))
4882 if (dump_file && (dump_flags & TDF_DETAILS))
4884 fprintf (dump_file, "Array bound warning for ");
4885 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
4886 fprintf (dump_file, "\n");
4888 warning_at (location, OPT_Warray_bounds,
4889 "array subscript %E is above array bounds of %qT",
4890 up_sub, artype);
4891 TREE_NO_WARNING (ref) = 1;
4893 else if (TREE_CODE (low_sub) == INTEGER_CST
4894 && tree_int_cst_lt (low_sub, low_bound))
4896 if (dump_file && (dump_flags & TDF_DETAILS))
4898 fprintf (dump_file, "Array bound warning for ");
4899 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
4900 fprintf (dump_file, "\n");
4902 warning_at (location, OPT_Warray_bounds,
4903 "array subscript %E is below array bounds of %qT",
4904 low_sub, artype);
4905 TREE_NO_WARNING (ref) = 1;
4909 /* Checks one MEM_REF in REF, located at LOCATION, for out-of-bounds
4910 references to string constants. If VRP can determine that the array
4911 subscript is a constant, check if it is outside valid range.
4912 If the array subscript is a RANGE, warn if it is non-overlapping
4913 with valid range.
4914 IGNORE_OFF_BY_ONE is true if the MEM_REF is inside an ADDR_EXPR
4915 (used to allow one-past-the-end indices for code that takes
4916 the address of the just-past-the-end element of an array). */
4918 void
4919 vrp_prop::check_mem_ref (location_t location, tree ref, bool ignore_off_by_one)
4921 if (TREE_NO_WARNING (ref))
4922 return;
4924 tree arg = TREE_OPERAND (ref, 0);
4925 /* The constant and variable offset of the reference. */
4926 tree cstoff = TREE_OPERAND (ref, 1);
4927 tree varoff = NULL_TREE;
4929 const offset_int maxobjsize = tree_to_shwi (max_object_size ());
4931 /* The array or string constant bounds in bytes. Initially set
4932 to [-MAXOBJSIZE - 1, MAXOBJSIZE] until a tighter bound is
4933 determined. */
4934 offset_int arrbounds[2] = { -maxobjsize - 1, maxobjsize };
4936 /* The minimum and maximum intermediate offset. For a reference
4937 to be valid, not only does the final offset/subscript must be
4938 in bounds but all intermediate offsets should be as well.
4939 GCC may be able to deal gracefully with such out-of-bounds
4940 offsets so the checking is only enbaled at -Warray-bounds=2
4941 where it may help detect bugs in uses of the intermediate
4942 offsets that could otherwise not be detectable. */
4943 offset_int ioff = wi::to_offset (fold_convert (ptrdiff_type_node, cstoff));
4944 offset_int extrema[2] = { 0, wi::abs (ioff) };
4946 /* The range of the byte offset into the reference. */
4947 offset_int offrange[2] = { 0, 0 };
4949 value_range *vr = NULL;
4951 /* Determine the offsets and increment OFFRANGE for the bounds of each.
4952 The loop computes the the range of the final offset for expressions
4953 such as (A + i0 + ... + iN)[CSTOFF] where i0 through iN are SSA_NAMEs
4954 in some range. */
4955 while (TREE_CODE (arg) == SSA_NAME)
4957 gimple *def = SSA_NAME_DEF_STMT (arg);
4958 if (!is_gimple_assign (def))
4959 break;
4961 tree_code code = gimple_assign_rhs_code (def);
4962 if (code == POINTER_PLUS_EXPR)
4964 arg = gimple_assign_rhs1 (def);
4965 varoff = gimple_assign_rhs2 (def);
4967 else if (code == ASSERT_EXPR)
4969 arg = TREE_OPERAND (gimple_assign_rhs1 (def), 0);
4970 continue;
4972 else
4973 return;
4975 /* VAROFF should always be a SSA_NAME here (and not even
4976 INTEGER_CST) but there's no point in taking chances. */
4977 if (TREE_CODE (varoff) != SSA_NAME)
4978 break;
4980 vr = get_value_range (varoff);
4981 if (!vr || vr->type == VR_UNDEFINED || !vr->min || !vr->max)
4982 break;
4984 if (TREE_CODE (vr->min) != INTEGER_CST
4985 || TREE_CODE (vr->max) != INTEGER_CST)
4986 break;
4988 if (vr->type == VR_RANGE)
4990 if (tree_int_cst_lt (vr->min, vr->max))
4992 offset_int min
4993 = wi::to_offset (fold_convert (ptrdiff_type_node, vr->min));
4994 offset_int max
4995 = wi::to_offset (fold_convert (ptrdiff_type_node, vr->max));
4996 if (min < max)
4998 offrange[0] += min;
4999 offrange[1] += max;
5001 else
5003 offrange[0] += max;
5004 offrange[1] += min;
5007 else
5009 /* Conservatively add [-MAXOBJSIZE -1, MAXOBJSIZE]
5010 to OFFRANGE. */
5011 offrange[0] += arrbounds[0];
5012 offrange[1] += arrbounds[1];
5015 else
5017 /* For an anti-range, analogously to the above, conservatively
5018 add [-MAXOBJSIZE -1, MAXOBJSIZE] to OFFRANGE. */
5019 offrange[0] += arrbounds[0];
5020 offrange[1] += arrbounds[1];
5023 /* Keep track of the minimum and maximum offset. */
5024 if (offrange[1] < 0 && offrange[1] < extrema[0])
5025 extrema[0] = offrange[1];
5026 if (offrange[0] > 0 && offrange[0] > extrema[1])
5027 extrema[1] = offrange[0];
5029 if (offrange[0] < arrbounds[0])
5030 offrange[0] = arrbounds[0];
5032 if (offrange[1] > arrbounds[1])
5033 offrange[1] = arrbounds[1];
5036 if (TREE_CODE (arg) == ADDR_EXPR)
5038 arg = TREE_OPERAND (arg, 0);
5039 if (TREE_CODE (arg) != STRING_CST
5040 && TREE_CODE (arg) != VAR_DECL)
5041 return;
5043 else
5044 return;
5046 /* The type of the object being referred to. It can be an array,
5047 string literal, or a non-array type when the MEM_REF represents
5048 a reference/subscript via a pointer to an object that is not
5049 an element of an array. References to members of structs and
5050 unions are excluded because MEM_REF doesn't make it possible
5051 to identify the member where the reference originated. */
5052 tree reftype = TREE_TYPE (arg);
5053 if (POINTER_TYPE_P (reftype)
5054 || RECORD_OR_UNION_TYPE_P (reftype))
5055 return;
5057 offset_int eltsize;
5058 if (TREE_CODE (reftype) == ARRAY_TYPE)
5060 eltsize = wi::to_offset (TYPE_SIZE_UNIT (TREE_TYPE (reftype)));
5062 if (tree dom = TYPE_DOMAIN (reftype))
5064 tree bnds[] = { TYPE_MIN_VALUE (dom), TYPE_MAX_VALUE (dom) };
5065 if (array_at_struct_end_p (arg)
5066 || !bnds[0] || !bnds[1])
5068 arrbounds[0] = 0;
5069 arrbounds[1] = wi::lrshift (maxobjsize, wi::floor_log2 (eltsize));
5071 else
5073 arrbounds[0] = wi::to_offset (bnds[0]) * eltsize;
5074 arrbounds[1] = (wi::to_offset (bnds[1]) + 1) * eltsize;
5077 else
5079 arrbounds[0] = 0;
5080 arrbounds[1] = wi::lrshift (maxobjsize, wi::floor_log2 (eltsize));
5083 if (TREE_CODE (ref) == MEM_REF)
5085 /* For MEM_REF determine a tighter bound of the non-array
5086 element type. */
5087 tree eltype = TREE_TYPE (reftype);
5088 while (TREE_CODE (eltype) == ARRAY_TYPE)
5089 eltype = TREE_TYPE (eltype);
5090 eltsize = wi::to_offset (TYPE_SIZE_UNIT (eltype));
5093 else
5095 eltsize = 1;
5096 arrbounds[0] = 0;
5097 arrbounds[1] = wi::to_offset (TYPE_SIZE_UNIT (reftype));
5100 offrange[0] += ioff;
5101 offrange[1] += ioff;
5103 /* Compute the more permissive upper bound when IGNORE_OFF_BY_ONE
5104 is set (when taking the address of the one-past-last element
5105 of an array) but always use the stricter bound in diagnostics. */
5106 offset_int ubound = arrbounds[1];
5107 if (ignore_off_by_one)
5108 ubound += 1;
5110 if (offrange[0] >= ubound || offrange[1] < arrbounds[0])
5112 /* Treat a reference to a non-array object as one to an array
5113 of a single element. */
5114 if (TREE_CODE (reftype) != ARRAY_TYPE)
5115 reftype = build_array_type_nelts (reftype, 1);
5117 if (TREE_CODE (ref) == MEM_REF)
5119 /* Extract the element type out of MEM_REF and use its size
5120 to compute the index to print in the diagnostic; arrays
5121 in MEM_REF don't mean anything. */
5122 tree type = TREE_TYPE (ref);
5123 while (TREE_CODE (type) == ARRAY_TYPE)
5124 type = TREE_TYPE (type);
5125 tree size = TYPE_SIZE_UNIT (type);
5126 offrange[0] = offrange[0] / wi::to_offset (size);
5127 offrange[1] = offrange[1] / wi::to_offset (size);
5129 else
5131 /* For anything other than MEM_REF, compute the index to
5132 print in the diagnostic as the offset over element size. */
5133 offrange[0] = offrange[0] / eltsize;
5134 offrange[1] = offrange[1] / eltsize;
5137 if (offrange[0] == offrange[1])
5138 warning_at (location, OPT_Warray_bounds,
5139 "array subscript %wi is outside array bounds "
5140 "of %qT",
5141 offrange[0].to_shwi (), reftype);
5142 else
5143 warning_at (location, OPT_Warray_bounds,
5144 "array subscript [%wi, %wi] is outside array bounds "
5145 "of %qT",
5146 offrange[0].to_shwi (), offrange[1].to_shwi (), reftype);
5147 TREE_NO_WARNING (ref) = 1;
5148 return;
5151 if (warn_array_bounds < 2)
5152 return;
5154 /* At level 2 check also intermediate offsets. */
5155 int i = 0;
5156 if (extrema[i] < -arrbounds[1] || extrema[i = 1] > ubound)
5158 HOST_WIDE_INT tmpidx = extrema[i].to_shwi () / eltsize.to_shwi ();
5160 warning_at (location, OPT_Warray_bounds,
5161 "intermediate array offset %wi is outside array bounds "
5162 "of %qT",
5163 tmpidx, reftype);
5164 TREE_NO_WARNING (ref) = 1;
5168 /* Searches if the expr T, located at LOCATION computes
5169 address of an ARRAY_REF, and call check_array_ref on it. */
5171 void
5172 vrp_prop::search_for_addr_array (tree t, location_t location)
5174 /* Check each ARRAY_REF and MEM_REF in the reference chain. */
5177 if (TREE_CODE (t) == ARRAY_REF)
5178 check_array_ref (location, t, true /*ignore_off_by_one*/);
5179 else if (TREE_CODE (t) == MEM_REF)
5180 check_mem_ref (location, t, true /*ignore_off_by_one*/);
5182 t = TREE_OPERAND (t, 0);
5184 while (handled_component_p (t) || TREE_CODE (t) == MEM_REF);
5186 if (TREE_CODE (t) == MEM_REF
5187 && TREE_CODE (TREE_OPERAND (t, 0)) == ADDR_EXPR
5188 && !TREE_NO_WARNING (t))
5190 tree tem = TREE_OPERAND (TREE_OPERAND (t, 0), 0);
5191 tree low_bound, up_bound, el_sz;
5192 offset_int idx;
5193 if (TREE_CODE (TREE_TYPE (tem)) != ARRAY_TYPE
5194 || TREE_CODE (TREE_TYPE (TREE_TYPE (tem))) == ARRAY_TYPE
5195 || !TYPE_DOMAIN (TREE_TYPE (tem)))
5196 return;
5198 low_bound = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
5199 up_bound = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
5200 el_sz = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (tem)));
5201 if (!low_bound
5202 || TREE_CODE (low_bound) != INTEGER_CST
5203 || !up_bound
5204 || TREE_CODE (up_bound) != INTEGER_CST
5205 || !el_sz
5206 || TREE_CODE (el_sz) != INTEGER_CST)
5207 return;
5209 if (!mem_ref_offset (t).is_constant (&idx))
5210 return;
5212 idx = wi::sdiv_trunc (idx, wi::to_offset (el_sz));
5213 if (idx < 0)
5215 if (dump_file && (dump_flags & TDF_DETAILS))
5217 fprintf (dump_file, "Array bound warning for ");
5218 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
5219 fprintf (dump_file, "\n");
5221 warning_at (location, OPT_Warray_bounds,
5222 "array subscript %wi is below array bounds of %qT",
5223 idx.to_shwi (), TREE_TYPE (tem));
5224 TREE_NO_WARNING (t) = 1;
5226 else if (idx > (wi::to_offset (up_bound)
5227 - wi::to_offset (low_bound) + 1))
5229 if (dump_file && (dump_flags & TDF_DETAILS))
5231 fprintf (dump_file, "Array bound warning for ");
5232 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
5233 fprintf (dump_file, "\n");
5235 warning_at (location, OPT_Warray_bounds,
5236 "array subscript %wu is above array bounds of %qT",
5237 idx.to_uhwi (), TREE_TYPE (tem));
5238 TREE_NO_WARNING (t) = 1;
5243 /* walk_tree() callback that checks if *TP is
5244 an ARRAY_REF inside an ADDR_EXPR (in which an array
5245 subscript one outside the valid range is allowed). Call
5246 check_array_ref for each ARRAY_REF found. The location is
5247 passed in DATA. */
5249 static tree
5250 check_array_bounds (tree *tp, int *walk_subtree, void *data)
5252 tree t = *tp;
5253 struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
5254 location_t location;
5256 if (EXPR_HAS_LOCATION (t))
5257 location = EXPR_LOCATION (t);
5258 else
5259 location = gimple_location (wi->stmt);
5261 *walk_subtree = TRUE;
5263 vrp_prop *vrp_prop = (class vrp_prop *)wi->info;
5264 if (TREE_CODE (t) == ARRAY_REF)
5265 vrp_prop->check_array_ref (location, t, false /*ignore_off_by_one*/);
5266 else if (TREE_CODE (t) == MEM_REF)
5267 vrp_prop->check_mem_ref (location, t, false /*ignore_off_by_one*/);
5268 else if (TREE_CODE (t) == ADDR_EXPR)
5270 vrp_prop->search_for_addr_array (t, location);
5271 *walk_subtree = FALSE;
5274 return NULL_TREE;
5277 /* A dom_walker subclass for use by vrp_prop::check_all_array_refs,
5278 to walk over all statements of all reachable BBs and call
5279 check_array_bounds on them. */
5281 class check_array_bounds_dom_walker : public dom_walker
5283 public:
5284 check_array_bounds_dom_walker (vrp_prop *prop)
5285 : dom_walker (CDI_DOMINATORS,
5286 /* Discover non-executable edges, preserving EDGE_EXECUTABLE
5287 flags, so that we can merge in information on
5288 non-executable edges from vrp_folder . */
5289 REACHABLE_BLOCKS_PRESERVING_FLAGS),
5290 m_prop (prop) {}
5291 ~check_array_bounds_dom_walker () {}
5293 edge before_dom_children (basic_block) FINAL OVERRIDE;
5295 private:
5296 vrp_prop *m_prop;
5299 /* Implementation of dom_walker::before_dom_children.
5301 Walk over all statements of BB and call check_array_bounds on them,
5302 and determine if there's a unique successor edge. */
5304 edge
5305 check_array_bounds_dom_walker::before_dom_children (basic_block bb)
5307 gimple_stmt_iterator si;
5308 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
5310 gimple *stmt = gsi_stmt (si);
5311 struct walk_stmt_info wi;
5312 if (!gimple_has_location (stmt)
5313 || is_gimple_debug (stmt))
5314 continue;
5316 memset (&wi, 0, sizeof (wi));
5318 wi.info = m_prop;
5320 walk_gimple_op (stmt, check_array_bounds, &wi);
5323 /* Determine if there's a unique successor edge, and if so, return
5324 that back to dom_walker, ensuring that we don't visit blocks that
5325 became unreachable during the VRP propagation
5326 (PR tree-optimization/83312). */
5327 return find_taken_edge (bb, NULL_TREE);
5330 /* Walk over all statements of all reachable BBs and call check_array_bounds
5331 on them. */
5333 void
5334 vrp_prop::check_all_array_refs ()
5336 check_array_bounds_dom_walker w (this);
5337 w.walk (ENTRY_BLOCK_PTR_FOR_FN (cfun));
5340 /* Return true if all imm uses of VAR are either in STMT, or
5341 feed (optionally through a chain of single imm uses) GIMPLE_COND
5342 in basic block COND_BB. */
5344 static bool
5345 all_imm_uses_in_stmt_or_feed_cond (tree var, gimple *stmt, basic_block cond_bb)
5347 use_operand_p use_p, use2_p;
5348 imm_use_iterator iter;
5350 FOR_EACH_IMM_USE_FAST (use_p, iter, var)
5351 if (USE_STMT (use_p) != stmt)
5353 gimple *use_stmt = USE_STMT (use_p), *use_stmt2;
5354 if (is_gimple_debug (use_stmt))
5355 continue;
5356 while (is_gimple_assign (use_stmt)
5357 && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
5358 && single_imm_use (gimple_assign_lhs (use_stmt),
5359 &use2_p, &use_stmt2))
5360 use_stmt = use_stmt2;
5361 if (gimple_code (use_stmt) != GIMPLE_COND
5362 || gimple_bb (use_stmt) != cond_bb)
5363 return false;
5365 return true;
5368 /* Handle
5369 _4 = x_3 & 31;
5370 if (_4 != 0)
5371 goto <bb 6>;
5372 else
5373 goto <bb 7>;
5374 <bb 6>:
5375 __builtin_unreachable ();
5376 <bb 7>:
5377 x_5 = ASSERT_EXPR <x_3, ...>;
5378 If x_3 has no other immediate uses (checked by caller),
5379 var is the x_3 var from ASSERT_EXPR, we can clear low 5 bits
5380 from the non-zero bitmask. */
5382 void
5383 maybe_set_nonzero_bits (edge e, tree var)
5385 basic_block cond_bb = e->src;
5386 gimple *stmt = last_stmt (cond_bb);
5387 tree cst;
5389 if (stmt == NULL
5390 || gimple_code (stmt) != GIMPLE_COND
5391 || gimple_cond_code (stmt) != ((e->flags & EDGE_TRUE_VALUE)
5392 ? EQ_EXPR : NE_EXPR)
5393 || TREE_CODE (gimple_cond_lhs (stmt)) != SSA_NAME
5394 || !integer_zerop (gimple_cond_rhs (stmt)))
5395 return;
5397 stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt));
5398 if (!is_gimple_assign (stmt)
5399 || gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
5400 || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
5401 return;
5402 if (gimple_assign_rhs1 (stmt) != var)
5404 gimple *stmt2;
5406 if (TREE_CODE (gimple_assign_rhs1 (stmt)) != SSA_NAME)
5407 return;
5408 stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
5409 if (!gimple_assign_cast_p (stmt2)
5410 || gimple_assign_rhs1 (stmt2) != var
5411 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt2))
5412 || (TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (stmt)))
5413 != TYPE_PRECISION (TREE_TYPE (var))))
5414 return;
5416 cst = gimple_assign_rhs2 (stmt);
5417 set_nonzero_bits (var, wi::bit_and_not (get_nonzero_bits (var),
5418 wi::to_wide (cst)));
5421 /* Convert range assertion expressions into the implied copies and
5422 copy propagate away the copies. Doing the trivial copy propagation
5423 here avoids the need to run the full copy propagation pass after
5424 VRP.
5426 FIXME, this will eventually lead to copy propagation removing the
5427 names that had useful range information attached to them. For
5428 instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
5429 then N_i will have the range [3, +INF].
5431 However, by converting the assertion into the implied copy
5432 operation N_i = N_j, we will then copy-propagate N_j into the uses
5433 of N_i and lose the range information. We may want to hold on to
5434 ASSERT_EXPRs a little while longer as the ranges could be used in
5435 things like jump threading.
5437 The problem with keeping ASSERT_EXPRs around is that passes after
5438 VRP need to handle them appropriately.
5440 Another approach would be to make the range information a first
5441 class property of the SSA_NAME so that it can be queried from
5442 any pass. This is made somewhat more complex by the need for
5443 multiple ranges to be associated with one SSA_NAME. */
5445 static void
5446 remove_range_assertions (void)
5448 basic_block bb;
5449 gimple_stmt_iterator si;
5450 /* 1 if looking at ASSERT_EXPRs immediately at the beginning of
5451 a basic block preceeded by GIMPLE_COND branching to it and
5452 __builtin_trap, -1 if not yet checked, 0 otherwise. */
5453 int is_unreachable;
5455 /* Note that the BSI iterator bump happens at the bottom of the
5456 loop and no bump is necessary if we're removing the statement
5457 referenced by the current BSI. */
5458 FOR_EACH_BB_FN (bb, cfun)
5459 for (si = gsi_after_labels (bb), is_unreachable = -1; !gsi_end_p (si);)
5461 gimple *stmt = gsi_stmt (si);
5463 if (is_gimple_assign (stmt)
5464 && gimple_assign_rhs_code (stmt) == ASSERT_EXPR)
5466 tree lhs = gimple_assign_lhs (stmt);
5467 tree rhs = gimple_assign_rhs1 (stmt);
5468 tree var;
5470 var = ASSERT_EXPR_VAR (rhs);
5472 if (TREE_CODE (var) == SSA_NAME
5473 && !POINTER_TYPE_P (TREE_TYPE (lhs))
5474 && SSA_NAME_RANGE_INFO (lhs))
5476 if (is_unreachable == -1)
5478 is_unreachable = 0;
5479 if (single_pred_p (bb)
5480 && assert_unreachable_fallthru_edge_p
5481 (single_pred_edge (bb)))
5482 is_unreachable = 1;
5484 /* Handle
5485 if (x_7 >= 10 && x_7 < 20)
5486 __builtin_unreachable ();
5487 x_8 = ASSERT_EXPR <x_7, ...>;
5488 if the only uses of x_7 are in the ASSERT_EXPR and
5489 in the condition. In that case, we can copy the
5490 range info from x_8 computed in this pass also
5491 for x_7. */
5492 if (is_unreachable
5493 && all_imm_uses_in_stmt_or_feed_cond (var, stmt,
5494 single_pred (bb)))
5496 set_range_info (var, SSA_NAME_RANGE_TYPE (lhs),
5497 SSA_NAME_RANGE_INFO (lhs)->get_min (),
5498 SSA_NAME_RANGE_INFO (lhs)->get_max ());
5499 maybe_set_nonzero_bits (single_pred_edge (bb), var);
5503 /* Propagate the RHS into every use of the LHS. For SSA names
5504 also propagate abnormals as it merely restores the original
5505 IL in this case (an replace_uses_by would assert). */
5506 if (TREE_CODE (var) == SSA_NAME)
5508 imm_use_iterator iter;
5509 use_operand_p use_p;
5510 gimple *use_stmt;
5511 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
5512 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
5513 SET_USE (use_p, var);
5515 else
5516 replace_uses_by (lhs, var);
5518 /* And finally, remove the copy, it is not needed. */
5519 gsi_remove (&si, true);
5520 release_defs (stmt);
5522 else
5524 if (!is_gimple_debug (gsi_stmt (si)))
5525 is_unreachable = 0;
5526 gsi_next (&si);
5531 /* Return true if STMT is interesting for VRP. */
5533 bool
5534 stmt_interesting_for_vrp (gimple *stmt)
5536 if (gimple_code (stmt) == GIMPLE_PHI)
5538 tree res = gimple_phi_result (stmt);
5539 return (!virtual_operand_p (res)
5540 && (INTEGRAL_TYPE_P (TREE_TYPE (res))
5541 || POINTER_TYPE_P (TREE_TYPE (res))));
5543 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
5545 tree lhs = gimple_get_lhs (stmt);
5547 /* In general, assignments with virtual operands are not useful
5548 for deriving ranges, with the obvious exception of calls to
5549 builtin functions. */
5550 if (lhs && TREE_CODE (lhs) == SSA_NAME
5551 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
5552 || POINTER_TYPE_P (TREE_TYPE (lhs)))
5553 && (is_gimple_call (stmt)
5554 || !gimple_vuse (stmt)))
5555 return true;
5556 else if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
5557 switch (gimple_call_internal_fn (stmt))
5559 case IFN_ADD_OVERFLOW:
5560 case IFN_SUB_OVERFLOW:
5561 case IFN_MUL_OVERFLOW:
5562 case IFN_ATOMIC_COMPARE_EXCHANGE:
5563 /* These internal calls return _Complex integer type,
5564 but are interesting to VRP nevertheless. */
5565 if (lhs && TREE_CODE (lhs) == SSA_NAME)
5566 return true;
5567 break;
5568 default:
5569 break;
5572 else if (gimple_code (stmt) == GIMPLE_COND
5573 || gimple_code (stmt) == GIMPLE_SWITCH)
5574 return true;
5576 return false;
5579 /* Initialization required by ssa_propagate engine. */
5581 void
5582 vrp_prop::vrp_initialize ()
5584 basic_block bb;
5586 FOR_EACH_BB_FN (bb, cfun)
5588 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
5589 gsi_next (&si))
5591 gphi *phi = si.phi ();
5592 if (!stmt_interesting_for_vrp (phi))
5594 tree lhs = PHI_RESULT (phi);
5595 set_value_range_to_varying (get_value_range (lhs));
5596 prop_set_simulate_again (phi, false);
5598 else
5599 prop_set_simulate_again (phi, true);
5602 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
5603 gsi_next (&si))
5605 gimple *stmt = gsi_stmt (si);
5607 /* If the statement is a control insn, then we do not
5608 want to avoid simulating the statement once. Failure
5609 to do so means that those edges will never get added. */
5610 if (stmt_ends_bb_p (stmt))
5611 prop_set_simulate_again (stmt, true);
5612 else if (!stmt_interesting_for_vrp (stmt))
5614 set_defs_to_varying (stmt);
5615 prop_set_simulate_again (stmt, false);
5617 else
5618 prop_set_simulate_again (stmt, true);
5623 /* Searches the case label vector VEC for the index *IDX of the CASE_LABEL
5624 that includes the value VAL. The search is restricted to the range
5625 [START_IDX, n - 1] where n is the size of VEC.
5627 If there is a CASE_LABEL for VAL, its index is placed in IDX and true is
5628 returned.
5630 If there is no CASE_LABEL for VAL and there is one that is larger than VAL,
5631 it is placed in IDX and false is returned.
5633 If VAL is larger than any CASE_LABEL, n is placed on IDX and false is
5634 returned. */
5636 bool
5637 find_case_label_index (gswitch *stmt, size_t start_idx, tree val, size_t *idx)
5639 size_t n = gimple_switch_num_labels (stmt);
5640 size_t low, high;
5642 /* Find case label for minimum of the value range or the next one.
5643 At each iteration we are searching in [low, high - 1]. */
5645 for (low = start_idx, high = n; high != low; )
5647 tree t;
5648 int cmp;
5649 /* Note that i != high, so we never ask for n. */
5650 size_t i = (high + low) / 2;
5651 t = gimple_switch_label (stmt, i);
5653 /* Cache the result of comparing CASE_LOW and val. */
5654 cmp = tree_int_cst_compare (CASE_LOW (t), val);
5656 if (cmp == 0)
5658 /* Ranges cannot be empty. */
5659 *idx = i;
5660 return true;
5662 else if (cmp > 0)
5663 high = i;
5664 else
5666 low = i + 1;
5667 if (CASE_HIGH (t) != NULL
5668 && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
5670 *idx = i;
5671 return true;
5676 *idx = high;
5677 return false;
5680 /* Searches the case label vector VEC for the range of CASE_LABELs that is used
5681 for values between MIN and MAX. The first index is placed in MIN_IDX. The
5682 last index is placed in MAX_IDX. If the range of CASE_LABELs is empty
5683 then MAX_IDX < MIN_IDX.
5684 Returns true if the default label is not needed. */
5686 bool
5687 find_case_label_range (gswitch *stmt, tree min, tree max, size_t *min_idx,
5688 size_t *max_idx)
5690 size_t i, j;
5691 bool min_take_default = !find_case_label_index (stmt, 1, min, &i);
5692 bool max_take_default = !find_case_label_index (stmt, i, max, &j);
5694 if (i == j
5695 && min_take_default
5696 && max_take_default)
5698 /* Only the default case label reached.
5699 Return an empty range. */
5700 *min_idx = 1;
5701 *max_idx = 0;
5702 return false;
5704 else
5706 bool take_default = min_take_default || max_take_default;
5707 tree low, high;
5708 size_t k;
5710 if (max_take_default)
5711 j--;
5713 /* If the case label range is continuous, we do not need
5714 the default case label. Verify that. */
5715 high = CASE_LOW (gimple_switch_label (stmt, i));
5716 if (CASE_HIGH (gimple_switch_label (stmt, i)))
5717 high = CASE_HIGH (gimple_switch_label (stmt, i));
5718 for (k = i + 1; k <= j; ++k)
5720 low = CASE_LOW (gimple_switch_label (stmt, k));
5721 if (!integer_onep (int_const_binop (MINUS_EXPR, low, high)))
5723 take_default = true;
5724 break;
5726 high = low;
5727 if (CASE_HIGH (gimple_switch_label (stmt, k)))
5728 high = CASE_HIGH (gimple_switch_label (stmt, k));
5731 *min_idx = i;
5732 *max_idx = j;
5733 return !take_default;
5737 /* Evaluate statement STMT. If the statement produces a useful range,
5738 return SSA_PROP_INTERESTING and record the SSA name with the
5739 interesting range into *OUTPUT_P.
5741 If STMT is a conditional branch and we can determine its truth
5742 value, the taken edge is recorded in *TAKEN_EDGE_P.
5744 If STMT produces a varying value, return SSA_PROP_VARYING. */
5746 enum ssa_prop_result
5747 vrp_prop::visit_stmt (gimple *stmt, edge *taken_edge_p, tree *output_p)
5749 value_range vr = VR_INITIALIZER;
5750 tree lhs = gimple_get_lhs (stmt);
5751 extract_range_from_stmt (stmt, taken_edge_p, output_p, &vr);
5753 if (*output_p)
5755 if (update_value_range (*output_p, &vr))
5757 if (dump_file && (dump_flags & TDF_DETAILS))
5759 fprintf (dump_file, "Found new range for ");
5760 print_generic_expr (dump_file, *output_p);
5761 fprintf (dump_file, ": ");
5762 dump_value_range (dump_file, &vr);
5763 fprintf (dump_file, "\n");
5766 if (vr.type == VR_VARYING)
5767 return SSA_PROP_VARYING;
5769 return SSA_PROP_INTERESTING;
5771 return SSA_PROP_NOT_INTERESTING;
5774 if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
5775 switch (gimple_call_internal_fn (stmt))
5777 case IFN_ADD_OVERFLOW:
5778 case IFN_SUB_OVERFLOW:
5779 case IFN_MUL_OVERFLOW:
5780 case IFN_ATOMIC_COMPARE_EXCHANGE:
5781 /* These internal calls return _Complex integer type,
5782 which VRP does not track, but the immediate uses
5783 thereof might be interesting. */
5784 if (lhs && TREE_CODE (lhs) == SSA_NAME)
5786 imm_use_iterator iter;
5787 use_operand_p use_p;
5788 enum ssa_prop_result res = SSA_PROP_VARYING;
5790 set_value_range_to_varying (get_value_range (lhs));
5792 FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
5794 gimple *use_stmt = USE_STMT (use_p);
5795 if (!is_gimple_assign (use_stmt))
5796 continue;
5797 enum tree_code rhs_code = gimple_assign_rhs_code (use_stmt);
5798 if (rhs_code != REALPART_EXPR && rhs_code != IMAGPART_EXPR)
5799 continue;
5800 tree rhs1 = gimple_assign_rhs1 (use_stmt);
5801 tree use_lhs = gimple_assign_lhs (use_stmt);
5802 if (TREE_CODE (rhs1) != rhs_code
5803 || TREE_OPERAND (rhs1, 0) != lhs
5804 || TREE_CODE (use_lhs) != SSA_NAME
5805 || !stmt_interesting_for_vrp (use_stmt)
5806 || (!INTEGRAL_TYPE_P (TREE_TYPE (use_lhs))
5807 || !TYPE_MIN_VALUE (TREE_TYPE (use_lhs))
5808 || !TYPE_MAX_VALUE (TREE_TYPE (use_lhs))))
5809 continue;
5811 /* If there is a change in the value range for any of the
5812 REALPART_EXPR/IMAGPART_EXPR immediate uses, return
5813 SSA_PROP_INTERESTING. If there are any REALPART_EXPR
5814 or IMAGPART_EXPR immediate uses, but none of them have
5815 a change in their value ranges, return
5816 SSA_PROP_NOT_INTERESTING. If there are no
5817 {REAL,IMAG}PART_EXPR uses at all,
5818 return SSA_PROP_VARYING. */
5819 value_range new_vr = VR_INITIALIZER;
5820 extract_range_basic (&new_vr, use_stmt);
5821 value_range *old_vr = get_value_range (use_lhs);
5822 if (old_vr->type != new_vr.type
5823 || !vrp_operand_equal_p (old_vr->min, new_vr.min)
5824 || !vrp_operand_equal_p (old_vr->max, new_vr.max)
5825 || !vrp_bitmap_equal_p (old_vr->equiv, new_vr.equiv))
5826 res = SSA_PROP_INTERESTING;
5827 else
5828 res = SSA_PROP_NOT_INTERESTING;
5829 BITMAP_FREE (new_vr.equiv);
5830 if (res == SSA_PROP_INTERESTING)
5832 *output_p = lhs;
5833 return res;
5837 return res;
5839 break;
5840 default:
5841 break;
5844 /* All other statements produce nothing of interest for VRP, so mark
5845 their outputs varying and prevent further simulation. */
5846 set_defs_to_varying (stmt);
5848 return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
5851 /* Union the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
5852 { VR1TYPE, VR0MIN, VR0MAX } and store the result
5853 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
5854 possible such range. The resulting range is not canonicalized. */
5856 static void
5857 union_ranges (enum value_range_type *vr0type,
5858 tree *vr0min, tree *vr0max,
5859 enum value_range_type vr1type,
5860 tree vr1min, tree vr1max)
5862 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
5863 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
5865 /* [] is vr0, () is vr1 in the following classification comments. */
5866 if (mineq && maxeq)
5868 /* [( )] */
5869 if (*vr0type == vr1type)
5870 /* Nothing to do for equal ranges. */
5872 else if ((*vr0type == VR_RANGE
5873 && vr1type == VR_ANTI_RANGE)
5874 || (*vr0type == VR_ANTI_RANGE
5875 && vr1type == VR_RANGE))
5877 /* For anti-range with range union the result is varying. */
5878 goto give_up;
5880 else
5881 gcc_unreachable ();
5883 else if (operand_less_p (*vr0max, vr1min) == 1
5884 || operand_less_p (vr1max, *vr0min) == 1)
5886 /* [ ] ( ) or ( ) [ ]
5887 If the ranges have an empty intersection, result of the union
5888 operation is the anti-range or if both are anti-ranges
5889 it covers all. */
5890 if (*vr0type == VR_ANTI_RANGE
5891 && vr1type == VR_ANTI_RANGE)
5892 goto give_up;
5893 else if (*vr0type == VR_ANTI_RANGE
5894 && vr1type == VR_RANGE)
5896 else if (*vr0type == VR_RANGE
5897 && vr1type == VR_ANTI_RANGE)
5899 *vr0type = vr1type;
5900 *vr0min = vr1min;
5901 *vr0max = vr1max;
5903 else if (*vr0type == VR_RANGE
5904 && vr1type == VR_RANGE)
5906 /* The result is the convex hull of both ranges. */
5907 if (operand_less_p (*vr0max, vr1min) == 1)
5909 /* If the result can be an anti-range, create one. */
5910 if (TREE_CODE (*vr0max) == INTEGER_CST
5911 && TREE_CODE (vr1min) == INTEGER_CST
5912 && vrp_val_is_min (*vr0min)
5913 && vrp_val_is_max (vr1max))
5915 tree min = int_const_binop (PLUS_EXPR,
5916 *vr0max,
5917 build_int_cst (TREE_TYPE (*vr0max), 1));
5918 tree max = int_const_binop (MINUS_EXPR,
5919 vr1min,
5920 build_int_cst (TREE_TYPE (vr1min), 1));
5921 if (!operand_less_p (max, min))
5923 *vr0type = VR_ANTI_RANGE;
5924 *vr0min = min;
5925 *vr0max = max;
5927 else
5928 *vr0max = vr1max;
5930 else
5931 *vr0max = vr1max;
5933 else
5935 /* If the result can be an anti-range, create one. */
5936 if (TREE_CODE (vr1max) == INTEGER_CST
5937 && TREE_CODE (*vr0min) == INTEGER_CST
5938 && vrp_val_is_min (vr1min)
5939 && vrp_val_is_max (*vr0max))
5941 tree min = int_const_binop (PLUS_EXPR,
5942 vr1max,
5943 build_int_cst (TREE_TYPE (vr1max), 1));
5944 tree max = int_const_binop (MINUS_EXPR,
5945 *vr0min,
5946 build_int_cst (TREE_TYPE (*vr0min), 1));
5947 if (!operand_less_p (max, min))
5949 *vr0type = VR_ANTI_RANGE;
5950 *vr0min = min;
5951 *vr0max = max;
5953 else
5954 *vr0min = vr1min;
5956 else
5957 *vr0min = vr1min;
5960 else
5961 gcc_unreachable ();
5963 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
5964 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
5966 /* [ ( ) ] or [( ) ] or [ ( )] */
5967 if (*vr0type == VR_RANGE
5968 && vr1type == VR_RANGE)
5970 else if (*vr0type == VR_ANTI_RANGE
5971 && vr1type == VR_ANTI_RANGE)
5973 *vr0type = vr1type;
5974 *vr0min = vr1min;
5975 *vr0max = vr1max;
5977 else if (*vr0type == VR_ANTI_RANGE
5978 && vr1type == VR_RANGE)
5980 /* Arbitrarily choose the right or left gap. */
5981 if (!mineq && TREE_CODE (vr1min) == INTEGER_CST)
5982 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
5983 build_int_cst (TREE_TYPE (vr1min), 1));
5984 else if (!maxeq && TREE_CODE (vr1max) == INTEGER_CST)
5985 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
5986 build_int_cst (TREE_TYPE (vr1max), 1));
5987 else
5988 goto give_up;
5990 else if (*vr0type == VR_RANGE
5991 && vr1type == VR_ANTI_RANGE)
5992 /* The result covers everything. */
5993 goto give_up;
5994 else
5995 gcc_unreachable ();
5997 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
5998 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
6000 /* ( [ ] ) or ([ ] ) or ( [ ]) */
6001 if (*vr0type == VR_RANGE
6002 && vr1type == VR_RANGE)
6004 *vr0type = vr1type;
6005 *vr0min = vr1min;
6006 *vr0max = vr1max;
6008 else if (*vr0type == VR_ANTI_RANGE
6009 && vr1type == VR_ANTI_RANGE)
6011 else if (*vr0type == VR_RANGE
6012 && vr1type == VR_ANTI_RANGE)
6014 *vr0type = VR_ANTI_RANGE;
6015 if (!mineq && TREE_CODE (*vr0min) == INTEGER_CST)
6017 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
6018 build_int_cst (TREE_TYPE (*vr0min), 1));
6019 *vr0min = vr1min;
6021 else if (!maxeq && TREE_CODE (*vr0max) == INTEGER_CST)
6023 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
6024 build_int_cst (TREE_TYPE (*vr0max), 1));
6025 *vr0max = vr1max;
6027 else
6028 goto give_up;
6030 else if (*vr0type == VR_ANTI_RANGE
6031 && vr1type == VR_RANGE)
6032 /* The result covers everything. */
6033 goto give_up;
6034 else
6035 gcc_unreachable ();
6037 else if ((operand_less_p (vr1min, *vr0max) == 1
6038 || operand_equal_p (vr1min, *vr0max, 0))
6039 && operand_less_p (*vr0min, vr1min) == 1
6040 && operand_less_p (*vr0max, vr1max) == 1)
6042 /* [ ( ] ) or [ ]( ) */
6043 if (*vr0type == VR_RANGE
6044 && vr1type == VR_RANGE)
6045 *vr0max = vr1max;
6046 else if (*vr0type == VR_ANTI_RANGE
6047 && vr1type == VR_ANTI_RANGE)
6048 *vr0min = vr1min;
6049 else if (*vr0type == VR_ANTI_RANGE
6050 && vr1type == VR_RANGE)
6052 if (TREE_CODE (vr1min) == INTEGER_CST)
6053 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
6054 build_int_cst (TREE_TYPE (vr1min), 1));
6055 else
6056 goto give_up;
6058 else if (*vr0type == VR_RANGE
6059 && vr1type == VR_ANTI_RANGE)
6061 if (TREE_CODE (*vr0max) == INTEGER_CST)
6063 *vr0type = vr1type;
6064 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
6065 build_int_cst (TREE_TYPE (*vr0max), 1));
6066 *vr0max = vr1max;
6068 else
6069 goto give_up;
6071 else
6072 gcc_unreachable ();
6074 else if ((operand_less_p (*vr0min, vr1max) == 1
6075 || operand_equal_p (*vr0min, vr1max, 0))
6076 && operand_less_p (vr1min, *vr0min) == 1
6077 && operand_less_p (vr1max, *vr0max) == 1)
6079 /* ( [ ) ] or ( )[ ] */
6080 if (*vr0type == VR_RANGE
6081 && vr1type == VR_RANGE)
6082 *vr0min = vr1min;
6083 else if (*vr0type == VR_ANTI_RANGE
6084 && vr1type == VR_ANTI_RANGE)
6085 *vr0max = vr1max;
6086 else if (*vr0type == VR_ANTI_RANGE
6087 && vr1type == VR_RANGE)
6089 if (TREE_CODE (vr1max) == INTEGER_CST)
6090 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
6091 build_int_cst (TREE_TYPE (vr1max), 1));
6092 else
6093 goto give_up;
6095 else if (*vr0type == VR_RANGE
6096 && vr1type == VR_ANTI_RANGE)
6098 if (TREE_CODE (*vr0min) == INTEGER_CST)
6100 *vr0type = vr1type;
6101 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
6102 build_int_cst (TREE_TYPE (*vr0min), 1));
6103 *vr0min = vr1min;
6105 else
6106 goto give_up;
6108 else
6109 gcc_unreachable ();
6111 else
6112 goto give_up;
6114 return;
6116 give_up:
6117 *vr0type = VR_VARYING;
6118 *vr0min = NULL_TREE;
6119 *vr0max = NULL_TREE;
6122 /* Intersect the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
6123 { VR1TYPE, VR0MIN, VR0MAX } and store the result
6124 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
6125 possible such range. The resulting range is not canonicalized. */
6127 static void
6128 intersect_ranges (enum value_range_type *vr0type,
6129 tree *vr0min, tree *vr0max,
6130 enum value_range_type vr1type,
6131 tree vr1min, tree vr1max)
6133 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
6134 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
6136 /* [] is vr0, () is vr1 in the following classification comments. */
6137 if (mineq && maxeq)
6139 /* [( )] */
6140 if (*vr0type == vr1type)
6141 /* Nothing to do for equal ranges. */
6143 else if ((*vr0type == VR_RANGE
6144 && vr1type == VR_ANTI_RANGE)
6145 || (*vr0type == VR_ANTI_RANGE
6146 && vr1type == VR_RANGE))
6148 /* For anti-range with range intersection the result is empty. */
6149 *vr0type = VR_UNDEFINED;
6150 *vr0min = NULL_TREE;
6151 *vr0max = NULL_TREE;
6153 else
6154 gcc_unreachable ();
6156 else if (operand_less_p (*vr0max, vr1min) == 1
6157 || operand_less_p (vr1max, *vr0min) == 1)
6159 /* [ ] ( ) or ( ) [ ]
6160 If the ranges have an empty intersection, the result of the
6161 intersect operation is the range for intersecting an
6162 anti-range with a range or empty when intersecting two ranges. */
6163 if (*vr0type == VR_RANGE
6164 && vr1type == VR_ANTI_RANGE)
6166 else if (*vr0type == VR_ANTI_RANGE
6167 && vr1type == VR_RANGE)
6169 *vr0type = vr1type;
6170 *vr0min = vr1min;
6171 *vr0max = vr1max;
6173 else if (*vr0type == VR_RANGE
6174 && vr1type == VR_RANGE)
6176 *vr0type = VR_UNDEFINED;
6177 *vr0min = NULL_TREE;
6178 *vr0max = NULL_TREE;
6180 else if (*vr0type == VR_ANTI_RANGE
6181 && vr1type == VR_ANTI_RANGE)
6183 /* If the anti-ranges are adjacent to each other merge them. */
6184 if (TREE_CODE (*vr0max) == INTEGER_CST
6185 && TREE_CODE (vr1min) == INTEGER_CST
6186 && operand_less_p (*vr0max, vr1min) == 1
6187 && integer_onep (int_const_binop (MINUS_EXPR,
6188 vr1min, *vr0max)))
6189 *vr0max = vr1max;
6190 else if (TREE_CODE (vr1max) == INTEGER_CST
6191 && TREE_CODE (*vr0min) == INTEGER_CST
6192 && operand_less_p (vr1max, *vr0min) == 1
6193 && integer_onep (int_const_binop (MINUS_EXPR,
6194 *vr0min, vr1max)))
6195 *vr0min = vr1min;
6196 /* Else arbitrarily take VR0. */
6199 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
6200 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
6202 /* [ ( ) ] or [( ) ] or [ ( )] */
6203 if (*vr0type == VR_RANGE
6204 && vr1type == VR_RANGE)
6206 /* If both are ranges the result is the inner one. */
6207 *vr0type = vr1type;
6208 *vr0min = vr1min;
6209 *vr0max = vr1max;
6211 else if (*vr0type == VR_RANGE
6212 && vr1type == VR_ANTI_RANGE)
6214 /* Choose the right gap if the left one is empty. */
6215 if (mineq)
6217 if (TREE_CODE (vr1max) != INTEGER_CST)
6218 *vr0min = vr1max;
6219 else if (TYPE_PRECISION (TREE_TYPE (vr1max)) == 1
6220 && !TYPE_UNSIGNED (TREE_TYPE (vr1max)))
6221 *vr0min
6222 = int_const_binop (MINUS_EXPR, vr1max,
6223 build_int_cst (TREE_TYPE (vr1max), -1));
6224 else
6225 *vr0min
6226 = int_const_binop (PLUS_EXPR, vr1max,
6227 build_int_cst (TREE_TYPE (vr1max), 1));
6229 /* Choose the left gap if the right one is empty. */
6230 else if (maxeq)
6232 if (TREE_CODE (vr1min) != INTEGER_CST)
6233 *vr0max = vr1min;
6234 else if (TYPE_PRECISION (TREE_TYPE (vr1min)) == 1
6235 && !TYPE_UNSIGNED (TREE_TYPE (vr1min)))
6236 *vr0max
6237 = int_const_binop (PLUS_EXPR, vr1min,
6238 build_int_cst (TREE_TYPE (vr1min), -1));
6239 else
6240 *vr0max
6241 = int_const_binop (MINUS_EXPR, vr1min,
6242 build_int_cst (TREE_TYPE (vr1min), 1));
6244 /* Choose the anti-range if the range is effectively varying. */
6245 else if (vrp_val_is_min (*vr0min)
6246 && vrp_val_is_max (*vr0max))
6248 *vr0type = vr1type;
6249 *vr0min = vr1min;
6250 *vr0max = vr1max;
6252 /* Else choose the range. */
6254 else if (*vr0type == VR_ANTI_RANGE
6255 && vr1type == VR_ANTI_RANGE)
6256 /* If both are anti-ranges the result is the outer one. */
6258 else if (*vr0type == VR_ANTI_RANGE
6259 && vr1type == VR_RANGE)
6261 /* The intersection is empty. */
6262 *vr0type = VR_UNDEFINED;
6263 *vr0min = NULL_TREE;
6264 *vr0max = NULL_TREE;
6266 else
6267 gcc_unreachable ();
6269 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
6270 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
6272 /* ( [ ] ) or ([ ] ) or ( [ ]) */
6273 if (*vr0type == VR_RANGE
6274 && vr1type == VR_RANGE)
6275 /* Choose the inner range. */
6277 else if (*vr0type == VR_ANTI_RANGE
6278 && vr1type == VR_RANGE)
6280 /* Choose the right gap if the left is empty. */
6281 if (mineq)
6283 *vr0type = VR_RANGE;
6284 if (TREE_CODE (*vr0max) != INTEGER_CST)
6285 *vr0min = *vr0max;
6286 else if (TYPE_PRECISION (TREE_TYPE (*vr0max)) == 1
6287 && !TYPE_UNSIGNED (TREE_TYPE (*vr0max)))
6288 *vr0min
6289 = int_const_binop (MINUS_EXPR, *vr0max,
6290 build_int_cst (TREE_TYPE (*vr0max), -1));
6291 else
6292 *vr0min
6293 = int_const_binop (PLUS_EXPR, *vr0max,
6294 build_int_cst (TREE_TYPE (*vr0max), 1));
6295 *vr0max = vr1max;
6297 /* Choose the left gap if the right is empty. */
6298 else if (maxeq)
6300 *vr0type = VR_RANGE;
6301 if (TREE_CODE (*vr0min) != INTEGER_CST)
6302 *vr0max = *vr0min;
6303 else if (TYPE_PRECISION (TREE_TYPE (*vr0min)) == 1
6304 && !TYPE_UNSIGNED (TREE_TYPE (*vr0min)))
6305 *vr0max
6306 = int_const_binop (PLUS_EXPR, *vr0min,
6307 build_int_cst (TREE_TYPE (*vr0min), -1));
6308 else
6309 *vr0max
6310 = int_const_binop (MINUS_EXPR, *vr0min,
6311 build_int_cst (TREE_TYPE (*vr0min), 1));
6312 *vr0min = vr1min;
6314 /* Choose the anti-range if the range is effectively varying. */
6315 else if (vrp_val_is_min (vr1min)
6316 && vrp_val_is_max (vr1max))
6318 /* Choose the anti-range if it is ~[0,0], that range is special
6319 enough to special case when vr1's range is relatively wide.
6320 At least for types bigger than int - this covers pointers
6321 and arguments to functions like ctz. */
6322 else if (*vr0min == *vr0max
6323 && integer_zerop (*vr0min)
6324 && ((TYPE_PRECISION (TREE_TYPE (*vr0min))
6325 >= TYPE_PRECISION (integer_type_node))
6326 || POINTER_TYPE_P (TREE_TYPE (*vr0min)))
6327 && TREE_CODE (vr1max) == INTEGER_CST
6328 && TREE_CODE (vr1min) == INTEGER_CST
6329 && (wi::clz (wi::to_wide (vr1max) - wi::to_wide (vr1min))
6330 < TYPE_PRECISION (TREE_TYPE (*vr0min)) / 2))
6332 /* Else choose the range. */
6333 else
6335 *vr0type = vr1type;
6336 *vr0min = vr1min;
6337 *vr0max = vr1max;
6340 else if (*vr0type == VR_ANTI_RANGE
6341 && vr1type == VR_ANTI_RANGE)
6343 /* If both are anti-ranges the result is the outer one. */
6344 *vr0type = vr1type;
6345 *vr0min = vr1min;
6346 *vr0max = vr1max;
6348 else if (vr1type == VR_ANTI_RANGE
6349 && *vr0type == VR_RANGE)
6351 /* The intersection is empty. */
6352 *vr0type = VR_UNDEFINED;
6353 *vr0min = NULL_TREE;
6354 *vr0max = NULL_TREE;
6356 else
6357 gcc_unreachable ();
6359 else if ((operand_less_p (vr1min, *vr0max) == 1
6360 || operand_equal_p (vr1min, *vr0max, 0))
6361 && operand_less_p (*vr0min, vr1min) == 1)
6363 /* [ ( ] ) or [ ]( ) */
6364 if (*vr0type == VR_ANTI_RANGE
6365 && vr1type == VR_ANTI_RANGE)
6366 *vr0max = vr1max;
6367 else if (*vr0type == VR_RANGE
6368 && vr1type == VR_RANGE)
6369 *vr0min = vr1min;
6370 else if (*vr0type == VR_RANGE
6371 && vr1type == VR_ANTI_RANGE)
6373 if (TREE_CODE (vr1min) == INTEGER_CST)
6374 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
6375 build_int_cst (TREE_TYPE (vr1min), 1));
6376 else
6377 *vr0max = vr1min;
6379 else if (*vr0type == VR_ANTI_RANGE
6380 && vr1type == VR_RANGE)
6382 *vr0type = VR_RANGE;
6383 if (TREE_CODE (*vr0max) == INTEGER_CST)
6384 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
6385 build_int_cst (TREE_TYPE (*vr0max), 1));
6386 else
6387 *vr0min = *vr0max;
6388 *vr0max = vr1max;
6390 else
6391 gcc_unreachable ();
6393 else if ((operand_less_p (*vr0min, vr1max) == 1
6394 || operand_equal_p (*vr0min, vr1max, 0))
6395 && operand_less_p (vr1min, *vr0min) == 1)
6397 /* ( [ ) ] or ( )[ ] */
6398 if (*vr0type == VR_ANTI_RANGE
6399 && vr1type == VR_ANTI_RANGE)
6400 *vr0min = vr1min;
6401 else if (*vr0type == VR_RANGE
6402 && vr1type == VR_RANGE)
6403 *vr0max = vr1max;
6404 else if (*vr0type == VR_RANGE
6405 && vr1type == VR_ANTI_RANGE)
6407 if (TREE_CODE (vr1max) == INTEGER_CST)
6408 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
6409 build_int_cst (TREE_TYPE (vr1max), 1));
6410 else
6411 *vr0min = vr1max;
6413 else if (*vr0type == VR_ANTI_RANGE
6414 && vr1type == VR_RANGE)
6416 *vr0type = VR_RANGE;
6417 if (TREE_CODE (*vr0min) == INTEGER_CST)
6418 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
6419 build_int_cst (TREE_TYPE (*vr0min), 1));
6420 else
6421 *vr0max = *vr0min;
6422 *vr0min = vr1min;
6424 else
6425 gcc_unreachable ();
6428 /* As a fallback simply use { *VRTYPE, *VR0MIN, *VR0MAX } as
6429 result for the intersection. That's always a conservative
6430 correct estimate unless VR1 is a constant singleton range
6431 in which case we choose that. */
6432 if (vr1type == VR_RANGE
6433 && is_gimple_min_invariant (vr1min)
6434 && vrp_operand_equal_p (vr1min, vr1max))
6436 *vr0type = vr1type;
6437 *vr0min = vr1min;
6438 *vr0max = vr1max;
6441 return;
6445 /* Intersect the two value-ranges *VR0 and *VR1 and store the result
6446 in *VR0. This may not be the smallest possible such range. */
6448 static void
6449 vrp_intersect_ranges_1 (value_range *vr0, value_range *vr1)
6451 value_range saved;
6453 /* If either range is VR_VARYING the other one wins. */
6454 if (vr1->type == VR_VARYING)
6455 return;
6456 if (vr0->type == VR_VARYING)
6458 copy_value_range (vr0, vr1);
6459 return;
6462 /* When either range is VR_UNDEFINED the resulting range is
6463 VR_UNDEFINED, too. */
6464 if (vr0->type == VR_UNDEFINED)
6465 return;
6466 if (vr1->type == VR_UNDEFINED)
6468 set_value_range_to_undefined (vr0);
6469 return;
6472 /* Save the original vr0 so we can return it as conservative intersection
6473 result when our worker turns things to varying. */
6474 saved = *vr0;
6475 intersect_ranges (&vr0->type, &vr0->min, &vr0->max,
6476 vr1->type, vr1->min, vr1->max);
6477 /* Make sure to canonicalize the result though as the inversion of a
6478 VR_RANGE can still be a VR_RANGE. */
6479 set_and_canonicalize_value_range (vr0, vr0->type,
6480 vr0->min, vr0->max, vr0->equiv);
6481 /* If that failed, use the saved original VR0. */
6482 if (vr0->type == VR_VARYING)
6484 *vr0 = saved;
6485 return;
6487 /* If the result is VR_UNDEFINED there is no need to mess with
6488 the equivalencies. */
6489 if (vr0->type == VR_UNDEFINED)
6490 return;
6492 /* The resulting set of equivalences for range intersection is the union of
6493 the two sets. */
6494 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
6495 bitmap_ior_into (vr0->equiv, vr1->equiv);
6496 else if (vr1->equiv && !vr0->equiv)
6498 /* All equivalence bitmaps are allocated from the same obstack. So
6499 we can use the obstack associated with VR to allocate vr0->equiv. */
6500 vr0->equiv = BITMAP_ALLOC (vr1->equiv->obstack);
6501 bitmap_copy (vr0->equiv, vr1->equiv);
6505 void
6506 vrp_intersect_ranges (value_range *vr0, value_range *vr1)
6508 if (dump_file && (dump_flags & TDF_DETAILS))
6510 fprintf (dump_file, "Intersecting\n ");
6511 dump_value_range (dump_file, vr0);
6512 fprintf (dump_file, "\nand\n ");
6513 dump_value_range (dump_file, vr1);
6514 fprintf (dump_file, "\n");
6516 vrp_intersect_ranges_1 (vr0, vr1);
6517 if (dump_file && (dump_flags & TDF_DETAILS))
6519 fprintf (dump_file, "to\n ");
6520 dump_value_range (dump_file, vr0);
6521 fprintf (dump_file, "\n");
6525 /* Meet operation for value ranges. Given two value ranges VR0 and
6526 VR1, store in VR0 a range that contains both VR0 and VR1. This
6527 may not be the smallest possible such range. */
6529 static void
6530 vrp_meet_1 (value_range *vr0, const value_range *vr1)
6532 value_range saved;
6534 if (vr0->type == VR_UNDEFINED)
6536 set_value_range (vr0, vr1->type, vr1->min, vr1->max, vr1->equiv);
6537 return;
6540 if (vr1->type == VR_UNDEFINED)
6542 /* VR0 already has the resulting range. */
6543 return;
6546 if (vr0->type == VR_VARYING)
6548 /* Nothing to do. VR0 already has the resulting range. */
6549 return;
6552 if (vr1->type == VR_VARYING)
6554 set_value_range_to_varying (vr0);
6555 return;
6558 saved = *vr0;
6559 union_ranges (&vr0->type, &vr0->min, &vr0->max,
6560 vr1->type, vr1->min, vr1->max);
6561 if (vr0->type == VR_VARYING)
6563 /* Failed to find an efficient meet. Before giving up and setting
6564 the result to VARYING, see if we can at least derive a useful
6565 anti-range. FIXME, all this nonsense about distinguishing
6566 anti-ranges from ranges is necessary because of the odd
6567 semantics of range_includes_zero_p and friends. */
6568 if (((saved.type == VR_RANGE
6569 && range_includes_zero_p (saved.min, saved.max) == 0)
6570 || (saved.type == VR_ANTI_RANGE
6571 && range_includes_zero_p (saved.min, saved.max) == 1))
6572 && ((vr1->type == VR_RANGE
6573 && range_includes_zero_p (vr1->min, vr1->max) == 0)
6574 || (vr1->type == VR_ANTI_RANGE
6575 && range_includes_zero_p (vr1->min, vr1->max) == 1)))
6577 set_value_range_to_nonnull (vr0, TREE_TYPE (saved.min));
6579 /* Since this meet operation did not result from the meeting of
6580 two equivalent names, VR0 cannot have any equivalences. */
6581 if (vr0->equiv)
6582 bitmap_clear (vr0->equiv);
6583 return;
6586 set_value_range_to_varying (vr0);
6587 return;
6589 set_and_canonicalize_value_range (vr0, vr0->type, vr0->min, vr0->max,
6590 vr0->equiv);
6591 if (vr0->type == VR_VARYING)
6592 return;
6594 /* The resulting set of equivalences is always the intersection of
6595 the two sets. */
6596 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
6597 bitmap_and_into (vr0->equiv, vr1->equiv);
6598 else if (vr0->equiv && !vr1->equiv)
6599 bitmap_clear (vr0->equiv);
6602 void
6603 vrp_meet (value_range *vr0, const value_range *vr1)
6605 if (dump_file && (dump_flags & TDF_DETAILS))
6607 fprintf (dump_file, "Meeting\n ");
6608 dump_value_range (dump_file, vr0);
6609 fprintf (dump_file, "\nand\n ");
6610 dump_value_range (dump_file, vr1);
6611 fprintf (dump_file, "\n");
6613 vrp_meet_1 (vr0, vr1);
6614 if (dump_file && (dump_flags & TDF_DETAILS))
6616 fprintf (dump_file, "to\n ");
6617 dump_value_range (dump_file, vr0);
6618 fprintf (dump_file, "\n");
6623 /* Visit all arguments for PHI node PHI that flow through executable
6624 edges. If a valid value range can be derived from all the incoming
6625 value ranges, set a new range for the LHS of PHI. */
6627 enum ssa_prop_result
6628 vrp_prop::visit_phi (gphi *phi)
6630 tree lhs = PHI_RESULT (phi);
6631 value_range vr_result = VR_INITIALIZER;
6632 extract_range_from_phi_node (phi, &vr_result);
6633 if (update_value_range (lhs, &vr_result))
6635 if (dump_file && (dump_flags & TDF_DETAILS))
6637 fprintf (dump_file, "Found new range for ");
6638 print_generic_expr (dump_file, lhs);
6639 fprintf (dump_file, ": ");
6640 dump_value_range (dump_file, &vr_result);
6641 fprintf (dump_file, "\n");
6644 if (vr_result.type == VR_VARYING)
6645 return SSA_PROP_VARYING;
6647 return SSA_PROP_INTERESTING;
6650 /* Nothing changed, don't add outgoing edges. */
6651 return SSA_PROP_NOT_INTERESTING;
6654 class vrp_folder : public substitute_and_fold_engine
6656 public:
6657 tree get_value (tree) FINAL OVERRIDE;
6658 bool fold_stmt (gimple_stmt_iterator *) FINAL OVERRIDE;
6659 bool fold_predicate_in (gimple_stmt_iterator *);
6661 class vr_values *vr_values;
6663 /* Delegators. */
6664 tree vrp_evaluate_conditional (tree_code code, tree op0,
6665 tree op1, gimple *stmt)
6666 { return vr_values->vrp_evaluate_conditional (code, op0, op1, stmt); }
6667 bool simplify_stmt_using_ranges (gimple_stmt_iterator *gsi)
6668 { return vr_values->simplify_stmt_using_ranges (gsi); }
6669 tree op_with_constant_singleton_value_range (tree op)
6670 { return vr_values->op_with_constant_singleton_value_range (op); }
6673 /* If the statement pointed by SI has a predicate whose value can be
6674 computed using the value range information computed by VRP, compute
6675 its value and return true. Otherwise, return false. */
6677 bool
6678 vrp_folder::fold_predicate_in (gimple_stmt_iterator *si)
6680 bool assignment_p = false;
6681 tree val;
6682 gimple *stmt = gsi_stmt (*si);
6684 if (is_gimple_assign (stmt)
6685 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
6687 assignment_p = true;
6688 val = vrp_evaluate_conditional (gimple_assign_rhs_code (stmt),
6689 gimple_assign_rhs1 (stmt),
6690 gimple_assign_rhs2 (stmt),
6691 stmt);
6693 else if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
6694 val = vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
6695 gimple_cond_lhs (cond_stmt),
6696 gimple_cond_rhs (cond_stmt),
6697 stmt);
6698 else
6699 return false;
6701 if (val)
6703 if (assignment_p)
6704 val = fold_convert (gimple_expr_type (stmt), val);
6706 if (dump_file)
6708 fprintf (dump_file, "Folding predicate ");
6709 print_gimple_expr (dump_file, stmt, 0);
6710 fprintf (dump_file, " to ");
6711 print_generic_expr (dump_file, val);
6712 fprintf (dump_file, "\n");
6715 if (is_gimple_assign (stmt))
6716 gimple_assign_set_rhs_from_tree (si, val);
6717 else
6719 gcc_assert (gimple_code (stmt) == GIMPLE_COND);
6720 gcond *cond_stmt = as_a <gcond *> (stmt);
6721 if (integer_zerop (val))
6722 gimple_cond_make_false (cond_stmt);
6723 else if (integer_onep (val))
6724 gimple_cond_make_true (cond_stmt);
6725 else
6726 gcc_unreachable ();
6729 return true;
6732 return false;
6735 /* Callback for substitute_and_fold folding the stmt at *SI. */
6737 bool
6738 vrp_folder::fold_stmt (gimple_stmt_iterator *si)
6740 if (fold_predicate_in (si))
6741 return true;
6743 return simplify_stmt_using_ranges (si);
6746 /* If OP has a value range with a single constant value return that,
6747 otherwise return NULL_TREE. This returns OP itself if OP is a
6748 constant.
6750 Implemented as a pure wrapper right now, but this will change. */
6752 tree
6753 vrp_folder::get_value (tree op)
6755 return op_with_constant_singleton_value_range (op);
6758 /* Return the LHS of any ASSERT_EXPR where OP appears as the first
6759 argument to the ASSERT_EXPR and in which the ASSERT_EXPR dominates
6760 BB. If no such ASSERT_EXPR is found, return OP. */
6762 static tree
6763 lhs_of_dominating_assert (tree op, basic_block bb, gimple *stmt)
6765 imm_use_iterator imm_iter;
6766 gimple *use_stmt;
6767 use_operand_p use_p;
6769 if (TREE_CODE (op) == SSA_NAME)
6771 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, op)
6773 use_stmt = USE_STMT (use_p);
6774 if (use_stmt != stmt
6775 && gimple_assign_single_p (use_stmt)
6776 && TREE_CODE (gimple_assign_rhs1 (use_stmt)) == ASSERT_EXPR
6777 && TREE_OPERAND (gimple_assign_rhs1 (use_stmt), 0) == op
6778 && dominated_by_p (CDI_DOMINATORS, bb, gimple_bb (use_stmt)))
6779 return gimple_assign_lhs (use_stmt);
6782 return op;
6785 /* A hack. */
6786 static class vr_values *x_vr_values;
6788 /* A trivial wrapper so that we can present the generic jump threading
6789 code with a simple API for simplifying statements. STMT is the
6790 statement we want to simplify, WITHIN_STMT provides the location
6791 for any overflow warnings. */
6793 static tree
6794 simplify_stmt_for_jump_threading (gimple *stmt, gimple *within_stmt,
6795 class avail_exprs_stack *avail_exprs_stack ATTRIBUTE_UNUSED,
6796 basic_block bb)
6798 /* First see if the conditional is in the hash table. */
6799 tree cached_lhs = avail_exprs_stack->lookup_avail_expr (stmt, false, true);
6800 if (cached_lhs && is_gimple_min_invariant (cached_lhs))
6801 return cached_lhs;
6803 vr_values *vr_values = x_vr_values;
6804 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
6806 tree op0 = gimple_cond_lhs (cond_stmt);
6807 op0 = lhs_of_dominating_assert (op0, bb, stmt);
6809 tree op1 = gimple_cond_rhs (cond_stmt);
6810 op1 = lhs_of_dominating_assert (op1, bb, stmt);
6812 return vr_values->vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
6813 op0, op1, within_stmt);
6816 /* We simplify a switch statement by trying to determine which case label
6817 will be taken. If we are successful then we return the corresponding
6818 CASE_LABEL_EXPR. */
6819 if (gswitch *switch_stmt = dyn_cast <gswitch *> (stmt))
6821 tree op = gimple_switch_index (switch_stmt);
6822 if (TREE_CODE (op) != SSA_NAME)
6823 return NULL_TREE;
6825 op = lhs_of_dominating_assert (op, bb, stmt);
6827 value_range *vr = vr_values->get_value_range (op);
6828 if ((vr->type != VR_RANGE && vr->type != VR_ANTI_RANGE)
6829 || symbolic_range_p (vr))
6830 return NULL_TREE;
6832 if (vr->type == VR_RANGE)
6834 size_t i, j;
6835 /* Get the range of labels that contain a part of the operand's
6836 value range. */
6837 find_case_label_range (switch_stmt, vr->min, vr->max, &i, &j);
6839 /* Is there only one such label? */
6840 if (i == j)
6842 tree label = gimple_switch_label (switch_stmt, i);
6844 /* The i'th label will be taken only if the value range of the
6845 operand is entirely within the bounds of this label. */
6846 if (CASE_HIGH (label) != NULL_TREE
6847 ? (tree_int_cst_compare (CASE_LOW (label), vr->min) <= 0
6848 && tree_int_cst_compare (CASE_HIGH (label), vr->max) >= 0)
6849 : (tree_int_cst_equal (CASE_LOW (label), vr->min)
6850 && tree_int_cst_equal (vr->min, vr->max)))
6851 return label;
6854 /* If there are no such labels then the default label will be
6855 taken. */
6856 if (i > j)
6857 return gimple_switch_label (switch_stmt, 0);
6860 if (vr->type == VR_ANTI_RANGE)
6862 unsigned n = gimple_switch_num_labels (switch_stmt);
6863 tree min_label = gimple_switch_label (switch_stmt, 1);
6864 tree max_label = gimple_switch_label (switch_stmt, n - 1);
6866 /* The default label will be taken only if the anti-range of the
6867 operand is entirely outside the bounds of all the (non-default)
6868 case labels. */
6869 if (tree_int_cst_compare (vr->min, CASE_LOW (min_label)) <= 0
6870 && (CASE_HIGH (max_label) != NULL_TREE
6871 ? tree_int_cst_compare (vr->max, CASE_HIGH (max_label)) >= 0
6872 : tree_int_cst_compare (vr->max, CASE_LOW (max_label)) >= 0))
6873 return gimple_switch_label (switch_stmt, 0);
6876 return NULL_TREE;
6879 if (gassign *assign_stmt = dyn_cast <gassign *> (stmt))
6881 tree lhs = gimple_assign_lhs (assign_stmt);
6882 if (TREE_CODE (lhs) == SSA_NAME
6883 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
6884 || POINTER_TYPE_P (TREE_TYPE (lhs)))
6885 && stmt_interesting_for_vrp (stmt))
6887 edge dummy_e;
6888 tree dummy_tree;
6889 value_range new_vr = VR_INITIALIZER;
6890 vr_values->extract_range_from_stmt (stmt, &dummy_e,
6891 &dummy_tree, &new_vr);
6892 if (range_int_cst_singleton_p (&new_vr))
6893 return new_vr.min;
6897 return NULL_TREE;
6900 class vrp_dom_walker : public dom_walker
6902 public:
6903 vrp_dom_walker (cdi_direction direction,
6904 class const_and_copies *const_and_copies,
6905 class avail_exprs_stack *avail_exprs_stack)
6906 : dom_walker (direction, REACHABLE_BLOCKS),
6907 m_const_and_copies (const_and_copies),
6908 m_avail_exprs_stack (avail_exprs_stack),
6909 m_dummy_cond (NULL) {}
6911 virtual edge before_dom_children (basic_block);
6912 virtual void after_dom_children (basic_block);
6914 class vr_values *vr_values;
6916 private:
6917 class const_and_copies *m_const_and_copies;
6918 class avail_exprs_stack *m_avail_exprs_stack;
6920 gcond *m_dummy_cond;
6924 /* Called before processing dominator children of BB. We want to look
6925 at ASSERT_EXPRs and record information from them in the appropriate
6926 tables.
6928 We could look at other statements here. It's not seen as likely
6929 to significantly increase the jump threads we discover. */
6931 edge
6932 vrp_dom_walker::before_dom_children (basic_block bb)
6934 gimple_stmt_iterator gsi;
6936 m_avail_exprs_stack->push_marker ();
6937 m_const_and_copies->push_marker ();
6938 for (gsi = gsi_start_nondebug_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
6940 gimple *stmt = gsi_stmt (gsi);
6941 if (gimple_assign_single_p (stmt)
6942 && TREE_CODE (gimple_assign_rhs1 (stmt)) == ASSERT_EXPR)
6944 tree rhs1 = gimple_assign_rhs1 (stmt);
6945 tree cond = TREE_OPERAND (rhs1, 1);
6946 tree inverted = invert_truthvalue (cond);
6947 vec<cond_equivalence> p;
6948 p.create (3);
6949 record_conditions (&p, cond, inverted);
6950 for (unsigned int i = 0; i < p.length (); i++)
6951 m_avail_exprs_stack->record_cond (&p[i]);
6953 tree lhs = gimple_assign_lhs (stmt);
6954 m_const_and_copies->record_const_or_copy (lhs,
6955 TREE_OPERAND (rhs1, 0));
6956 p.release ();
6957 continue;
6959 break;
6961 return NULL;
6964 /* Called after processing dominator children of BB. This is where we
6965 actually call into the threader. */
6966 void
6967 vrp_dom_walker::after_dom_children (basic_block bb)
6969 if (!m_dummy_cond)
6970 m_dummy_cond = gimple_build_cond (NE_EXPR,
6971 integer_zero_node, integer_zero_node,
6972 NULL, NULL);
6974 x_vr_values = vr_values;
6975 thread_outgoing_edges (bb, m_dummy_cond, m_const_and_copies,
6976 m_avail_exprs_stack, NULL,
6977 simplify_stmt_for_jump_threading);
6978 x_vr_values = NULL;
6980 m_avail_exprs_stack->pop_to_marker ();
6981 m_const_and_copies->pop_to_marker ();
6984 /* Blocks which have more than one predecessor and more than
6985 one successor present jump threading opportunities, i.e.,
6986 when the block is reached from a specific predecessor, we
6987 may be able to determine which of the outgoing edges will
6988 be traversed. When this optimization applies, we are able
6989 to avoid conditionals at runtime and we may expose secondary
6990 optimization opportunities.
6992 This routine is effectively a driver for the generic jump
6993 threading code. It basically just presents the generic code
6994 with edges that may be suitable for jump threading.
6996 Unlike DOM, we do not iterate VRP if jump threading was successful.
6997 While iterating may expose new opportunities for VRP, it is expected
6998 those opportunities would be very limited and the compile time cost
6999 to expose those opportunities would be significant.
7001 As jump threading opportunities are discovered, they are registered
7002 for later realization. */
7004 static void
7005 identify_jump_threads (class vr_values *vr_values)
7007 int i;
7008 edge e;
7010 /* Ugh. When substituting values earlier in this pass we can
7011 wipe the dominance information. So rebuild the dominator
7012 information as we need it within the jump threading code. */
7013 calculate_dominance_info (CDI_DOMINATORS);
7015 /* We do not allow VRP information to be used for jump threading
7016 across a back edge in the CFG. Otherwise it becomes too
7017 difficult to avoid eliminating loop exit tests. Of course
7018 EDGE_DFS_BACK is not accurate at this time so we have to
7019 recompute it. */
7020 mark_dfs_back_edges ();
7022 /* Do not thread across edges we are about to remove. Just marking
7023 them as EDGE_IGNORE will do. */
7024 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
7025 e->flags |= EDGE_IGNORE;
7027 /* Allocate our unwinder stack to unwind any temporary equivalences
7028 that might be recorded. */
7029 const_and_copies *equiv_stack = new const_and_copies ();
7031 hash_table<expr_elt_hasher> *avail_exprs
7032 = new hash_table<expr_elt_hasher> (1024);
7033 avail_exprs_stack *avail_exprs_stack
7034 = new class avail_exprs_stack (avail_exprs);
7036 vrp_dom_walker walker (CDI_DOMINATORS, equiv_stack, avail_exprs_stack);
7037 walker.vr_values = vr_values;
7038 walker.walk (cfun->cfg->x_entry_block_ptr);
7040 /* Clear EDGE_IGNORE. */
7041 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
7042 e->flags &= ~EDGE_IGNORE;
7044 /* We do not actually update the CFG or SSA graphs at this point as
7045 ASSERT_EXPRs are still in the IL and cfg cleanup code does not yet
7046 handle ASSERT_EXPRs gracefully. */
7047 delete equiv_stack;
7048 delete avail_exprs;
7049 delete avail_exprs_stack;
7052 /* Traverse all the blocks folding conditionals with known ranges. */
7054 void
7055 vrp_prop::vrp_finalize (bool warn_array_bounds_p)
7057 size_t i;
7059 /* We have completed propagating through the lattice. */
7060 vr_values.set_lattice_propagation_complete ();
7062 if (dump_file)
7064 fprintf (dump_file, "\nValue ranges after VRP:\n\n");
7065 vr_values.dump_all_value_ranges (dump_file);
7066 fprintf (dump_file, "\n");
7069 /* Set value range to non pointer SSA_NAMEs. */
7070 for (i = 0; i < num_ssa_names; i++)
7072 tree name = ssa_name (i);
7073 if (!name)
7074 continue;
7076 value_range *vr = get_value_range (name);
7077 if (!name
7078 || (vr->type == VR_VARYING)
7079 || (vr->type == VR_UNDEFINED)
7080 || (TREE_CODE (vr->min) != INTEGER_CST)
7081 || (TREE_CODE (vr->max) != INTEGER_CST))
7082 continue;
7084 if (POINTER_TYPE_P (TREE_TYPE (name))
7085 && ((vr->type == VR_RANGE
7086 && range_includes_zero_p (vr->min, vr->max) == 0)
7087 || (vr->type == VR_ANTI_RANGE
7088 && range_includes_zero_p (vr->min, vr->max) == 1)))
7089 set_ptr_nonnull (name);
7090 else if (!POINTER_TYPE_P (TREE_TYPE (name)))
7091 set_range_info (name, vr->type,
7092 wi::to_wide (vr->min),
7093 wi::to_wide (vr->max));
7096 /* If we're checking array refs, we want to merge information on
7097 the executability of each edge between vrp_folder and the
7098 check_array_bounds_dom_walker: each can clear the
7099 EDGE_EXECUTABLE flag on edges, in different ways.
7101 Hence, if we're going to call check_all_array_refs, set
7102 the flag on every edge now, rather than in
7103 check_array_bounds_dom_walker's ctor; vrp_folder may clear
7104 it from some edges. */
7105 if (warn_array_bounds && warn_array_bounds_p)
7106 set_all_edges_as_executable (cfun);
7108 class vrp_folder vrp_folder;
7109 vrp_folder.vr_values = &vr_values;
7110 vrp_folder.substitute_and_fold ();
7112 if (warn_array_bounds && warn_array_bounds_p)
7113 check_all_array_refs ();
7116 /* Main entry point to VRP (Value Range Propagation). This pass is
7117 loosely based on J. R. C. Patterson, ``Accurate Static Branch
7118 Prediction by Value Range Propagation,'' in SIGPLAN Conference on
7119 Programming Language Design and Implementation, pp. 67-78, 1995.
7120 Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
7122 This is essentially an SSA-CCP pass modified to deal with ranges
7123 instead of constants.
7125 While propagating ranges, we may find that two or more SSA name
7126 have equivalent, though distinct ranges. For instance,
7128 1 x_9 = p_3->a;
7129 2 p_4 = ASSERT_EXPR <p_3, p_3 != 0>
7130 3 if (p_4 == q_2)
7131 4 p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
7132 5 endif
7133 6 if (q_2)
7135 In the code above, pointer p_5 has range [q_2, q_2], but from the
7136 code we can also determine that p_5 cannot be NULL and, if q_2 had
7137 a non-varying range, p_5's range should also be compatible with it.
7139 These equivalences are created by two expressions: ASSERT_EXPR and
7140 copy operations. Since p_5 is an assertion on p_4, and p_4 was the
7141 result of another assertion, then we can use the fact that p_5 and
7142 p_4 are equivalent when evaluating p_5's range.
7144 Together with value ranges, we also propagate these equivalences
7145 between names so that we can take advantage of information from
7146 multiple ranges when doing final replacement. Note that this
7147 equivalency relation is transitive but not symmetric.
7149 In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
7150 cannot assert that q_2 is equivalent to p_5 because q_2 may be used
7151 in contexts where that assertion does not hold (e.g., in line 6).
7153 TODO, the main difference between this pass and Patterson's is that
7154 we do not propagate edge probabilities. We only compute whether
7155 edges can be taken or not. That is, instead of having a spectrum
7156 of jump probabilities between 0 and 1, we only deal with 0, 1 and
7157 DON'T KNOW. In the future, it may be worthwhile to propagate
7158 probabilities to aid branch prediction. */
7160 static unsigned int
7161 execute_vrp (bool warn_array_bounds_p)
7163 int i;
7164 edge e;
7165 switch_update *su;
7167 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
7168 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
7169 scev_initialize ();
7171 /* ??? This ends up using stale EDGE_DFS_BACK for liveness computation.
7172 Inserting assertions may split edges which will invalidate
7173 EDGE_DFS_BACK. */
7174 insert_range_assertions ();
7176 to_remove_edges.create (10);
7177 to_update_switch_stmts.create (5);
7178 threadedge_initialize_values ();
7180 /* For visiting PHI nodes we need EDGE_DFS_BACK computed. */
7181 mark_dfs_back_edges ();
7183 class vrp_prop vrp_prop;
7184 vrp_prop.vrp_initialize ();
7185 vrp_prop.ssa_propagate ();
7186 vrp_prop.vrp_finalize (warn_array_bounds_p);
7188 /* We must identify jump threading opportunities before we release
7189 the datastructures built by VRP. */
7190 identify_jump_threads (&vrp_prop.vr_values);
7192 /* A comparison of an SSA_NAME against a constant where the SSA_NAME
7193 was set by a type conversion can often be rewritten to use the
7194 RHS of the type conversion.
7196 However, doing so inhibits jump threading through the comparison.
7197 So that transformation is not performed until after jump threading
7198 is complete. */
7199 basic_block bb;
7200 FOR_EACH_BB_FN (bb, cfun)
7202 gimple *last = last_stmt (bb);
7203 if (last && gimple_code (last) == GIMPLE_COND)
7204 vrp_prop.vr_values.simplify_cond_using_ranges_2 (as_a <gcond *> (last));
7207 free_numbers_of_iterations_estimates (cfun);
7209 /* ASSERT_EXPRs must be removed before finalizing jump threads
7210 as finalizing jump threads calls the CFG cleanup code which
7211 does not properly handle ASSERT_EXPRs. */
7212 remove_range_assertions ();
7214 /* If we exposed any new variables, go ahead and put them into
7215 SSA form now, before we handle jump threading. This simplifies
7216 interactions between rewriting of _DECL nodes into SSA form
7217 and rewriting SSA_NAME nodes into SSA form after block
7218 duplication and CFG manipulation. */
7219 update_ssa (TODO_update_ssa);
7221 /* We identified all the jump threading opportunities earlier, but could
7222 not transform the CFG at that time. This routine transforms the
7223 CFG and arranges for the dominator tree to be rebuilt if necessary.
7225 Note the SSA graph update will occur during the normal TODO
7226 processing by the pass manager. */
7227 thread_through_all_blocks (false);
7229 /* Remove dead edges from SWITCH_EXPR optimization. This leaves the
7230 CFG in a broken state and requires a cfg_cleanup run. */
7231 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
7232 remove_edge (e);
7233 /* Update SWITCH_EXPR case label vector. */
7234 FOR_EACH_VEC_ELT (to_update_switch_stmts, i, su)
7236 size_t j;
7237 size_t n = TREE_VEC_LENGTH (su->vec);
7238 tree label;
7239 gimple_switch_set_num_labels (su->stmt, n);
7240 for (j = 0; j < n; j++)
7241 gimple_switch_set_label (su->stmt, j, TREE_VEC_ELT (su->vec, j));
7242 /* As we may have replaced the default label with a regular one
7243 make sure to make it a real default label again. This ensures
7244 optimal expansion. */
7245 label = gimple_switch_label (su->stmt, 0);
7246 CASE_LOW (label) = NULL_TREE;
7247 CASE_HIGH (label) = NULL_TREE;
7250 if (to_remove_edges.length () > 0)
7252 free_dominance_info (CDI_DOMINATORS);
7253 loops_state_set (LOOPS_NEED_FIXUP);
7256 to_remove_edges.release ();
7257 to_update_switch_stmts.release ();
7258 threadedge_finalize_values ();
7260 scev_finalize ();
7261 loop_optimizer_finalize ();
7262 return 0;
7265 namespace {
7267 const pass_data pass_data_vrp =
7269 GIMPLE_PASS, /* type */
7270 "vrp", /* name */
7271 OPTGROUP_NONE, /* optinfo_flags */
7272 TV_TREE_VRP, /* tv_id */
7273 PROP_ssa, /* properties_required */
7274 0, /* properties_provided */
7275 0, /* properties_destroyed */
7276 0, /* todo_flags_start */
7277 ( TODO_cleanup_cfg | TODO_update_ssa ), /* todo_flags_finish */
7280 class pass_vrp : public gimple_opt_pass
7282 public:
7283 pass_vrp (gcc::context *ctxt)
7284 : gimple_opt_pass (pass_data_vrp, ctxt), warn_array_bounds_p (false)
7287 /* opt_pass methods: */
7288 opt_pass * clone () { return new pass_vrp (m_ctxt); }
7289 void set_pass_param (unsigned int n, bool param)
7291 gcc_assert (n == 0);
7292 warn_array_bounds_p = param;
7294 virtual bool gate (function *) { return flag_tree_vrp != 0; }
7295 virtual unsigned int execute (function *)
7296 { return execute_vrp (warn_array_bounds_p); }
7298 private:
7299 bool warn_array_bounds_p;
7300 }; // class pass_vrp
7302 } // anon namespace
7304 gimple_opt_pass *
7305 make_pass_vrp (gcc::context *ctxt)
7307 return new pass_vrp (ctxt);
7311 /* Worker for determine_value_range. */
7313 static void
7314 determine_value_range_1 (value_range *vr, tree expr)
7316 if (BINARY_CLASS_P (expr))
7318 value_range vr0 = VR_INITIALIZER, vr1 = VR_INITIALIZER;
7319 determine_value_range_1 (&vr0, TREE_OPERAND (expr, 0));
7320 determine_value_range_1 (&vr1, TREE_OPERAND (expr, 1));
7321 extract_range_from_binary_expr_1 (vr, TREE_CODE (expr), TREE_TYPE (expr),
7322 &vr0, &vr1);
7324 else if (UNARY_CLASS_P (expr))
7326 value_range vr0 = VR_INITIALIZER;
7327 determine_value_range_1 (&vr0, TREE_OPERAND (expr, 0));
7328 extract_range_from_unary_expr (vr, TREE_CODE (expr), TREE_TYPE (expr),
7329 &vr0, TREE_TYPE (TREE_OPERAND (expr, 0)));
7331 else if (TREE_CODE (expr) == INTEGER_CST)
7332 set_value_range_to_value (vr, expr, NULL);
7333 else
7335 value_range_type kind;
7336 wide_int min, max;
7337 /* For SSA names try to extract range info computed by VRP. Otherwise
7338 fall back to varying. */
7339 if (TREE_CODE (expr) == SSA_NAME
7340 && INTEGRAL_TYPE_P (TREE_TYPE (expr))
7341 && (kind = get_range_info (expr, &min, &max)) != VR_VARYING)
7342 set_value_range (vr, kind, wide_int_to_tree (TREE_TYPE (expr), min),
7343 wide_int_to_tree (TREE_TYPE (expr), max), NULL);
7344 else
7345 set_value_range_to_varying (vr);
7349 /* Compute a value-range for EXPR and set it in *MIN and *MAX. Return
7350 the determined range type. */
7352 value_range_type
7353 determine_value_range (tree expr, wide_int *min, wide_int *max)
7355 value_range vr = VR_INITIALIZER;
7356 determine_value_range_1 (&vr, expr);
7357 if ((vr.type == VR_RANGE
7358 || vr.type == VR_ANTI_RANGE)
7359 && !symbolic_range_p (&vr))
7361 *min = wi::to_wide (vr.min);
7362 *max = wi::to_wide (vr.max);
7363 return vr.type;
7366 return VR_VARYING;