Define arm_arch_core_flags in a single file
[official-gcc.git] / gcc / tree-vrp.c
blob600634d1804d37f3b307d0c1582db2ff83bb094e
1 /* Support routines for Value Range Propagation (VRP).
2 Copyright (C) 2005-2016 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-ssa-loop-manip.h"
46 #include "tree-ssa-loop-niter.h"
47 #include "tree-ssa-loop.h"
48 #include "tree-into-ssa.h"
49 #include "tree-ssa.h"
50 #include "intl.h"
51 #include "cfgloop.h"
52 #include "tree-scalar-evolution.h"
53 #include "tree-ssa-propagate.h"
54 #include "tree-chrec.h"
55 #include "tree-ssa-threadupdate.h"
56 #include "tree-ssa-scopedtables.h"
57 #include "tree-ssa-threadedge.h"
58 #include "omp-low.h"
59 #include "target.h"
60 #include "case-cfn-macros.h"
61 #include "params.h"
62 #include "alloc-pool.h"
63 #include "domwalk.h"
64 #include "tree-cfgcleanup.h"
66 #define VR_INITIALIZER { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL }
68 /* Allocation pools for tree-vrp allocations. */
69 static object_allocator<value_range> vrp_value_range_pool ("Tree VRP value ranges");
70 static bitmap_obstack vrp_equiv_obstack;
72 /* Set of SSA names found live during the RPO traversal of the function
73 for still active basic-blocks. */
74 static sbitmap *live;
76 /* Return true if the SSA name NAME is live on the edge E. */
78 static bool
79 live_on_edge (edge e, tree name)
81 return (live[e->dest->index]
82 && bitmap_bit_p (live[e->dest->index], SSA_NAME_VERSION (name)));
85 /* Local functions. */
86 static int compare_values (tree val1, tree val2);
87 static int compare_values_warnv (tree val1, tree val2, bool *);
88 static tree vrp_evaluate_conditional_warnv_with_ops (enum tree_code,
89 tree, tree, bool, bool *,
90 bool *);
92 /* Location information for ASSERT_EXPRs. Each instance of this
93 structure describes an ASSERT_EXPR for an SSA name. Since a single
94 SSA name may have more than one assertion associated with it, these
95 locations are kept in a linked list attached to the corresponding
96 SSA name. */
97 struct assert_locus
99 /* Basic block where the assertion would be inserted. */
100 basic_block bb;
102 /* Some assertions need to be inserted on an edge (e.g., assertions
103 generated by COND_EXPRs). In those cases, BB will be NULL. */
104 edge e;
106 /* Pointer to the statement that generated this assertion. */
107 gimple_stmt_iterator si;
109 /* Predicate code for the ASSERT_EXPR. Must be COMPARISON_CLASS_P. */
110 enum tree_code comp_code;
112 /* Value being compared against. */
113 tree val;
115 /* Expression to compare. */
116 tree expr;
118 /* Next node in the linked list. */
119 assert_locus *next;
122 /* If bit I is present, it means that SSA name N_i has a list of
123 assertions that should be inserted in the IL. */
124 static bitmap need_assert_for;
126 /* Array of locations lists where to insert assertions. ASSERTS_FOR[I]
127 holds a list of ASSERT_LOCUS_T nodes that describe where
128 ASSERT_EXPRs for SSA name N_I should be inserted. */
129 static assert_locus **asserts_for;
131 /* Value range array. After propagation, VR_VALUE[I] holds the range
132 of values that SSA name N_I may take. */
133 static unsigned num_vr_values;
134 static value_range **vr_value;
135 static bool values_propagated;
137 /* For a PHI node which sets SSA name N_I, VR_COUNTS[I] holds the
138 number of executable edges we saw the last time we visited the
139 node. */
140 static int *vr_phi_edge_counts;
142 struct switch_update {
143 gswitch *stmt;
144 tree vec;
147 static vec<edge> to_remove_edges;
148 static vec<switch_update> to_update_switch_stmts;
151 /* Return the maximum value for TYPE. */
153 static inline tree
154 vrp_val_max (const_tree type)
156 if (!INTEGRAL_TYPE_P (type))
157 return NULL_TREE;
159 return TYPE_MAX_VALUE (type);
162 /* Return the minimum value for TYPE. */
164 static inline tree
165 vrp_val_min (const_tree type)
167 if (!INTEGRAL_TYPE_P (type))
168 return NULL_TREE;
170 return TYPE_MIN_VALUE (type);
173 /* Return whether VAL is equal to the maximum value of its type. This
174 will be true for a positive overflow infinity. We can't do a
175 simple equality comparison with TYPE_MAX_VALUE because C typedefs
176 and Ada subtypes can produce types whose TYPE_MAX_VALUE is not ==
177 to the integer constant with the same value in the type. */
179 static inline bool
180 vrp_val_is_max (const_tree val)
182 tree type_max = vrp_val_max (TREE_TYPE (val));
183 return (val == type_max
184 || (type_max != NULL_TREE
185 && operand_equal_p (val, type_max, 0)));
188 /* Return whether VAL is equal to the minimum value of its type. This
189 will be true for a negative overflow infinity. */
191 static inline bool
192 vrp_val_is_min (const_tree val)
194 tree type_min = vrp_val_min (TREE_TYPE (val));
195 return (val == type_min
196 || (type_min != NULL_TREE
197 && operand_equal_p (val, type_min, 0)));
201 /* Return whether TYPE should use an overflow infinity distinct from
202 TYPE_{MIN,MAX}_VALUE. We use an overflow infinity value to
203 represent a signed overflow during VRP computations. An infinity
204 is distinct from a half-range, which will go from some number to
205 TYPE_{MIN,MAX}_VALUE. */
207 static inline bool
208 needs_overflow_infinity (const_tree type)
210 return INTEGRAL_TYPE_P (type) && !TYPE_OVERFLOW_WRAPS (type);
213 /* Return whether TYPE can support our overflow infinity
214 representation: we use the TREE_OVERFLOW flag, which only exists
215 for constants. If TYPE doesn't support this, we don't optimize
216 cases which would require signed overflow--we drop them to
217 VARYING. */
219 static inline bool
220 supports_overflow_infinity (const_tree type)
222 tree min = vrp_val_min (type), max = vrp_val_max (type);
223 gcc_checking_assert (needs_overflow_infinity (type));
224 return (min != NULL_TREE
225 && CONSTANT_CLASS_P (min)
226 && max != NULL_TREE
227 && CONSTANT_CLASS_P (max));
230 /* VAL is the maximum or minimum value of a type. Return a
231 corresponding overflow infinity. */
233 static inline tree
234 make_overflow_infinity (tree val)
236 gcc_checking_assert (val != NULL_TREE && CONSTANT_CLASS_P (val));
237 val = copy_node (val);
238 TREE_OVERFLOW (val) = 1;
239 return val;
242 /* Return a negative overflow infinity for TYPE. */
244 static inline tree
245 negative_overflow_infinity (tree type)
247 gcc_checking_assert (supports_overflow_infinity (type));
248 return make_overflow_infinity (vrp_val_min (type));
251 /* Return a positive overflow infinity for TYPE. */
253 static inline tree
254 positive_overflow_infinity (tree type)
256 gcc_checking_assert (supports_overflow_infinity (type));
257 return make_overflow_infinity (vrp_val_max (type));
260 /* Return whether VAL is a negative overflow infinity. */
262 static inline bool
263 is_negative_overflow_infinity (const_tree val)
265 return (TREE_OVERFLOW_P (val)
266 && needs_overflow_infinity (TREE_TYPE (val))
267 && vrp_val_is_min (val));
270 /* Return whether VAL is a positive overflow infinity. */
272 static inline bool
273 is_positive_overflow_infinity (const_tree val)
275 return (TREE_OVERFLOW_P (val)
276 && needs_overflow_infinity (TREE_TYPE (val))
277 && vrp_val_is_max (val));
280 /* Return whether VAL is a positive or negative overflow infinity. */
282 static inline bool
283 is_overflow_infinity (const_tree val)
285 return (TREE_OVERFLOW_P (val)
286 && needs_overflow_infinity (TREE_TYPE (val))
287 && (vrp_val_is_min (val) || vrp_val_is_max (val)));
290 /* Return whether STMT has a constant rhs that is_overflow_infinity. */
292 static inline bool
293 stmt_overflow_infinity (gimple *stmt)
295 if (is_gimple_assign (stmt)
296 && get_gimple_rhs_class (gimple_assign_rhs_code (stmt)) ==
297 GIMPLE_SINGLE_RHS)
298 return is_overflow_infinity (gimple_assign_rhs1 (stmt));
299 return false;
302 /* If VAL is now an overflow infinity, return VAL. Otherwise, return
303 the same value with TREE_OVERFLOW clear. This can be used to avoid
304 confusing a regular value with an overflow value. */
306 static inline tree
307 avoid_overflow_infinity (tree val)
309 if (!is_overflow_infinity (val))
310 return val;
312 if (vrp_val_is_max (val))
313 return vrp_val_max (TREE_TYPE (val));
314 else
316 gcc_checking_assert (vrp_val_is_min (val));
317 return vrp_val_min (TREE_TYPE (val));
322 /* Set value range VR to VR_UNDEFINED. */
324 static inline void
325 set_value_range_to_undefined (value_range *vr)
327 vr->type = VR_UNDEFINED;
328 vr->min = vr->max = NULL_TREE;
329 if (vr->equiv)
330 bitmap_clear (vr->equiv);
334 /* Set value range VR to VR_VARYING. */
336 static inline void
337 set_value_range_to_varying (value_range *vr)
339 vr->type = VR_VARYING;
340 vr->min = vr->max = NULL_TREE;
341 if (vr->equiv)
342 bitmap_clear (vr->equiv);
346 /* Set value range VR to {T, MIN, MAX, EQUIV}. */
348 static void
349 set_value_range (value_range *vr, enum value_range_type t, tree min,
350 tree max, bitmap equiv)
352 /* Check the validity of the range. */
353 if (flag_checking
354 && (t == VR_RANGE || t == VR_ANTI_RANGE))
356 int cmp;
358 gcc_assert (min && max);
360 gcc_assert ((!TREE_OVERFLOW_P (min) || is_overflow_infinity (min))
361 && (!TREE_OVERFLOW_P (max) || is_overflow_infinity (max)));
363 if (INTEGRAL_TYPE_P (TREE_TYPE (min)) && t == VR_ANTI_RANGE)
364 gcc_assert (!vrp_val_is_min (min) || !vrp_val_is_max (max));
366 cmp = compare_values (min, max);
367 gcc_assert (cmp == 0 || cmp == -1 || cmp == -2);
369 if (needs_overflow_infinity (TREE_TYPE (min)))
370 gcc_assert (!is_overflow_infinity (min)
371 || !is_overflow_infinity (max));
374 if (flag_checking
375 && (t == VR_UNDEFINED || t == VR_VARYING))
377 gcc_assert (min == NULL_TREE && max == NULL_TREE);
378 gcc_assert (equiv == NULL || bitmap_empty_p (equiv));
381 vr->type = t;
382 vr->min = min;
383 vr->max = max;
385 /* Since updating the equivalence set involves deep copying the
386 bitmaps, only do it if absolutely necessary. */
387 if (vr->equiv == NULL
388 && equiv != NULL)
389 vr->equiv = BITMAP_ALLOC (&vrp_equiv_obstack);
391 if (equiv != vr->equiv)
393 if (equiv && !bitmap_empty_p (equiv))
394 bitmap_copy (vr->equiv, equiv);
395 else
396 bitmap_clear (vr->equiv);
401 /* Set value range VR to the canonical form of {T, MIN, MAX, EQUIV}.
402 This means adjusting T, MIN and MAX representing the case of a
403 wrapping range with MAX < MIN covering [MIN, type_max] U [type_min, MAX]
404 as anti-rage ~[MAX+1, MIN-1]. Likewise for wrapping anti-ranges.
405 In corner cases where MAX+1 or MIN-1 wraps this will fall back
406 to varying.
407 This routine exists to ease canonicalization in the case where we
408 extract ranges from var + CST op limit. */
410 static void
411 set_and_canonicalize_value_range (value_range *vr, enum value_range_type t,
412 tree min, tree max, bitmap equiv)
414 /* Use the canonical setters for VR_UNDEFINED and VR_VARYING. */
415 if (t == VR_UNDEFINED)
417 set_value_range_to_undefined (vr);
418 return;
420 else if (t == VR_VARYING)
422 set_value_range_to_varying (vr);
423 return;
426 /* Nothing to canonicalize for symbolic ranges. */
427 if (TREE_CODE (min) != INTEGER_CST
428 || TREE_CODE (max) != INTEGER_CST)
430 set_value_range (vr, t, min, max, equiv);
431 return;
434 /* Wrong order for min and max, to swap them and the VR type we need
435 to adjust them. */
436 if (tree_int_cst_lt (max, min))
438 tree one, tmp;
440 /* For one bit precision if max < min, then the swapped
441 range covers all values, so for VR_RANGE it is varying and
442 for VR_ANTI_RANGE empty range, so drop to varying as well. */
443 if (TYPE_PRECISION (TREE_TYPE (min)) == 1)
445 set_value_range_to_varying (vr);
446 return;
449 one = build_int_cst (TREE_TYPE (min), 1);
450 tmp = int_const_binop (PLUS_EXPR, max, one);
451 max = int_const_binop (MINUS_EXPR, min, one);
452 min = tmp;
454 /* There's one corner case, if we had [C+1, C] before we now have
455 that again. But this represents an empty value range, so drop
456 to varying in this case. */
457 if (tree_int_cst_lt (max, min))
459 set_value_range_to_varying (vr);
460 return;
463 t = t == VR_RANGE ? VR_ANTI_RANGE : VR_RANGE;
466 /* Anti-ranges that can be represented as ranges should be so. */
467 if (t == VR_ANTI_RANGE)
469 bool is_min = vrp_val_is_min (min);
470 bool is_max = vrp_val_is_max (max);
472 if (is_min && is_max)
474 /* We cannot deal with empty ranges, drop to varying.
475 ??? This could be VR_UNDEFINED instead. */
476 set_value_range_to_varying (vr);
477 return;
479 else if (TYPE_PRECISION (TREE_TYPE (min)) == 1
480 && (is_min || is_max))
482 /* Non-empty boolean ranges can always be represented
483 as a singleton range. */
484 if (is_min)
485 min = max = vrp_val_max (TREE_TYPE (min));
486 else
487 min = max = vrp_val_min (TREE_TYPE (min));
488 t = VR_RANGE;
490 else if (is_min
491 /* As a special exception preserve non-null ranges. */
492 && !(TYPE_UNSIGNED (TREE_TYPE (min))
493 && integer_zerop (max)))
495 tree one = build_int_cst (TREE_TYPE (max), 1);
496 min = int_const_binop (PLUS_EXPR, max, one);
497 max = vrp_val_max (TREE_TYPE (max));
498 t = VR_RANGE;
500 else if (is_max)
502 tree one = build_int_cst (TREE_TYPE (min), 1);
503 max = int_const_binop (MINUS_EXPR, min, one);
504 min = vrp_val_min (TREE_TYPE (min));
505 t = VR_RANGE;
509 /* Drop [-INF(OVF), +INF(OVF)] to varying. */
510 if (needs_overflow_infinity (TREE_TYPE (min))
511 && is_overflow_infinity (min)
512 && is_overflow_infinity (max))
514 set_value_range_to_varying (vr);
515 return;
518 set_value_range (vr, t, min, max, equiv);
521 /* Copy value range FROM into value range TO. */
523 static inline void
524 copy_value_range (value_range *to, value_range *from)
526 set_value_range (to, from->type, from->min, from->max, from->equiv);
529 /* Set value range VR to a single value. This function is only called
530 with values we get from statements, and exists to clear the
531 TREE_OVERFLOW flag so that we don't think we have an overflow
532 infinity when we shouldn't. */
534 static inline void
535 set_value_range_to_value (value_range *vr, tree val, bitmap equiv)
537 gcc_assert (is_gimple_min_invariant (val));
538 if (TREE_OVERFLOW_P (val))
539 val = drop_tree_overflow (val);
540 set_value_range (vr, VR_RANGE, val, val, equiv);
543 /* Set value range VR to a non-negative range of type TYPE.
544 OVERFLOW_INFINITY indicates whether to use an overflow infinity
545 rather than TYPE_MAX_VALUE; this should be true if we determine
546 that the range is nonnegative based on the assumption that signed
547 overflow does not occur. */
549 static inline void
550 set_value_range_to_nonnegative (value_range *vr, tree type,
551 bool overflow_infinity)
553 tree zero;
555 if (overflow_infinity && !supports_overflow_infinity (type))
557 set_value_range_to_varying (vr);
558 return;
561 zero = build_int_cst (type, 0);
562 set_value_range (vr, VR_RANGE, zero,
563 (overflow_infinity
564 ? positive_overflow_infinity (type)
565 : TYPE_MAX_VALUE (type)),
566 vr->equiv);
569 /* Set value range VR to a non-NULL range of type TYPE. */
571 static inline void
572 set_value_range_to_nonnull (value_range *vr, tree type)
574 tree zero = build_int_cst (type, 0);
575 set_value_range (vr, VR_ANTI_RANGE, zero, zero, vr->equiv);
579 /* Set value range VR to a NULL range of type TYPE. */
581 static inline void
582 set_value_range_to_null (value_range *vr, tree type)
584 set_value_range_to_value (vr, build_int_cst (type, 0), vr->equiv);
588 /* Set value range VR to a range of a truthvalue of type TYPE. */
590 static inline void
591 set_value_range_to_truthvalue (value_range *vr, tree type)
593 if (TYPE_PRECISION (type) == 1)
594 set_value_range_to_varying (vr);
595 else
596 set_value_range (vr, VR_RANGE,
597 build_int_cst (type, 0), build_int_cst (type, 1),
598 vr->equiv);
602 /* If abs (min) < abs (max), set VR to [-max, max], if
603 abs (min) >= abs (max), set VR to [-min, min]. */
605 static void
606 abs_extent_range (value_range *vr, tree min, tree max)
608 int cmp;
610 gcc_assert (TREE_CODE (min) == INTEGER_CST);
611 gcc_assert (TREE_CODE (max) == INTEGER_CST);
612 gcc_assert (INTEGRAL_TYPE_P (TREE_TYPE (min)));
613 gcc_assert (!TYPE_UNSIGNED (TREE_TYPE (min)));
614 min = fold_unary (ABS_EXPR, TREE_TYPE (min), min);
615 max = fold_unary (ABS_EXPR, TREE_TYPE (max), max);
616 if (TREE_OVERFLOW (min) || TREE_OVERFLOW (max))
618 set_value_range_to_varying (vr);
619 return;
621 cmp = compare_values (min, max);
622 if (cmp == -1)
623 min = fold_unary (NEGATE_EXPR, TREE_TYPE (min), max);
624 else if (cmp == 0 || cmp == 1)
626 max = min;
627 min = fold_unary (NEGATE_EXPR, TREE_TYPE (min), min);
629 else
631 set_value_range_to_varying (vr);
632 return;
634 set_and_canonicalize_value_range (vr, VR_RANGE, min, max, NULL);
638 /* Return value range information for VAR.
640 If we have no values ranges recorded (ie, VRP is not running), then
641 return NULL. Otherwise create an empty range if none existed for VAR. */
643 static value_range *
644 get_value_range (const_tree var)
646 static const value_range vr_const_varying
647 = { VR_VARYING, NULL_TREE, NULL_TREE, NULL };
648 value_range *vr;
649 tree sym;
650 unsigned ver = SSA_NAME_VERSION (var);
652 /* If we have no recorded ranges, then return NULL. */
653 if (! vr_value)
654 return NULL;
656 /* If we query the range for a new SSA name return an unmodifiable VARYING.
657 We should get here at most from the substitute-and-fold stage which
658 will never try to change values. */
659 if (ver >= num_vr_values)
660 return CONST_CAST (value_range *, &vr_const_varying);
662 vr = vr_value[ver];
663 if (vr)
664 return vr;
666 /* After propagation finished do not allocate new value-ranges. */
667 if (values_propagated)
668 return CONST_CAST (value_range *, &vr_const_varying);
670 /* Create a default value range. */
671 vr_value[ver] = vr = vrp_value_range_pool.allocate ();
672 memset (vr, 0, sizeof (*vr));
674 /* Defer allocating the equivalence set. */
675 vr->equiv = NULL;
677 /* If VAR is a default definition of a parameter, the variable can
678 take any value in VAR's type. */
679 if (SSA_NAME_IS_DEFAULT_DEF (var))
681 sym = SSA_NAME_VAR (var);
682 if (TREE_CODE (sym) == PARM_DECL)
684 /* Try to use the "nonnull" attribute to create ~[0, 0]
685 anti-ranges for pointers. Note that this is only valid with
686 default definitions of PARM_DECLs. */
687 if (POINTER_TYPE_P (TREE_TYPE (sym))
688 && (nonnull_arg_p (sym)
689 || get_ptr_nonnull (var)))
690 set_value_range_to_nonnull (vr, TREE_TYPE (sym));
691 else if (INTEGRAL_TYPE_P (TREE_TYPE (sym)))
693 wide_int min, max;
694 value_range_type rtype = get_range_info (var, &min, &max);
695 if (rtype == VR_RANGE || rtype == VR_ANTI_RANGE)
696 set_value_range (vr, rtype,
697 wide_int_to_tree (TREE_TYPE (var), min),
698 wide_int_to_tree (TREE_TYPE (var), max),
699 NULL);
700 else
701 set_value_range_to_varying (vr);
703 else
704 set_value_range_to_varying (vr);
706 else if (TREE_CODE (sym) == RESULT_DECL
707 && DECL_BY_REFERENCE (sym))
708 set_value_range_to_nonnull (vr, TREE_TYPE (sym));
711 return vr;
714 /* Set value-ranges of all SSA names defined by STMT to varying. */
716 static void
717 set_defs_to_varying (gimple *stmt)
719 ssa_op_iter i;
720 tree def;
721 FOR_EACH_SSA_TREE_OPERAND (def, stmt, i, SSA_OP_DEF)
723 value_range *vr = get_value_range (def);
724 /* Avoid writing to vr_const_varying get_value_range may return. */
725 if (vr->type != VR_VARYING)
726 set_value_range_to_varying (vr);
731 /* Return true, if VAL1 and VAL2 are equal values for VRP purposes. */
733 static inline bool
734 vrp_operand_equal_p (const_tree val1, const_tree val2)
736 if (val1 == val2)
737 return true;
738 if (!val1 || !val2 || !operand_equal_p (val1, val2, 0))
739 return false;
740 return is_overflow_infinity (val1) == is_overflow_infinity (val2);
743 /* Return true, if the bitmaps B1 and B2 are equal. */
745 static inline bool
746 vrp_bitmap_equal_p (const_bitmap b1, const_bitmap b2)
748 return (b1 == b2
749 || ((!b1 || bitmap_empty_p (b1))
750 && (!b2 || bitmap_empty_p (b2)))
751 || (b1 && b2
752 && bitmap_equal_p (b1, b2)));
755 /* Update the value range and equivalence set for variable VAR to
756 NEW_VR. Return true if NEW_VR is different from VAR's previous
757 value.
759 NOTE: This function assumes that NEW_VR is a temporary value range
760 object created for the sole purpose of updating VAR's range. The
761 storage used by the equivalence set from NEW_VR will be freed by
762 this function. Do not call update_value_range when NEW_VR
763 is the range object associated with another SSA name. */
765 static inline bool
766 update_value_range (const_tree var, value_range *new_vr)
768 value_range *old_vr;
769 bool is_new;
771 /* If there is a value-range on the SSA name from earlier analysis
772 factor that in. */
773 if (INTEGRAL_TYPE_P (TREE_TYPE (var)))
775 wide_int min, max;
776 value_range_type rtype = get_range_info (var, &min, &max);
777 if (rtype == VR_RANGE || rtype == VR_ANTI_RANGE)
779 tree nr_min, nr_max;
780 /* Range info on SSA names doesn't carry overflow information
781 so make sure to preserve the overflow bit on the lattice. */
782 if (rtype == VR_RANGE
783 && needs_overflow_infinity (TREE_TYPE (var))
784 && (new_vr->type == VR_VARYING
785 || (new_vr->type == VR_RANGE
786 && is_negative_overflow_infinity (new_vr->min)))
787 && wi::eq_p (vrp_val_min (TREE_TYPE (var)), min))
788 nr_min = negative_overflow_infinity (TREE_TYPE (var));
789 else
790 nr_min = wide_int_to_tree (TREE_TYPE (var), min);
791 if (rtype == VR_RANGE
792 && needs_overflow_infinity (TREE_TYPE (var))
793 && (new_vr->type == VR_VARYING
794 || (new_vr->type == VR_RANGE
795 && is_positive_overflow_infinity (new_vr->max)))
796 && wi::eq_p (vrp_val_max (TREE_TYPE (var)), max))
797 nr_max = positive_overflow_infinity (TREE_TYPE (var));
798 else
799 nr_max = wide_int_to_tree (TREE_TYPE (var), max);
800 value_range nr = VR_INITIALIZER;
801 set_and_canonicalize_value_range (&nr, rtype, nr_min, nr_max, NULL);
802 vrp_intersect_ranges (new_vr, &nr);
806 /* Update the value range, if necessary. */
807 old_vr = get_value_range (var);
808 is_new = old_vr->type != new_vr->type
809 || !vrp_operand_equal_p (old_vr->min, new_vr->min)
810 || !vrp_operand_equal_p (old_vr->max, new_vr->max)
811 || !vrp_bitmap_equal_p (old_vr->equiv, new_vr->equiv);
813 if (is_new)
815 /* Do not allow transitions up the lattice. The following
816 is slightly more awkward than just new_vr->type < old_vr->type
817 because VR_RANGE and VR_ANTI_RANGE need to be considered
818 the same. We may not have is_new when transitioning to
819 UNDEFINED. If old_vr->type is VARYING, we shouldn't be
820 called. */
821 if (new_vr->type == VR_UNDEFINED)
823 BITMAP_FREE (new_vr->equiv);
824 set_value_range_to_varying (old_vr);
825 set_value_range_to_varying (new_vr);
826 return true;
828 else
829 set_value_range (old_vr, new_vr->type, new_vr->min, new_vr->max,
830 new_vr->equiv);
833 BITMAP_FREE (new_vr->equiv);
835 return is_new;
839 /* Add VAR and VAR's equivalence set to EQUIV. This is the central
840 point where equivalence processing can be turned on/off. */
842 static void
843 add_equivalence (bitmap *equiv, const_tree var)
845 unsigned ver = SSA_NAME_VERSION (var);
846 value_range *vr = get_value_range (var);
848 if (*equiv == NULL)
849 *equiv = BITMAP_ALLOC (&vrp_equiv_obstack);
850 bitmap_set_bit (*equiv, ver);
851 if (vr && vr->equiv)
852 bitmap_ior_into (*equiv, vr->equiv);
856 /* Return true if VR is ~[0, 0]. */
858 static inline bool
859 range_is_nonnull (value_range *vr)
861 return vr->type == VR_ANTI_RANGE
862 && integer_zerop (vr->min)
863 && integer_zerop (vr->max);
867 /* Return true if VR is [0, 0]. */
869 static inline bool
870 range_is_null (value_range *vr)
872 return vr->type == VR_RANGE
873 && integer_zerop (vr->min)
874 && integer_zerop (vr->max);
877 /* Return true if max and min of VR are INTEGER_CST. It's not necessary
878 a singleton. */
880 static inline bool
881 range_int_cst_p (value_range *vr)
883 return (vr->type == VR_RANGE
884 && TREE_CODE (vr->max) == INTEGER_CST
885 && TREE_CODE (vr->min) == INTEGER_CST);
888 /* Return true if VR is a INTEGER_CST singleton. */
890 static inline bool
891 range_int_cst_singleton_p (value_range *vr)
893 return (range_int_cst_p (vr)
894 && !is_overflow_infinity (vr->min)
895 && !is_overflow_infinity (vr->max)
896 && tree_int_cst_equal (vr->min, vr->max));
899 /* Return true if value range VR involves at least one symbol. */
901 static inline bool
902 symbolic_range_p (value_range *vr)
904 return (!is_gimple_min_invariant (vr->min)
905 || !is_gimple_min_invariant (vr->max));
908 /* Return the single symbol (an SSA_NAME) contained in T if any, or NULL_TREE
909 otherwise. We only handle additive operations and set NEG to true if the
910 symbol is negated and INV to the invariant part, if any. */
912 static tree
913 get_single_symbol (tree t, bool *neg, tree *inv)
915 bool neg_;
916 tree inv_;
918 *inv = NULL_TREE;
919 *neg = false;
921 if (TREE_CODE (t) == PLUS_EXPR
922 || TREE_CODE (t) == POINTER_PLUS_EXPR
923 || TREE_CODE (t) == MINUS_EXPR)
925 if (is_gimple_min_invariant (TREE_OPERAND (t, 0)))
927 neg_ = (TREE_CODE (t) == MINUS_EXPR);
928 inv_ = TREE_OPERAND (t, 0);
929 t = TREE_OPERAND (t, 1);
931 else if (is_gimple_min_invariant (TREE_OPERAND (t, 1)))
933 neg_ = false;
934 inv_ = TREE_OPERAND (t, 1);
935 t = TREE_OPERAND (t, 0);
937 else
938 return NULL_TREE;
940 else
942 neg_ = false;
943 inv_ = NULL_TREE;
946 if (TREE_CODE (t) == NEGATE_EXPR)
948 t = TREE_OPERAND (t, 0);
949 neg_ = !neg_;
952 if (TREE_CODE (t) != SSA_NAME)
953 return NULL_TREE;
955 *neg = neg_;
956 *inv = inv_;
957 return t;
960 /* The reverse operation: build a symbolic expression with TYPE
961 from symbol SYM, negated according to NEG, and invariant INV. */
963 static tree
964 build_symbolic_expr (tree type, tree sym, bool neg, tree inv)
966 const bool pointer_p = POINTER_TYPE_P (type);
967 tree t = sym;
969 if (neg)
970 t = build1 (NEGATE_EXPR, type, t);
972 if (integer_zerop (inv))
973 return t;
975 return build2 (pointer_p ? POINTER_PLUS_EXPR : PLUS_EXPR, type, t, inv);
978 /* Return true if value range VR involves exactly one symbol SYM. */
980 static bool
981 symbolic_range_based_on_p (value_range *vr, const_tree sym)
983 bool neg, min_has_symbol, max_has_symbol;
984 tree inv;
986 if (is_gimple_min_invariant (vr->min))
987 min_has_symbol = false;
988 else if (get_single_symbol (vr->min, &neg, &inv) == sym)
989 min_has_symbol = true;
990 else
991 return false;
993 if (is_gimple_min_invariant (vr->max))
994 max_has_symbol = false;
995 else if (get_single_symbol (vr->max, &neg, &inv) == sym)
996 max_has_symbol = true;
997 else
998 return false;
1000 return (min_has_symbol || max_has_symbol);
1003 /* Return true if value range VR uses an overflow infinity. */
1005 static inline bool
1006 overflow_infinity_range_p (value_range *vr)
1008 return (vr->type == VR_RANGE
1009 && (is_overflow_infinity (vr->min)
1010 || is_overflow_infinity (vr->max)));
1013 /* Return false if we can not make a valid comparison based on VR;
1014 this will be the case if it uses an overflow infinity and overflow
1015 is not undefined (i.e., -fno-strict-overflow is in effect).
1016 Otherwise return true, and set *STRICT_OVERFLOW_P to true if VR
1017 uses an overflow infinity. */
1019 static bool
1020 usable_range_p (value_range *vr, bool *strict_overflow_p)
1022 gcc_assert (vr->type == VR_RANGE);
1023 if (is_overflow_infinity (vr->min))
1025 *strict_overflow_p = true;
1026 if (!TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (vr->min)))
1027 return false;
1029 if (is_overflow_infinity (vr->max))
1031 *strict_overflow_p = true;
1032 if (!TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (vr->max)))
1033 return false;
1035 return true;
1038 /* Return true if the result of assignment STMT is know to be non-zero.
1039 If the return value is based on the assumption that signed overflow is
1040 undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
1041 *STRICT_OVERFLOW_P.*/
1043 static bool
1044 gimple_assign_nonzero_warnv_p (gimple *stmt, bool *strict_overflow_p)
1046 enum tree_code code = gimple_assign_rhs_code (stmt);
1047 switch (get_gimple_rhs_class (code))
1049 case GIMPLE_UNARY_RHS:
1050 return tree_unary_nonzero_warnv_p (gimple_assign_rhs_code (stmt),
1051 gimple_expr_type (stmt),
1052 gimple_assign_rhs1 (stmt),
1053 strict_overflow_p);
1054 case GIMPLE_BINARY_RHS:
1055 return tree_binary_nonzero_warnv_p (gimple_assign_rhs_code (stmt),
1056 gimple_expr_type (stmt),
1057 gimple_assign_rhs1 (stmt),
1058 gimple_assign_rhs2 (stmt),
1059 strict_overflow_p);
1060 case GIMPLE_TERNARY_RHS:
1061 return false;
1062 case GIMPLE_SINGLE_RHS:
1063 return tree_single_nonzero_warnv_p (gimple_assign_rhs1 (stmt),
1064 strict_overflow_p);
1065 case GIMPLE_INVALID_RHS:
1066 gcc_unreachable ();
1067 default:
1068 gcc_unreachable ();
1072 /* Return true if STMT is known to compute a non-zero value.
1073 If the return value is based on the assumption that signed overflow is
1074 undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
1075 *STRICT_OVERFLOW_P.*/
1077 static bool
1078 gimple_stmt_nonzero_warnv_p (gimple *stmt, bool *strict_overflow_p)
1080 switch (gimple_code (stmt))
1082 case GIMPLE_ASSIGN:
1083 return gimple_assign_nonzero_warnv_p (stmt, strict_overflow_p);
1084 case GIMPLE_CALL:
1086 tree fndecl = gimple_call_fndecl (stmt);
1087 if (!fndecl) return false;
1088 if (flag_delete_null_pointer_checks && !flag_check_new
1089 && DECL_IS_OPERATOR_NEW (fndecl)
1090 && !TREE_NOTHROW (fndecl))
1091 return true;
1092 /* References are always non-NULL. */
1093 if (flag_delete_null_pointer_checks
1094 && TREE_CODE (TREE_TYPE (fndecl)) == REFERENCE_TYPE)
1095 return true;
1096 if (flag_delete_null_pointer_checks &&
1097 lookup_attribute ("returns_nonnull",
1098 TYPE_ATTRIBUTES (gimple_call_fntype (stmt))))
1099 return true;
1101 gcall *call_stmt = as_a<gcall *> (stmt);
1102 unsigned rf = gimple_call_return_flags (call_stmt);
1103 if (rf & ERF_RETURNS_ARG)
1105 unsigned argnum = rf & ERF_RETURN_ARG_MASK;
1106 if (argnum < gimple_call_num_args (call_stmt))
1108 tree arg = gimple_call_arg (call_stmt, argnum);
1109 if (SSA_VAR_P (arg)
1110 && infer_nonnull_range_by_attribute (stmt, arg))
1111 return true;
1114 return gimple_alloca_call_p (stmt);
1116 default:
1117 gcc_unreachable ();
1121 /* Like tree_expr_nonzero_warnv_p, but this function uses value ranges
1122 obtained so far. */
1124 static bool
1125 vrp_stmt_computes_nonzero (gimple *stmt, bool *strict_overflow_p)
1127 if (gimple_stmt_nonzero_warnv_p (stmt, strict_overflow_p))
1128 return true;
1130 /* If we have an expression of the form &X->a, then the expression
1131 is nonnull if X is nonnull. */
1132 if (is_gimple_assign (stmt)
1133 && gimple_assign_rhs_code (stmt) == ADDR_EXPR)
1135 tree expr = gimple_assign_rhs1 (stmt);
1136 tree base = get_base_address (TREE_OPERAND (expr, 0));
1138 if (base != NULL_TREE
1139 && TREE_CODE (base) == MEM_REF
1140 && TREE_CODE (TREE_OPERAND (base, 0)) == SSA_NAME)
1142 value_range *vr = get_value_range (TREE_OPERAND (base, 0));
1143 if (range_is_nonnull (vr))
1144 return true;
1148 return false;
1151 /* Returns true if EXPR is a valid value (as expected by compare_values) --
1152 a gimple invariant, or SSA_NAME +- CST. */
1154 static bool
1155 valid_value_p (tree expr)
1157 if (TREE_CODE (expr) == SSA_NAME)
1158 return true;
1160 if (TREE_CODE (expr) == PLUS_EXPR
1161 || TREE_CODE (expr) == MINUS_EXPR)
1162 return (TREE_CODE (TREE_OPERAND (expr, 0)) == SSA_NAME
1163 && TREE_CODE (TREE_OPERAND (expr, 1)) == INTEGER_CST);
1165 return is_gimple_min_invariant (expr);
1168 /* Return
1169 1 if VAL < VAL2
1170 0 if !(VAL < VAL2)
1171 -2 if those are incomparable. */
1172 static inline int
1173 operand_less_p (tree val, tree val2)
1175 /* LT is folded faster than GE and others. Inline the common case. */
1176 if (TREE_CODE (val) == INTEGER_CST && TREE_CODE (val2) == INTEGER_CST)
1178 if (! is_positive_overflow_infinity (val2))
1179 return tree_int_cst_lt (val, val2);
1181 else
1183 tree tcmp;
1185 fold_defer_overflow_warnings ();
1187 tcmp = fold_binary_to_constant (LT_EXPR, boolean_type_node, val, val2);
1189 fold_undefer_and_ignore_overflow_warnings ();
1191 if (!tcmp
1192 || TREE_CODE (tcmp) != INTEGER_CST)
1193 return -2;
1195 if (!integer_zerop (tcmp))
1196 return 1;
1199 /* val >= val2, not considering overflow infinity. */
1200 if (is_negative_overflow_infinity (val))
1201 return is_negative_overflow_infinity (val2) ? 0 : 1;
1202 else if (is_positive_overflow_infinity (val2))
1203 return is_positive_overflow_infinity (val) ? 0 : 1;
1205 return 0;
1208 /* Compare two values VAL1 and VAL2. Return
1210 -2 if VAL1 and VAL2 cannot be compared at compile-time,
1211 -1 if VAL1 < VAL2,
1212 0 if VAL1 == VAL2,
1213 +1 if VAL1 > VAL2, and
1214 +2 if VAL1 != VAL2
1216 This is similar to tree_int_cst_compare but supports pointer values
1217 and values that cannot be compared at compile time.
1219 If STRICT_OVERFLOW_P is not NULL, then set *STRICT_OVERFLOW_P to
1220 true if the return value is only valid if we assume that signed
1221 overflow is undefined. */
1223 static int
1224 compare_values_warnv (tree val1, tree val2, bool *strict_overflow_p)
1226 if (val1 == val2)
1227 return 0;
1229 /* Below we rely on the fact that VAL1 and VAL2 are both pointers or
1230 both integers. */
1231 gcc_assert (POINTER_TYPE_P (TREE_TYPE (val1))
1232 == POINTER_TYPE_P (TREE_TYPE (val2)));
1234 /* Convert the two values into the same type. This is needed because
1235 sizetype causes sign extension even for unsigned types. */
1236 val2 = fold_convert (TREE_TYPE (val1), val2);
1237 STRIP_USELESS_TYPE_CONVERSION (val2);
1239 const bool overflow_undefined
1240 = INTEGRAL_TYPE_P (TREE_TYPE (val1))
1241 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1));
1242 tree inv1, inv2;
1243 bool neg1, neg2;
1244 tree sym1 = get_single_symbol (val1, &neg1, &inv1);
1245 tree sym2 = get_single_symbol (val2, &neg2, &inv2);
1247 /* If VAL1 and VAL2 are of the form '[-]NAME [+ CST]', return -1 or +1
1248 accordingly. If VAL1 and VAL2 don't use the same name, return -2. */
1249 if (sym1 && sym2)
1251 /* Both values must use the same name with the same sign. */
1252 if (sym1 != sym2 || neg1 != neg2)
1253 return -2;
1255 /* [-]NAME + CST == [-]NAME + CST. */
1256 if (inv1 == inv2)
1257 return 0;
1259 /* If overflow is defined we cannot simplify more. */
1260 if (!overflow_undefined)
1261 return -2;
1263 if (strict_overflow_p != NULL
1264 && (!inv1 || !TREE_NO_WARNING (val1))
1265 && (!inv2 || !TREE_NO_WARNING (val2)))
1266 *strict_overflow_p = true;
1268 if (!inv1)
1269 inv1 = build_int_cst (TREE_TYPE (val1), 0);
1270 if (!inv2)
1271 inv2 = build_int_cst (TREE_TYPE (val2), 0);
1273 return compare_values_warnv (inv1, inv2, strict_overflow_p);
1276 const bool cst1 = is_gimple_min_invariant (val1);
1277 const bool cst2 = is_gimple_min_invariant (val2);
1279 /* If one is of the form '[-]NAME + CST' and the other is constant, then
1280 it might be possible to say something depending on the constants. */
1281 if ((sym1 && inv1 && cst2) || (sym2 && inv2 && cst1))
1283 if (!overflow_undefined)
1284 return -2;
1286 if (strict_overflow_p != NULL
1287 && (!sym1 || !TREE_NO_WARNING (val1))
1288 && (!sym2 || !TREE_NO_WARNING (val2)))
1289 *strict_overflow_p = true;
1291 const signop sgn = TYPE_SIGN (TREE_TYPE (val1));
1292 tree cst = cst1 ? val1 : val2;
1293 tree inv = cst1 ? inv2 : inv1;
1295 /* Compute the difference between the constants. If it overflows or
1296 underflows, this means that we can trivially compare the NAME with
1297 it and, consequently, the two values with each other. */
1298 wide_int diff = wi::sub (cst, inv);
1299 if (wi::cmp (0, inv, sgn) != wi::cmp (diff, cst, sgn))
1301 const int res = wi::cmp (cst, inv, sgn);
1302 return cst1 ? res : -res;
1305 return -2;
1308 /* We cannot say anything more for non-constants. */
1309 if (!cst1 || !cst2)
1310 return -2;
1312 if (!POINTER_TYPE_P (TREE_TYPE (val1)))
1314 /* We cannot compare overflowed values, except for overflow
1315 infinities. */
1316 if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
1318 if (strict_overflow_p != NULL)
1319 *strict_overflow_p = true;
1320 if (is_negative_overflow_infinity (val1))
1321 return is_negative_overflow_infinity (val2) ? 0 : -1;
1322 else if (is_negative_overflow_infinity (val2))
1323 return 1;
1324 else if (is_positive_overflow_infinity (val1))
1325 return is_positive_overflow_infinity (val2) ? 0 : 1;
1326 else if (is_positive_overflow_infinity (val2))
1327 return -1;
1328 return -2;
1331 return tree_int_cst_compare (val1, val2);
1333 else
1335 tree t;
1337 /* First see if VAL1 and VAL2 are not the same. */
1338 if (val1 == val2 || operand_equal_p (val1, val2, 0))
1339 return 0;
1341 /* If VAL1 is a lower address than VAL2, return -1. */
1342 if (operand_less_p (val1, val2) == 1)
1343 return -1;
1345 /* If VAL1 is a higher address than VAL2, return +1. */
1346 if (operand_less_p (val2, val1) == 1)
1347 return 1;
1349 /* If VAL1 is different than VAL2, return +2.
1350 For integer constants we either have already returned -1 or 1
1351 or they are equivalent. We still might succeed in proving
1352 something about non-trivial operands. */
1353 if (TREE_CODE (val1) != INTEGER_CST
1354 || TREE_CODE (val2) != INTEGER_CST)
1356 t = fold_binary_to_constant (NE_EXPR, boolean_type_node, val1, val2);
1357 if (t && integer_onep (t))
1358 return 2;
1361 return -2;
1365 /* Compare values like compare_values_warnv, but treat comparisons of
1366 nonconstants which rely on undefined overflow as incomparable. */
1368 static int
1369 compare_values (tree val1, tree val2)
1371 bool sop;
1372 int ret;
1374 sop = false;
1375 ret = compare_values_warnv (val1, val2, &sop);
1376 if (sop
1377 && (!is_gimple_min_invariant (val1) || !is_gimple_min_invariant (val2)))
1378 ret = -2;
1379 return ret;
1383 /* Return 1 if VAL is inside value range MIN <= VAL <= MAX,
1384 0 if VAL is not inside [MIN, MAX],
1385 -2 if we cannot tell either way.
1387 Benchmark compile/20001226-1.c compilation time after changing this
1388 function. */
1390 static inline int
1391 value_inside_range (tree val, tree min, tree max)
1393 int cmp1, cmp2;
1395 cmp1 = operand_less_p (val, min);
1396 if (cmp1 == -2)
1397 return -2;
1398 if (cmp1 == 1)
1399 return 0;
1401 cmp2 = operand_less_p (max, val);
1402 if (cmp2 == -2)
1403 return -2;
1405 return !cmp2;
1409 /* Return true if value ranges VR0 and VR1 have a non-empty
1410 intersection.
1412 Benchmark compile/20001226-1.c compilation time after changing this
1413 function.
1416 static inline bool
1417 value_ranges_intersect_p (value_range *vr0, value_range *vr1)
1419 /* The value ranges do not intersect if the maximum of the first range is
1420 less than the minimum of the second range or vice versa.
1421 When those relations are unknown, we can't do any better. */
1422 if (operand_less_p (vr0->max, vr1->min) != 0)
1423 return false;
1424 if (operand_less_p (vr1->max, vr0->min) != 0)
1425 return false;
1426 return true;
1430 /* Return 1 if [MIN, MAX] includes the value zero, 0 if it does not
1431 include the value zero, -2 if we cannot tell. */
1433 static inline int
1434 range_includes_zero_p (tree min, tree max)
1436 tree zero = build_int_cst (TREE_TYPE (min), 0);
1437 return value_inside_range (zero, min, max);
1440 /* Return true if *VR is know to only contain nonnegative values. */
1442 static inline bool
1443 value_range_nonnegative_p (value_range *vr)
1445 /* Testing for VR_ANTI_RANGE is not useful here as any anti-range
1446 which would return a useful value should be encoded as a
1447 VR_RANGE. */
1448 if (vr->type == VR_RANGE)
1450 int result = compare_values (vr->min, integer_zero_node);
1451 return (result == 0 || result == 1);
1454 return false;
1457 /* If *VR has a value rante that is a single constant value return that,
1458 otherwise return NULL_TREE. */
1460 static tree
1461 value_range_constant_singleton (value_range *vr)
1463 if (vr->type == VR_RANGE
1464 && vrp_operand_equal_p (vr->min, vr->max)
1465 && is_gimple_min_invariant (vr->min))
1466 return vr->min;
1468 return NULL_TREE;
1471 /* If OP has a value range with a single constant value return that,
1472 otherwise return NULL_TREE. This returns OP itself if OP is a
1473 constant. */
1475 static tree
1476 op_with_constant_singleton_value_range (tree op)
1478 if (is_gimple_min_invariant (op))
1479 return op;
1481 if (TREE_CODE (op) != SSA_NAME)
1482 return NULL_TREE;
1484 return value_range_constant_singleton (get_value_range (op));
1487 /* Return true if op is in a boolean [0, 1] value-range. */
1489 static bool
1490 op_with_boolean_value_range_p (tree op)
1492 value_range *vr;
1494 if (TYPE_PRECISION (TREE_TYPE (op)) == 1)
1495 return true;
1497 if (integer_zerop (op)
1498 || integer_onep (op))
1499 return true;
1501 if (TREE_CODE (op) != SSA_NAME)
1502 return false;
1504 vr = get_value_range (op);
1505 return (vr->type == VR_RANGE
1506 && integer_zerop (vr->min)
1507 && integer_onep (vr->max));
1510 /* Extract value range information for VAR when (OP COND_CODE LIMIT) is
1511 true and store it in *VR_P. */
1513 static void
1514 extract_range_for_var_from_comparison_expr (tree var, enum tree_code cond_code,
1515 tree op, tree limit,
1516 value_range *vr_p)
1518 tree min, max, type;
1519 value_range *limit_vr;
1520 limit = avoid_overflow_infinity (limit);
1521 type = TREE_TYPE (var);
1522 gcc_assert (limit != var);
1524 /* For pointer arithmetic, we only keep track of pointer equality
1525 and inequality. */
1526 if (POINTER_TYPE_P (type) && cond_code != NE_EXPR && cond_code != EQ_EXPR)
1528 set_value_range_to_varying (vr_p);
1529 return;
1532 /* If LIMIT is another SSA name and LIMIT has a range of its own,
1533 try to use LIMIT's range to avoid creating symbolic ranges
1534 unnecessarily. */
1535 limit_vr = (TREE_CODE (limit) == SSA_NAME) ? get_value_range (limit) : NULL;
1537 /* LIMIT's range is only interesting if it has any useful information. */
1538 if (! limit_vr
1539 || limit_vr->type == VR_UNDEFINED
1540 || limit_vr->type == VR_VARYING
1541 || (symbolic_range_p (limit_vr)
1542 && ! (limit_vr->type == VR_RANGE
1543 && (limit_vr->min == limit_vr->max
1544 || operand_equal_p (limit_vr->min, limit_vr->max, 0)))))
1545 limit_vr = NULL;
1547 /* Initially, the new range has the same set of equivalences of
1548 VAR's range. This will be revised before returning the final
1549 value. Since assertions may be chained via mutually exclusive
1550 predicates, we will need to trim the set of equivalences before
1551 we are done. */
1552 gcc_assert (vr_p->equiv == NULL);
1553 add_equivalence (&vr_p->equiv, var);
1555 /* Extract a new range based on the asserted comparison for VAR and
1556 LIMIT's value range. Notice that if LIMIT has an anti-range, we
1557 will only use it for equality comparisons (EQ_EXPR). For any
1558 other kind of assertion, we cannot derive a range from LIMIT's
1559 anti-range that can be used to describe the new range. For
1560 instance, ASSERT_EXPR <x_2, x_2 <= b_4>. If b_4 is ~[2, 10],
1561 then b_4 takes on the ranges [-INF, 1] and [11, +INF]. There is
1562 no single range for x_2 that could describe LE_EXPR, so we might
1563 as well build the range [b_4, +INF] for it.
1564 One special case we handle is extracting a range from a
1565 range test encoded as (unsigned)var + CST <= limit. */
1566 if (TREE_CODE (op) == NOP_EXPR
1567 || TREE_CODE (op) == PLUS_EXPR)
1569 if (TREE_CODE (op) == PLUS_EXPR)
1571 min = fold_build1 (NEGATE_EXPR, TREE_TYPE (TREE_OPERAND (op, 1)),
1572 TREE_OPERAND (op, 1));
1573 max = int_const_binop (PLUS_EXPR, limit, min);
1574 op = TREE_OPERAND (op, 0);
1576 else
1578 min = build_int_cst (TREE_TYPE (var), 0);
1579 max = limit;
1582 /* Make sure to not set TREE_OVERFLOW on the final type
1583 conversion. We are willingly interpreting large positive
1584 unsigned values as negative signed values here. */
1585 min = force_fit_type (TREE_TYPE (var), wi::to_widest (min), 0, false);
1586 max = force_fit_type (TREE_TYPE (var), wi::to_widest (max), 0, false);
1588 /* We can transform a max, min range to an anti-range or
1589 vice-versa. Use set_and_canonicalize_value_range which does
1590 this for us. */
1591 if (cond_code == LE_EXPR)
1592 set_and_canonicalize_value_range (vr_p, VR_RANGE,
1593 min, max, vr_p->equiv);
1594 else if (cond_code == GT_EXPR)
1595 set_and_canonicalize_value_range (vr_p, VR_ANTI_RANGE,
1596 min, max, vr_p->equiv);
1597 else
1598 gcc_unreachable ();
1600 else if (cond_code == EQ_EXPR)
1602 enum value_range_type range_type;
1604 if (limit_vr)
1606 range_type = limit_vr->type;
1607 min = limit_vr->min;
1608 max = limit_vr->max;
1610 else
1612 range_type = VR_RANGE;
1613 min = limit;
1614 max = limit;
1617 set_value_range (vr_p, range_type, min, max, vr_p->equiv);
1619 /* When asserting the equality VAR == LIMIT and LIMIT is another
1620 SSA name, the new range will also inherit the equivalence set
1621 from LIMIT. */
1622 if (TREE_CODE (limit) == SSA_NAME)
1623 add_equivalence (&vr_p->equiv, limit);
1625 else if (cond_code == NE_EXPR)
1627 /* As described above, when LIMIT's range is an anti-range and
1628 this assertion is an inequality (NE_EXPR), then we cannot
1629 derive anything from the anti-range. For instance, if
1630 LIMIT's range was ~[0, 0], the assertion 'VAR != LIMIT' does
1631 not imply that VAR's range is [0, 0]. So, in the case of
1632 anti-ranges, we just assert the inequality using LIMIT and
1633 not its anti-range.
1635 If LIMIT_VR is a range, we can only use it to build a new
1636 anti-range if LIMIT_VR is a single-valued range. For
1637 instance, if LIMIT_VR is [0, 1], the predicate
1638 VAR != [0, 1] does not mean that VAR's range is ~[0, 1].
1639 Rather, it means that for value 0 VAR should be ~[0, 0]
1640 and for value 1, VAR should be ~[1, 1]. We cannot
1641 represent these ranges.
1643 The only situation in which we can build a valid
1644 anti-range is when LIMIT_VR is a single-valued range
1645 (i.e., LIMIT_VR->MIN == LIMIT_VR->MAX). In that case,
1646 build the anti-range ~[LIMIT_VR->MIN, LIMIT_VR->MAX]. */
1647 if (limit_vr
1648 && limit_vr->type == VR_RANGE
1649 && compare_values (limit_vr->min, limit_vr->max) == 0)
1651 min = limit_vr->min;
1652 max = limit_vr->max;
1654 else
1656 /* In any other case, we cannot use LIMIT's range to build a
1657 valid anti-range. */
1658 min = max = limit;
1661 /* If MIN and MAX cover the whole range for their type, then
1662 just use the original LIMIT. */
1663 if (INTEGRAL_TYPE_P (type)
1664 && vrp_val_is_min (min)
1665 && vrp_val_is_max (max))
1666 min = max = limit;
1668 set_and_canonicalize_value_range (vr_p, VR_ANTI_RANGE,
1669 min, max, vr_p->equiv);
1671 else if (cond_code == LE_EXPR || cond_code == LT_EXPR)
1673 min = TYPE_MIN_VALUE (type);
1675 if (limit_vr == NULL || limit_vr->type == VR_ANTI_RANGE)
1676 max = limit;
1677 else
1679 /* If LIMIT_VR is of the form [N1, N2], we need to build the
1680 range [MIN, N2] for LE_EXPR and [MIN, N2 - 1] for
1681 LT_EXPR. */
1682 max = limit_vr->max;
1685 /* If the maximum value forces us to be out of bounds, simply punt.
1686 It would be pointless to try and do anything more since this
1687 all should be optimized away above us. */
1688 if ((cond_code == LT_EXPR
1689 && compare_values (max, min) == 0)
1690 || is_overflow_infinity (max))
1691 set_value_range_to_varying (vr_p);
1692 else
1694 /* For LT_EXPR, we create the range [MIN, MAX - 1]. */
1695 if (cond_code == LT_EXPR)
1697 if (TYPE_PRECISION (TREE_TYPE (max)) == 1
1698 && !TYPE_UNSIGNED (TREE_TYPE (max)))
1699 max = fold_build2 (PLUS_EXPR, TREE_TYPE (max), max,
1700 build_int_cst (TREE_TYPE (max), -1));
1701 else
1702 max = fold_build2 (MINUS_EXPR, TREE_TYPE (max), max,
1703 build_int_cst (TREE_TYPE (max), 1));
1704 if (EXPR_P (max))
1705 TREE_NO_WARNING (max) = 1;
1708 set_value_range (vr_p, VR_RANGE, min, max, vr_p->equiv);
1711 else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
1713 max = TYPE_MAX_VALUE (type);
1715 if (limit_vr == NULL || limit_vr->type == VR_ANTI_RANGE)
1716 min = limit;
1717 else
1719 /* If LIMIT_VR is of the form [N1, N2], we need to build the
1720 range [N1, MAX] for GE_EXPR and [N1 + 1, MAX] for
1721 GT_EXPR. */
1722 min = limit_vr->min;
1725 /* If the minimum value forces us to be out of bounds, simply punt.
1726 It would be pointless to try and do anything more since this
1727 all should be optimized away above us. */
1728 if ((cond_code == GT_EXPR
1729 && compare_values (min, max) == 0)
1730 || is_overflow_infinity (min))
1731 set_value_range_to_varying (vr_p);
1732 else
1734 /* For GT_EXPR, we create the range [MIN + 1, MAX]. */
1735 if (cond_code == GT_EXPR)
1737 if (TYPE_PRECISION (TREE_TYPE (min)) == 1
1738 && !TYPE_UNSIGNED (TREE_TYPE (min)))
1739 min = fold_build2 (MINUS_EXPR, TREE_TYPE (min), min,
1740 build_int_cst (TREE_TYPE (min), -1));
1741 else
1742 min = fold_build2 (PLUS_EXPR, TREE_TYPE (min), min,
1743 build_int_cst (TREE_TYPE (min), 1));
1744 if (EXPR_P (min))
1745 TREE_NO_WARNING (min) = 1;
1748 set_value_range (vr_p, VR_RANGE, min, max, vr_p->equiv);
1751 else
1752 gcc_unreachable ();
1754 /* Finally intersect the new range with what we already know about var. */
1755 vrp_intersect_ranges (vr_p, get_value_range (var));
1758 /* Extract value range information from an ASSERT_EXPR EXPR and store
1759 it in *VR_P. */
1761 static void
1762 extract_range_from_assert (value_range *vr_p, tree expr)
1764 tree var = ASSERT_EXPR_VAR (expr);
1765 tree cond = ASSERT_EXPR_COND (expr);
1766 tree limit, op;
1767 enum tree_code cond_code;
1768 gcc_assert (COMPARISON_CLASS_P (cond));
1770 /* Find VAR in the ASSERT_EXPR conditional. */
1771 if (var == TREE_OPERAND (cond, 0)
1772 || TREE_CODE (TREE_OPERAND (cond, 0)) == PLUS_EXPR
1773 || TREE_CODE (TREE_OPERAND (cond, 0)) == NOP_EXPR)
1775 /* If the predicate is of the form VAR COMP LIMIT, then we just
1776 take LIMIT from the RHS and use the same comparison code. */
1777 cond_code = TREE_CODE (cond);
1778 limit = TREE_OPERAND (cond, 1);
1779 op = TREE_OPERAND (cond, 0);
1781 else
1783 /* If the predicate is of the form LIMIT COMP VAR, then we need
1784 to flip around the comparison code to create the proper range
1785 for VAR. */
1786 cond_code = swap_tree_comparison (TREE_CODE (cond));
1787 limit = TREE_OPERAND (cond, 0);
1788 op = TREE_OPERAND (cond, 1);
1790 extract_range_for_var_from_comparison_expr (var, cond_code, op,
1791 limit, vr_p);
1794 /* Extract range information from SSA name VAR and store it in VR. If
1795 VAR has an interesting range, use it. Otherwise, create the
1796 range [VAR, VAR] and return it. This is useful in situations where
1797 we may have conditionals testing values of VARYING names. For
1798 instance,
1800 x_3 = y_5;
1801 if (x_3 > y_5)
1804 Even if y_5 is deemed VARYING, we can determine that x_3 > y_5 is
1805 always false. */
1807 static void
1808 extract_range_from_ssa_name (value_range *vr, tree var)
1810 value_range *var_vr = get_value_range (var);
1812 if (var_vr->type != VR_VARYING)
1813 copy_value_range (vr, var_vr);
1814 else
1815 set_value_range (vr, VR_RANGE, var, var, NULL);
1817 add_equivalence (&vr->equiv, var);
1821 /* Wrapper around int_const_binop. If the operation overflows and we
1822 are not using wrapping arithmetic, then adjust the result to be
1823 -INF or +INF depending on CODE, VAL1 and VAL2. This can return
1824 NULL_TREE if we need to use an overflow infinity representation but
1825 the type does not support it. */
1827 static tree
1828 vrp_int_const_binop (enum tree_code code, tree val1, tree val2)
1830 tree res;
1832 res = int_const_binop (code, val1, val2);
1834 /* If we are using unsigned arithmetic, operate symbolically
1835 on -INF and +INF as int_const_binop only handles signed overflow. */
1836 if (TYPE_UNSIGNED (TREE_TYPE (val1)))
1838 int checkz = compare_values (res, val1);
1839 bool overflow = false;
1841 /* Ensure that res = val1 [+*] val2 >= val1
1842 or that res = val1 - val2 <= val1. */
1843 if ((code == PLUS_EXPR
1844 && !(checkz == 1 || checkz == 0))
1845 || (code == MINUS_EXPR
1846 && !(checkz == 0 || checkz == -1)))
1848 overflow = true;
1850 /* Checking for multiplication overflow is done by dividing the
1851 output of the multiplication by the first input of the
1852 multiplication. If the result of that division operation is
1853 not equal to the second input of the multiplication, then the
1854 multiplication overflowed. */
1855 else if (code == MULT_EXPR && !integer_zerop (val1))
1857 tree tmp = int_const_binop (TRUNC_DIV_EXPR,
1858 res,
1859 val1);
1860 int check = compare_values (tmp, val2);
1862 if (check != 0)
1863 overflow = true;
1866 if (overflow)
1868 res = copy_node (res);
1869 TREE_OVERFLOW (res) = 1;
1873 else if (TYPE_OVERFLOW_WRAPS (TREE_TYPE (val1)))
1874 /* If the singed operation wraps then int_const_binop has done
1875 everything we want. */
1877 /* Signed division of -1/0 overflows and by the time it gets here
1878 returns NULL_TREE. */
1879 else if (!res)
1880 return NULL_TREE;
1881 else if ((TREE_OVERFLOW (res)
1882 && !TREE_OVERFLOW (val1)
1883 && !TREE_OVERFLOW (val2))
1884 || is_overflow_infinity (val1)
1885 || is_overflow_infinity (val2))
1887 /* If the operation overflowed but neither VAL1 nor VAL2 are
1888 overflown, return -INF or +INF depending on the operation
1889 and the combination of signs of the operands. */
1890 int sgn1 = tree_int_cst_sgn (val1);
1891 int sgn2 = tree_int_cst_sgn (val2);
1893 if (needs_overflow_infinity (TREE_TYPE (res))
1894 && !supports_overflow_infinity (TREE_TYPE (res)))
1895 return NULL_TREE;
1897 /* We have to punt on adding infinities of different signs,
1898 since we can't tell what the sign of the result should be.
1899 Likewise for subtracting infinities of the same sign. */
1900 if (((code == PLUS_EXPR && sgn1 != sgn2)
1901 || (code == MINUS_EXPR && sgn1 == sgn2))
1902 && is_overflow_infinity (val1)
1903 && is_overflow_infinity (val2))
1904 return NULL_TREE;
1906 /* Don't try to handle division or shifting of infinities. */
1907 if ((code == TRUNC_DIV_EXPR
1908 || code == FLOOR_DIV_EXPR
1909 || code == CEIL_DIV_EXPR
1910 || code == EXACT_DIV_EXPR
1911 || code == ROUND_DIV_EXPR
1912 || code == RSHIFT_EXPR)
1913 && (is_overflow_infinity (val1)
1914 || is_overflow_infinity (val2)))
1915 return NULL_TREE;
1917 /* Notice that we only need to handle the restricted set of
1918 operations handled by extract_range_from_binary_expr.
1919 Among them, only multiplication, addition and subtraction
1920 can yield overflow without overflown operands because we
1921 are working with integral types only... except in the
1922 case VAL1 = -INF and VAL2 = -1 which overflows to +INF
1923 for division too. */
1925 /* For multiplication, the sign of the overflow is given
1926 by the comparison of the signs of the operands. */
1927 if ((code == MULT_EXPR && sgn1 == sgn2)
1928 /* For addition, the operands must be of the same sign
1929 to yield an overflow. Its sign is therefore that
1930 of one of the operands, for example the first. For
1931 infinite operands X + -INF is negative, not positive. */
1932 || (code == PLUS_EXPR
1933 && (sgn1 >= 0
1934 ? !is_negative_overflow_infinity (val2)
1935 : is_positive_overflow_infinity (val2)))
1936 /* For subtraction, non-infinite operands must be of
1937 different signs to yield an overflow. Its sign is
1938 therefore that of the first operand or the opposite of
1939 that of the second operand. A first operand of 0 counts
1940 as positive here, for the corner case 0 - (-INF), which
1941 overflows, but must yield +INF. For infinite operands 0
1942 - INF is negative, not positive. */
1943 || (code == MINUS_EXPR
1944 && (sgn1 >= 0
1945 ? !is_positive_overflow_infinity (val2)
1946 : is_negative_overflow_infinity (val2)))
1947 /* We only get in here with positive shift count, so the
1948 overflow direction is the same as the sign of val1.
1949 Actually rshift does not overflow at all, but we only
1950 handle the case of shifting overflowed -INF and +INF. */
1951 || (code == RSHIFT_EXPR
1952 && sgn1 >= 0)
1953 /* For division, the only case is -INF / -1 = +INF. */
1954 || code == TRUNC_DIV_EXPR
1955 || code == FLOOR_DIV_EXPR
1956 || code == CEIL_DIV_EXPR
1957 || code == EXACT_DIV_EXPR
1958 || code == ROUND_DIV_EXPR)
1959 return (needs_overflow_infinity (TREE_TYPE (res))
1960 ? positive_overflow_infinity (TREE_TYPE (res))
1961 : TYPE_MAX_VALUE (TREE_TYPE (res)));
1962 else
1963 return (needs_overflow_infinity (TREE_TYPE (res))
1964 ? negative_overflow_infinity (TREE_TYPE (res))
1965 : TYPE_MIN_VALUE (TREE_TYPE (res)));
1968 return res;
1972 /* For range VR compute two wide_int bitmasks. In *MAY_BE_NONZERO
1973 bitmask if some bit is unset, it means for all numbers in the range
1974 the bit is 0, otherwise it might be 0 or 1. In *MUST_BE_NONZERO
1975 bitmask if some bit is set, it means for all numbers in the range
1976 the bit is 1, otherwise it might be 0 or 1. */
1978 static bool
1979 zero_nonzero_bits_from_vr (const tree expr_type,
1980 value_range *vr,
1981 wide_int *may_be_nonzero,
1982 wide_int *must_be_nonzero)
1984 *may_be_nonzero = wi::minus_one (TYPE_PRECISION (expr_type));
1985 *must_be_nonzero = wi::zero (TYPE_PRECISION (expr_type));
1986 if (!range_int_cst_p (vr)
1987 || is_overflow_infinity (vr->min)
1988 || is_overflow_infinity (vr->max))
1989 return false;
1991 if (range_int_cst_singleton_p (vr))
1993 *may_be_nonzero = vr->min;
1994 *must_be_nonzero = *may_be_nonzero;
1996 else if (tree_int_cst_sgn (vr->min) >= 0
1997 || tree_int_cst_sgn (vr->max) < 0)
1999 wide_int xor_mask = wi::bit_xor (vr->min, vr->max);
2000 *may_be_nonzero = wi::bit_or (vr->min, vr->max);
2001 *must_be_nonzero = wi::bit_and (vr->min, vr->max);
2002 if (xor_mask != 0)
2004 wide_int mask = wi::mask (wi::floor_log2 (xor_mask), false,
2005 may_be_nonzero->get_precision ());
2006 *may_be_nonzero = *may_be_nonzero | mask;
2007 *must_be_nonzero = must_be_nonzero->and_not (mask);
2011 return true;
2014 /* Create two value-ranges in *VR0 and *VR1 from the anti-range *AR
2015 so that *VR0 U *VR1 == *AR. Returns true if that is possible,
2016 false otherwise. If *AR can be represented with a single range
2017 *VR1 will be VR_UNDEFINED. */
2019 static bool
2020 ranges_from_anti_range (value_range *ar,
2021 value_range *vr0, value_range *vr1)
2023 tree type = TREE_TYPE (ar->min);
2025 vr0->type = VR_UNDEFINED;
2026 vr1->type = VR_UNDEFINED;
2028 if (ar->type != VR_ANTI_RANGE
2029 || TREE_CODE (ar->min) != INTEGER_CST
2030 || TREE_CODE (ar->max) != INTEGER_CST
2031 || !vrp_val_min (type)
2032 || !vrp_val_max (type))
2033 return false;
2035 if (!vrp_val_is_min (ar->min))
2037 vr0->type = VR_RANGE;
2038 vr0->min = vrp_val_min (type);
2039 vr0->max = wide_int_to_tree (type, wi::sub (ar->min, 1));
2041 if (!vrp_val_is_max (ar->max))
2043 vr1->type = VR_RANGE;
2044 vr1->min = wide_int_to_tree (type, wi::add (ar->max, 1));
2045 vr1->max = vrp_val_max (type);
2047 if (vr0->type == VR_UNDEFINED)
2049 *vr0 = *vr1;
2050 vr1->type = VR_UNDEFINED;
2053 return vr0->type != VR_UNDEFINED;
2056 /* Helper to extract a value-range *VR for a multiplicative operation
2057 *VR0 CODE *VR1. */
2059 static void
2060 extract_range_from_multiplicative_op_1 (value_range *vr,
2061 enum tree_code code,
2062 value_range *vr0, value_range *vr1)
2064 enum value_range_type type;
2065 tree val[4];
2066 size_t i;
2067 tree min, max;
2068 bool sop;
2069 int cmp;
2071 /* Multiplications, divisions and shifts are a bit tricky to handle,
2072 depending on the mix of signs we have in the two ranges, we
2073 need to operate on different values to get the minimum and
2074 maximum values for the new range. One approach is to figure
2075 out all the variations of range combinations and do the
2076 operations.
2078 However, this involves several calls to compare_values and it
2079 is pretty convoluted. It's simpler to do the 4 operations
2080 (MIN0 OP MIN1, MIN0 OP MAX1, MAX0 OP MIN1 and MAX0 OP MAX0 OP
2081 MAX1) and then figure the smallest and largest values to form
2082 the new range. */
2083 gcc_assert (code == MULT_EXPR
2084 || code == TRUNC_DIV_EXPR
2085 || code == FLOOR_DIV_EXPR
2086 || code == CEIL_DIV_EXPR
2087 || code == EXACT_DIV_EXPR
2088 || code == ROUND_DIV_EXPR
2089 || code == RSHIFT_EXPR
2090 || code == LSHIFT_EXPR);
2091 gcc_assert ((vr0->type == VR_RANGE
2092 || (code == MULT_EXPR && vr0->type == VR_ANTI_RANGE))
2093 && vr0->type == vr1->type);
2095 type = vr0->type;
2097 /* Compute the 4 cross operations. */
2098 sop = false;
2099 val[0] = vrp_int_const_binop (code, vr0->min, vr1->min);
2100 if (val[0] == NULL_TREE)
2101 sop = true;
2103 if (vr1->max == vr1->min)
2104 val[1] = NULL_TREE;
2105 else
2107 val[1] = vrp_int_const_binop (code, vr0->min, vr1->max);
2108 if (val[1] == NULL_TREE)
2109 sop = true;
2112 if (vr0->max == vr0->min)
2113 val[2] = NULL_TREE;
2114 else
2116 val[2] = vrp_int_const_binop (code, vr0->max, vr1->min);
2117 if (val[2] == NULL_TREE)
2118 sop = true;
2121 if (vr0->min == vr0->max || vr1->min == vr1->max)
2122 val[3] = NULL_TREE;
2123 else
2125 val[3] = vrp_int_const_binop (code, vr0->max, vr1->max);
2126 if (val[3] == NULL_TREE)
2127 sop = true;
2130 if (sop)
2132 set_value_range_to_varying (vr);
2133 return;
2136 /* Set MIN to the minimum of VAL[i] and MAX to the maximum
2137 of VAL[i]. */
2138 min = val[0];
2139 max = val[0];
2140 for (i = 1; i < 4; i++)
2142 if (!is_gimple_min_invariant (min)
2143 || (TREE_OVERFLOW (min) && !is_overflow_infinity (min))
2144 || !is_gimple_min_invariant (max)
2145 || (TREE_OVERFLOW (max) && !is_overflow_infinity (max)))
2146 break;
2148 if (val[i])
2150 if (!is_gimple_min_invariant (val[i])
2151 || (TREE_OVERFLOW (val[i])
2152 && !is_overflow_infinity (val[i])))
2154 /* If we found an overflowed value, set MIN and MAX
2155 to it so that we set the resulting range to
2156 VARYING. */
2157 min = max = val[i];
2158 break;
2161 if (compare_values (val[i], min) == -1)
2162 min = val[i];
2164 if (compare_values (val[i], max) == 1)
2165 max = val[i];
2169 /* If either MIN or MAX overflowed, then set the resulting range to
2170 VARYING. But we do accept an overflow infinity
2171 representation. */
2172 if (min == NULL_TREE
2173 || !is_gimple_min_invariant (min)
2174 || (TREE_OVERFLOW (min) && !is_overflow_infinity (min))
2175 || max == NULL_TREE
2176 || !is_gimple_min_invariant (max)
2177 || (TREE_OVERFLOW (max) && !is_overflow_infinity (max)))
2179 set_value_range_to_varying (vr);
2180 return;
2183 /* We punt if:
2184 1) [-INF, +INF]
2185 2) [-INF, +-INF(OVF)]
2186 3) [+-INF(OVF), +INF]
2187 4) [+-INF(OVF), +-INF(OVF)]
2188 We learn nothing when we have INF and INF(OVF) on both sides.
2189 Note that we do accept [-INF, -INF] and [+INF, +INF] without
2190 overflow. */
2191 if ((vrp_val_is_min (min) || is_overflow_infinity (min))
2192 && (vrp_val_is_max (max) || is_overflow_infinity (max)))
2194 set_value_range_to_varying (vr);
2195 return;
2198 cmp = compare_values (min, max);
2199 if (cmp == -2 || cmp == 1)
2201 /* If the new range has its limits swapped around (MIN > MAX),
2202 then the operation caused one of them to wrap around, mark
2203 the new range VARYING. */
2204 set_value_range_to_varying (vr);
2206 else
2207 set_value_range (vr, type, min, max, NULL);
2210 /* Extract range information from a binary operation CODE based on
2211 the ranges of each of its operands *VR0 and *VR1 with resulting
2212 type EXPR_TYPE. The resulting range is stored in *VR. */
2214 static void
2215 extract_range_from_binary_expr_1 (value_range *vr,
2216 enum tree_code code, tree expr_type,
2217 value_range *vr0_, value_range *vr1_)
2219 value_range vr0 = *vr0_, vr1 = *vr1_;
2220 value_range vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
2221 enum value_range_type type;
2222 tree min = NULL_TREE, max = NULL_TREE;
2223 int cmp;
2225 if (!INTEGRAL_TYPE_P (expr_type)
2226 && !POINTER_TYPE_P (expr_type))
2228 set_value_range_to_varying (vr);
2229 return;
2232 /* Not all binary expressions can be applied to ranges in a
2233 meaningful way. Handle only arithmetic operations. */
2234 if (code != PLUS_EXPR
2235 && code != MINUS_EXPR
2236 && code != POINTER_PLUS_EXPR
2237 && code != MULT_EXPR
2238 && code != TRUNC_DIV_EXPR
2239 && code != FLOOR_DIV_EXPR
2240 && code != CEIL_DIV_EXPR
2241 && code != EXACT_DIV_EXPR
2242 && code != ROUND_DIV_EXPR
2243 && code != TRUNC_MOD_EXPR
2244 && code != RSHIFT_EXPR
2245 && code != LSHIFT_EXPR
2246 && code != MIN_EXPR
2247 && code != MAX_EXPR
2248 && code != BIT_AND_EXPR
2249 && code != BIT_IOR_EXPR
2250 && code != BIT_XOR_EXPR)
2252 set_value_range_to_varying (vr);
2253 return;
2256 /* If both ranges are UNDEFINED, so is the result. */
2257 if (vr0.type == VR_UNDEFINED && vr1.type == VR_UNDEFINED)
2259 set_value_range_to_undefined (vr);
2260 return;
2262 /* If one of the ranges is UNDEFINED drop it to VARYING for the following
2263 code. At some point we may want to special-case operations that
2264 have UNDEFINED result for all or some value-ranges of the not UNDEFINED
2265 operand. */
2266 else if (vr0.type == VR_UNDEFINED)
2267 set_value_range_to_varying (&vr0);
2268 else if (vr1.type == VR_UNDEFINED)
2269 set_value_range_to_varying (&vr1);
2271 /* Now canonicalize anti-ranges to ranges when they are not symbolic
2272 and express ~[] op X as ([]' op X) U ([]'' op X). */
2273 if (vr0.type == VR_ANTI_RANGE
2274 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
2276 extract_range_from_binary_expr_1 (vr, code, expr_type, &vrtem0, vr1_);
2277 if (vrtem1.type != VR_UNDEFINED)
2279 value_range vrres = VR_INITIALIZER;
2280 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
2281 &vrtem1, vr1_);
2282 vrp_meet (vr, &vrres);
2284 return;
2286 /* Likewise for X op ~[]. */
2287 if (vr1.type == VR_ANTI_RANGE
2288 && ranges_from_anti_range (&vr1, &vrtem0, &vrtem1))
2290 extract_range_from_binary_expr_1 (vr, code, expr_type, vr0_, &vrtem0);
2291 if (vrtem1.type != VR_UNDEFINED)
2293 value_range vrres = VR_INITIALIZER;
2294 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
2295 vr0_, &vrtem1);
2296 vrp_meet (vr, &vrres);
2298 return;
2301 /* The type of the resulting value range defaults to VR0.TYPE. */
2302 type = vr0.type;
2304 /* Refuse to operate on VARYING ranges, ranges of different kinds
2305 and symbolic ranges. As an exception, we allow BIT_{AND,IOR}
2306 because we may be able to derive a useful range even if one of
2307 the operands is VR_VARYING or symbolic range. Similarly for
2308 divisions, MIN/MAX and PLUS/MINUS.
2310 TODO, we may be able to derive anti-ranges in some cases. */
2311 if (code != BIT_AND_EXPR
2312 && code != BIT_IOR_EXPR
2313 && code != TRUNC_DIV_EXPR
2314 && code != FLOOR_DIV_EXPR
2315 && code != CEIL_DIV_EXPR
2316 && code != EXACT_DIV_EXPR
2317 && code != ROUND_DIV_EXPR
2318 && code != TRUNC_MOD_EXPR
2319 && code != MIN_EXPR
2320 && code != MAX_EXPR
2321 && code != PLUS_EXPR
2322 && code != MINUS_EXPR
2323 && code != RSHIFT_EXPR
2324 && (vr0.type == VR_VARYING
2325 || vr1.type == VR_VARYING
2326 || vr0.type != vr1.type
2327 || symbolic_range_p (&vr0)
2328 || symbolic_range_p (&vr1)))
2330 set_value_range_to_varying (vr);
2331 return;
2334 /* Now evaluate the expression to determine the new range. */
2335 if (POINTER_TYPE_P (expr_type))
2337 if (code == MIN_EXPR || code == MAX_EXPR)
2339 /* For MIN/MAX expressions with pointers, we only care about
2340 nullness, if both are non null, then the result is nonnull.
2341 If both are null, then the result is null. Otherwise they
2342 are varying. */
2343 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
2344 set_value_range_to_nonnull (vr, expr_type);
2345 else if (range_is_null (&vr0) && range_is_null (&vr1))
2346 set_value_range_to_null (vr, expr_type);
2347 else
2348 set_value_range_to_varying (vr);
2350 else if (code == POINTER_PLUS_EXPR)
2352 /* For pointer types, we are really only interested in asserting
2353 whether the expression evaluates to non-NULL. */
2354 if (range_is_nonnull (&vr0) || range_is_nonnull (&vr1))
2355 set_value_range_to_nonnull (vr, expr_type);
2356 else if (range_is_null (&vr0) && range_is_null (&vr1))
2357 set_value_range_to_null (vr, expr_type);
2358 else
2359 set_value_range_to_varying (vr);
2361 else if (code == BIT_AND_EXPR)
2363 /* For pointer types, we are really only interested in asserting
2364 whether the expression evaluates to non-NULL. */
2365 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
2366 set_value_range_to_nonnull (vr, expr_type);
2367 else if (range_is_null (&vr0) || range_is_null (&vr1))
2368 set_value_range_to_null (vr, expr_type);
2369 else
2370 set_value_range_to_varying (vr);
2372 else
2373 set_value_range_to_varying (vr);
2375 return;
2378 /* For integer ranges, apply the operation to each end of the
2379 range and see what we end up with. */
2380 if (code == PLUS_EXPR || code == MINUS_EXPR)
2382 const bool minus_p = (code == MINUS_EXPR);
2383 tree min_op0 = vr0.min;
2384 tree min_op1 = minus_p ? vr1.max : vr1.min;
2385 tree max_op0 = vr0.max;
2386 tree max_op1 = minus_p ? vr1.min : vr1.max;
2387 tree sym_min_op0 = NULL_TREE;
2388 tree sym_min_op1 = NULL_TREE;
2389 tree sym_max_op0 = NULL_TREE;
2390 tree sym_max_op1 = NULL_TREE;
2391 bool neg_min_op0, neg_min_op1, neg_max_op0, neg_max_op1;
2393 /* If we have a PLUS or MINUS with two VR_RANGEs, either constant or
2394 single-symbolic ranges, try to compute the precise resulting range,
2395 but only if we know that this resulting range will also be constant
2396 or single-symbolic. */
2397 if (vr0.type == VR_RANGE && vr1.type == VR_RANGE
2398 && (TREE_CODE (min_op0) == INTEGER_CST
2399 || (sym_min_op0
2400 = get_single_symbol (min_op0, &neg_min_op0, &min_op0)))
2401 && (TREE_CODE (min_op1) == INTEGER_CST
2402 || (sym_min_op1
2403 = get_single_symbol (min_op1, &neg_min_op1, &min_op1)))
2404 && (!(sym_min_op0 && sym_min_op1)
2405 || (sym_min_op0 == sym_min_op1
2406 && neg_min_op0 == (minus_p ? neg_min_op1 : !neg_min_op1)))
2407 && (TREE_CODE (max_op0) == INTEGER_CST
2408 || (sym_max_op0
2409 = get_single_symbol (max_op0, &neg_max_op0, &max_op0)))
2410 && (TREE_CODE (max_op1) == INTEGER_CST
2411 || (sym_max_op1
2412 = get_single_symbol (max_op1, &neg_max_op1, &max_op1)))
2413 && (!(sym_max_op0 && sym_max_op1)
2414 || (sym_max_op0 == sym_max_op1
2415 && neg_max_op0 == (minus_p ? neg_max_op1 : !neg_max_op1))))
2417 const signop sgn = TYPE_SIGN (expr_type);
2418 const unsigned int prec = TYPE_PRECISION (expr_type);
2419 wide_int type_min, type_max, wmin, wmax;
2420 int min_ovf = 0;
2421 int max_ovf = 0;
2423 /* Get the lower and upper bounds of the type. */
2424 if (TYPE_OVERFLOW_WRAPS (expr_type))
2426 type_min = wi::min_value (prec, sgn);
2427 type_max = wi::max_value (prec, sgn);
2429 else
2431 type_min = vrp_val_min (expr_type);
2432 type_max = vrp_val_max (expr_type);
2435 /* Combine the lower bounds, if any. */
2436 if (min_op0 && min_op1)
2438 if (minus_p)
2440 wmin = wi::sub (min_op0, min_op1);
2442 /* Check for overflow. */
2443 if (wi::cmp (0, min_op1, sgn)
2444 != wi::cmp (wmin, min_op0, sgn))
2445 min_ovf = wi::cmp (min_op0, min_op1, sgn);
2447 else
2449 wmin = wi::add (min_op0, min_op1);
2451 /* Check for overflow. */
2452 if (wi::cmp (min_op1, 0, sgn)
2453 != wi::cmp (wmin, min_op0, sgn))
2454 min_ovf = wi::cmp (min_op0, wmin, sgn);
2457 else if (min_op0)
2458 wmin = min_op0;
2459 else if (min_op1)
2460 wmin = minus_p ? wi::neg (min_op1) : min_op1;
2461 else
2462 wmin = wi::shwi (0, prec);
2464 /* Combine the upper bounds, if any. */
2465 if (max_op0 && max_op1)
2467 if (minus_p)
2469 wmax = wi::sub (max_op0, max_op1);
2471 /* Check for overflow. */
2472 if (wi::cmp (0, max_op1, sgn)
2473 != wi::cmp (wmax, max_op0, sgn))
2474 max_ovf = wi::cmp (max_op0, max_op1, sgn);
2476 else
2478 wmax = wi::add (max_op0, max_op1);
2480 if (wi::cmp (max_op1, 0, sgn)
2481 != wi::cmp (wmax, max_op0, sgn))
2482 max_ovf = wi::cmp (max_op0, wmax, sgn);
2485 else if (max_op0)
2486 wmax = max_op0;
2487 else if (max_op1)
2488 wmax = minus_p ? wi::neg (max_op1) : max_op1;
2489 else
2490 wmax = wi::shwi (0, prec);
2492 /* Check for type overflow. */
2493 if (min_ovf == 0)
2495 if (wi::cmp (wmin, type_min, sgn) == -1)
2496 min_ovf = -1;
2497 else if (wi::cmp (wmin, type_max, sgn) == 1)
2498 min_ovf = 1;
2500 if (max_ovf == 0)
2502 if (wi::cmp (wmax, type_min, sgn) == -1)
2503 max_ovf = -1;
2504 else if (wi::cmp (wmax, type_max, sgn) == 1)
2505 max_ovf = 1;
2508 /* If we have overflow for the constant part and the resulting
2509 range will be symbolic, drop to VR_VARYING. */
2510 if ((min_ovf && sym_min_op0 != sym_min_op1)
2511 || (max_ovf && sym_max_op0 != sym_max_op1))
2513 set_value_range_to_varying (vr);
2514 return;
2517 if (TYPE_OVERFLOW_WRAPS (expr_type))
2519 /* If overflow wraps, truncate the values and adjust the
2520 range kind and bounds appropriately. */
2521 wide_int tmin = wide_int::from (wmin, prec, sgn);
2522 wide_int tmax = wide_int::from (wmax, prec, sgn);
2523 if (min_ovf == max_ovf)
2525 /* No overflow or both overflow or underflow. The
2526 range kind stays VR_RANGE. */
2527 min = wide_int_to_tree (expr_type, tmin);
2528 max = wide_int_to_tree (expr_type, tmax);
2530 else if ((min_ovf == -1 && max_ovf == 0)
2531 || (max_ovf == 1 && min_ovf == 0))
2533 /* Min underflow or max overflow. The range kind
2534 changes to VR_ANTI_RANGE. */
2535 bool covers = false;
2536 wide_int tem = tmin;
2537 type = VR_ANTI_RANGE;
2538 tmin = tmax + 1;
2539 if (wi::cmp (tmin, tmax, sgn) < 0)
2540 covers = true;
2541 tmax = tem - 1;
2542 if (wi::cmp (tmax, tem, sgn) > 0)
2543 covers = true;
2544 /* If the anti-range would cover nothing, drop to varying.
2545 Likewise if the anti-range bounds are outside of the
2546 types values. */
2547 if (covers || wi::cmp (tmin, tmax, sgn) > 0)
2549 set_value_range_to_varying (vr);
2550 return;
2552 min = wide_int_to_tree (expr_type, tmin);
2553 max = wide_int_to_tree (expr_type, tmax);
2555 else
2557 /* Other underflow and/or overflow, drop to VR_VARYING. */
2558 set_value_range_to_varying (vr);
2559 return;
2562 else
2564 /* If overflow does not wrap, saturate to the types min/max
2565 value. */
2566 if (min_ovf == -1)
2568 if (needs_overflow_infinity (expr_type)
2569 && supports_overflow_infinity (expr_type))
2570 min = negative_overflow_infinity (expr_type);
2571 else
2572 min = wide_int_to_tree (expr_type, type_min);
2574 else if (min_ovf == 1)
2576 if (needs_overflow_infinity (expr_type)
2577 && supports_overflow_infinity (expr_type))
2578 min = positive_overflow_infinity (expr_type);
2579 else
2580 min = wide_int_to_tree (expr_type, type_max);
2582 else
2583 min = wide_int_to_tree (expr_type, wmin);
2585 if (max_ovf == -1)
2587 if (needs_overflow_infinity (expr_type)
2588 && supports_overflow_infinity (expr_type))
2589 max = negative_overflow_infinity (expr_type);
2590 else
2591 max = wide_int_to_tree (expr_type, type_min);
2593 else if (max_ovf == 1)
2595 if (needs_overflow_infinity (expr_type)
2596 && supports_overflow_infinity (expr_type))
2597 max = positive_overflow_infinity (expr_type);
2598 else
2599 max = wide_int_to_tree (expr_type, type_max);
2601 else
2602 max = wide_int_to_tree (expr_type, wmax);
2605 if (needs_overflow_infinity (expr_type)
2606 && supports_overflow_infinity (expr_type))
2608 if ((min_op0 && is_negative_overflow_infinity (min_op0))
2609 || (min_op1
2610 && (minus_p
2611 ? is_positive_overflow_infinity (min_op1)
2612 : is_negative_overflow_infinity (min_op1))))
2613 min = negative_overflow_infinity (expr_type);
2614 if ((max_op0 && is_positive_overflow_infinity (max_op0))
2615 || (max_op1
2616 && (minus_p
2617 ? is_negative_overflow_infinity (max_op1)
2618 : is_positive_overflow_infinity (max_op1))))
2619 max = positive_overflow_infinity (expr_type);
2622 /* If the result lower bound is constant, we're done;
2623 otherwise, build the symbolic lower bound. */
2624 if (sym_min_op0 == sym_min_op1)
2626 else if (sym_min_op0)
2627 min = build_symbolic_expr (expr_type, sym_min_op0,
2628 neg_min_op0, min);
2629 else if (sym_min_op1)
2630 min = build_symbolic_expr (expr_type, sym_min_op1,
2631 neg_min_op1 ^ minus_p, min);
2633 /* Likewise for the upper bound. */
2634 if (sym_max_op0 == sym_max_op1)
2636 else if (sym_max_op0)
2637 max = build_symbolic_expr (expr_type, sym_max_op0,
2638 neg_max_op0, max);
2639 else if (sym_max_op1)
2640 max = build_symbolic_expr (expr_type, sym_max_op1,
2641 neg_max_op1 ^ minus_p, max);
2643 else
2645 /* For other cases, for example if we have a PLUS_EXPR with two
2646 VR_ANTI_RANGEs, drop to VR_VARYING. It would take more effort
2647 to compute a precise range for such a case.
2648 ??? General even mixed range kind operations can be expressed
2649 by for example transforming ~[3, 5] + [1, 2] to range-only
2650 operations and a union primitive:
2651 [-INF, 2] + [1, 2] U [5, +INF] + [1, 2]
2652 [-INF+1, 4] U [6, +INF(OVF)]
2653 though usually the union is not exactly representable with
2654 a single range or anti-range as the above is
2655 [-INF+1, +INF(OVF)] intersected with ~[5, 5]
2656 but one could use a scheme similar to equivalences for this. */
2657 set_value_range_to_varying (vr);
2658 return;
2661 else if (code == MIN_EXPR
2662 || code == MAX_EXPR)
2664 if (vr0.type == VR_RANGE
2665 && !symbolic_range_p (&vr0))
2667 type = VR_RANGE;
2668 if (vr1.type == VR_RANGE
2669 && !symbolic_range_p (&vr1))
2671 /* For operations that make the resulting range directly
2672 proportional to the original ranges, apply the operation to
2673 the same end of each range. */
2674 min = vrp_int_const_binop (code, vr0.min, vr1.min);
2675 max = vrp_int_const_binop (code, vr0.max, vr1.max);
2677 else if (code == MIN_EXPR)
2679 min = vrp_val_min (expr_type);
2680 max = vr0.max;
2682 else if (code == MAX_EXPR)
2684 min = vr0.min;
2685 max = vrp_val_max (expr_type);
2688 else if (vr1.type == VR_RANGE
2689 && !symbolic_range_p (&vr1))
2691 type = VR_RANGE;
2692 if (code == MIN_EXPR)
2694 min = vrp_val_min (expr_type);
2695 max = vr1.max;
2697 else if (code == MAX_EXPR)
2699 min = vr1.min;
2700 max = vrp_val_max (expr_type);
2703 else
2705 set_value_range_to_varying (vr);
2706 return;
2709 else if (code == MULT_EXPR)
2711 /* Fancy code so that with unsigned, [-3,-1]*[-3,-1] does not
2712 drop to varying. This test requires 2*prec bits if both
2713 operands are signed and 2*prec + 2 bits if either is not. */
2715 signop sign = TYPE_SIGN (expr_type);
2716 unsigned int prec = TYPE_PRECISION (expr_type);
2718 if (range_int_cst_p (&vr0)
2719 && range_int_cst_p (&vr1)
2720 && TYPE_OVERFLOW_WRAPS (expr_type))
2722 typedef FIXED_WIDE_INT (WIDE_INT_MAX_PRECISION * 2) vrp_int;
2723 typedef generic_wide_int
2724 <wi::extended_tree <WIDE_INT_MAX_PRECISION * 2> > vrp_int_cst;
2725 vrp_int sizem1 = wi::mask <vrp_int> (prec, false);
2726 vrp_int size = sizem1 + 1;
2728 /* Extend the values using the sign of the result to PREC2.
2729 From here on out, everthing is just signed math no matter
2730 what the input types were. */
2731 vrp_int min0 = vrp_int_cst (vr0.min);
2732 vrp_int max0 = vrp_int_cst (vr0.max);
2733 vrp_int min1 = vrp_int_cst (vr1.min);
2734 vrp_int max1 = vrp_int_cst (vr1.max);
2735 /* Canonicalize the intervals. */
2736 if (sign == UNSIGNED)
2738 if (wi::ltu_p (size, min0 + max0))
2740 min0 -= size;
2741 max0 -= size;
2744 if (wi::ltu_p (size, min1 + max1))
2746 min1 -= size;
2747 max1 -= size;
2751 vrp_int prod0 = min0 * min1;
2752 vrp_int prod1 = min0 * max1;
2753 vrp_int prod2 = max0 * min1;
2754 vrp_int prod3 = max0 * max1;
2756 /* Sort the 4 products so that min is in prod0 and max is in
2757 prod3. */
2758 /* min0min1 > max0max1 */
2759 if (prod0 > prod3)
2760 std::swap (prod0, prod3);
2762 /* min0max1 > max0min1 */
2763 if (prod1 > prod2)
2764 std::swap (prod1, prod2);
2766 if (prod0 > prod1)
2767 std::swap (prod0, prod1);
2769 if (prod2 > prod3)
2770 std::swap (prod2, prod3);
2772 /* diff = max - min. */
2773 prod2 = prod3 - prod0;
2774 if (wi::geu_p (prod2, sizem1))
2776 /* the range covers all values. */
2777 set_value_range_to_varying (vr);
2778 return;
2781 /* The following should handle the wrapping and selecting
2782 VR_ANTI_RANGE for us. */
2783 min = wide_int_to_tree (expr_type, prod0);
2784 max = wide_int_to_tree (expr_type, prod3);
2785 set_and_canonicalize_value_range (vr, VR_RANGE, min, max, NULL);
2786 return;
2789 /* If we have an unsigned MULT_EXPR with two VR_ANTI_RANGEs,
2790 drop to VR_VARYING. It would take more effort to compute a
2791 precise range for such a case. For example, if we have
2792 op0 == 65536 and op1 == 65536 with their ranges both being
2793 ~[0,0] on a 32-bit machine, we would have op0 * op1 == 0, so
2794 we cannot claim that the product is in ~[0,0]. Note that we
2795 are guaranteed to have vr0.type == vr1.type at this
2796 point. */
2797 if (vr0.type == VR_ANTI_RANGE
2798 && !TYPE_OVERFLOW_UNDEFINED (expr_type))
2800 set_value_range_to_varying (vr);
2801 return;
2804 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2805 return;
2807 else if (code == RSHIFT_EXPR
2808 || code == LSHIFT_EXPR)
2810 /* If we have a RSHIFT_EXPR with any shift values outside [0..prec-1],
2811 then drop to VR_VARYING. Outside of this range we get undefined
2812 behavior from the shift operation. We cannot even trust
2813 SHIFT_COUNT_TRUNCATED at this stage, because that applies to rtl
2814 shifts, and the operation at the tree level may be widened. */
2815 if (range_int_cst_p (&vr1)
2816 && compare_tree_int (vr1.min, 0) >= 0
2817 && compare_tree_int (vr1.max, TYPE_PRECISION (expr_type)) == -1)
2819 if (code == RSHIFT_EXPR)
2821 /* Even if vr0 is VARYING or otherwise not usable, we can derive
2822 useful ranges just from the shift count. E.g.
2823 x >> 63 for signed 64-bit x is always [-1, 0]. */
2824 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
2826 vr0.type = type = VR_RANGE;
2827 vr0.min = vrp_val_min (expr_type);
2828 vr0.max = vrp_val_max (expr_type);
2830 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2831 return;
2833 /* We can map lshifts by constants to MULT_EXPR handling. */
2834 else if (code == LSHIFT_EXPR
2835 && range_int_cst_singleton_p (&vr1))
2837 bool saved_flag_wrapv;
2838 value_range vr1p = VR_INITIALIZER;
2839 vr1p.type = VR_RANGE;
2840 vr1p.min = (wide_int_to_tree
2841 (expr_type,
2842 wi::set_bit_in_zero (tree_to_shwi (vr1.min),
2843 TYPE_PRECISION (expr_type))));
2844 vr1p.max = vr1p.min;
2845 /* We have to use a wrapping multiply though as signed overflow
2846 on lshifts is implementation defined in C89. */
2847 saved_flag_wrapv = flag_wrapv;
2848 flag_wrapv = 1;
2849 extract_range_from_binary_expr_1 (vr, MULT_EXPR, expr_type,
2850 &vr0, &vr1p);
2851 flag_wrapv = saved_flag_wrapv;
2852 return;
2854 else if (code == LSHIFT_EXPR
2855 && range_int_cst_p (&vr0))
2857 int prec = TYPE_PRECISION (expr_type);
2858 int overflow_pos = prec;
2859 int bound_shift;
2860 wide_int low_bound, high_bound;
2861 bool uns = TYPE_UNSIGNED (expr_type);
2862 bool in_bounds = false;
2864 if (!uns)
2865 overflow_pos -= 1;
2867 bound_shift = overflow_pos - tree_to_shwi (vr1.max);
2868 /* If bound_shift == HOST_BITS_PER_WIDE_INT, the llshift can
2869 overflow. However, for that to happen, vr1.max needs to be
2870 zero, which means vr1 is a singleton range of zero, which
2871 means it should be handled by the previous LSHIFT_EXPR
2872 if-clause. */
2873 wide_int bound = wi::set_bit_in_zero (bound_shift, prec);
2874 wide_int complement = ~(bound - 1);
2876 if (uns)
2878 low_bound = bound;
2879 high_bound = complement;
2880 if (wi::ltu_p (vr0.max, low_bound))
2882 /* [5, 6] << [1, 2] == [10, 24]. */
2883 /* We're shifting out only zeroes, the value increases
2884 monotonically. */
2885 in_bounds = true;
2887 else if (wi::ltu_p (high_bound, vr0.min))
2889 /* [0xffffff00, 0xffffffff] << [1, 2]
2890 == [0xfffffc00, 0xfffffffe]. */
2891 /* We're shifting out only ones, the value decreases
2892 monotonically. */
2893 in_bounds = true;
2896 else
2898 /* [-1, 1] << [1, 2] == [-4, 4]. */
2899 low_bound = complement;
2900 high_bound = bound;
2901 if (wi::lts_p (vr0.max, high_bound)
2902 && wi::lts_p (low_bound, vr0.min))
2904 /* For non-negative numbers, we're shifting out only
2905 zeroes, the value increases monotonically.
2906 For negative numbers, we're shifting out only ones, the
2907 value decreases monotomically. */
2908 in_bounds = true;
2912 if (in_bounds)
2914 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2915 return;
2919 set_value_range_to_varying (vr);
2920 return;
2922 else if (code == TRUNC_DIV_EXPR
2923 || code == FLOOR_DIV_EXPR
2924 || code == CEIL_DIV_EXPR
2925 || code == EXACT_DIV_EXPR
2926 || code == ROUND_DIV_EXPR)
2928 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
2930 /* For division, if op1 has VR_RANGE but op0 does not, something
2931 can be deduced just from that range. Say [min, max] / [4, max]
2932 gives [min / 4, max / 4] range. */
2933 if (vr1.type == VR_RANGE
2934 && !symbolic_range_p (&vr1)
2935 && range_includes_zero_p (vr1.min, vr1.max) == 0)
2937 vr0.type = type = VR_RANGE;
2938 vr0.min = vrp_val_min (expr_type);
2939 vr0.max = vrp_val_max (expr_type);
2941 else
2943 set_value_range_to_varying (vr);
2944 return;
2948 /* For divisions, if flag_non_call_exceptions is true, we must
2949 not eliminate a division by zero. */
2950 if (cfun->can_throw_non_call_exceptions
2951 && (vr1.type != VR_RANGE
2952 || range_includes_zero_p (vr1.min, vr1.max) != 0))
2954 set_value_range_to_varying (vr);
2955 return;
2958 /* For divisions, if op0 is VR_RANGE, we can deduce a range
2959 even if op1 is VR_VARYING, VR_ANTI_RANGE, symbolic or can
2960 include 0. */
2961 if (vr0.type == VR_RANGE
2962 && (vr1.type != VR_RANGE
2963 || range_includes_zero_p (vr1.min, vr1.max) != 0))
2965 tree zero = build_int_cst (TREE_TYPE (vr0.min), 0);
2966 int cmp;
2968 min = NULL_TREE;
2969 max = NULL_TREE;
2970 if (TYPE_UNSIGNED (expr_type)
2971 || value_range_nonnegative_p (&vr1))
2973 /* For unsigned division or when divisor is known
2974 to be non-negative, the range has to cover
2975 all numbers from 0 to max for positive max
2976 and all numbers from min to 0 for negative min. */
2977 cmp = compare_values (vr0.max, zero);
2978 if (cmp == -1)
2980 /* When vr0.max < 0, vr1.min != 0 and value
2981 ranges for dividend and divisor are available. */
2982 if (vr1.type == VR_RANGE
2983 && !symbolic_range_p (&vr0)
2984 && !symbolic_range_p (&vr1)
2985 && compare_values (vr1.min, zero) != 0)
2986 max = int_const_binop (code, vr0.max, vr1.min);
2987 else
2988 max = zero;
2990 else if (cmp == 0 || cmp == 1)
2991 max = vr0.max;
2992 else
2993 type = VR_VARYING;
2994 cmp = compare_values (vr0.min, zero);
2995 if (cmp == 1)
2997 /* For unsigned division when value ranges for dividend
2998 and divisor are available. */
2999 if (vr1.type == VR_RANGE
3000 && !symbolic_range_p (&vr0)
3001 && !symbolic_range_p (&vr1)
3002 && compare_values (vr1.max, zero) != 0)
3003 min = int_const_binop (code, vr0.min, vr1.max);
3004 else
3005 min = zero;
3007 else if (cmp == 0 || cmp == -1)
3008 min = vr0.min;
3009 else
3010 type = VR_VARYING;
3012 else
3014 /* Otherwise the range is -max .. max or min .. -min
3015 depending on which bound is bigger in absolute value,
3016 as the division can change the sign. */
3017 abs_extent_range (vr, vr0.min, vr0.max);
3018 return;
3020 if (type == VR_VARYING)
3022 set_value_range_to_varying (vr);
3023 return;
3026 else if (!symbolic_range_p (&vr0) && !symbolic_range_p (&vr1))
3028 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
3029 return;
3032 else if (code == TRUNC_MOD_EXPR)
3034 if (range_is_null (&vr1))
3036 set_value_range_to_undefined (vr);
3037 return;
3039 /* ABS (A % B) < ABS (B) and either
3040 0 <= A % B <= A or A <= A % B <= 0. */
3041 type = VR_RANGE;
3042 signop sgn = TYPE_SIGN (expr_type);
3043 unsigned int prec = TYPE_PRECISION (expr_type);
3044 wide_int wmin, wmax, tmp;
3045 wide_int zero = wi::zero (prec);
3046 wide_int one = wi::one (prec);
3047 if (vr1.type == VR_RANGE && !symbolic_range_p (&vr1))
3049 wmax = wi::sub (vr1.max, one);
3050 if (sgn == SIGNED)
3052 tmp = wi::sub (wi::minus_one (prec), vr1.min);
3053 wmax = wi::smax (wmax, tmp);
3056 else
3058 wmax = wi::max_value (prec, sgn);
3059 /* X % INT_MIN may be INT_MAX. */
3060 if (sgn == UNSIGNED)
3061 wmax = wmax - one;
3064 if (sgn == UNSIGNED)
3065 wmin = zero;
3066 else
3068 wmin = -wmax;
3069 if (vr0.type == VR_RANGE && TREE_CODE (vr0.min) == INTEGER_CST)
3071 tmp = vr0.min;
3072 if (wi::gts_p (tmp, zero))
3073 tmp = zero;
3074 wmin = wi::smax (wmin, tmp);
3078 if (vr0.type == VR_RANGE && TREE_CODE (vr0.max) == INTEGER_CST)
3080 tmp = vr0.max;
3081 if (sgn == SIGNED && wi::neg_p (tmp))
3082 tmp = zero;
3083 wmax = wi::min (wmax, tmp, sgn);
3086 min = wide_int_to_tree (expr_type, wmin);
3087 max = wide_int_to_tree (expr_type, wmax);
3089 else if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR || code == BIT_XOR_EXPR)
3091 bool int_cst_range0, int_cst_range1;
3092 wide_int may_be_nonzero0, may_be_nonzero1;
3093 wide_int must_be_nonzero0, must_be_nonzero1;
3095 int_cst_range0 = zero_nonzero_bits_from_vr (expr_type, &vr0,
3096 &may_be_nonzero0,
3097 &must_be_nonzero0);
3098 int_cst_range1 = zero_nonzero_bits_from_vr (expr_type, &vr1,
3099 &may_be_nonzero1,
3100 &must_be_nonzero1);
3102 type = VR_RANGE;
3103 if (code == BIT_AND_EXPR)
3105 min = wide_int_to_tree (expr_type,
3106 must_be_nonzero0 & must_be_nonzero1);
3107 wide_int wmax = may_be_nonzero0 & may_be_nonzero1;
3108 /* If both input ranges contain only negative values we can
3109 truncate the result range maximum to the minimum of the
3110 input range maxima. */
3111 if (int_cst_range0 && int_cst_range1
3112 && tree_int_cst_sgn (vr0.max) < 0
3113 && tree_int_cst_sgn (vr1.max) < 0)
3115 wmax = wi::min (wmax, vr0.max, TYPE_SIGN (expr_type));
3116 wmax = wi::min (wmax, vr1.max, TYPE_SIGN (expr_type));
3118 /* If either input range contains only non-negative values
3119 we can truncate the result range maximum to the respective
3120 maximum of the input range. */
3121 if (int_cst_range0 && tree_int_cst_sgn (vr0.min) >= 0)
3122 wmax = wi::min (wmax, vr0.max, TYPE_SIGN (expr_type));
3123 if (int_cst_range1 && tree_int_cst_sgn (vr1.min) >= 0)
3124 wmax = wi::min (wmax, vr1.max, TYPE_SIGN (expr_type));
3125 max = wide_int_to_tree (expr_type, wmax);
3126 cmp = compare_values (min, max);
3127 /* PR68217: In case of signed & sign-bit-CST should
3128 result in [-INF, 0] instead of [-INF, INF]. */
3129 if (cmp == -2 || cmp == 1)
3131 wide_int sign_bit
3132 = wi::set_bit_in_zero (TYPE_PRECISION (expr_type) - 1,
3133 TYPE_PRECISION (expr_type));
3134 if (!TYPE_UNSIGNED (expr_type)
3135 && ((value_range_constant_singleton (&vr0)
3136 && !wi::cmps (vr0.min, sign_bit))
3137 || (value_range_constant_singleton (&vr1)
3138 && !wi::cmps (vr1.min, sign_bit))))
3140 min = TYPE_MIN_VALUE (expr_type);
3141 max = build_int_cst (expr_type, 0);
3145 else if (code == BIT_IOR_EXPR)
3147 max = wide_int_to_tree (expr_type,
3148 may_be_nonzero0 | may_be_nonzero1);
3149 wide_int wmin = must_be_nonzero0 | must_be_nonzero1;
3150 /* If the input ranges contain only positive values we can
3151 truncate the minimum of the result range to the maximum
3152 of the input range minima. */
3153 if (int_cst_range0 && int_cst_range1
3154 && tree_int_cst_sgn (vr0.min) >= 0
3155 && tree_int_cst_sgn (vr1.min) >= 0)
3157 wmin = wi::max (wmin, vr0.min, TYPE_SIGN (expr_type));
3158 wmin = wi::max (wmin, vr1.min, TYPE_SIGN (expr_type));
3160 /* If either input range contains only negative values
3161 we can truncate the minimum of the result range to the
3162 respective minimum range. */
3163 if (int_cst_range0 && tree_int_cst_sgn (vr0.max) < 0)
3164 wmin = wi::max (wmin, vr0.min, TYPE_SIGN (expr_type));
3165 if (int_cst_range1 && tree_int_cst_sgn (vr1.max) < 0)
3166 wmin = wi::max (wmin, vr1.min, TYPE_SIGN (expr_type));
3167 min = wide_int_to_tree (expr_type, wmin);
3169 else if (code == BIT_XOR_EXPR)
3171 wide_int result_zero_bits = ((must_be_nonzero0 & must_be_nonzero1)
3172 | ~(may_be_nonzero0 | may_be_nonzero1));
3173 wide_int result_one_bits
3174 = (must_be_nonzero0.and_not (may_be_nonzero1)
3175 | must_be_nonzero1.and_not (may_be_nonzero0));
3176 max = wide_int_to_tree (expr_type, ~result_zero_bits);
3177 min = wide_int_to_tree (expr_type, result_one_bits);
3178 /* If the range has all positive or all negative values the
3179 result is better than VARYING. */
3180 if (tree_int_cst_sgn (min) < 0
3181 || tree_int_cst_sgn (max) >= 0)
3183 else
3184 max = min = NULL_TREE;
3187 else
3188 gcc_unreachable ();
3190 /* If either MIN or MAX overflowed, then set the resulting range to
3191 VARYING. But we do accept an overflow infinity representation. */
3192 if (min == NULL_TREE
3193 || (TREE_OVERFLOW_P (min) && !is_overflow_infinity (min))
3194 || max == NULL_TREE
3195 || (TREE_OVERFLOW_P (max) && !is_overflow_infinity (max)))
3197 set_value_range_to_varying (vr);
3198 return;
3201 /* We punt if:
3202 1) [-INF, +INF]
3203 2) [-INF, +-INF(OVF)]
3204 3) [+-INF(OVF), +INF]
3205 4) [+-INF(OVF), +-INF(OVF)]
3206 We learn nothing when we have INF and INF(OVF) on both sides.
3207 Note that we do accept [-INF, -INF] and [+INF, +INF] without
3208 overflow. */
3209 if ((vrp_val_is_min (min) || is_overflow_infinity (min))
3210 && (vrp_val_is_max (max) || is_overflow_infinity (max)))
3212 set_value_range_to_varying (vr);
3213 return;
3216 cmp = compare_values (min, max);
3217 if (cmp == -2 || cmp == 1)
3219 /* If the new range has its limits swapped around (MIN > MAX),
3220 then the operation caused one of them to wrap around, mark
3221 the new range VARYING. */
3222 set_value_range_to_varying (vr);
3224 else
3225 set_value_range (vr, type, min, max, NULL);
3228 /* Extract range information from a binary expression OP0 CODE OP1 based on
3229 the ranges of each of its operands with resulting type EXPR_TYPE.
3230 The resulting range is stored in *VR. */
3232 static void
3233 extract_range_from_binary_expr (value_range *vr,
3234 enum tree_code code,
3235 tree expr_type, tree op0, tree op1)
3237 value_range vr0 = VR_INITIALIZER;
3238 value_range vr1 = VR_INITIALIZER;
3240 /* Get value ranges for each operand. For constant operands, create
3241 a new value range with the operand to simplify processing. */
3242 if (TREE_CODE (op0) == SSA_NAME)
3243 vr0 = *(get_value_range (op0));
3244 else if (is_gimple_min_invariant (op0))
3245 set_value_range_to_value (&vr0, op0, NULL);
3246 else
3247 set_value_range_to_varying (&vr0);
3249 if (TREE_CODE (op1) == SSA_NAME)
3250 vr1 = *(get_value_range (op1));
3251 else if (is_gimple_min_invariant (op1))
3252 set_value_range_to_value (&vr1, op1, NULL);
3253 else
3254 set_value_range_to_varying (&vr1);
3256 extract_range_from_binary_expr_1 (vr, code, expr_type, &vr0, &vr1);
3258 /* Try harder for PLUS and MINUS if the range of one operand is symbolic
3259 and based on the other operand, for example if it was deduced from a
3260 symbolic comparison. When a bound of the range of the first operand
3261 is invariant, we set the corresponding bound of the new range to INF
3262 in order to avoid recursing on the range of the second operand. */
3263 if (vr->type == VR_VARYING
3264 && (code == PLUS_EXPR || code == MINUS_EXPR)
3265 && TREE_CODE (op1) == SSA_NAME
3266 && vr0.type == VR_RANGE
3267 && symbolic_range_based_on_p (&vr0, op1))
3269 const bool minus_p = (code == MINUS_EXPR);
3270 value_range n_vr1 = VR_INITIALIZER;
3272 /* Try with VR0 and [-INF, OP1]. */
3273 if (is_gimple_min_invariant (minus_p ? vr0.max : vr0.min))
3274 set_value_range (&n_vr1, VR_RANGE, vrp_val_min (expr_type), op1, NULL);
3276 /* Try with VR0 and [OP1, +INF]. */
3277 else if (is_gimple_min_invariant (minus_p ? vr0.min : vr0.max))
3278 set_value_range (&n_vr1, VR_RANGE, op1, vrp_val_max (expr_type), NULL);
3280 /* Try with VR0 and [OP1, OP1]. */
3281 else
3282 set_value_range (&n_vr1, VR_RANGE, op1, op1, NULL);
3284 extract_range_from_binary_expr_1 (vr, code, expr_type, &vr0, &n_vr1);
3287 if (vr->type == VR_VARYING
3288 && (code == PLUS_EXPR || code == MINUS_EXPR)
3289 && TREE_CODE (op0) == SSA_NAME
3290 && vr1.type == VR_RANGE
3291 && symbolic_range_based_on_p (&vr1, op0))
3293 const bool minus_p = (code == MINUS_EXPR);
3294 value_range n_vr0 = VR_INITIALIZER;
3296 /* Try with [-INF, OP0] and VR1. */
3297 if (is_gimple_min_invariant (minus_p ? vr1.max : vr1.min))
3298 set_value_range (&n_vr0, VR_RANGE, vrp_val_min (expr_type), op0, NULL);
3300 /* Try with [OP0, +INF] and VR1. */
3301 else if (is_gimple_min_invariant (minus_p ? vr1.min : vr1.max))
3302 set_value_range (&n_vr0, VR_RANGE, op0, vrp_val_max (expr_type), NULL);
3304 /* Try with [OP0, OP0] and VR1. */
3305 else
3306 set_value_range (&n_vr0, VR_RANGE, op0, op0, NULL);
3308 extract_range_from_binary_expr_1 (vr, code, expr_type, &n_vr0, &vr1);
3312 /* Extract range information from a unary operation CODE based on
3313 the range of its operand *VR0 with type OP0_TYPE with resulting type TYPE.
3314 The resulting range is stored in *VR. */
3316 void
3317 extract_range_from_unary_expr (value_range *vr,
3318 enum tree_code code, tree type,
3319 value_range *vr0_, tree op0_type)
3321 value_range vr0 = *vr0_, vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
3323 /* VRP only operates on integral and pointer types. */
3324 if (!(INTEGRAL_TYPE_P (op0_type)
3325 || POINTER_TYPE_P (op0_type))
3326 || !(INTEGRAL_TYPE_P (type)
3327 || POINTER_TYPE_P (type)))
3329 set_value_range_to_varying (vr);
3330 return;
3333 /* If VR0 is UNDEFINED, so is the result. */
3334 if (vr0.type == VR_UNDEFINED)
3336 set_value_range_to_undefined (vr);
3337 return;
3340 /* Handle operations that we express in terms of others. */
3341 if (code == PAREN_EXPR || code == OBJ_TYPE_REF)
3343 /* PAREN_EXPR and OBJ_TYPE_REF are simple copies. */
3344 copy_value_range (vr, &vr0);
3345 return;
3347 else if (code == NEGATE_EXPR)
3349 /* -X is simply 0 - X, so re-use existing code that also handles
3350 anti-ranges fine. */
3351 value_range zero = VR_INITIALIZER;
3352 set_value_range_to_value (&zero, build_int_cst (type, 0), NULL);
3353 extract_range_from_binary_expr_1 (vr, MINUS_EXPR, type, &zero, &vr0);
3354 return;
3356 else if (code == BIT_NOT_EXPR)
3358 /* ~X is simply -1 - X, so re-use existing code that also handles
3359 anti-ranges fine. */
3360 value_range minusone = VR_INITIALIZER;
3361 set_value_range_to_value (&minusone, build_int_cst (type, -1), NULL);
3362 extract_range_from_binary_expr_1 (vr, MINUS_EXPR,
3363 type, &minusone, &vr0);
3364 return;
3367 /* Now canonicalize anti-ranges to ranges when they are not symbolic
3368 and express op ~[] as (op []') U (op []''). */
3369 if (vr0.type == VR_ANTI_RANGE
3370 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
3372 extract_range_from_unary_expr (vr, code, type, &vrtem0, op0_type);
3373 if (vrtem1.type != VR_UNDEFINED)
3375 value_range vrres = VR_INITIALIZER;
3376 extract_range_from_unary_expr (&vrres, code, type,
3377 &vrtem1, op0_type);
3378 vrp_meet (vr, &vrres);
3380 return;
3383 if (CONVERT_EXPR_CODE_P (code))
3385 tree inner_type = op0_type;
3386 tree outer_type = type;
3388 /* If the expression evaluates to a pointer, we are only interested in
3389 determining if it evaluates to NULL [0, 0] or non-NULL (~[0, 0]). */
3390 if (POINTER_TYPE_P (type))
3392 if (range_is_nonnull (&vr0))
3393 set_value_range_to_nonnull (vr, type);
3394 else if (range_is_null (&vr0))
3395 set_value_range_to_null (vr, type);
3396 else
3397 set_value_range_to_varying (vr);
3398 return;
3401 /* If VR0 is varying and we increase the type precision, assume
3402 a full range for the following transformation. */
3403 if (vr0.type == VR_VARYING
3404 && INTEGRAL_TYPE_P (inner_type)
3405 && TYPE_PRECISION (inner_type) < TYPE_PRECISION (outer_type))
3407 vr0.type = VR_RANGE;
3408 vr0.min = TYPE_MIN_VALUE (inner_type);
3409 vr0.max = TYPE_MAX_VALUE (inner_type);
3412 /* If VR0 is a constant range or anti-range and the conversion is
3413 not truncating we can convert the min and max values and
3414 canonicalize the resulting range. Otherwise we can do the
3415 conversion if the size of the range is less than what the
3416 precision of the target type can represent and the range is
3417 not an anti-range. */
3418 if ((vr0.type == VR_RANGE
3419 || vr0.type == VR_ANTI_RANGE)
3420 && TREE_CODE (vr0.min) == INTEGER_CST
3421 && TREE_CODE (vr0.max) == INTEGER_CST
3422 && (!is_overflow_infinity (vr0.min)
3423 || (vr0.type == VR_RANGE
3424 && TYPE_PRECISION (outer_type) > TYPE_PRECISION (inner_type)
3425 && needs_overflow_infinity (outer_type)
3426 && supports_overflow_infinity (outer_type)))
3427 && (!is_overflow_infinity (vr0.max)
3428 || (vr0.type == VR_RANGE
3429 && TYPE_PRECISION (outer_type) > TYPE_PRECISION (inner_type)
3430 && needs_overflow_infinity (outer_type)
3431 && supports_overflow_infinity (outer_type)))
3432 && (TYPE_PRECISION (outer_type) >= TYPE_PRECISION (inner_type)
3433 || (vr0.type == VR_RANGE
3434 && integer_zerop (int_const_binop (RSHIFT_EXPR,
3435 int_const_binop (MINUS_EXPR, vr0.max, vr0.min),
3436 size_int (TYPE_PRECISION (outer_type)))))))
3438 tree new_min, new_max;
3439 if (is_overflow_infinity (vr0.min))
3440 new_min = negative_overflow_infinity (outer_type);
3441 else
3442 new_min = force_fit_type (outer_type, wi::to_widest (vr0.min),
3443 0, false);
3444 if (is_overflow_infinity (vr0.max))
3445 new_max = positive_overflow_infinity (outer_type);
3446 else
3447 new_max = force_fit_type (outer_type, wi::to_widest (vr0.max),
3448 0, false);
3449 set_and_canonicalize_value_range (vr, vr0.type,
3450 new_min, new_max, NULL);
3451 return;
3454 set_value_range_to_varying (vr);
3455 return;
3457 else if (code == ABS_EXPR)
3459 tree min, max;
3460 int cmp;
3462 /* Pass through vr0 in the easy cases. */
3463 if (TYPE_UNSIGNED (type)
3464 || value_range_nonnegative_p (&vr0))
3466 copy_value_range (vr, &vr0);
3467 return;
3470 /* For the remaining varying or symbolic ranges we can't do anything
3471 useful. */
3472 if (vr0.type == VR_VARYING
3473 || symbolic_range_p (&vr0))
3475 set_value_range_to_varying (vr);
3476 return;
3479 /* -TYPE_MIN_VALUE = TYPE_MIN_VALUE with flag_wrapv so we can't get a
3480 useful range. */
3481 if (!TYPE_OVERFLOW_UNDEFINED (type)
3482 && ((vr0.type == VR_RANGE
3483 && vrp_val_is_min (vr0.min))
3484 || (vr0.type == VR_ANTI_RANGE
3485 && !vrp_val_is_min (vr0.min))))
3487 set_value_range_to_varying (vr);
3488 return;
3491 /* ABS_EXPR may flip the range around, if the original range
3492 included negative values. */
3493 if (is_overflow_infinity (vr0.min))
3494 min = positive_overflow_infinity (type);
3495 else if (!vrp_val_is_min (vr0.min))
3496 min = fold_unary_to_constant (code, type, vr0.min);
3497 else if (!needs_overflow_infinity (type))
3498 min = TYPE_MAX_VALUE (type);
3499 else if (supports_overflow_infinity (type))
3500 min = positive_overflow_infinity (type);
3501 else
3503 set_value_range_to_varying (vr);
3504 return;
3507 if (is_overflow_infinity (vr0.max))
3508 max = positive_overflow_infinity (type);
3509 else if (!vrp_val_is_min (vr0.max))
3510 max = fold_unary_to_constant (code, type, vr0.max);
3511 else if (!needs_overflow_infinity (type))
3512 max = TYPE_MAX_VALUE (type);
3513 else if (supports_overflow_infinity (type)
3514 /* We shouldn't generate [+INF, +INF] as set_value_range
3515 doesn't like this and ICEs. */
3516 && !is_positive_overflow_infinity (min))
3517 max = positive_overflow_infinity (type);
3518 else
3520 set_value_range_to_varying (vr);
3521 return;
3524 cmp = compare_values (min, max);
3526 /* If a VR_ANTI_RANGEs contains zero, then we have
3527 ~[-INF, min(MIN, MAX)]. */
3528 if (vr0.type == VR_ANTI_RANGE)
3530 if (range_includes_zero_p (vr0.min, vr0.max) == 1)
3532 /* Take the lower of the two values. */
3533 if (cmp != 1)
3534 max = min;
3536 /* Create ~[-INF, min (abs(MIN), abs(MAX))]
3537 or ~[-INF + 1, min (abs(MIN), abs(MAX))] when
3538 flag_wrapv is set and the original anti-range doesn't include
3539 TYPE_MIN_VALUE, remember -TYPE_MIN_VALUE = TYPE_MIN_VALUE. */
3540 if (TYPE_OVERFLOW_WRAPS (type))
3542 tree type_min_value = TYPE_MIN_VALUE (type);
3544 min = (vr0.min != type_min_value
3545 ? int_const_binop (PLUS_EXPR, type_min_value,
3546 build_int_cst (TREE_TYPE (type_min_value), 1))
3547 : type_min_value);
3549 else
3551 if (overflow_infinity_range_p (&vr0))
3552 min = negative_overflow_infinity (type);
3553 else
3554 min = TYPE_MIN_VALUE (type);
3557 else
3559 /* All else has failed, so create the range [0, INF], even for
3560 flag_wrapv since TYPE_MIN_VALUE is in the original
3561 anti-range. */
3562 vr0.type = VR_RANGE;
3563 min = build_int_cst (type, 0);
3564 if (needs_overflow_infinity (type))
3566 if (supports_overflow_infinity (type))
3567 max = positive_overflow_infinity (type);
3568 else
3570 set_value_range_to_varying (vr);
3571 return;
3574 else
3575 max = TYPE_MAX_VALUE (type);
3579 /* If the range contains zero then we know that the minimum value in the
3580 range will be zero. */
3581 else if (range_includes_zero_p (vr0.min, vr0.max) == 1)
3583 if (cmp == 1)
3584 max = min;
3585 min = build_int_cst (type, 0);
3587 else
3589 /* If the range was reversed, swap MIN and MAX. */
3590 if (cmp == 1)
3591 std::swap (min, max);
3594 cmp = compare_values (min, max);
3595 if (cmp == -2 || cmp == 1)
3597 /* If the new range has its limits swapped around (MIN > MAX),
3598 then the operation caused one of them to wrap around, mark
3599 the new range VARYING. */
3600 set_value_range_to_varying (vr);
3602 else
3603 set_value_range (vr, vr0.type, min, max, NULL);
3604 return;
3607 /* For unhandled operations fall back to varying. */
3608 set_value_range_to_varying (vr);
3609 return;
3613 /* Extract range information from a unary expression CODE OP0 based on
3614 the range of its operand with resulting type TYPE.
3615 The resulting range is stored in *VR. */
3617 static void
3618 extract_range_from_unary_expr (value_range *vr, enum tree_code code,
3619 tree type, tree op0)
3621 value_range vr0 = VR_INITIALIZER;
3623 /* Get value ranges for the operand. For constant operands, create
3624 a new value range with the operand to simplify processing. */
3625 if (TREE_CODE (op0) == SSA_NAME)
3626 vr0 = *(get_value_range (op0));
3627 else if (is_gimple_min_invariant (op0))
3628 set_value_range_to_value (&vr0, op0, NULL);
3629 else
3630 set_value_range_to_varying (&vr0);
3632 extract_range_from_unary_expr (vr, code, type, &vr0, TREE_TYPE (op0));
3636 /* Extract range information from a conditional expression STMT based on
3637 the ranges of each of its operands and the expression code. */
3639 static void
3640 extract_range_from_cond_expr (value_range *vr, gassign *stmt)
3642 tree op0, op1;
3643 value_range vr0 = VR_INITIALIZER;
3644 value_range vr1 = VR_INITIALIZER;
3646 /* Get value ranges for each operand. For constant operands, create
3647 a new value range with the operand to simplify processing. */
3648 op0 = gimple_assign_rhs2 (stmt);
3649 if (TREE_CODE (op0) == SSA_NAME)
3650 vr0 = *(get_value_range (op0));
3651 else if (is_gimple_min_invariant (op0))
3652 set_value_range_to_value (&vr0, op0, NULL);
3653 else
3654 set_value_range_to_varying (&vr0);
3656 op1 = gimple_assign_rhs3 (stmt);
3657 if (TREE_CODE (op1) == SSA_NAME)
3658 vr1 = *(get_value_range (op1));
3659 else if (is_gimple_min_invariant (op1))
3660 set_value_range_to_value (&vr1, op1, NULL);
3661 else
3662 set_value_range_to_varying (&vr1);
3664 /* The resulting value range is the union of the operand ranges */
3665 copy_value_range (vr, &vr0);
3666 vrp_meet (vr, &vr1);
3670 /* Extract range information from a comparison expression EXPR based
3671 on the range of its operand and the expression code. */
3673 static void
3674 extract_range_from_comparison (value_range *vr, enum tree_code code,
3675 tree type, tree op0, tree op1)
3677 bool sop = false;
3678 tree val;
3680 val = vrp_evaluate_conditional_warnv_with_ops (code, op0, op1, false, &sop,
3681 NULL);
3683 /* A disadvantage of using a special infinity as an overflow
3684 representation is that we lose the ability to record overflow
3685 when we don't have an infinity. So we have to ignore a result
3686 which relies on overflow. */
3688 if (val && !is_overflow_infinity (val) && !sop)
3690 /* Since this expression was found on the RHS of an assignment,
3691 its type may be different from _Bool. Convert VAL to EXPR's
3692 type. */
3693 val = fold_convert (type, val);
3694 if (is_gimple_min_invariant (val))
3695 set_value_range_to_value (vr, val, vr->equiv);
3696 else
3697 set_value_range (vr, VR_RANGE, val, val, vr->equiv);
3699 else
3700 /* The result of a comparison is always true or false. */
3701 set_value_range_to_truthvalue (vr, type);
3704 /* Helper function for simplify_internal_call_using_ranges and
3705 extract_range_basic. Return true if OP0 SUBCODE OP1 for
3706 SUBCODE {PLUS,MINUS,MULT}_EXPR is known to never overflow or
3707 always overflow. Set *OVF to true if it is known to always
3708 overflow. */
3710 static bool
3711 check_for_binary_op_overflow (enum tree_code subcode, tree type,
3712 tree op0, tree op1, bool *ovf)
3714 value_range vr0 = VR_INITIALIZER;
3715 value_range vr1 = VR_INITIALIZER;
3716 if (TREE_CODE (op0) == SSA_NAME)
3717 vr0 = *get_value_range (op0);
3718 else if (TREE_CODE (op0) == INTEGER_CST)
3719 set_value_range_to_value (&vr0, op0, NULL);
3720 else
3721 set_value_range_to_varying (&vr0);
3723 if (TREE_CODE (op1) == SSA_NAME)
3724 vr1 = *get_value_range (op1);
3725 else if (TREE_CODE (op1) == INTEGER_CST)
3726 set_value_range_to_value (&vr1, op1, NULL);
3727 else
3728 set_value_range_to_varying (&vr1);
3730 if (!range_int_cst_p (&vr0)
3731 || TREE_OVERFLOW (vr0.min)
3732 || TREE_OVERFLOW (vr0.max))
3734 vr0.min = vrp_val_min (TREE_TYPE (op0));
3735 vr0.max = vrp_val_max (TREE_TYPE (op0));
3737 if (!range_int_cst_p (&vr1)
3738 || TREE_OVERFLOW (vr1.min)
3739 || TREE_OVERFLOW (vr1.max))
3741 vr1.min = vrp_val_min (TREE_TYPE (op1));
3742 vr1.max = vrp_val_max (TREE_TYPE (op1));
3744 *ovf = arith_overflowed_p (subcode, type, vr0.min,
3745 subcode == MINUS_EXPR ? vr1.max : vr1.min);
3746 if (arith_overflowed_p (subcode, type, vr0.max,
3747 subcode == MINUS_EXPR ? vr1.min : vr1.max) != *ovf)
3748 return false;
3749 if (subcode == MULT_EXPR)
3751 if (arith_overflowed_p (subcode, type, vr0.min, vr1.max) != *ovf
3752 || arith_overflowed_p (subcode, type, vr0.max, vr1.min) != *ovf)
3753 return false;
3755 if (*ovf)
3757 /* So far we found that there is an overflow on the boundaries.
3758 That doesn't prove that there is an overflow even for all values
3759 in between the boundaries. For that compute widest_int range
3760 of the result and see if it doesn't overlap the range of
3761 type. */
3762 widest_int wmin, wmax;
3763 widest_int w[4];
3764 int i;
3765 w[0] = wi::to_widest (vr0.min);
3766 w[1] = wi::to_widest (vr0.max);
3767 w[2] = wi::to_widest (vr1.min);
3768 w[3] = wi::to_widest (vr1.max);
3769 for (i = 0; i < 4; i++)
3771 widest_int wt;
3772 switch (subcode)
3774 case PLUS_EXPR:
3775 wt = wi::add (w[i & 1], w[2 + (i & 2) / 2]);
3776 break;
3777 case MINUS_EXPR:
3778 wt = wi::sub (w[i & 1], w[2 + (i & 2) / 2]);
3779 break;
3780 case MULT_EXPR:
3781 wt = wi::mul (w[i & 1], w[2 + (i & 2) / 2]);
3782 break;
3783 default:
3784 gcc_unreachable ();
3786 if (i == 0)
3788 wmin = wt;
3789 wmax = wt;
3791 else
3793 wmin = wi::smin (wmin, wt);
3794 wmax = wi::smax (wmax, wt);
3797 /* The result of op0 CODE op1 is known to be in range
3798 [wmin, wmax]. */
3799 widest_int wtmin = wi::to_widest (vrp_val_min (type));
3800 widest_int wtmax = wi::to_widest (vrp_val_max (type));
3801 /* If all values in [wmin, wmax] are smaller than
3802 [wtmin, wtmax] or all are larger than [wtmin, wtmax],
3803 the arithmetic operation will always overflow. */
3804 if (wmax < wtmin || wmin > wtmax)
3805 return true;
3806 return false;
3808 return true;
3811 /* Try to derive a nonnegative or nonzero range out of STMT relying
3812 primarily on generic routines in fold in conjunction with range data.
3813 Store the result in *VR */
3815 static void
3816 extract_range_basic (value_range *vr, gimple *stmt)
3818 bool sop = false;
3819 tree type = gimple_expr_type (stmt);
3821 if (is_gimple_call (stmt))
3823 tree arg;
3824 int mini, maxi, zerov = 0, prec;
3825 enum tree_code subcode = ERROR_MARK;
3826 combined_fn cfn = gimple_call_combined_fn (stmt);
3828 switch (cfn)
3830 case CFN_BUILT_IN_CONSTANT_P:
3831 /* If the call is __builtin_constant_p and the argument is a
3832 function parameter resolve it to false. This avoids bogus
3833 array bound warnings.
3834 ??? We could do this as early as inlining is finished. */
3835 arg = gimple_call_arg (stmt, 0);
3836 if (TREE_CODE (arg) == SSA_NAME
3837 && SSA_NAME_IS_DEFAULT_DEF (arg)
3838 && TREE_CODE (SSA_NAME_VAR (arg)) == PARM_DECL
3839 && cfun->after_inlining)
3841 set_value_range_to_null (vr, type);
3842 return;
3844 break;
3845 /* Both __builtin_ffs* and __builtin_popcount return
3846 [0, prec]. */
3847 CASE_CFN_FFS:
3848 CASE_CFN_POPCOUNT:
3849 arg = gimple_call_arg (stmt, 0);
3850 prec = TYPE_PRECISION (TREE_TYPE (arg));
3851 mini = 0;
3852 maxi = prec;
3853 if (TREE_CODE (arg) == SSA_NAME)
3855 value_range *vr0 = get_value_range (arg);
3856 /* If arg is non-zero, then ffs or popcount
3857 are non-zero. */
3858 if (((vr0->type == VR_RANGE
3859 && range_includes_zero_p (vr0->min, vr0->max) == 0)
3860 || (vr0->type == VR_ANTI_RANGE
3861 && range_includes_zero_p (vr0->min, vr0->max) == 1))
3862 && !is_overflow_infinity (vr0->min)
3863 && !is_overflow_infinity (vr0->max))
3864 mini = 1;
3865 /* If some high bits are known to be zero,
3866 we can decrease the maximum. */
3867 if (vr0->type == VR_RANGE
3868 && TREE_CODE (vr0->max) == INTEGER_CST
3869 && !operand_less_p (vr0->min,
3870 build_zero_cst (TREE_TYPE (vr0->min)))
3871 && !is_overflow_infinity (vr0->max))
3872 maxi = tree_floor_log2 (vr0->max) + 1;
3874 goto bitop_builtin;
3875 /* __builtin_parity* returns [0, 1]. */
3876 CASE_CFN_PARITY:
3877 mini = 0;
3878 maxi = 1;
3879 goto bitop_builtin;
3880 /* __builtin_c[lt]z* return [0, prec-1], except for
3881 when the argument is 0, but that is undefined behavior.
3882 On many targets where the CLZ RTL or optab value is defined
3883 for 0 the value is prec, so include that in the range
3884 by default. */
3885 CASE_CFN_CLZ:
3886 arg = gimple_call_arg (stmt, 0);
3887 prec = TYPE_PRECISION (TREE_TYPE (arg));
3888 mini = 0;
3889 maxi = prec;
3890 if (optab_handler (clz_optab, TYPE_MODE (TREE_TYPE (arg)))
3891 != CODE_FOR_nothing
3892 && CLZ_DEFINED_VALUE_AT_ZERO (TYPE_MODE (TREE_TYPE (arg)),
3893 zerov)
3894 /* Handle only the single common value. */
3895 && zerov != prec)
3896 /* Magic value to give up, unless vr0 proves
3897 arg is non-zero. */
3898 mini = -2;
3899 if (TREE_CODE (arg) == SSA_NAME)
3901 value_range *vr0 = get_value_range (arg);
3902 /* From clz of VR_RANGE minimum we can compute
3903 result maximum. */
3904 if (vr0->type == VR_RANGE
3905 && TREE_CODE (vr0->min) == INTEGER_CST
3906 && !is_overflow_infinity (vr0->min))
3908 maxi = prec - 1 - tree_floor_log2 (vr0->min);
3909 if (maxi != prec)
3910 mini = 0;
3912 else if (vr0->type == VR_ANTI_RANGE
3913 && integer_zerop (vr0->min)
3914 && !is_overflow_infinity (vr0->min))
3916 maxi = prec - 1;
3917 mini = 0;
3919 if (mini == -2)
3920 break;
3921 /* From clz of VR_RANGE maximum we can compute
3922 result minimum. */
3923 if (vr0->type == VR_RANGE
3924 && TREE_CODE (vr0->max) == INTEGER_CST
3925 && !is_overflow_infinity (vr0->max))
3927 mini = prec - 1 - tree_floor_log2 (vr0->max);
3928 if (mini == prec)
3929 break;
3932 if (mini == -2)
3933 break;
3934 goto bitop_builtin;
3935 /* __builtin_ctz* return [0, prec-1], except for
3936 when the argument is 0, but that is undefined behavior.
3937 If there is a ctz optab for this mode and
3938 CTZ_DEFINED_VALUE_AT_ZERO, include that in the range,
3939 otherwise just assume 0 won't be seen. */
3940 CASE_CFN_CTZ:
3941 arg = gimple_call_arg (stmt, 0);
3942 prec = TYPE_PRECISION (TREE_TYPE (arg));
3943 mini = 0;
3944 maxi = prec - 1;
3945 if (optab_handler (ctz_optab, TYPE_MODE (TREE_TYPE (arg)))
3946 != CODE_FOR_nothing
3947 && CTZ_DEFINED_VALUE_AT_ZERO (TYPE_MODE (TREE_TYPE (arg)),
3948 zerov))
3950 /* Handle only the two common values. */
3951 if (zerov == -1)
3952 mini = -1;
3953 else if (zerov == prec)
3954 maxi = prec;
3955 else
3956 /* Magic value to give up, unless vr0 proves
3957 arg is non-zero. */
3958 mini = -2;
3960 if (TREE_CODE (arg) == SSA_NAME)
3962 value_range *vr0 = get_value_range (arg);
3963 /* If arg is non-zero, then use [0, prec - 1]. */
3964 if (((vr0->type == VR_RANGE
3965 && integer_nonzerop (vr0->min))
3966 || (vr0->type == VR_ANTI_RANGE
3967 && integer_zerop (vr0->min)))
3968 && !is_overflow_infinity (vr0->min))
3970 mini = 0;
3971 maxi = prec - 1;
3973 /* If some high bits are known to be zero,
3974 we can decrease the result maximum. */
3975 if (vr0->type == VR_RANGE
3976 && TREE_CODE (vr0->max) == INTEGER_CST
3977 && !is_overflow_infinity (vr0->max))
3979 maxi = tree_floor_log2 (vr0->max);
3980 /* For vr0 [0, 0] give up. */
3981 if (maxi == -1)
3982 break;
3985 if (mini == -2)
3986 break;
3987 goto bitop_builtin;
3988 /* __builtin_clrsb* returns [0, prec-1]. */
3989 CASE_CFN_CLRSB:
3990 arg = gimple_call_arg (stmt, 0);
3991 prec = TYPE_PRECISION (TREE_TYPE (arg));
3992 mini = 0;
3993 maxi = prec - 1;
3994 goto bitop_builtin;
3995 bitop_builtin:
3996 set_value_range (vr, VR_RANGE, build_int_cst (type, mini),
3997 build_int_cst (type, maxi), NULL);
3998 return;
3999 case CFN_UBSAN_CHECK_ADD:
4000 subcode = PLUS_EXPR;
4001 break;
4002 case CFN_UBSAN_CHECK_SUB:
4003 subcode = MINUS_EXPR;
4004 break;
4005 case CFN_UBSAN_CHECK_MUL:
4006 subcode = MULT_EXPR;
4007 break;
4008 case CFN_GOACC_DIM_SIZE:
4009 case CFN_GOACC_DIM_POS:
4010 /* Optimizing these two internal functions helps the loop
4011 optimizer eliminate outer comparisons. Size is [1,N]
4012 and pos is [0,N-1]. */
4014 bool is_pos = cfn == CFN_GOACC_DIM_POS;
4015 int axis = get_oacc_ifn_dim_arg (stmt);
4016 int size = get_oacc_fn_dim_size (current_function_decl, axis);
4018 if (!size)
4019 /* If it's dynamic, the backend might know a hardware
4020 limitation. */
4021 size = targetm.goacc.dim_limit (axis);
4023 tree type = TREE_TYPE (gimple_call_lhs (stmt));
4024 set_value_range (vr, VR_RANGE,
4025 build_int_cst (type, is_pos ? 0 : 1),
4026 size ? build_int_cst (type, size - is_pos)
4027 : vrp_val_max (type), NULL);
4029 return;
4030 case CFN_BUILT_IN_STRLEN:
4031 if (tree lhs = gimple_call_lhs (stmt))
4032 if (ptrdiff_type_node
4033 && (TYPE_PRECISION (ptrdiff_type_node)
4034 == TYPE_PRECISION (TREE_TYPE (lhs))))
4036 tree type = TREE_TYPE (lhs);
4037 tree max = vrp_val_max (ptrdiff_type_node);
4038 wide_int wmax = wi::to_wide (max, TYPE_PRECISION (TREE_TYPE (max)));
4039 tree range_min = build_zero_cst (type);
4040 tree range_max = wide_int_to_tree (type, wmax - 1);
4041 set_value_range (vr, VR_RANGE, range_min, range_max, NULL);
4042 return;
4044 break;
4045 default:
4046 break;
4048 if (subcode != ERROR_MARK)
4050 bool saved_flag_wrapv = flag_wrapv;
4051 /* Pretend the arithmetics is wrapping. If there is
4052 any overflow, we'll complain, but will actually do
4053 wrapping operation. */
4054 flag_wrapv = 1;
4055 extract_range_from_binary_expr (vr, subcode, type,
4056 gimple_call_arg (stmt, 0),
4057 gimple_call_arg (stmt, 1));
4058 flag_wrapv = saved_flag_wrapv;
4060 /* If for both arguments vrp_valueize returned non-NULL,
4061 this should have been already folded and if not, it
4062 wasn't folded because of overflow. Avoid removing the
4063 UBSAN_CHECK_* calls in that case. */
4064 if (vr->type == VR_RANGE
4065 && (vr->min == vr->max
4066 || operand_equal_p (vr->min, vr->max, 0)))
4067 set_value_range_to_varying (vr);
4068 return;
4071 /* Handle extraction of the two results (result of arithmetics and
4072 a flag whether arithmetics overflowed) from {ADD,SUB,MUL}_OVERFLOW
4073 internal function. */
4074 else if (is_gimple_assign (stmt)
4075 && (gimple_assign_rhs_code (stmt) == REALPART_EXPR
4076 || gimple_assign_rhs_code (stmt) == IMAGPART_EXPR)
4077 && INTEGRAL_TYPE_P (type))
4079 enum tree_code code = gimple_assign_rhs_code (stmt);
4080 tree op = gimple_assign_rhs1 (stmt);
4081 if (TREE_CODE (op) == code && TREE_CODE (TREE_OPERAND (op, 0)) == SSA_NAME)
4083 gimple *g = SSA_NAME_DEF_STMT (TREE_OPERAND (op, 0));
4084 if (is_gimple_call (g) && gimple_call_internal_p (g))
4086 enum tree_code subcode = ERROR_MARK;
4087 switch (gimple_call_internal_fn (g))
4089 case IFN_ADD_OVERFLOW:
4090 subcode = PLUS_EXPR;
4091 break;
4092 case IFN_SUB_OVERFLOW:
4093 subcode = MINUS_EXPR;
4094 break;
4095 case IFN_MUL_OVERFLOW:
4096 subcode = MULT_EXPR;
4097 break;
4098 default:
4099 break;
4101 if (subcode != ERROR_MARK)
4103 tree op0 = gimple_call_arg (g, 0);
4104 tree op1 = gimple_call_arg (g, 1);
4105 if (code == IMAGPART_EXPR)
4107 bool ovf = false;
4108 if (check_for_binary_op_overflow (subcode, type,
4109 op0, op1, &ovf))
4110 set_value_range_to_value (vr,
4111 build_int_cst (type, ovf),
4112 NULL);
4113 else if (TYPE_PRECISION (type) == 1
4114 && !TYPE_UNSIGNED (type))
4115 set_value_range_to_varying (vr);
4116 else
4117 set_value_range (vr, VR_RANGE, build_int_cst (type, 0),
4118 build_int_cst (type, 1), NULL);
4120 else if (types_compatible_p (type, TREE_TYPE (op0))
4121 && types_compatible_p (type, TREE_TYPE (op1)))
4123 bool saved_flag_wrapv = flag_wrapv;
4124 /* Pretend the arithmetics is wrapping. If there is
4125 any overflow, IMAGPART_EXPR will be set. */
4126 flag_wrapv = 1;
4127 extract_range_from_binary_expr (vr, subcode, type,
4128 op0, op1);
4129 flag_wrapv = saved_flag_wrapv;
4131 else
4133 value_range vr0 = VR_INITIALIZER;
4134 value_range vr1 = VR_INITIALIZER;
4135 bool saved_flag_wrapv = flag_wrapv;
4136 /* Pretend the arithmetics is wrapping. If there is
4137 any overflow, IMAGPART_EXPR will be set. */
4138 flag_wrapv = 1;
4139 extract_range_from_unary_expr (&vr0, NOP_EXPR,
4140 type, op0);
4141 extract_range_from_unary_expr (&vr1, NOP_EXPR,
4142 type, op1);
4143 extract_range_from_binary_expr_1 (vr, subcode, type,
4144 &vr0, &vr1);
4145 flag_wrapv = saved_flag_wrapv;
4147 return;
4152 if (INTEGRAL_TYPE_P (type)
4153 && gimple_stmt_nonnegative_warnv_p (stmt, &sop))
4154 set_value_range_to_nonnegative (vr, type,
4155 sop || stmt_overflow_infinity (stmt));
4156 else if (vrp_stmt_computes_nonzero (stmt, &sop)
4157 && !sop)
4158 set_value_range_to_nonnull (vr, type);
4159 else
4160 set_value_range_to_varying (vr);
4164 /* Try to compute a useful range out of assignment STMT and store it
4165 in *VR. */
4167 static void
4168 extract_range_from_assignment (value_range *vr, gassign *stmt)
4170 enum tree_code code = gimple_assign_rhs_code (stmt);
4172 if (code == ASSERT_EXPR)
4173 extract_range_from_assert (vr, gimple_assign_rhs1 (stmt));
4174 else if (code == SSA_NAME)
4175 extract_range_from_ssa_name (vr, gimple_assign_rhs1 (stmt));
4176 else if (TREE_CODE_CLASS (code) == tcc_binary)
4177 extract_range_from_binary_expr (vr, gimple_assign_rhs_code (stmt),
4178 gimple_expr_type (stmt),
4179 gimple_assign_rhs1 (stmt),
4180 gimple_assign_rhs2 (stmt));
4181 else if (TREE_CODE_CLASS (code) == tcc_unary)
4182 extract_range_from_unary_expr (vr, gimple_assign_rhs_code (stmt),
4183 gimple_expr_type (stmt),
4184 gimple_assign_rhs1 (stmt));
4185 else if (code == COND_EXPR)
4186 extract_range_from_cond_expr (vr, stmt);
4187 else if (TREE_CODE_CLASS (code) == tcc_comparison)
4188 extract_range_from_comparison (vr, gimple_assign_rhs_code (stmt),
4189 gimple_expr_type (stmt),
4190 gimple_assign_rhs1 (stmt),
4191 gimple_assign_rhs2 (stmt));
4192 else if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS
4193 && is_gimple_min_invariant (gimple_assign_rhs1 (stmt)))
4194 set_value_range_to_value (vr, gimple_assign_rhs1 (stmt), NULL);
4195 else
4196 set_value_range_to_varying (vr);
4198 if (vr->type == VR_VARYING)
4199 extract_range_basic (vr, stmt);
4202 /* Given a range VR, a LOOP and a variable VAR, determine whether it
4203 would be profitable to adjust VR using scalar evolution information
4204 for VAR. If so, update VR with the new limits. */
4206 static void
4207 adjust_range_with_scev (value_range *vr, struct loop *loop,
4208 gimple *stmt, tree var)
4210 tree init, step, chrec, tmin, tmax, min, max, type, tem;
4211 enum ev_direction dir;
4213 /* TODO. Don't adjust anti-ranges. An anti-range may provide
4214 better opportunities than a regular range, but I'm not sure. */
4215 if (vr->type == VR_ANTI_RANGE)
4216 return;
4218 chrec = instantiate_parameters (loop, analyze_scalar_evolution (loop, var));
4220 /* Like in PR19590, scev can return a constant function. */
4221 if (is_gimple_min_invariant (chrec))
4223 set_value_range_to_value (vr, chrec, vr->equiv);
4224 return;
4227 if (TREE_CODE (chrec) != POLYNOMIAL_CHREC)
4228 return;
4230 init = initial_condition_in_loop_num (chrec, loop->num);
4231 tem = op_with_constant_singleton_value_range (init);
4232 if (tem)
4233 init = tem;
4234 step = evolution_part_in_loop_num (chrec, loop->num);
4235 tem = op_with_constant_singleton_value_range (step);
4236 if (tem)
4237 step = tem;
4239 /* If STEP is symbolic, we can't know whether INIT will be the
4240 minimum or maximum value in the range. Also, unless INIT is
4241 a simple expression, compare_values and possibly other functions
4242 in tree-vrp won't be able to handle it. */
4243 if (step == NULL_TREE
4244 || !is_gimple_min_invariant (step)
4245 || !valid_value_p (init))
4246 return;
4248 dir = scev_direction (chrec);
4249 if (/* Do not adjust ranges if we do not know whether the iv increases
4250 or decreases, ... */
4251 dir == EV_DIR_UNKNOWN
4252 /* ... or if it may wrap. */
4253 || scev_probably_wraps_p (NULL_TREE, init, step, stmt,
4254 get_chrec_loop (chrec), true))
4255 return;
4257 /* We use TYPE_MIN_VALUE and TYPE_MAX_VALUE here instead of
4258 negative_overflow_infinity and positive_overflow_infinity,
4259 because we have concluded that the loop probably does not
4260 wrap. */
4262 type = TREE_TYPE (var);
4263 if (POINTER_TYPE_P (type) || !TYPE_MIN_VALUE (type))
4264 tmin = lower_bound_in_type (type, type);
4265 else
4266 tmin = TYPE_MIN_VALUE (type);
4267 if (POINTER_TYPE_P (type) || !TYPE_MAX_VALUE (type))
4268 tmax = upper_bound_in_type (type, type);
4269 else
4270 tmax = TYPE_MAX_VALUE (type);
4272 /* Try to use estimated number of iterations for the loop to constrain the
4273 final value in the evolution. */
4274 if (TREE_CODE (step) == INTEGER_CST
4275 && is_gimple_val (init)
4276 && (TREE_CODE (init) != SSA_NAME
4277 || get_value_range (init)->type == VR_RANGE))
4279 widest_int nit;
4281 /* We are only entering here for loop header PHI nodes, so using
4282 the number of latch executions is the correct thing to use. */
4283 if (max_loop_iterations (loop, &nit))
4285 value_range maxvr = VR_INITIALIZER;
4286 signop sgn = TYPE_SIGN (TREE_TYPE (step));
4287 bool overflow;
4289 widest_int wtmp = wi::mul (wi::to_widest (step), nit, sgn,
4290 &overflow);
4291 /* If the multiplication overflowed we can't do a meaningful
4292 adjustment. Likewise if the result doesn't fit in the type
4293 of the induction variable. For a signed type we have to
4294 check whether the result has the expected signedness which
4295 is that of the step as number of iterations is unsigned. */
4296 if (!overflow
4297 && wi::fits_to_tree_p (wtmp, TREE_TYPE (init))
4298 && (sgn == UNSIGNED
4299 || wi::gts_p (wtmp, 0) == wi::gts_p (step, 0)))
4301 tem = wide_int_to_tree (TREE_TYPE (init), wtmp);
4302 extract_range_from_binary_expr (&maxvr, PLUS_EXPR,
4303 TREE_TYPE (init), init, tem);
4304 /* Likewise if the addition did. */
4305 if (maxvr.type == VR_RANGE)
4307 value_range initvr = VR_INITIALIZER;
4309 if (TREE_CODE (init) == SSA_NAME)
4310 initvr = *(get_value_range (init));
4311 else if (is_gimple_min_invariant (init))
4312 set_value_range_to_value (&initvr, init, NULL);
4313 else
4314 return;
4316 /* Check if init + nit * step overflows. Though we checked
4317 scev {init, step}_loop doesn't wrap, it is not enough
4318 because the loop may exit immediately. Overflow could
4319 happen in the plus expression in this case. */
4320 if ((dir == EV_DIR_DECREASES
4321 && (is_negative_overflow_infinity (maxvr.min)
4322 || compare_values (maxvr.min, initvr.min) != -1))
4323 || (dir == EV_DIR_GROWS
4324 && (is_positive_overflow_infinity (maxvr.max)
4325 || compare_values (maxvr.max, initvr.max) != 1)))
4326 return;
4328 tmin = maxvr.min;
4329 tmax = maxvr.max;
4335 if (vr->type == VR_VARYING || vr->type == VR_UNDEFINED)
4337 min = tmin;
4338 max = tmax;
4340 /* For VARYING or UNDEFINED ranges, just about anything we get
4341 from scalar evolutions should be better. */
4343 if (dir == EV_DIR_DECREASES)
4344 max = init;
4345 else
4346 min = init;
4348 else if (vr->type == VR_RANGE)
4350 min = vr->min;
4351 max = vr->max;
4353 if (dir == EV_DIR_DECREASES)
4355 /* INIT is the maximum value. If INIT is lower than VR->MAX
4356 but no smaller than VR->MIN, set VR->MAX to INIT. */
4357 if (compare_values (init, max) == -1)
4358 max = init;
4360 /* According to the loop information, the variable does not
4361 overflow. If we think it does, probably because of an
4362 overflow due to arithmetic on a different INF value,
4363 reset now. */
4364 if (is_negative_overflow_infinity (min)
4365 || compare_values (min, tmin) == -1)
4366 min = tmin;
4369 else
4371 /* If INIT is bigger than VR->MIN, set VR->MIN to INIT. */
4372 if (compare_values (init, min) == 1)
4373 min = init;
4375 if (is_positive_overflow_infinity (max)
4376 || compare_values (tmax, max) == -1)
4377 max = tmax;
4380 else
4381 return;
4383 /* If we just created an invalid range with the minimum
4384 greater than the maximum, we fail conservatively.
4385 This should happen only in unreachable
4386 parts of code, or for invalid programs. */
4387 if (compare_values (min, max) == 1
4388 || (is_negative_overflow_infinity (min)
4389 && is_positive_overflow_infinity (max)))
4390 return;
4392 /* Even for valid range info, sometimes overflow flag will leak in.
4393 As GIMPLE IL should have no constants with TREE_OVERFLOW set, we
4394 drop them except for +-overflow_infinity which still need special
4395 handling in vrp pass. */
4396 if (TREE_OVERFLOW_P (min)
4397 && ! is_negative_overflow_infinity (min))
4398 min = drop_tree_overflow (min);
4399 if (TREE_OVERFLOW_P (max)
4400 && ! is_positive_overflow_infinity (max))
4401 max = drop_tree_overflow (max);
4403 set_value_range (vr, VR_RANGE, min, max, vr->equiv);
4407 /* Given two numeric value ranges VR0, VR1 and a comparison code COMP:
4409 - Return BOOLEAN_TRUE_NODE if VR0 COMP VR1 always returns true for
4410 all the values in the ranges.
4412 - Return BOOLEAN_FALSE_NODE if the comparison always returns false.
4414 - Return NULL_TREE if it is not always possible to determine the
4415 value of the comparison.
4417 Also set *STRICT_OVERFLOW_P to indicate whether a range with an
4418 overflow infinity was used in the test. */
4421 static tree
4422 compare_ranges (enum tree_code comp, value_range *vr0, value_range *vr1,
4423 bool *strict_overflow_p)
4425 /* VARYING or UNDEFINED ranges cannot be compared. */
4426 if (vr0->type == VR_VARYING
4427 || vr0->type == VR_UNDEFINED
4428 || vr1->type == VR_VARYING
4429 || vr1->type == VR_UNDEFINED)
4430 return NULL_TREE;
4432 /* Anti-ranges need to be handled separately. */
4433 if (vr0->type == VR_ANTI_RANGE || vr1->type == VR_ANTI_RANGE)
4435 /* If both are anti-ranges, then we cannot compute any
4436 comparison. */
4437 if (vr0->type == VR_ANTI_RANGE && vr1->type == VR_ANTI_RANGE)
4438 return NULL_TREE;
4440 /* These comparisons are never statically computable. */
4441 if (comp == GT_EXPR
4442 || comp == GE_EXPR
4443 || comp == LT_EXPR
4444 || comp == LE_EXPR)
4445 return NULL_TREE;
4447 /* Equality can be computed only between a range and an
4448 anti-range. ~[VAL1, VAL2] == [VAL1, VAL2] is always false. */
4449 if (vr0->type == VR_RANGE)
4451 /* To simplify processing, make VR0 the anti-range. */
4452 value_range *tmp = vr0;
4453 vr0 = vr1;
4454 vr1 = tmp;
4457 gcc_assert (comp == NE_EXPR || comp == EQ_EXPR);
4459 if (compare_values_warnv (vr0->min, vr1->min, strict_overflow_p) == 0
4460 && compare_values_warnv (vr0->max, vr1->max, strict_overflow_p) == 0)
4461 return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
4463 return NULL_TREE;
4466 if (!usable_range_p (vr0, strict_overflow_p)
4467 || !usable_range_p (vr1, strict_overflow_p))
4468 return NULL_TREE;
4470 /* Simplify processing. If COMP is GT_EXPR or GE_EXPR, switch the
4471 operands around and change the comparison code. */
4472 if (comp == GT_EXPR || comp == GE_EXPR)
4474 comp = (comp == GT_EXPR) ? LT_EXPR : LE_EXPR;
4475 std::swap (vr0, vr1);
4478 if (comp == EQ_EXPR)
4480 /* Equality may only be computed if both ranges represent
4481 exactly one value. */
4482 if (compare_values_warnv (vr0->min, vr0->max, strict_overflow_p) == 0
4483 && compare_values_warnv (vr1->min, vr1->max, strict_overflow_p) == 0)
4485 int cmp_min = compare_values_warnv (vr0->min, vr1->min,
4486 strict_overflow_p);
4487 int cmp_max = compare_values_warnv (vr0->max, vr1->max,
4488 strict_overflow_p);
4489 if (cmp_min == 0 && cmp_max == 0)
4490 return boolean_true_node;
4491 else if (cmp_min != -2 && cmp_max != -2)
4492 return boolean_false_node;
4494 /* If [V0_MIN, V1_MAX] < [V1_MIN, V1_MAX] then V0 != V1. */
4495 else if (compare_values_warnv (vr0->min, vr1->max,
4496 strict_overflow_p) == 1
4497 || compare_values_warnv (vr1->min, vr0->max,
4498 strict_overflow_p) == 1)
4499 return boolean_false_node;
4501 return NULL_TREE;
4503 else if (comp == NE_EXPR)
4505 int cmp1, cmp2;
4507 /* If VR0 is completely to the left or completely to the right
4508 of VR1, they are always different. Notice that we need to
4509 make sure that both comparisons yield similar results to
4510 avoid comparing values that cannot be compared at
4511 compile-time. */
4512 cmp1 = compare_values_warnv (vr0->max, vr1->min, strict_overflow_p);
4513 cmp2 = compare_values_warnv (vr0->min, vr1->max, strict_overflow_p);
4514 if ((cmp1 == -1 && cmp2 == -1) || (cmp1 == 1 && cmp2 == 1))
4515 return boolean_true_node;
4517 /* If VR0 and VR1 represent a single value and are identical,
4518 return false. */
4519 else if (compare_values_warnv (vr0->min, vr0->max,
4520 strict_overflow_p) == 0
4521 && compare_values_warnv (vr1->min, vr1->max,
4522 strict_overflow_p) == 0
4523 && compare_values_warnv (vr0->min, vr1->min,
4524 strict_overflow_p) == 0
4525 && compare_values_warnv (vr0->max, vr1->max,
4526 strict_overflow_p) == 0)
4527 return boolean_false_node;
4529 /* Otherwise, they may or may not be different. */
4530 else
4531 return NULL_TREE;
4533 else if (comp == LT_EXPR || comp == LE_EXPR)
4535 int tst;
4537 /* If VR0 is to the left of VR1, return true. */
4538 tst = compare_values_warnv (vr0->max, vr1->min, strict_overflow_p);
4539 if ((comp == LT_EXPR && tst == -1)
4540 || (comp == LE_EXPR && (tst == -1 || tst == 0)))
4542 if (overflow_infinity_range_p (vr0)
4543 || overflow_infinity_range_p (vr1))
4544 *strict_overflow_p = true;
4545 return boolean_true_node;
4548 /* If VR0 is to the right of VR1, return false. */
4549 tst = compare_values_warnv (vr0->min, vr1->max, strict_overflow_p);
4550 if ((comp == LT_EXPR && (tst == 0 || tst == 1))
4551 || (comp == LE_EXPR && tst == 1))
4553 if (overflow_infinity_range_p (vr0)
4554 || overflow_infinity_range_p (vr1))
4555 *strict_overflow_p = true;
4556 return boolean_false_node;
4559 /* Otherwise, we don't know. */
4560 return NULL_TREE;
4563 gcc_unreachable ();
4567 /* Given a value range VR, a value VAL and a comparison code COMP, return
4568 BOOLEAN_TRUE_NODE if VR COMP VAL always returns true for all the
4569 values in VR. Return BOOLEAN_FALSE_NODE if the comparison
4570 always returns false. Return NULL_TREE if it is not always
4571 possible to determine the value of the comparison. Also set
4572 *STRICT_OVERFLOW_P to indicate whether a range with an overflow
4573 infinity was used in the test. */
4575 static tree
4576 compare_range_with_value (enum tree_code comp, value_range *vr, tree val,
4577 bool *strict_overflow_p)
4579 if (vr->type == VR_VARYING || vr->type == VR_UNDEFINED)
4580 return NULL_TREE;
4582 /* Anti-ranges need to be handled separately. */
4583 if (vr->type == VR_ANTI_RANGE)
4585 /* For anti-ranges, the only predicates that we can compute at
4586 compile time are equality and inequality. */
4587 if (comp == GT_EXPR
4588 || comp == GE_EXPR
4589 || comp == LT_EXPR
4590 || comp == LE_EXPR)
4591 return NULL_TREE;
4593 /* ~[VAL_1, VAL_2] OP VAL is known if VAL_1 <= VAL <= VAL_2. */
4594 if (value_inside_range (val, vr->min, vr->max) == 1)
4595 return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
4597 return NULL_TREE;
4600 if (!usable_range_p (vr, strict_overflow_p))
4601 return NULL_TREE;
4603 if (comp == EQ_EXPR)
4605 /* EQ_EXPR may only be computed if VR represents exactly
4606 one value. */
4607 if (compare_values_warnv (vr->min, vr->max, strict_overflow_p) == 0)
4609 int cmp = compare_values_warnv (vr->min, val, strict_overflow_p);
4610 if (cmp == 0)
4611 return boolean_true_node;
4612 else if (cmp == -1 || cmp == 1 || cmp == 2)
4613 return boolean_false_node;
4615 else if (compare_values_warnv (val, vr->min, strict_overflow_p) == -1
4616 || compare_values_warnv (vr->max, val, strict_overflow_p) == -1)
4617 return boolean_false_node;
4619 return NULL_TREE;
4621 else if (comp == NE_EXPR)
4623 /* If VAL is not inside VR, then they are always different. */
4624 if (compare_values_warnv (vr->max, val, strict_overflow_p) == -1
4625 || compare_values_warnv (vr->min, val, strict_overflow_p) == 1)
4626 return boolean_true_node;
4628 /* If VR represents exactly one value equal to VAL, then return
4629 false. */
4630 if (compare_values_warnv (vr->min, vr->max, strict_overflow_p) == 0
4631 && compare_values_warnv (vr->min, val, strict_overflow_p) == 0)
4632 return boolean_false_node;
4634 /* Otherwise, they may or may not be different. */
4635 return NULL_TREE;
4637 else if (comp == LT_EXPR || comp == LE_EXPR)
4639 int tst;
4641 /* If VR is to the left of VAL, return true. */
4642 tst = compare_values_warnv (vr->max, val, strict_overflow_p);
4643 if ((comp == LT_EXPR && tst == -1)
4644 || (comp == LE_EXPR && (tst == -1 || tst == 0)))
4646 if (overflow_infinity_range_p (vr))
4647 *strict_overflow_p = true;
4648 return boolean_true_node;
4651 /* If VR is to the right of VAL, return false. */
4652 tst = compare_values_warnv (vr->min, val, strict_overflow_p);
4653 if ((comp == LT_EXPR && (tst == 0 || tst == 1))
4654 || (comp == LE_EXPR && tst == 1))
4656 if (overflow_infinity_range_p (vr))
4657 *strict_overflow_p = true;
4658 return boolean_false_node;
4661 /* Otherwise, we don't know. */
4662 return NULL_TREE;
4664 else if (comp == GT_EXPR || comp == GE_EXPR)
4666 int tst;
4668 /* If VR is to the right of VAL, return true. */
4669 tst = compare_values_warnv (vr->min, val, strict_overflow_p);
4670 if ((comp == GT_EXPR && tst == 1)
4671 || (comp == GE_EXPR && (tst == 0 || tst == 1)))
4673 if (overflow_infinity_range_p (vr))
4674 *strict_overflow_p = true;
4675 return boolean_true_node;
4678 /* If VR is to the left of VAL, return false. */
4679 tst = compare_values_warnv (vr->max, val, strict_overflow_p);
4680 if ((comp == GT_EXPR && (tst == -1 || tst == 0))
4681 || (comp == GE_EXPR && tst == -1))
4683 if (overflow_infinity_range_p (vr))
4684 *strict_overflow_p = true;
4685 return boolean_false_node;
4688 /* Otherwise, we don't know. */
4689 return NULL_TREE;
4692 gcc_unreachable ();
4696 /* Debugging dumps. */
4698 void dump_value_range (FILE *, const value_range *);
4699 void debug_value_range (value_range *);
4700 void dump_all_value_ranges (FILE *);
4701 void debug_all_value_ranges (void);
4702 void dump_vr_equiv (FILE *, bitmap);
4703 void debug_vr_equiv (bitmap);
4706 /* Dump value range VR to FILE. */
4708 void
4709 dump_value_range (FILE *file, const value_range *vr)
4711 if (vr == NULL)
4712 fprintf (file, "[]");
4713 else if (vr->type == VR_UNDEFINED)
4714 fprintf (file, "UNDEFINED");
4715 else if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
4717 tree type = TREE_TYPE (vr->min);
4719 fprintf (file, "%s[", (vr->type == VR_ANTI_RANGE) ? "~" : "");
4721 if (is_negative_overflow_infinity (vr->min))
4722 fprintf (file, "-INF(OVF)");
4723 else if (INTEGRAL_TYPE_P (type)
4724 && !TYPE_UNSIGNED (type)
4725 && vrp_val_is_min (vr->min))
4726 fprintf (file, "-INF");
4727 else
4728 print_generic_expr (file, vr->min, 0);
4730 fprintf (file, ", ");
4732 if (is_positive_overflow_infinity (vr->max))
4733 fprintf (file, "+INF(OVF)");
4734 else if (INTEGRAL_TYPE_P (type)
4735 && vrp_val_is_max (vr->max))
4736 fprintf (file, "+INF");
4737 else
4738 print_generic_expr (file, vr->max, 0);
4740 fprintf (file, "]");
4742 if (vr->equiv)
4744 bitmap_iterator bi;
4745 unsigned i, c = 0;
4747 fprintf (file, " EQUIVALENCES: { ");
4749 EXECUTE_IF_SET_IN_BITMAP (vr->equiv, 0, i, bi)
4751 print_generic_expr (file, ssa_name (i), 0);
4752 fprintf (file, " ");
4753 c++;
4756 fprintf (file, "} (%u elements)", c);
4759 else if (vr->type == VR_VARYING)
4760 fprintf (file, "VARYING");
4761 else
4762 fprintf (file, "INVALID RANGE");
4766 /* Dump value range VR to stderr. */
4768 DEBUG_FUNCTION void
4769 debug_value_range (value_range *vr)
4771 dump_value_range (stderr, vr);
4772 fprintf (stderr, "\n");
4776 /* Dump value ranges of all SSA_NAMEs to FILE. */
4778 void
4779 dump_all_value_ranges (FILE *file)
4781 size_t i;
4783 for (i = 0; i < num_vr_values; i++)
4785 if (vr_value[i])
4787 print_generic_expr (file, ssa_name (i), 0);
4788 fprintf (file, ": ");
4789 dump_value_range (file, vr_value[i]);
4790 fprintf (file, "\n");
4794 fprintf (file, "\n");
4798 /* Dump all value ranges to stderr. */
4800 DEBUG_FUNCTION void
4801 debug_all_value_ranges (void)
4803 dump_all_value_ranges (stderr);
4807 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
4808 create a new SSA name N and return the assertion assignment
4809 'N = ASSERT_EXPR <V, V OP W>'. */
4811 static gimple *
4812 build_assert_expr_for (tree cond, tree v)
4814 tree a;
4815 gassign *assertion;
4817 gcc_assert (TREE_CODE (v) == SSA_NAME
4818 && COMPARISON_CLASS_P (cond));
4820 a = build2 (ASSERT_EXPR, TREE_TYPE (v), v, cond);
4821 assertion = gimple_build_assign (NULL_TREE, a);
4823 /* The new ASSERT_EXPR, creates a new SSA name that replaces the
4824 operand of the ASSERT_EXPR. Create it so the new name and the old one
4825 are registered in the replacement table so that we can fix the SSA web
4826 after adding all the ASSERT_EXPRs. */
4827 create_new_def_for (v, assertion, NULL);
4829 return assertion;
4833 /* Return false if EXPR is a predicate expression involving floating
4834 point values. */
4836 static inline bool
4837 fp_predicate (gimple *stmt)
4839 GIMPLE_CHECK (stmt, GIMPLE_COND);
4841 return FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)));
4844 /* If the range of values taken by OP can be inferred after STMT executes,
4845 return the comparison code (COMP_CODE_P) and value (VAL_P) that
4846 describes the inferred range. Return true if a range could be
4847 inferred. */
4849 static bool
4850 infer_value_range (gimple *stmt, tree op, tree_code *comp_code_p, tree *val_p)
4852 *val_p = NULL_TREE;
4853 *comp_code_p = ERROR_MARK;
4855 /* Do not attempt to infer anything in names that flow through
4856 abnormal edges. */
4857 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
4858 return false;
4860 /* If STMT is the last statement of a basic block with no normal
4861 successors, there is no point inferring anything about any of its
4862 operands. We would not be able to find a proper insertion point
4863 for the assertion, anyway. */
4864 if (stmt_ends_bb_p (stmt))
4866 edge_iterator ei;
4867 edge e;
4869 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
4870 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
4871 break;
4872 if (e == NULL)
4873 return false;
4876 if (infer_nonnull_range (stmt, op))
4878 *val_p = build_int_cst (TREE_TYPE (op), 0);
4879 *comp_code_p = NE_EXPR;
4880 return true;
4883 return false;
4887 void dump_asserts_for (FILE *, tree);
4888 void debug_asserts_for (tree);
4889 void dump_all_asserts (FILE *);
4890 void debug_all_asserts (void);
4892 /* Dump all the registered assertions for NAME to FILE. */
4894 void
4895 dump_asserts_for (FILE *file, tree name)
4897 assert_locus *loc;
4899 fprintf (file, "Assertions to be inserted for ");
4900 print_generic_expr (file, name, 0);
4901 fprintf (file, "\n");
4903 loc = asserts_for[SSA_NAME_VERSION (name)];
4904 while (loc)
4906 fprintf (file, "\t");
4907 print_gimple_stmt (file, gsi_stmt (loc->si), 0, 0);
4908 fprintf (file, "\n\tBB #%d", loc->bb->index);
4909 if (loc->e)
4911 fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
4912 loc->e->dest->index);
4913 dump_edge_info (file, loc->e, dump_flags, 0);
4915 fprintf (file, "\n\tPREDICATE: ");
4916 print_generic_expr (file, loc->expr, 0);
4917 fprintf (file, " %s ", get_tree_code_name (loc->comp_code));
4918 print_generic_expr (file, loc->val, 0);
4919 fprintf (file, "\n\n");
4920 loc = loc->next;
4923 fprintf (file, "\n");
4927 /* Dump all the registered assertions for NAME to stderr. */
4929 DEBUG_FUNCTION void
4930 debug_asserts_for (tree name)
4932 dump_asserts_for (stderr, name);
4936 /* Dump all the registered assertions for all the names to FILE. */
4938 void
4939 dump_all_asserts (FILE *file)
4941 unsigned i;
4942 bitmap_iterator bi;
4944 fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
4945 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
4946 dump_asserts_for (file, ssa_name (i));
4947 fprintf (file, "\n");
4951 /* Dump all the registered assertions for all the names to stderr. */
4953 DEBUG_FUNCTION void
4954 debug_all_asserts (void)
4956 dump_all_asserts (stderr);
4960 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
4961 'EXPR COMP_CODE VAL' at a location that dominates block BB or
4962 E->DEST, then register this location as a possible insertion point
4963 for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
4965 BB, E and SI provide the exact insertion point for the new
4966 ASSERT_EXPR. If BB is NULL, then the ASSERT_EXPR is to be inserted
4967 on edge E. Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
4968 BB. If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
4969 must not be NULL. */
4971 static void
4972 register_new_assert_for (tree name, tree expr,
4973 enum tree_code comp_code,
4974 tree val,
4975 basic_block bb,
4976 edge e,
4977 gimple_stmt_iterator si)
4979 assert_locus *n, *loc, *last_loc;
4980 basic_block dest_bb;
4982 gcc_checking_assert (bb == NULL || e == NULL);
4984 if (e == NULL)
4985 gcc_checking_assert (gimple_code (gsi_stmt (si)) != GIMPLE_COND
4986 && gimple_code (gsi_stmt (si)) != GIMPLE_SWITCH);
4988 /* Never build an assert comparing against an integer constant with
4989 TREE_OVERFLOW set. This confuses our undefined overflow warning
4990 machinery. */
4991 if (TREE_OVERFLOW_P (val))
4992 val = drop_tree_overflow (val);
4994 /* The new assertion A will be inserted at BB or E. We need to
4995 determine if the new location is dominated by a previously
4996 registered location for A. If we are doing an edge insertion,
4997 assume that A will be inserted at E->DEST. Note that this is not
4998 necessarily true.
5000 If E is a critical edge, it will be split. But even if E is
5001 split, the new block will dominate the same set of blocks that
5002 E->DEST dominates.
5004 The reverse, however, is not true, blocks dominated by E->DEST
5005 will not be dominated by the new block created to split E. So,
5006 if the insertion location is on a critical edge, we will not use
5007 the new location to move another assertion previously registered
5008 at a block dominated by E->DEST. */
5009 dest_bb = (bb) ? bb : e->dest;
5011 /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
5012 VAL at a block dominating DEST_BB, then we don't need to insert a new
5013 one. Similarly, if the same assertion already exists at a block
5014 dominated by DEST_BB and the new location is not on a critical
5015 edge, then update the existing location for the assertion (i.e.,
5016 move the assertion up in the dominance tree).
5018 Note, this is implemented as a simple linked list because there
5019 should not be more than a handful of assertions registered per
5020 name. If this becomes a performance problem, a table hashed by
5021 COMP_CODE and VAL could be implemented. */
5022 loc = asserts_for[SSA_NAME_VERSION (name)];
5023 last_loc = loc;
5024 while (loc)
5026 if (loc->comp_code == comp_code
5027 && (loc->val == val
5028 || operand_equal_p (loc->val, val, 0))
5029 && (loc->expr == expr
5030 || operand_equal_p (loc->expr, expr, 0)))
5032 /* If E is not a critical edge and DEST_BB
5033 dominates the existing location for the assertion, move
5034 the assertion up in the dominance tree by updating its
5035 location information. */
5036 if ((e == NULL || !EDGE_CRITICAL_P (e))
5037 && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
5039 loc->bb = dest_bb;
5040 loc->e = e;
5041 loc->si = si;
5042 return;
5046 /* Update the last node of the list and move to the next one. */
5047 last_loc = loc;
5048 loc = loc->next;
5051 /* If we didn't find an assertion already registered for
5052 NAME COMP_CODE VAL, add a new one at the end of the list of
5053 assertions associated with NAME. */
5054 n = XNEW (struct assert_locus);
5055 n->bb = dest_bb;
5056 n->e = e;
5057 n->si = si;
5058 n->comp_code = comp_code;
5059 n->val = val;
5060 n->expr = expr;
5061 n->next = NULL;
5063 if (last_loc)
5064 last_loc->next = n;
5065 else
5066 asserts_for[SSA_NAME_VERSION (name)] = n;
5068 bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
5071 /* (COND_OP0 COND_CODE COND_OP1) is a predicate which uses NAME.
5072 Extract a suitable test code and value and store them into *CODE_P and
5073 *VAL_P so the predicate is normalized to NAME *CODE_P *VAL_P.
5075 If no extraction was possible, return FALSE, otherwise return TRUE.
5077 If INVERT is true, then we invert the result stored into *CODE_P. */
5079 static bool
5080 extract_code_and_val_from_cond_with_ops (tree name, enum tree_code cond_code,
5081 tree cond_op0, tree cond_op1,
5082 bool invert, enum tree_code *code_p,
5083 tree *val_p)
5085 enum tree_code comp_code;
5086 tree val;
5088 /* Otherwise, we have a comparison of the form NAME COMP VAL
5089 or VAL COMP NAME. */
5090 if (name == cond_op1)
5092 /* If the predicate is of the form VAL COMP NAME, flip
5093 COMP around because we need to register NAME as the
5094 first operand in the predicate. */
5095 comp_code = swap_tree_comparison (cond_code);
5096 val = cond_op0;
5098 else if (name == cond_op0)
5100 /* The comparison is of the form NAME COMP VAL, so the
5101 comparison code remains unchanged. */
5102 comp_code = cond_code;
5103 val = cond_op1;
5105 else
5106 gcc_unreachable ();
5108 /* Invert the comparison code as necessary. */
5109 if (invert)
5110 comp_code = invert_tree_comparison (comp_code, 0);
5112 /* VRP only handles integral and pointer types. */
5113 if (! INTEGRAL_TYPE_P (TREE_TYPE (val))
5114 && ! POINTER_TYPE_P (TREE_TYPE (val)))
5115 return false;
5117 /* Do not register always-false predicates.
5118 FIXME: this works around a limitation in fold() when dealing with
5119 enumerations. Given 'enum { N1, N2 } x;', fold will not
5120 fold 'if (x > N2)' to 'if (0)'. */
5121 if ((comp_code == GT_EXPR || comp_code == LT_EXPR)
5122 && INTEGRAL_TYPE_P (TREE_TYPE (val)))
5124 tree min = TYPE_MIN_VALUE (TREE_TYPE (val));
5125 tree max = TYPE_MAX_VALUE (TREE_TYPE (val));
5127 if (comp_code == GT_EXPR
5128 && (!max
5129 || compare_values (val, max) == 0))
5130 return false;
5132 if (comp_code == LT_EXPR
5133 && (!min
5134 || compare_values (val, min) == 0))
5135 return false;
5137 *code_p = comp_code;
5138 *val_p = val;
5139 return true;
5142 /* Find out smallest RES where RES > VAL && (RES & MASK) == RES, if any
5143 (otherwise return VAL). VAL and MASK must be zero-extended for
5144 precision PREC. If SGNBIT is non-zero, first xor VAL with SGNBIT
5145 (to transform signed values into unsigned) and at the end xor
5146 SGNBIT back. */
5148 static wide_int
5149 masked_increment (const wide_int &val_in, const wide_int &mask,
5150 const wide_int &sgnbit, unsigned int prec)
5152 wide_int bit = wi::one (prec), res;
5153 unsigned int i;
5155 wide_int val = val_in ^ sgnbit;
5156 for (i = 0; i < prec; i++, bit += bit)
5158 res = mask;
5159 if ((res & bit) == 0)
5160 continue;
5161 res = bit - 1;
5162 res = (val + bit).and_not (res);
5163 res &= mask;
5164 if (wi::gtu_p (res, val))
5165 return res ^ sgnbit;
5167 return val ^ sgnbit;
5170 /* Try to register an edge assertion for SSA name NAME on edge E for
5171 the condition COND contributing to the conditional jump pointed to by BSI.
5172 Invert the condition COND if INVERT is true. */
5174 static void
5175 register_edge_assert_for_2 (tree name, edge e, gimple_stmt_iterator bsi,
5176 enum tree_code cond_code,
5177 tree cond_op0, tree cond_op1, bool invert)
5179 tree val;
5180 enum tree_code comp_code;
5182 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
5183 cond_op0,
5184 cond_op1,
5185 invert, &comp_code, &val))
5186 return;
5188 /* Only register an ASSERT_EXPR if NAME was found in the sub-graph
5189 reachable from E. */
5190 if (live_on_edge (e, name))
5191 register_new_assert_for (name, name, comp_code, val, NULL, e, bsi);
5193 /* In the case of NAME <= CST and NAME being defined as
5194 NAME = (unsigned) NAME2 + CST2 we can assert NAME2 >= -CST2
5195 and NAME2 <= CST - CST2. We can do the same for NAME > CST.
5196 This catches range and anti-range tests. */
5197 if ((comp_code == LE_EXPR
5198 || comp_code == GT_EXPR)
5199 && TREE_CODE (val) == INTEGER_CST
5200 && TYPE_UNSIGNED (TREE_TYPE (val)))
5202 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5203 tree cst2 = NULL_TREE, name2 = NULL_TREE, name3 = NULL_TREE;
5205 /* Extract CST2 from the (optional) addition. */
5206 if (is_gimple_assign (def_stmt)
5207 && gimple_assign_rhs_code (def_stmt) == PLUS_EXPR)
5209 name2 = gimple_assign_rhs1 (def_stmt);
5210 cst2 = gimple_assign_rhs2 (def_stmt);
5211 if (TREE_CODE (name2) == SSA_NAME
5212 && TREE_CODE (cst2) == INTEGER_CST)
5213 def_stmt = SSA_NAME_DEF_STMT (name2);
5216 /* Extract NAME2 from the (optional) sign-changing cast. */
5217 if (gimple_assign_cast_p (def_stmt))
5219 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt))
5220 && ! TYPE_UNSIGNED (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
5221 && (TYPE_PRECISION (gimple_expr_type (def_stmt))
5222 == TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))))
5223 name3 = gimple_assign_rhs1 (def_stmt);
5226 /* If name3 is used later, create an ASSERT_EXPR for it. */
5227 if (name3 != NULL_TREE
5228 && TREE_CODE (name3) == SSA_NAME
5229 && (cst2 == NULL_TREE
5230 || TREE_CODE (cst2) == INTEGER_CST)
5231 && INTEGRAL_TYPE_P (TREE_TYPE (name3))
5232 && live_on_edge (e, name3))
5234 tree tmp;
5236 /* Build an expression for the range test. */
5237 tmp = build1 (NOP_EXPR, TREE_TYPE (name), name3);
5238 if (cst2 != NULL_TREE)
5239 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
5241 if (dump_file)
5243 fprintf (dump_file, "Adding assert for ");
5244 print_generic_expr (dump_file, name3, 0);
5245 fprintf (dump_file, " from ");
5246 print_generic_expr (dump_file, tmp, 0);
5247 fprintf (dump_file, "\n");
5250 register_new_assert_for (name3, tmp, comp_code, val, NULL, e, bsi);
5253 /* If name2 is used later, create an ASSERT_EXPR for it. */
5254 if (name2 != NULL_TREE
5255 && TREE_CODE (name2) == SSA_NAME
5256 && TREE_CODE (cst2) == INTEGER_CST
5257 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
5258 && live_on_edge (e, name2))
5260 tree tmp;
5262 /* Build an expression for the range test. */
5263 tmp = name2;
5264 if (TREE_TYPE (name) != TREE_TYPE (name2))
5265 tmp = build1 (NOP_EXPR, TREE_TYPE (name), tmp);
5266 if (cst2 != NULL_TREE)
5267 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
5269 if (dump_file)
5271 fprintf (dump_file, "Adding assert for ");
5272 print_generic_expr (dump_file, name2, 0);
5273 fprintf (dump_file, " from ");
5274 print_generic_expr (dump_file, tmp, 0);
5275 fprintf (dump_file, "\n");
5278 register_new_assert_for (name2, tmp, comp_code, val, NULL, e, bsi);
5282 /* In the case of post-in/decrement tests like if (i++) ... and uses
5283 of the in/decremented value on the edge the extra name we want to
5284 assert for is not on the def chain of the name compared. Instead
5285 it is in the set of use stmts.
5286 Similar cases happen for conversions that were simplified through
5287 fold_{sign_changed,widened}_comparison. */
5288 if ((comp_code == NE_EXPR
5289 || comp_code == EQ_EXPR)
5290 && TREE_CODE (val) == INTEGER_CST)
5292 imm_use_iterator ui;
5293 gimple *use_stmt;
5294 FOR_EACH_IMM_USE_STMT (use_stmt, ui, name)
5296 if (!is_gimple_assign (use_stmt))
5297 continue;
5299 /* Cut off to use-stmts that are dominating the predecessor. */
5300 if (!dominated_by_p (CDI_DOMINATORS, e->src, gimple_bb (use_stmt)))
5301 continue;
5303 tree name2 = gimple_assign_lhs (use_stmt);
5304 if (TREE_CODE (name2) != SSA_NAME
5305 || !live_on_edge (e, name2))
5306 continue;
5308 enum tree_code code = gimple_assign_rhs_code (use_stmt);
5309 tree cst;
5310 if (code == PLUS_EXPR
5311 || code == MINUS_EXPR)
5313 cst = gimple_assign_rhs2 (use_stmt);
5314 if (TREE_CODE (cst) != INTEGER_CST)
5315 continue;
5316 cst = int_const_binop (code, val, cst);
5318 else if (CONVERT_EXPR_CODE_P (code))
5320 /* For truncating conversions we cannot record
5321 an inequality. */
5322 if (comp_code == NE_EXPR
5323 && (TYPE_PRECISION (TREE_TYPE (name2))
5324 < TYPE_PRECISION (TREE_TYPE (name))))
5325 continue;
5326 cst = fold_convert (TREE_TYPE (name2), val);
5328 else
5329 continue;
5331 if (TREE_OVERFLOW_P (cst))
5332 cst = drop_tree_overflow (cst);
5333 register_new_assert_for (name2, name2, comp_code, cst,
5334 NULL, e, bsi);
5338 if (TREE_CODE_CLASS (comp_code) == tcc_comparison
5339 && TREE_CODE (val) == INTEGER_CST)
5341 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5342 tree name2 = NULL_TREE, names[2], cst2 = NULL_TREE;
5343 tree val2 = NULL_TREE;
5344 unsigned int prec = TYPE_PRECISION (TREE_TYPE (val));
5345 wide_int mask = wi::zero (prec);
5346 unsigned int nprec = prec;
5347 enum tree_code rhs_code = ERROR_MARK;
5349 if (is_gimple_assign (def_stmt))
5350 rhs_code = gimple_assign_rhs_code (def_stmt);
5352 /* In the case of NAME != CST1 where NAME = A +- CST2 we can
5353 assert that A != CST1 -+ CST2. */
5354 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
5355 && (rhs_code == PLUS_EXPR || rhs_code == MINUS_EXPR))
5357 tree op0 = gimple_assign_rhs1 (def_stmt);
5358 tree op1 = gimple_assign_rhs2 (def_stmt);
5359 if (TREE_CODE (op0) == SSA_NAME
5360 && TREE_CODE (op1) == INTEGER_CST
5361 && live_on_edge (e, op0))
5363 enum tree_code reverse_op = (rhs_code == PLUS_EXPR
5364 ? MINUS_EXPR : PLUS_EXPR);
5365 op1 = int_const_binop (reverse_op, val, op1);
5366 if (TREE_OVERFLOW (op1))
5367 op1 = drop_tree_overflow (op1);
5368 register_new_assert_for (op0, op0, comp_code, op1, NULL, e, bsi);
5372 /* Add asserts for NAME cmp CST and NAME being defined
5373 as NAME = (int) NAME2. */
5374 if (!TYPE_UNSIGNED (TREE_TYPE (val))
5375 && (comp_code == LE_EXPR || comp_code == LT_EXPR
5376 || comp_code == GT_EXPR || comp_code == GE_EXPR)
5377 && gimple_assign_cast_p (def_stmt))
5379 name2 = gimple_assign_rhs1 (def_stmt);
5380 if (CONVERT_EXPR_CODE_P (rhs_code)
5381 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
5382 && TYPE_UNSIGNED (TREE_TYPE (name2))
5383 && prec == TYPE_PRECISION (TREE_TYPE (name2))
5384 && (comp_code == LE_EXPR || comp_code == GT_EXPR
5385 || !tree_int_cst_equal (val,
5386 TYPE_MIN_VALUE (TREE_TYPE (val))))
5387 && live_on_edge (e, name2))
5389 tree tmp, cst;
5390 enum tree_code new_comp_code = comp_code;
5392 cst = fold_convert (TREE_TYPE (name2),
5393 TYPE_MIN_VALUE (TREE_TYPE (val)));
5394 /* Build an expression for the range test. */
5395 tmp = build2 (PLUS_EXPR, TREE_TYPE (name2), name2, cst);
5396 cst = fold_build2 (PLUS_EXPR, TREE_TYPE (name2), cst,
5397 fold_convert (TREE_TYPE (name2), val));
5398 if (comp_code == LT_EXPR || comp_code == GE_EXPR)
5400 new_comp_code = comp_code == LT_EXPR ? LE_EXPR : GT_EXPR;
5401 cst = fold_build2 (MINUS_EXPR, TREE_TYPE (name2), cst,
5402 build_int_cst (TREE_TYPE (name2), 1));
5405 if (dump_file)
5407 fprintf (dump_file, "Adding assert for ");
5408 print_generic_expr (dump_file, name2, 0);
5409 fprintf (dump_file, " from ");
5410 print_generic_expr (dump_file, tmp, 0);
5411 fprintf (dump_file, "\n");
5414 register_new_assert_for (name2, tmp, new_comp_code, cst, NULL,
5415 e, bsi);
5419 /* Add asserts for NAME cmp CST and NAME being defined as
5420 NAME = NAME2 >> CST2.
5422 Extract CST2 from the right shift. */
5423 if (rhs_code == RSHIFT_EXPR)
5425 name2 = gimple_assign_rhs1 (def_stmt);
5426 cst2 = gimple_assign_rhs2 (def_stmt);
5427 if (TREE_CODE (name2) == SSA_NAME
5428 && tree_fits_uhwi_p (cst2)
5429 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
5430 && IN_RANGE (tree_to_uhwi (cst2), 1, prec - 1)
5431 && prec == GET_MODE_PRECISION (TYPE_MODE (TREE_TYPE (val)))
5432 && live_on_edge (e, name2))
5434 mask = wi::mask (tree_to_uhwi (cst2), false, prec);
5435 val2 = fold_binary (LSHIFT_EXPR, TREE_TYPE (val), val, cst2);
5438 if (val2 != NULL_TREE
5439 && TREE_CODE (val2) == INTEGER_CST
5440 && simple_cst_equal (fold_build2 (RSHIFT_EXPR,
5441 TREE_TYPE (val),
5442 val2, cst2), val))
5444 enum tree_code new_comp_code = comp_code;
5445 tree tmp, new_val;
5447 tmp = name2;
5448 if (comp_code == EQ_EXPR || comp_code == NE_EXPR)
5450 if (!TYPE_UNSIGNED (TREE_TYPE (val)))
5452 tree type = build_nonstandard_integer_type (prec, 1);
5453 tmp = build1 (NOP_EXPR, type, name2);
5454 val2 = fold_convert (type, val2);
5456 tmp = fold_build2 (MINUS_EXPR, TREE_TYPE (tmp), tmp, val2);
5457 new_val = wide_int_to_tree (TREE_TYPE (tmp), mask);
5458 new_comp_code = comp_code == EQ_EXPR ? LE_EXPR : GT_EXPR;
5460 else if (comp_code == LT_EXPR || comp_code == GE_EXPR)
5462 wide_int minval
5463 = wi::min_value (prec, TYPE_SIGN (TREE_TYPE (val)));
5464 new_val = val2;
5465 if (minval == new_val)
5466 new_val = NULL_TREE;
5468 else
5470 wide_int maxval
5471 = wi::max_value (prec, TYPE_SIGN (TREE_TYPE (val)));
5472 mask |= val2;
5473 if (mask == maxval)
5474 new_val = NULL_TREE;
5475 else
5476 new_val = wide_int_to_tree (TREE_TYPE (val2), mask);
5479 if (new_val)
5481 if (dump_file)
5483 fprintf (dump_file, "Adding assert for ");
5484 print_generic_expr (dump_file, name2, 0);
5485 fprintf (dump_file, " from ");
5486 print_generic_expr (dump_file, tmp, 0);
5487 fprintf (dump_file, "\n");
5490 register_new_assert_for (name2, tmp, new_comp_code, new_val,
5491 NULL, e, bsi);
5495 /* Add asserts for NAME cmp CST and NAME being defined as
5496 NAME = NAME2 & CST2.
5498 Extract CST2 from the and.
5500 Also handle
5501 NAME = (unsigned) NAME2;
5502 casts where NAME's type is unsigned and has smaller precision
5503 than NAME2's type as if it was NAME = NAME2 & MASK. */
5504 names[0] = NULL_TREE;
5505 names[1] = NULL_TREE;
5506 cst2 = NULL_TREE;
5507 if (rhs_code == BIT_AND_EXPR
5508 || (CONVERT_EXPR_CODE_P (rhs_code)
5509 && INTEGRAL_TYPE_P (TREE_TYPE (val))
5510 && TYPE_UNSIGNED (TREE_TYPE (val))
5511 && TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
5512 > prec))
5514 name2 = gimple_assign_rhs1 (def_stmt);
5515 if (rhs_code == BIT_AND_EXPR)
5516 cst2 = gimple_assign_rhs2 (def_stmt);
5517 else
5519 cst2 = TYPE_MAX_VALUE (TREE_TYPE (val));
5520 nprec = TYPE_PRECISION (TREE_TYPE (name2));
5522 if (TREE_CODE (name2) == SSA_NAME
5523 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
5524 && TREE_CODE (cst2) == INTEGER_CST
5525 && !integer_zerop (cst2)
5526 && (nprec > 1
5527 || TYPE_UNSIGNED (TREE_TYPE (val))))
5529 gimple *def_stmt2 = SSA_NAME_DEF_STMT (name2);
5530 if (gimple_assign_cast_p (def_stmt2))
5532 names[1] = gimple_assign_rhs1 (def_stmt2);
5533 if (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt2))
5534 || !INTEGRAL_TYPE_P (TREE_TYPE (names[1]))
5535 || (TYPE_PRECISION (TREE_TYPE (name2))
5536 != TYPE_PRECISION (TREE_TYPE (names[1])))
5537 || !live_on_edge (e, names[1]))
5538 names[1] = NULL_TREE;
5540 if (live_on_edge (e, name2))
5541 names[0] = name2;
5544 if (names[0] || names[1])
5546 wide_int minv, maxv, valv, cst2v;
5547 wide_int tem, sgnbit;
5548 bool valid_p = false, valn, cst2n;
5549 enum tree_code ccode = comp_code;
5551 valv = wide_int::from (val, nprec, UNSIGNED);
5552 cst2v = wide_int::from (cst2, nprec, UNSIGNED);
5553 valn = wi::neg_p (valv, TYPE_SIGN (TREE_TYPE (val)));
5554 cst2n = wi::neg_p (cst2v, TYPE_SIGN (TREE_TYPE (val)));
5555 /* If CST2 doesn't have most significant bit set,
5556 but VAL is negative, we have comparison like
5557 if ((x & 0x123) > -4) (always true). Just give up. */
5558 if (!cst2n && valn)
5559 ccode = ERROR_MARK;
5560 if (cst2n)
5561 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
5562 else
5563 sgnbit = wi::zero (nprec);
5564 minv = valv & cst2v;
5565 switch (ccode)
5567 case EQ_EXPR:
5568 /* Minimum unsigned value for equality is VAL & CST2
5569 (should be equal to VAL, otherwise we probably should
5570 have folded the comparison into false) and
5571 maximum unsigned value is VAL | ~CST2. */
5572 maxv = valv | ~cst2v;
5573 valid_p = true;
5574 break;
5576 case NE_EXPR:
5577 tem = valv | ~cst2v;
5578 /* If VAL is 0, handle (X & CST2) != 0 as (X & CST2) > 0U. */
5579 if (valv == 0)
5581 cst2n = false;
5582 sgnbit = wi::zero (nprec);
5583 goto gt_expr;
5585 /* If (VAL | ~CST2) is all ones, handle it as
5586 (X & CST2) < VAL. */
5587 if (tem == -1)
5589 cst2n = false;
5590 valn = false;
5591 sgnbit = wi::zero (nprec);
5592 goto lt_expr;
5594 if (!cst2n && wi::neg_p (cst2v))
5595 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
5596 if (sgnbit != 0)
5598 if (valv == sgnbit)
5600 cst2n = true;
5601 valn = true;
5602 goto gt_expr;
5604 if (tem == wi::mask (nprec - 1, false, nprec))
5606 cst2n = true;
5607 goto lt_expr;
5609 if (!cst2n)
5610 sgnbit = wi::zero (nprec);
5612 break;
5614 case GE_EXPR:
5615 /* Minimum unsigned value for >= if (VAL & CST2) == VAL
5616 is VAL and maximum unsigned value is ~0. For signed
5617 comparison, if CST2 doesn't have most significant bit
5618 set, handle it similarly. If CST2 has MSB set,
5619 the minimum is the same, and maximum is ~0U/2. */
5620 if (minv != valv)
5622 /* If (VAL & CST2) != VAL, X & CST2 can't be equal to
5623 VAL. */
5624 minv = masked_increment (valv, cst2v, sgnbit, nprec);
5625 if (minv == valv)
5626 break;
5628 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
5629 valid_p = true;
5630 break;
5632 case GT_EXPR:
5633 gt_expr:
5634 /* Find out smallest MINV where MINV > VAL
5635 && (MINV & CST2) == MINV, if any. If VAL is signed and
5636 CST2 has MSB set, compute it biased by 1 << (nprec - 1). */
5637 minv = masked_increment (valv, cst2v, sgnbit, nprec);
5638 if (minv == valv)
5639 break;
5640 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
5641 valid_p = true;
5642 break;
5644 case LE_EXPR:
5645 /* Minimum unsigned value for <= is 0 and maximum
5646 unsigned value is VAL | ~CST2 if (VAL & CST2) == VAL.
5647 Otherwise, find smallest VAL2 where VAL2 > VAL
5648 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
5649 as maximum.
5650 For signed comparison, if CST2 doesn't have most
5651 significant bit set, handle it similarly. If CST2 has
5652 MSB set, the maximum is the same and minimum is INT_MIN. */
5653 if (minv == valv)
5654 maxv = valv;
5655 else
5657 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
5658 if (maxv == valv)
5659 break;
5660 maxv -= 1;
5662 maxv |= ~cst2v;
5663 minv = sgnbit;
5664 valid_p = true;
5665 break;
5667 case LT_EXPR:
5668 lt_expr:
5669 /* Minimum unsigned value for < is 0 and maximum
5670 unsigned value is (VAL-1) | ~CST2 if (VAL & CST2) == VAL.
5671 Otherwise, find smallest VAL2 where VAL2 > VAL
5672 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
5673 as maximum.
5674 For signed comparison, if CST2 doesn't have most
5675 significant bit set, handle it similarly. If CST2 has
5676 MSB set, the maximum is the same and minimum is INT_MIN. */
5677 if (minv == valv)
5679 if (valv == sgnbit)
5680 break;
5681 maxv = valv;
5683 else
5685 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
5686 if (maxv == valv)
5687 break;
5689 maxv -= 1;
5690 maxv |= ~cst2v;
5691 minv = sgnbit;
5692 valid_p = true;
5693 break;
5695 default:
5696 break;
5698 if (valid_p
5699 && (maxv - minv) != -1)
5701 tree tmp, new_val, type;
5702 int i;
5704 for (i = 0; i < 2; i++)
5705 if (names[i])
5707 wide_int maxv2 = maxv;
5708 tmp = names[i];
5709 type = TREE_TYPE (names[i]);
5710 if (!TYPE_UNSIGNED (type))
5712 type = build_nonstandard_integer_type (nprec, 1);
5713 tmp = build1 (NOP_EXPR, type, names[i]);
5715 if (minv != 0)
5717 tmp = build2 (PLUS_EXPR, type, tmp,
5718 wide_int_to_tree (type, -minv));
5719 maxv2 = maxv - minv;
5721 new_val = wide_int_to_tree (type, maxv2);
5723 if (dump_file)
5725 fprintf (dump_file, "Adding assert for ");
5726 print_generic_expr (dump_file, names[i], 0);
5727 fprintf (dump_file, " from ");
5728 print_generic_expr (dump_file, tmp, 0);
5729 fprintf (dump_file, "\n");
5732 register_new_assert_for (names[i], tmp, LE_EXPR,
5733 new_val, NULL, e, bsi);
5740 /* OP is an operand of a truth value expression which is known to have
5741 a particular value. Register any asserts for OP and for any
5742 operands in OP's defining statement.
5744 If CODE is EQ_EXPR, then we want to register OP is zero (false),
5745 if CODE is NE_EXPR, then we want to register OP is nonzero (true). */
5747 static void
5748 register_edge_assert_for_1 (tree op, enum tree_code code,
5749 edge e, gimple_stmt_iterator bsi)
5751 gimple *op_def;
5752 tree val;
5753 enum tree_code rhs_code;
5755 /* We only care about SSA_NAMEs. */
5756 if (TREE_CODE (op) != SSA_NAME)
5757 return;
5759 /* We know that OP will have a zero or nonzero value. If OP is used
5760 more than once go ahead and register an assert for OP. */
5761 if (live_on_edge (e, op))
5763 val = build_int_cst (TREE_TYPE (op), 0);
5764 register_new_assert_for (op, op, code, val, NULL, e, bsi);
5767 /* Now look at how OP is set. If it's set from a comparison,
5768 a truth operation or some bit operations, then we may be able
5769 to register information about the operands of that assignment. */
5770 op_def = SSA_NAME_DEF_STMT (op);
5771 if (gimple_code (op_def) != GIMPLE_ASSIGN)
5772 return;
5774 rhs_code = gimple_assign_rhs_code (op_def);
5776 if (TREE_CODE_CLASS (rhs_code) == tcc_comparison)
5778 bool invert = (code == EQ_EXPR ? true : false);
5779 tree op0 = gimple_assign_rhs1 (op_def);
5780 tree op1 = gimple_assign_rhs2 (op_def);
5782 if (TREE_CODE (op0) == SSA_NAME)
5783 register_edge_assert_for_2 (op0, e, bsi, rhs_code, op0, op1, invert);
5784 if (TREE_CODE (op1) == SSA_NAME)
5785 register_edge_assert_for_2 (op1, e, bsi, rhs_code, op0, op1, invert);
5787 else if ((code == NE_EXPR
5788 && gimple_assign_rhs_code (op_def) == BIT_AND_EXPR)
5789 || (code == EQ_EXPR
5790 && gimple_assign_rhs_code (op_def) == BIT_IOR_EXPR))
5792 /* Recurse on each operand. */
5793 tree op0 = gimple_assign_rhs1 (op_def);
5794 tree op1 = gimple_assign_rhs2 (op_def);
5795 if (TREE_CODE (op0) == SSA_NAME
5796 && has_single_use (op0))
5797 register_edge_assert_for_1 (op0, code, e, bsi);
5798 if (TREE_CODE (op1) == SSA_NAME
5799 && has_single_use (op1))
5800 register_edge_assert_for_1 (op1, code, e, bsi);
5802 else if (gimple_assign_rhs_code (op_def) == BIT_NOT_EXPR
5803 && TYPE_PRECISION (TREE_TYPE (gimple_assign_lhs (op_def))) == 1)
5805 /* Recurse, flipping CODE. */
5806 code = invert_tree_comparison (code, false);
5807 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, bsi);
5809 else if (gimple_assign_rhs_code (op_def) == SSA_NAME)
5811 /* Recurse through the copy. */
5812 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, bsi);
5814 else if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (op_def)))
5816 /* Recurse through the type conversion, unless it is a narrowing
5817 conversion or conversion from non-integral type. */
5818 tree rhs = gimple_assign_rhs1 (op_def);
5819 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs))
5820 && (TYPE_PRECISION (TREE_TYPE (rhs))
5821 <= TYPE_PRECISION (TREE_TYPE (op))))
5822 register_edge_assert_for_1 (rhs, code, e, bsi);
5826 /* Try to register an edge assertion for SSA name NAME on edge E for
5827 the condition COND contributing to the conditional jump pointed to by
5828 SI. */
5830 static void
5831 register_edge_assert_for (tree name, edge e, gimple_stmt_iterator si,
5832 enum tree_code cond_code, tree cond_op0,
5833 tree cond_op1)
5835 tree val;
5836 enum tree_code comp_code;
5837 bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
5839 /* Do not attempt to infer anything in names that flow through
5840 abnormal edges. */
5841 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
5842 return;
5844 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
5845 cond_op0, cond_op1,
5846 is_else_edge,
5847 &comp_code, &val))
5848 return;
5850 /* Register ASSERT_EXPRs for name. */
5851 register_edge_assert_for_2 (name, e, si, cond_code, cond_op0,
5852 cond_op1, is_else_edge);
5855 /* If COND is effectively an equality test of an SSA_NAME against
5856 the value zero or one, then we may be able to assert values
5857 for SSA_NAMEs which flow into COND. */
5859 /* In the case of NAME == 1 or NAME != 0, for BIT_AND_EXPR defining
5860 statement of NAME we can assert both operands of the BIT_AND_EXPR
5861 have nonzero value. */
5862 if (((comp_code == EQ_EXPR && integer_onep (val))
5863 || (comp_code == NE_EXPR && integer_zerop (val))))
5865 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5867 if (is_gimple_assign (def_stmt)
5868 && gimple_assign_rhs_code (def_stmt) == BIT_AND_EXPR)
5870 tree op0 = gimple_assign_rhs1 (def_stmt);
5871 tree op1 = gimple_assign_rhs2 (def_stmt);
5872 register_edge_assert_for_1 (op0, NE_EXPR, e, si);
5873 register_edge_assert_for_1 (op1, NE_EXPR, e, si);
5877 /* In the case of NAME == 0 or NAME != 1, for BIT_IOR_EXPR defining
5878 statement of NAME we can assert both operands of the BIT_IOR_EXPR
5879 have zero value. */
5880 if (((comp_code == EQ_EXPR && integer_zerop (val))
5881 || (comp_code == NE_EXPR && integer_onep (val))))
5883 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5885 /* For BIT_IOR_EXPR only if NAME == 0 both operands have
5886 necessarily zero value, or if type-precision is one. */
5887 if (is_gimple_assign (def_stmt)
5888 && (gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR
5889 && (TYPE_PRECISION (TREE_TYPE (name)) == 1
5890 || comp_code == EQ_EXPR)))
5892 tree op0 = gimple_assign_rhs1 (def_stmt);
5893 tree op1 = gimple_assign_rhs2 (def_stmt);
5894 register_edge_assert_for_1 (op0, EQ_EXPR, e, si);
5895 register_edge_assert_for_1 (op1, EQ_EXPR, e, si);
5901 /* Determine whether the outgoing edges of BB should receive an
5902 ASSERT_EXPR for each of the operands of BB's LAST statement.
5903 The last statement of BB must be a COND_EXPR.
5905 If any of the sub-graphs rooted at BB have an interesting use of
5906 the predicate operands, an assert location node is added to the
5907 list of assertions for the corresponding operands. */
5909 static void
5910 find_conditional_asserts (basic_block bb, gcond *last)
5912 gimple_stmt_iterator bsi;
5913 tree op;
5914 edge_iterator ei;
5915 edge e;
5916 ssa_op_iter iter;
5918 bsi = gsi_for_stmt (last);
5920 /* Look for uses of the operands in each of the sub-graphs
5921 rooted at BB. We need to check each of the outgoing edges
5922 separately, so that we know what kind of ASSERT_EXPR to
5923 insert. */
5924 FOR_EACH_EDGE (e, ei, bb->succs)
5926 if (e->dest == bb)
5927 continue;
5929 /* Register the necessary assertions for each operand in the
5930 conditional predicate. */
5931 FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
5932 register_edge_assert_for (op, e, bsi,
5933 gimple_cond_code (last),
5934 gimple_cond_lhs (last),
5935 gimple_cond_rhs (last));
5939 struct case_info
5941 tree expr;
5942 basic_block bb;
5945 /* Compare two case labels sorting first by the destination bb index
5946 and then by the case value. */
5948 static int
5949 compare_case_labels (const void *p1, const void *p2)
5951 const struct case_info *ci1 = (const struct case_info *) p1;
5952 const struct case_info *ci2 = (const struct case_info *) p2;
5953 int idx1 = ci1->bb->index;
5954 int idx2 = ci2->bb->index;
5956 if (idx1 < idx2)
5957 return -1;
5958 else if (idx1 == idx2)
5960 /* Make sure the default label is first in a group. */
5961 if (!CASE_LOW (ci1->expr))
5962 return -1;
5963 else if (!CASE_LOW (ci2->expr))
5964 return 1;
5965 else
5966 return tree_int_cst_compare (CASE_LOW (ci1->expr),
5967 CASE_LOW (ci2->expr));
5969 else
5970 return 1;
5973 /* Determine whether the outgoing edges of BB should receive an
5974 ASSERT_EXPR for each of the operands of BB's LAST statement.
5975 The last statement of BB must be a SWITCH_EXPR.
5977 If any of the sub-graphs rooted at BB have an interesting use of
5978 the predicate operands, an assert location node is added to the
5979 list of assertions for the corresponding operands. */
5981 static void
5982 find_switch_asserts (basic_block bb, gswitch *last)
5984 gimple_stmt_iterator bsi;
5985 tree op;
5986 edge e;
5987 struct case_info *ci;
5988 size_t n = gimple_switch_num_labels (last);
5989 #if GCC_VERSION >= 4000
5990 unsigned int idx;
5991 #else
5992 /* Work around GCC 3.4 bug (PR 37086). */
5993 volatile unsigned int idx;
5994 #endif
5996 bsi = gsi_for_stmt (last);
5997 op = gimple_switch_index (last);
5998 if (TREE_CODE (op) != SSA_NAME)
5999 return;
6001 /* Build a vector of case labels sorted by destination label. */
6002 ci = XNEWVEC (struct case_info, n);
6003 for (idx = 0; idx < n; ++idx)
6005 ci[idx].expr = gimple_switch_label (last, idx);
6006 ci[idx].bb = label_to_block (CASE_LABEL (ci[idx].expr));
6008 edge default_edge = find_edge (bb, ci[0].bb);
6009 qsort (ci, n, sizeof (struct case_info), compare_case_labels);
6011 for (idx = 0; idx < n; ++idx)
6013 tree min, max;
6014 tree cl = ci[idx].expr;
6015 basic_block cbb = ci[idx].bb;
6017 min = CASE_LOW (cl);
6018 max = CASE_HIGH (cl);
6020 /* If there are multiple case labels with the same destination
6021 we need to combine them to a single value range for the edge. */
6022 if (idx + 1 < n && cbb == ci[idx + 1].bb)
6024 /* Skip labels until the last of the group. */
6025 do {
6026 ++idx;
6027 } while (idx < n && cbb == ci[idx].bb);
6028 --idx;
6030 /* Pick up the maximum of the case label range. */
6031 if (CASE_HIGH (ci[idx].expr))
6032 max = CASE_HIGH (ci[idx].expr);
6033 else
6034 max = CASE_LOW (ci[idx].expr);
6037 /* Can't extract a useful assertion out of a range that includes the
6038 default label. */
6039 if (min == NULL_TREE)
6040 continue;
6042 /* Find the edge to register the assert expr on. */
6043 e = find_edge (bb, cbb);
6045 /* Register the necessary assertions for the operand in the
6046 SWITCH_EXPR. */
6047 register_edge_assert_for (op, e, bsi,
6048 max ? GE_EXPR : EQ_EXPR,
6049 op, fold_convert (TREE_TYPE (op), min));
6050 if (max)
6051 register_edge_assert_for (op, e, bsi, LE_EXPR, op,
6052 fold_convert (TREE_TYPE (op), max));
6055 XDELETEVEC (ci);
6057 if (!live_on_edge (default_edge, op))
6058 return;
6060 /* Now register along the default label assertions that correspond to the
6061 anti-range of each label. */
6062 int insertion_limit = PARAM_VALUE (PARAM_MAX_VRP_SWITCH_ASSERTIONS);
6063 for (idx = 1; idx < n; idx++)
6065 tree min, max;
6066 tree cl = gimple_switch_label (last, idx);
6068 min = CASE_LOW (cl);
6069 max = CASE_HIGH (cl);
6071 /* Combine contiguous case ranges to reduce the number of assertions
6072 to insert. */
6073 for (idx = idx + 1; idx < n; idx++)
6075 tree next_min, next_max;
6076 tree next_cl = gimple_switch_label (last, idx);
6078 next_min = CASE_LOW (next_cl);
6079 next_max = CASE_HIGH (next_cl);
6081 wide_int difference = wi::sub (next_min, max ? max : min);
6082 if (wi::eq_p (difference, 1))
6083 max = next_max ? next_max : next_min;
6084 else
6085 break;
6087 idx--;
6089 if (max == NULL_TREE)
6091 /* Register the assertion OP != MIN. */
6092 min = fold_convert (TREE_TYPE (op), min);
6093 register_edge_assert_for (op, default_edge, bsi, NE_EXPR, op, min);
6095 else
6097 /* Register the assertion (unsigned)OP - MIN > (MAX - MIN),
6098 which will give OP the anti-range ~[MIN,MAX]. */
6099 tree uop = fold_convert (unsigned_type_for (TREE_TYPE (op)), op);
6100 min = fold_convert (TREE_TYPE (uop), min);
6101 max = fold_convert (TREE_TYPE (uop), max);
6103 tree lhs = fold_build2 (MINUS_EXPR, TREE_TYPE (uop), uop, min);
6104 tree rhs = int_const_binop (MINUS_EXPR, max, min);
6105 register_new_assert_for (op, lhs, GT_EXPR, rhs,
6106 NULL, default_edge, bsi);
6109 if (--insertion_limit == 0)
6110 break;
6115 /* Traverse all the statements in block BB looking for statements that
6116 may generate useful assertions for the SSA names in their operand.
6117 If a statement produces a useful assertion A for name N_i, then the
6118 list of assertions already generated for N_i is scanned to
6119 determine if A is actually needed.
6121 If N_i already had the assertion A at a location dominating the
6122 current location, then nothing needs to be done. Otherwise, the
6123 new location for A is recorded instead.
6125 1- For every statement S in BB, all the variables used by S are
6126 added to bitmap FOUND_IN_SUBGRAPH.
6128 2- If statement S uses an operand N in a way that exposes a known
6129 value range for N, then if N was not already generated by an
6130 ASSERT_EXPR, create a new assert location for N. For instance,
6131 if N is a pointer and the statement dereferences it, we can
6132 assume that N is not NULL.
6134 3- COND_EXPRs are a special case of #2. We can derive range
6135 information from the predicate but need to insert different
6136 ASSERT_EXPRs for each of the sub-graphs rooted at the
6137 conditional block. If the last statement of BB is a conditional
6138 expression of the form 'X op Y', then
6140 a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
6142 b) If the conditional is the only entry point to the sub-graph
6143 corresponding to the THEN_CLAUSE, recurse into it. On
6144 return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
6145 an ASSERT_EXPR is added for the corresponding variable.
6147 c) Repeat step (b) on the ELSE_CLAUSE.
6149 d) Mark X and Y in FOUND_IN_SUBGRAPH.
6151 For instance,
6153 if (a == 9)
6154 b = a;
6155 else
6156 b = c + 1;
6158 In this case, an assertion on the THEN clause is useful to
6159 determine that 'a' is always 9 on that edge. However, an assertion
6160 on the ELSE clause would be unnecessary.
6162 4- If BB does not end in a conditional expression, then we recurse
6163 into BB's dominator children.
6165 At the end of the recursive traversal, every SSA name will have a
6166 list of locations where ASSERT_EXPRs should be added. When a new
6167 location for name N is found, it is registered by calling
6168 register_new_assert_for. That function keeps track of all the
6169 registered assertions to prevent adding unnecessary assertions.
6170 For instance, if a pointer P_4 is dereferenced more than once in a
6171 dominator tree, only the location dominating all the dereference of
6172 P_4 will receive an ASSERT_EXPR. */
6174 static void
6175 find_assert_locations_1 (basic_block bb, sbitmap live)
6177 gimple *last;
6179 last = last_stmt (bb);
6181 /* If BB's last statement is a conditional statement involving integer
6182 operands, determine if we need to add ASSERT_EXPRs. */
6183 if (last
6184 && gimple_code (last) == GIMPLE_COND
6185 && !fp_predicate (last)
6186 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
6187 find_conditional_asserts (bb, as_a <gcond *> (last));
6189 /* If BB's last statement is a switch statement involving integer
6190 operands, determine if we need to add ASSERT_EXPRs. */
6191 if (last
6192 && gimple_code (last) == GIMPLE_SWITCH
6193 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
6194 find_switch_asserts (bb, as_a <gswitch *> (last));
6196 /* Traverse all the statements in BB marking used names and looking
6197 for statements that may infer assertions for their used operands. */
6198 for (gimple_stmt_iterator si = gsi_last_bb (bb); !gsi_end_p (si);
6199 gsi_prev (&si))
6201 gimple *stmt;
6202 tree op;
6203 ssa_op_iter i;
6205 stmt = gsi_stmt (si);
6207 if (is_gimple_debug (stmt))
6208 continue;
6210 /* See if we can derive an assertion for any of STMT's operands. */
6211 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
6213 tree value;
6214 enum tree_code comp_code;
6216 /* If op is not live beyond this stmt, do not bother to insert
6217 asserts for it. */
6218 if (!bitmap_bit_p (live, SSA_NAME_VERSION (op)))
6219 continue;
6221 /* If OP is used in such a way that we can infer a value
6222 range for it, and we don't find a previous assertion for
6223 it, create a new assertion location node for OP. */
6224 if (infer_value_range (stmt, op, &comp_code, &value))
6226 /* If we are able to infer a nonzero value range for OP,
6227 then walk backwards through the use-def chain to see if OP
6228 was set via a typecast.
6230 If so, then we can also infer a nonzero value range
6231 for the operand of the NOP_EXPR. */
6232 if (comp_code == NE_EXPR && integer_zerop (value))
6234 tree t = op;
6235 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
6237 while (is_gimple_assign (def_stmt)
6238 && CONVERT_EXPR_CODE_P
6239 (gimple_assign_rhs_code (def_stmt))
6240 && TREE_CODE
6241 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
6242 && POINTER_TYPE_P
6243 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
6245 t = gimple_assign_rhs1 (def_stmt);
6246 def_stmt = SSA_NAME_DEF_STMT (t);
6248 /* Note we want to register the assert for the
6249 operand of the NOP_EXPR after SI, not after the
6250 conversion. */
6251 if (bitmap_bit_p (live, SSA_NAME_VERSION (t)))
6252 register_new_assert_for (t, t, comp_code, value,
6253 bb, NULL, si);
6257 register_new_assert_for (op, op, comp_code, value, bb, NULL, si);
6261 /* Update live. */
6262 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
6263 bitmap_set_bit (live, SSA_NAME_VERSION (op));
6264 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_DEF)
6265 bitmap_clear_bit (live, SSA_NAME_VERSION (op));
6268 /* Traverse all PHI nodes in BB, updating live. */
6269 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
6270 gsi_next (&si))
6272 use_operand_p arg_p;
6273 ssa_op_iter i;
6274 gphi *phi = si.phi ();
6275 tree res = gimple_phi_result (phi);
6277 if (virtual_operand_p (res))
6278 continue;
6280 FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
6282 tree arg = USE_FROM_PTR (arg_p);
6283 if (TREE_CODE (arg) == SSA_NAME)
6284 bitmap_set_bit (live, SSA_NAME_VERSION (arg));
6287 bitmap_clear_bit (live, SSA_NAME_VERSION (res));
6291 /* Do an RPO walk over the function computing SSA name liveness
6292 on-the-fly and deciding on assert expressions to insert. */
6294 static void
6295 find_assert_locations (void)
6297 int *rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
6298 int *bb_rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
6299 int *last_rpo = XCNEWVEC (int, last_basic_block_for_fn (cfun));
6300 int rpo_cnt, i;
6302 live = XCNEWVEC (sbitmap, last_basic_block_for_fn (cfun));
6303 rpo_cnt = pre_and_rev_post_order_compute (NULL, rpo, false);
6304 for (i = 0; i < rpo_cnt; ++i)
6305 bb_rpo[rpo[i]] = i;
6307 /* Pre-seed loop latch liveness from loop header PHI nodes. Due to
6308 the order we compute liveness and insert asserts we otherwise
6309 fail to insert asserts into the loop latch. */
6310 loop_p loop;
6311 FOR_EACH_LOOP (loop, 0)
6313 i = loop->latch->index;
6314 unsigned int j = single_succ_edge (loop->latch)->dest_idx;
6315 for (gphi_iterator gsi = gsi_start_phis (loop->header);
6316 !gsi_end_p (gsi); gsi_next (&gsi))
6318 gphi *phi = gsi.phi ();
6319 if (virtual_operand_p (gimple_phi_result (phi)))
6320 continue;
6321 tree arg = gimple_phi_arg_def (phi, j);
6322 if (TREE_CODE (arg) == SSA_NAME)
6324 if (live[i] == NULL)
6326 live[i] = sbitmap_alloc (num_ssa_names);
6327 bitmap_clear (live[i]);
6329 bitmap_set_bit (live[i], SSA_NAME_VERSION (arg));
6334 for (i = rpo_cnt - 1; i >= 0; --i)
6336 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, rpo[i]);
6337 edge e;
6338 edge_iterator ei;
6340 if (!live[rpo[i]])
6342 live[rpo[i]] = sbitmap_alloc (num_ssa_names);
6343 bitmap_clear (live[rpo[i]]);
6346 /* Process BB and update the live information with uses in
6347 this block. */
6348 find_assert_locations_1 (bb, live[rpo[i]]);
6350 /* Merge liveness into the predecessor blocks and free it. */
6351 if (!bitmap_empty_p (live[rpo[i]]))
6353 int pred_rpo = i;
6354 FOR_EACH_EDGE (e, ei, bb->preds)
6356 int pred = e->src->index;
6357 if ((e->flags & EDGE_DFS_BACK) || pred == ENTRY_BLOCK)
6358 continue;
6360 if (!live[pred])
6362 live[pred] = sbitmap_alloc (num_ssa_names);
6363 bitmap_clear (live[pred]);
6365 bitmap_ior (live[pred], live[pred], live[rpo[i]]);
6367 if (bb_rpo[pred] < pred_rpo)
6368 pred_rpo = bb_rpo[pred];
6371 /* Record the RPO number of the last visited block that needs
6372 live information from this block. */
6373 last_rpo[rpo[i]] = pred_rpo;
6375 else
6377 sbitmap_free (live[rpo[i]]);
6378 live[rpo[i]] = NULL;
6381 /* We can free all successors live bitmaps if all their
6382 predecessors have been visited already. */
6383 FOR_EACH_EDGE (e, ei, bb->succs)
6384 if (last_rpo[e->dest->index] == i
6385 && live[e->dest->index])
6387 sbitmap_free (live[e->dest->index]);
6388 live[e->dest->index] = NULL;
6392 XDELETEVEC (rpo);
6393 XDELETEVEC (bb_rpo);
6394 XDELETEVEC (last_rpo);
6395 for (i = 0; i < last_basic_block_for_fn (cfun); ++i)
6396 if (live[i])
6397 sbitmap_free (live[i]);
6398 XDELETEVEC (live);
6401 /* Create an ASSERT_EXPR for NAME and insert it in the location
6402 indicated by LOC. Return true if we made any edge insertions. */
6404 static bool
6405 process_assert_insertions_for (tree name, assert_locus *loc)
6407 /* Build the comparison expression NAME_i COMP_CODE VAL. */
6408 gimple *stmt;
6409 tree cond;
6410 gimple *assert_stmt;
6411 edge_iterator ei;
6412 edge e;
6414 /* If we have X <=> X do not insert an assert expr for that. */
6415 if (loc->expr == loc->val)
6416 return false;
6418 cond = build2 (loc->comp_code, boolean_type_node, loc->expr, loc->val);
6419 assert_stmt = build_assert_expr_for (cond, name);
6420 if (loc->e)
6422 /* We have been asked to insert the assertion on an edge. This
6423 is used only by COND_EXPR and SWITCH_EXPR assertions. */
6424 gcc_checking_assert (gimple_code (gsi_stmt (loc->si)) == GIMPLE_COND
6425 || (gimple_code (gsi_stmt (loc->si))
6426 == GIMPLE_SWITCH));
6428 gsi_insert_on_edge (loc->e, assert_stmt);
6429 return true;
6432 /* Otherwise, we can insert right after LOC->SI iff the
6433 statement must not be the last statement in the block. */
6434 stmt = gsi_stmt (loc->si);
6435 if (!stmt_ends_bb_p (stmt))
6437 gsi_insert_after (&loc->si, assert_stmt, GSI_SAME_STMT);
6438 return false;
6441 /* If STMT must be the last statement in BB, we can only insert new
6442 assertions on the non-abnormal edge out of BB. Note that since
6443 STMT is not control flow, there may only be one non-abnormal/eh edge
6444 out of BB. */
6445 FOR_EACH_EDGE (e, ei, loc->bb->succs)
6446 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
6448 gsi_insert_on_edge (e, assert_stmt);
6449 return true;
6452 gcc_unreachable ();
6456 /* Process all the insertions registered for every name N_i registered
6457 in NEED_ASSERT_FOR. The list of assertions to be inserted are
6458 found in ASSERTS_FOR[i]. */
6460 static void
6461 process_assert_insertions (void)
6463 unsigned i;
6464 bitmap_iterator bi;
6465 bool update_edges_p = false;
6466 int num_asserts = 0;
6468 if (dump_file && (dump_flags & TDF_DETAILS))
6469 dump_all_asserts (dump_file);
6471 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
6473 assert_locus *loc = asserts_for[i];
6474 gcc_assert (loc);
6476 while (loc)
6478 assert_locus *next = loc->next;
6479 update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
6480 free (loc);
6481 loc = next;
6482 num_asserts++;
6486 if (update_edges_p)
6487 gsi_commit_edge_inserts ();
6489 statistics_counter_event (cfun, "Number of ASSERT_EXPR expressions inserted",
6490 num_asserts);
6494 /* Traverse the flowgraph looking for conditional jumps to insert range
6495 expressions. These range expressions are meant to provide information
6496 to optimizations that need to reason in terms of value ranges. They
6497 will not be expanded into RTL. For instance, given:
6499 x = ...
6500 y = ...
6501 if (x < y)
6502 y = x - 2;
6503 else
6504 x = y + 3;
6506 this pass will transform the code into:
6508 x = ...
6509 y = ...
6510 if (x < y)
6512 x = ASSERT_EXPR <x, x < y>
6513 y = x - 2
6515 else
6517 y = ASSERT_EXPR <y, x >= y>
6518 x = y + 3
6521 The idea is that once copy and constant propagation have run, other
6522 optimizations will be able to determine what ranges of values can 'x'
6523 take in different paths of the code, simply by checking the reaching
6524 definition of 'x'. */
6526 static void
6527 insert_range_assertions (void)
6529 need_assert_for = BITMAP_ALLOC (NULL);
6530 asserts_for = XCNEWVEC (assert_locus *, num_ssa_names);
6532 calculate_dominance_info (CDI_DOMINATORS);
6534 find_assert_locations ();
6535 if (!bitmap_empty_p (need_assert_for))
6537 process_assert_insertions ();
6538 update_ssa (TODO_update_ssa_no_phi);
6541 if (dump_file && (dump_flags & TDF_DETAILS))
6543 fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
6544 dump_function_to_file (current_function_decl, dump_file, dump_flags);
6547 free (asserts_for);
6548 BITMAP_FREE (need_assert_for);
6551 /* Checks one ARRAY_REF in REF, located at LOCUS. Ignores flexible arrays
6552 and "struct" hacks. If VRP can determine that the
6553 array subscript is a constant, check if it is outside valid
6554 range. If the array subscript is a RANGE, warn if it is
6555 non-overlapping with valid range.
6556 IGNORE_OFF_BY_ONE is true if the ARRAY_REF is inside a ADDR_EXPR. */
6558 static void
6559 check_array_ref (location_t location, tree ref, bool ignore_off_by_one)
6561 value_range *vr = NULL;
6562 tree low_sub, up_sub;
6563 tree low_bound, up_bound, up_bound_p1;
6565 if (TREE_NO_WARNING (ref))
6566 return;
6568 low_sub = up_sub = TREE_OPERAND (ref, 1);
6569 up_bound = array_ref_up_bound (ref);
6571 /* Can not check flexible arrays. */
6572 if (!up_bound
6573 || TREE_CODE (up_bound) != INTEGER_CST)
6574 return;
6576 /* Accesses to trailing arrays via pointers may access storage
6577 beyond the types array bounds. */
6578 if (warn_array_bounds < 2
6579 && array_at_struct_end_p (ref))
6580 return;
6582 low_bound = array_ref_low_bound (ref);
6583 up_bound_p1 = int_const_binop (PLUS_EXPR, up_bound,
6584 build_int_cst (TREE_TYPE (up_bound), 1));
6586 /* Empty array. */
6587 if (tree_int_cst_equal (low_bound, up_bound_p1))
6589 warning_at (location, OPT_Warray_bounds,
6590 "array subscript is above array bounds");
6591 TREE_NO_WARNING (ref) = 1;
6594 if (TREE_CODE (low_sub) == SSA_NAME)
6596 vr = get_value_range (low_sub);
6597 if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
6599 low_sub = vr->type == VR_RANGE ? vr->max : vr->min;
6600 up_sub = vr->type == VR_RANGE ? vr->min : vr->max;
6604 if (vr && vr->type == VR_ANTI_RANGE)
6606 if (TREE_CODE (up_sub) == INTEGER_CST
6607 && (ignore_off_by_one
6608 ? tree_int_cst_lt (up_bound, up_sub)
6609 : tree_int_cst_le (up_bound, up_sub))
6610 && TREE_CODE (low_sub) == INTEGER_CST
6611 && tree_int_cst_le (low_sub, low_bound))
6613 warning_at (location, OPT_Warray_bounds,
6614 "array subscript is outside array bounds");
6615 TREE_NO_WARNING (ref) = 1;
6618 else if (TREE_CODE (up_sub) == INTEGER_CST
6619 && (ignore_off_by_one
6620 ? !tree_int_cst_le (up_sub, up_bound_p1)
6621 : !tree_int_cst_le (up_sub, up_bound)))
6623 if (dump_file && (dump_flags & TDF_DETAILS))
6625 fprintf (dump_file, "Array bound warning for ");
6626 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
6627 fprintf (dump_file, "\n");
6629 warning_at (location, OPT_Warray_bounds,
6630 "array subscript is above array bounds");
6631 TREE_NO_WARNING (ref) = 1;
6633 else if (TREE_CODE (low_sub) == INTEGER_CST
6634 && tree_int_cst_lt (low_sub, low_bound))
6636 if (dump_file && (dump_flags & TDF_DETAILS))
6638 fprintf (dump_file, "Array bound warning for ");
6639 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
6640 fprintf (dump_file, "\n");
6642 warning_at (location, OPT_Warray_bounds,
6643 "array subscript is below array bounds");
6644 TREE_NO_WARNING (ref) = 1;
6648 /* Searches if the expr T, located at LOCATION computes
6649 address of an ARRAY_REF, and call check_array_ref on it. */
6651 static void
6652 search_for_addr_array (tree t, location_t location)
6654 /* Check each ARRAY_REFs in the reference chain. */
6657 if (TREE_CODE (t) == ARRAY_REF)
6658 check_array_ref (location, t, true /*ignore_off_by_one*/);
6660 t = TREE_OPERAND (t, 0);
6662 while (handled_component_p (t));
6664 if (TREE_CODE (t) == MEM_REF
6665 && TREE_CODE (TREE_OPERAND (t, 0)) == ADDR_EXPR
6666 && !TREE_NO_WARNING (t))
6668 tree tem = TREE_OPERAND (TREE_OPERAND (t, 0), 0);
6669 tree low_bound, up_bound, el_sz;
6670 offset_int idx;
6671 if (TREE_CODE (TREE_TYPE (tem)) != ARRAY_TYPE
6672 || TREE_CODE (TREE_TYPE (TREE_TYPE (tem))) == ARRAY_TYPE
6673 || !TYPE_DOMAIN (TREE_TYPE (tem)))
6674 return;
6676 low_bound = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
6677 up_bound = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
6678 el_sz = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (tem)));
6679 if (!low_bound
6680 || TREE_CODE (low_bound) != INTEGER_CST
6681 || !up_bound
6682 || TREE_CODE (up_bound) != INTEGER_CST
6683 || !el_sz
6684 || TREE_CODE (el_sz) != INTEGER_CST)
6685 return;
6687 idx = mem_ref_offset (t);
6688 idx = wi::sdiv_trunc (idx, wi::to_offset (el_sz));
6689 if (idx < 0)
6691 if (dump_file && (dump_flags & TDF_DETAILS))
6693 fprintf (dump_file, "Array bound warning for ");
6694 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
6695 fprintf (dump_file, "\n");
6697 warning_at (location, OPT_Warray_bounds,
6698 "array subscript is below array bounds");
6699 TREE_NO_WARNING (t) = 1;
6701 else if (idx > (wi::to_offset (up_bound)
6702 - wi::to_offset (low_bound) + 1))
6704 if (dump_file && (dump_flags & TDF_DETAILS))
6706 fprintf (dump_file, "Array bound warning for ");
6707 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
6708 fprintf (dump_file, "\n");
6710 warning_at (location, OPT_Warray_bounds,
6711 "array subscript is above array bounds");
6712 TREE_NO_WARNING (t) = 1;
6717 /* walk_tree() callback that checks if *TP is
6718 an ARRAY_REF inside an ADDR_EXPR (in which an array
6719 subscript one outside the valid range is allowed). Call
6720 check_array_ref for each ARRAY_REF found. The location is
6721 passed in DATA. */
6723 static tree
6724 check_array_bounds (tree *tp, int *walk_subtree, void *data)
6726 tree t = *tp;
6727 struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
6728 location_t location;
6730 if (EXPR_HAS_LOCATION (t))
6731 location = EXPR_LOCATION (t);
6732 else
6734 location_t *locp = (location_t *) wi->info;
6735 location = *locp;
6738 *walk_subtree = TRUE;
6740 if (TREE_CODE (t) == ARRAY_REF)
6741 check_array_ref (location, t, false /*ignore_off_by_one*/);
6743 else if (TREE_CODE (t) == ADDR_EXPR)
6745 search_for_addr_array (t, location);
6746 *walk_subtree = FALSE;
6749 return NULL_TREE;
6752 /* Walk over all statements of all reachable BBs and call check_array_bounds
6753 on them. */
6755 static void
6756 check_all_array_refs (void)
6758 basic_block bb;
6759 gimple_stmt_iterator si;
6761 FOR_EACH_BB_FN (bb, cfun)
6763 edge_iterator ei;
6764 edge e;
6765 bool executable = false;
6767 /* Skip blocks that were found to be unreachable. */
6768 FOR_EACH_EDGE (e, ei, bb->preds)
6769 executable |= !!(e->flags & EDGE_EXECUTABLE);
6770 if (!executable)
6771 continue;
6773 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
6775 gimple *stmt = gsi_stmt (si);
6776 struct walk_stmt_info wi;
6777 if (!gimple_has_location (stmt)
6778 || is_gimple_debug (stmt))
6779 continue;
6781 memset (&wi, 0, sizeof (wi));
6783 location_t loc = gimple_location (stmt);
6784 wi.info = &loc;
6786 walk_gimple_op (gsi_stmt (si),
6787 check_array_bounds,
6788 &wi);
6793 /* Return true if all imm uses of VAR are either in STMT, or
6794 feed (optionally through a chain of single imm uses) GIMPLE_COND
6795 in basic block COND_BB. */
6797 static bool
6798 all_imm_uses_in_stmt_or_feed_cond (tree var, gimple *stmt, basic_block cond_bb)
6800 use_operand_p use_p, use2_p;
6801 imm_use_iterator iter;
6803 FOR_EACH_IMM_USE_FAST (use_p, iter, var)
6804 if (USE_STMT (use_p) != stmt)
6806 gimple *use_stmt = USE_STMT (use_p), *use_stmt2;
6807 if (is_gimple_debug (use_stmt))
6808 continue;
6809 while (is_gimple_assign (use_stmt)
6810 && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
6811 && single_imm_use (gimple_assign_lhs (use_stmt),
6812 &use2_p, &use_stmt2))
6813 use_stmt = use_stmt2;
6814 if (gimple_code (use_stmt) != GIMPLE_COND
6815 || gimple_bb (use_stmt) != cond_bb)
6816 return false;
6818 return true;
6821 /* Handle
6822 _4 = x_3 & 31;
6823 if (_4 != 0)
6824 goto <bb 6>;
6825 else
6826 goto <bb 7>;
6827 <bb 6>:
6828 __builtin_unreachable ();
6829 <bb 7>:
6830 x_5 = ASSERT_EXPR <x_3, ...>;
6831 If x_3 has no other immediate uses (checked by caller),
6832 var is the x_3 var from ASSERT_EXPR, we can clear low 5 bits
6833 from the non-zero bitmask. */
6835 static void
6836 maybe_set_nonzero_bits (basic_block bb, tree var)
6838 edge e = single_pred_edge (bb);
6839 basic_block cond_bb = e->src;
6840 gimple *stmt = last_stmt (cond_bb);
6841 tree cst;
6843 if (stmt == NULL
6844 || gimple_code (stmt) != GIMPLE_COND
6845 || gimple_cond_code (stmt) != ((e->flags & EDGE_TRUE_VALUE)
6846 ? EQ_EXPR : NE_EXPR)
6847 || TREE_CODE (gimple_cond_lhs (stmt)) != SSA_NAME
6848 || !integer_zerop (gimple_cond_rhs (stmt)))
6849 return;
6851 stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt));
6852 if (!is_gimple_assign (stmt)
6853 || gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
6854 || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
6855 return;
6856 if (gimple_assign_rhs1 (stmt) != var)
6858 gimple *stmt2;
6860 if (TREE_CODE (gimple_assign_rhs1 (stmt)) != SSA_NAME)
6861 return;
6862 stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
6863 if (!gimple_assign_cast_p (stmt2)
6864 || gimple_assign_rhs1 (stmt2) != var
6865 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt2))
6866 || (TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (stmt)))
6867 != TYPE_PRECISION (TREE_TYPE (var))))
6868 return;
6870 cst = gimple_assign_rhs2 (stmt);
6871 set_nonzero_bits (var, wi::bit_and_not (get_nonzero_bits (var), cst));
6874 /* Convert range assertion expressions into the implied copies and
6875 copy propagate away the copies. Doing the trivial copy propagation
6876 here avoids the need to run the full copy propagation pass after
6877 VRP.
6879 FIXME, this will eventually lead to copy propagation removing the
6880 names that had useful range information attached to them. For
6881 instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
6882 then N_i will have the range [3, +INF].
6884 However, by converting the assertion into the implied copy
6885 operation N_i = N_j, we will then copy-propagate N_j into the uses
6886 of N_i and lose the range information. We may want to hold on to
6887 ASSERT_EXPRs a little while longer as the ranges could be used in
6888 things like jump threading.
6890 The problem with keeping ASSERT_EXPRs around is that passes after
6891 VRP need to handle them appropriately.
6893 Another approach would be to make the range information a first
6894 class property of the SSA_NAME so that it can be queried from
6895 any pass. This is made somewhat more complex by the need for
6896 multiple ranges to be associated with one SSA_NAME. */
6898 static void
6899 remove_range_assertions (void)
6901 basic_block bb;
6902 gimple_stmt_iterator si;
6903 /* 1 if looking at ASSERT_EXPRs immediately at the beginning of
6904 a basic block preceeded by GIMPLE_COND branching to it and
6905 __builtin_trap, -1 if not yet checked, 0 otherwise. */
6906 int is_unreachable;
6908 /* Note that the BSI iterator bump happens at the bottom of the
6909 loop and no bump is necessary if we're removing the statement
6910 referenced by the current BSI. */
6911 FOR_EACH_BB_FN (bb, cfun)
6912 for (si = gsi_after_labels (bb), is_unreachable = -1; !gsi_end_p (si);)
6914 gimple *stmt = gsi_stmt (si);
6916 if (is_gimple_assign (stmt)
6917 && gimple_assign_rhs_code (stmt) == ASSERT_EXPR)
6919 tree lhs = gimple_assign_lhs (stmt);
6920 tree rhs = gimple_assign_rhs1 (stmt);
6921 tree var;
6923 var = ASSERT_EXPR_VAR (rhs);
6925 if (TREE_CODE (var) == SSA_NAME
6926 && !POINTER_TYPE_P (TREE_TYPE (lhs))
6927 && SSA_NAME_RANGE_INFO (lhs))
6929 if (is_unreachable == -1)
6931 is_unreachable = 0;
6932 if (single_pred_p (bb)
6933 && assert_unreachable_fallthru_edge_p
6934 (single_pred_edge (bb)))
6935 is_unreachable = 1;
6937 /* Handle
6938 if (x_7 >= 10 && x_7 < 20)
6939 __builtin_unreachable ();
6940 x_8 = ASSERT_EXPR <x_7, ...>;
6941 if the only uses of x_7 are in the ASSERT_EXPR and
6942 in the condition. In that case, we can copy the
6943 range info from x_8 computed in this pass also
6944 for x_7. */
6945 if (is_unreachable
6946 && all_imm_uses_in_stmt_or_feed_cond (var, stmt,
6947 single_pred (bb)))
6949 set_range_info (var, SSA_NAME_RANGE_TYPE (lhs),
6950 SSA_NAME_RANGE_INFO (lhs)->get_min (),
6951 SSA_NAME_RANGE_INFO (lhs)->get_max ());
6952 maybe_set_nonzero_bits (bb, var);
6956 /* Propagate the RHS into every use of the LHS. */
6957 replace_uses_by (lhs, var);
6959 /* And finally, remove the copy, it is not needed. */
6960 gsi_remove (&si, true);
6961 release_defs (stmt);
6963 else
6965 if (!is_gimple_debug (gsi_stmt (si)))
6966 is_unreachable = 0;
6967 gsi_next (&si);
6973 /* Return true if STMT is interesting for VRP. */
6975 static bool
6976 stmt_interesting_for_vrp (gimple *stmt)
6978 if (gimple_code (stmt) == GIMPLE_PHI)
6980 tree res = gimple_phi_result (stmt);
6981 return (!virtual_operand_p (res)
6982 && (INTEGRAL_TYPE_P (TREE_TYPE (res))
6983 || POINTER_TYPE_P (TREE_TYPE (res))));
6985 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
6987 tree lhs = gimple_get_lhs (stmt);
6989 /* In general, assignments with virtual operands are not useful
6990 for deriving ranges, with the obvious exception of calls to
6991 builtin functions. */
6992 if (lhs && TREE_CODE (lhs) == SSA_NAME
6993 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
6994 || POINTER_TYPE_P (TREE_TYPE (lhs)))
6995 && (is_gimple_call (stmt)
6996 || !gimple_vuse (stmt)))
6997 return true;
6998 else if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
6999 switch (gimple_call_internal_fn (stmt))
7001 case IFN_ADD_OVERFLOW:
7002 case IFN_SUB_OVERFLOW:
7003 case IFN_MUL_OVERFLOW:
7004 /* These internal calls return _Complex integer type,
7005 but are interesting to VRP nevertheless. */
7006 if (lhs && TREE_CODE (lhs) == SSA_NAME)
7007 return true;
7008 break;
7009 default:
7010 break;
7013 else if (gimple_code (stmt) == GIMPLE_COND
7014 || gimple_code (stmt) == GIMPLE_SWITCH)
7015 return true;
7017 return false;
7020 /* Initialize VRP lattice. */
7022 static void
7023 vrp_initialize_lattice ()
7025 values_propagated = false;
7026 num_vr_values = num_ssa_names;
7027 vr_value = XCNEWVEC (value_range *, num_vr_values);
7028 vr_phi_edge_counts = XCNEWVEC (int, num_ssa_names);
7029 bitmap_obstack_initialize (&vrp_equiv_obstack);
7032 /* Initialization required by ssa_propagate engine. */
7034 static void
7035 vrp_initialize ()
7037 basic_block bb;
7039 FOR_EACH_BB_FN (bb, cfun)
7041 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
7042 gsi_next (&si))
7044 gphi *phi = si.phi ();
7045 if (!stmt_interesting_for_vrp (phi))
7047 tree lhs = PHI_RESULT (phi);
7048 set_value_range_to_varying (get_value_range (lhs));
7049 prop_set_simulate_again (phi, false);
7051 else
7052 prop_set_simulate_again (phi, true);
7055 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
7056 gsi_next (&si))
7058 gimple *stmt = gsi_stmt (si);
7060 /* If the statement is a control insn, then we do not
7061 want to avoid simulating the statement once. Failure
7062 to do so means that those edges will never get added. */
7063 if (stmt_ends_bb_p (stmt))
7064 prop_set_simulate_again (stmt, true);
7065 else if (!stmt_interesting_for_vrp (stmt))
7067 set_defs_to_varying (stmt);
7068 prop_set_simulate_again (stmt, false);
7070 else
7071 prop_set_simulate_again (stmt, true);
7076 /* Return the singleton value-range for NAME or NAME. */
7078 static inline tree
7079 vrp_valueize (tree name)
7081 if (TREE_CODE (name) == SSA_NAME)
7083 value_range *vr = get_value_range (name);
7084 if (vr->type == VR_RANGE
7085 && (TREE_CODE (vr->min) == SSA_NAME
7086 || is_gimple_min_invariant (vr->min))
7087 && vrp_operand_equal_p (vr->min, vr->max))
7088 return vr->min;
7090 return name;
7093 /* Return the singleton value-range for NAME if that is a constant
7094 but signal to not follow SSA edges. */
7096 static inline tree
7097 vrp_valueize_1 (tree name)
7099 if (TREE_CODE (name) == SSA_NAME)
7101 /* If the definition may be simulated again we cannot follow
7102 this SSA edge as the SSA propagator does not necessarily
7103 re-visit the use. */
7104 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
7105 if (!gimple_nop_p (def_stmt)
7106 && prop_simulate_again_p (def_stmt))
7107 return NULL_TREE;
7108 value_range *vr = get_value_range (name);
7109 if (range_int_cst_singleton_p (vr))
7110 return vr->min;
7112 return name;
7115 /* Visit assignment STMT. If it produces an interesting range, record
7116 the range in VR and set LHS to OUTPUT_P. */
7118 static void
7119 vrp_visit_assignment_or_call (gimple *stmt, tree *output_p, value_range *vr)
7121 tree lhs;
7122 enum gimple_code code = gimple_code (stmt);
7123 lhs = gimple_get_lhs (stmt);
7124 *output_p = NULL_TREE;
7126 /* We only keep track of ranges in integral and pointer types. */
7127 if (TREE_CODE (lhs) == SSA_NAME
7128 && ((INTEGRAL_TYPE_P (TREE_TYPE (lhs))
7129 /* It is valid to have NULL MIN/MAX values on a type. See
7130 build_range_type. */
7131 && TYPE_MIN_VALUE (TREE_TYPE (lhs))
7132 && TYPE_MAX_VALUE (TREE_TYPE (lhs)))
7133 || POINTER_TYPE_P (TREE_TYPE (lhs))))
7135 *output_p = lhs;
7137 /* Try folding the statement to a constant first. */
7138 tree tem = gimple_fold_stmt_to_constant_1 (stmt, vrp_valueize,
7139 vrp_valueize_1);
7140 if (tem)
7142 if (TREE_CODE (tem) == SSA_NAME
7143 && (SSA_NAME_IS_DEFAULT_DEF (tem)
7144 || ! prop_simulate_again_p (SSA_NAME_DEF_STMT (tem))))
7146 extract_range_from_ssa_name (vr, tem);
7147 return;
7149 else if (is_gimple_min_invariant (tem))
7151 set_value_range_to_value (vr, tem, NULL);
7152 return;
7155 /* Then dispatch to value-range extracting functions. */
7156 if (code == GIMPLE_CALL)
7157 extract_range_basic (vr, stmt);
7158 else
7159 extract_range_from_assignment (vr, as_a <gassign *> (stmt));
7163 /* Helper that gets the value range of the SSA_NAME with version I
7164 or a symbolic range containing the SSA_NAME only if the value range
7165 is varying or undefined. */
7167 static inline value_range
7168 get_vr_for_comparison (int i)
7170 value_range vr = *get_value_range (ssa_name (i));
7172 /* If name N_i does not have a valid range, use N_i as its own
7173 range. This allows us to compare against names that may
7174 have N_i in their ranges. */
7175 if (vr.type == VR_VARYING || vr.type == VR_UNDEFINED)
7177 vr.type = VR_RANGE;
7178 vr.min = ssa_name (i);
7179 vr.max = ssa_name (i);
7182 return vr;
7185 /* Compare all the value ranges for names equivalent to VAR with VAL
7186 using comparison code COMP. Return the same value returned by
7187 compare_range_with_value, including the setting of
7188 *STRICT_OVERFLOW_P. */
7190 static tree
7191 compare_name_with_value (enum tree_code comp, tree var, tree val,
7192 bool *strict_overflow_p, bool use_equiv_p)
7194 bitmap_iterator bi;
7195 unsigned i;
7196 bitmap e;
7197 tree retval, t;
7198 int used_strict_overflow;
7199 bool sop;
7200 value_range equiv_vr;
7202 /* Get the set of equivalences for VAR. */
7203 e = get_value_range (var)->equiv;
7205 /* Start at -1. Set it to 0 if we do a comparison without relying
7206 on overflow, or 1 if all comparisons rely on overflow. */
7207 used_strict_overflow = -1;
7209 /* Compare vars' value range with val. */
7210 equiv_vr = get_vr_for_comparison (SSA_NAME_VERSION (var));
7211 sop = false;
7212 retval = compare_range_with_value (comp, &equiv_vr, val, &sop);
7213 if (retval)
7214 used_strict_overflow = sop ? 1 : 0;
7216 /* If the equiv set is empty we have done all work we need to do. */
7217 if (e == NULL)
7219 if (retval
7220 && used_strict_overflow > 0)
7221 *strict_overflow_p = true;
7222 return retval;
7225 EXECUTE_IF_SET_IN_BITMAP (e, 0, i, bi)
7227 tree name = ssa_name (i);
7228 if (! name)
7229 continue;
7231 if (! use_equiv_p
7232 && ! SSA_NAME_IS_DEFAULT_DEF (name)
7233 && prop_simulate_again_p (SSA_NAME_DEF_STMT (name)))
7234 continue;
7236 equiv_vr = get_vr_for_comparison (i);
7237 sop = false;
7238 t = compare_range_with_value (comp, &equiv_vr, val, &sop);
7239 if (t)
7241 /* If we get different answers from different members
7242 of the equivalence set this check must be in a dead
7243 code region. Folding it to a trap representation
7244 would be correct here. For now just return don't-know. */
7245 if (retval != NULL
7246 && t != retval)
7248 retval = NULL_TREE;
7249 break;
7251 retval = t;
7253 if (!sop)
7254 used_strict_overflow = 0;
7255 else if (used_strict_overflow < 0)
7256 used_strict_overflow = 1;
7260 if (retval
7261 && used_strict_overflow > 0)
7262 *strict_overflow_p = true;
7264 return retval;
7268 /* Given a comparison code COMP and names N1 and N2, compare all the
7269 ranges equivalent to N1 against all the ranges equivalent to N2
7270 to determine the value of N1 COMP N2. Return the same value
7271 returned by compare_ranges. Set *STRICT_OVERFLOW_P to indicate
7272 whether we relied on an overflow infinity in the comparison. */
7275 static tree
7276 compare_names (enum tree_code comp, tree n1, tree n2,
7277 bool *strict_overflow_p)
7279 tree t, retval;
7280 bitmap e1, e2;
7281 bitmap_iterator bi1, bi2;
7282 unsigned i1, i2;
7283 int used_strict_overflow;
7284 static bitmap_obstack *s_obstack = NULL;
7285 static bitmap s_e1 = NULL, s_e2 = NULL;
7287 /* Compare the ranges of every name equivalent to N1 against the
7288 ranges of every name equivalent to N2. */
7289 e1 = get_value_range (n1)->equiv;
7290 e2 = get_value_range (n2)->equiv;
7292 /* Use the fake bitmaps if e1 or e2 are not available. */
7293 if (s_obstack == NULL)
7295 s_obstack = XNEW (bitmap_obstack);
7296 bitmap_obstack_initialize (s_obstack);
7297 s_e1 = BITMAP_ALLOC (s_obstack);
7298 s_e2 = BITMAP_ALLOC (s_obstack);
7300 if (e1 == NULL)
7301 e1 = s_e1;
7302 if (e2 == NULL)
7303 e2 = s_e2;
7305 /* Add N1 and N2 to their own set of equivalences to avoid
7306 duplicating the body of the loop just to check N1 and N2
7307 ranges. */
7308 bitmap_set_bit (e1, SSA_NAME_VERSION (n1));
7309 bitmap_set_bit (e2, SSA_NAME_VERSION (n2));
7311 /* If the equivalence sets have a common intersection, then the two
7312 names can be compared without checking their ranges. */
7313 if (bitmap_intersect_p (e1, e2))
7315 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7316 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7318 return (comp == EQ_EXPR || comp == GE_EXPR || comp == LE_EXPR)
7319 ? boolean_true_node
7320 : boolean_false_node;
7323 /* Start at -1. Set it to 0 if we do a comparison without relying
7324 on overflow, or 1 if all comparisons rely on overflow. */
7325 used_strict_overflow = -1;
7327 /* Otherwise, compare all the equivalent ranges. First, add N1 and
7328 N2 to their own set of equivalences to avoid duplicating the body
7329 of the loop just to check N1 and N2 ranges. */
7330 EXECUTE_IF_SET_IN_BITMAP (e1, 0, i1, bi1)
7332 if (! ssa_name (i1))
7333 continue;
7335 value_range vr1 = get_vr_for_comparison (i1);
7337 t = retval = NULL_TREE;
7338 EXECUTE_IF_SET_IN_BITMAP (e2, 0, i2, bi2)
7340 if (! ssa_name (i2))
7341 continue;
7343 bool sop = false;
7345 value_range vr2 = get_vr_for_comparison (i2);
7347 t = compare_ranges (comp, &vr1, &vr2, &sop);
7348 if (t)
7350 /* If we get different answers from different members
7351 of the equivalence set this check must be in a dead
7352 code region. Folding it to a trap representation
7353 would be correct here. For now just return don't-know. */
7354 if (retval != NULL
7355 && t != retval)
7357 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7358 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7359 return NULL_TREE;
7361 retval = t;
7363 if (!sop)
7364 used_strict_overflow = 0;
7365 else if (used_strict_overflow < 0)
7366 used_strict_overflow = 1;
7370 if (retval)
7372 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7373 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7374 if (used_strict_overflow > 0)
7375 *strict_overflow_p = true;
7376 return retval;
7380 /* None of the equivalent ranges are useful in computing this
7381 comparison. */
7382 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7383 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7384 return NULL_TREE;
7387 /* Helper function for vrp_evaluate_conditional_warnv & other
7388 optimizers. */
7390 static tree
7391 vrp_evaluate_conditional_warnv_with_ops_using_ranges (enum tree_code code,
7392 tree op0, tree op1,
7393 bool * strict_overflow_p)
7395 value_range *vr0, *vr1;
7397 vr0 = (TREE_CODE (op0) == SSA_NAME) ? get_value_range (op0) : NULL;
7398 vr1 = (TREE_CODE (op1) == SSA_NAME) ? get_value_range (op1) : NULL;
7400 tree res = NULL_TREE;
7401 if (vr0 && vr1)
7402 res = compare_ranges (code, vr0, vr1, strict_overflow_p);
7403 if (!res && vr0)
7404 res = compare_range_with_value (code, vr0, op1, strict_overflow_p);
7405 if (!res && vr1)
7406 res = (compare_range_with_value
7407 (swap_tree_comparison (code), vr1, op0, strict_overflow_p));
7408 return res;
7411 /* Helper function for vrp_evaluate_conditional_warnv. */
7413 static tree
7414 vrp_evaluate_conditional_warnv_with_ops (enum tree_code code, tree op0,
7415 tree op1, bool use_equiv_p,
7416 bool *strict_overflow_p, bool *only_ranges)
7418 tree ret;
7419 if (only_ranges)
7420 *only_ranges = true;
7422 /* We only deal with integral and pointer types. */
7423 if (!INTEGRAL_TYPE_P (TREE_TYPE (op0))
7424 && !POINTER_TYPE_P (TREE_TYPE (op0)))
7425 return NULL_TREE;
7427 if ((ret = vrp_evaluate_conditional_warnv_with_ops_using_ranges
7428 (code, op0, op1, strict_overflow_p)))
7429 return ret;
7430 if (only_ranges)
7431 *only_ranges = false;
7432 /* Do not use compare_names during propagation, it's quadratic. */
7433 if (TREE_CODE (op0) == SSA_NAME && TREE_CODE (op1) == SSA_NAME
7434 && use_equiv_p)
7435 return compare_names (code, op0, op1, strict_overflow_p);
7436 else if (TREE_CODE (op0) == SSA_NAME)
7437 return compare_name_with_value (code, op0, op1,
7438 strict_overflow_p, use_equiv_p);
7439 else if (TREE_CODE (op1) == SSA_NAME)
7440 return compare_name_with_value (swap_tree_comparison (code), op1, op0,
7441 strict_overflow_p, use_equiv_p);
7442 return NULL_TREE;
7445 /* Given (CODE OP0 OP1) within STMT, try to simplify it based on value range
7446 information. Return NULL if the conditional can not be evaluated.
7447 The ranges of all the names equivalent with the operands in COND
7448 will be used when trying to compute the value. If the result is
7449 based on undefined signed overflow, issue a warning if
7450 appropriate. */
7452 static tree
7453 vrp_evaluate_conditional (tree_code code, tree op0, tree op1, gimple *stmt)
7455 bool sop;
7456 tree ret;
7457 bool only_ranges;
7459 /* Some passes and foldings leak constants with overflow flag set
7460 into the IL. Avoid doing wrong things with these and bail out. */
7461 if ((TREE_CODE (op0) == INTEGER_CST
7462 && TREE_OVERFLOW (op0))
7463 || (TREE_CODE (op1) == INTEGER_CST
7464 && TREE_OVERFLOW (op1)))
7465 return NULL_TREE;
7467 sop = false;
7468 ret = vrp_evaluate_conditional_warnv_with_ops (code, op0, op1, true, &sop,
7469 &only_ranges);
7471 if (ret && sop)
7473 enum warn_strict_overflow_code wc;
7474 const char* warnmsg;
7476 if (is_gimple_min_invariant (ret))
7478 wc = WARN_STRICT_OVERFLOW_CONDITIONAL;
7479 warnmsg = G_("assuming signed overflow does not occur when "
7480 "simplifying conditional to constant");
7482 else
7484 wc = WARN_STRICT_OVERFLOW_COMPARISON;
7485 warnmsg = G_("assuming signed overflow does not occur when "
7486 "simplifying conditional");
7489 if (issue_strict_overflow_warning (wc))
7491 location_t location;
7493 if (!gimple_has_location (stmt))
7494 location = input_location;
7495 else
7496 location = gimple_location (stmt);
7497 warning_at (location, OPT_Wstrict_overflow, "%s", warnmsg);
7501 if (warn_type_limits
7502 && ret && only_ranges
7503 && TREE_CODE_CLASS (code) == tcc_comparison
7504 && TREE_CODE (op0) == SSA_NAME)
7506 /* If the comparison is being folded and the operand on the LHS
7507 is being compared against a constant value that is outside of
7508 the natural range of OP0's type, then the predicate will
7509 always fold regardless of the value of OP0. If -Wtype-limits
7510 was specified, emit a warning. */
7511 tree type = TREE_TYPE (op0);
7512 value_range *vr0 = get_value_range (op0);
7514 if (vr0->type == VR_RANGE
7515 && INTEGRAL_TYPE_P (type)
7516 && vrp_val_is_min (vr0->min)
7517 && vrp_val_is_max (vr0->max)
7518 && is_gimple_min_invariant (op1))
7520 location_t location;
7522 if (!gimple_has_location (stmt))
7523 location = input_location;
7524 else
7525 location = gimple_location (stmt);
7527 warning_at (location, OPT_Wtype_limits,
7528 integer_zerop (ret)
7529 ? G_("comparison always false "
7530 "due to limited range of data type")
7531 : G_("comparison always true "
7532 "due to limited range of data type"));
7536 return ret;
7540 /* Visit conditional statement STMT. If we can determine which edge
7541 will be taken out of STMT's basic block, record it in
7542 *TAKEN_EDGE_P. Otherwise, set *TAKEN_EDGE_P to NULL. */
7544 static void
7545 vrp_visit_cond_stmt (gcond *stmt, edge *taken_edge_p)
7547 tree val;
7548 bool sop;
7550 *taken_edge_p = NULL;
7552 if (dump_file && (dump_flags & TDF_DETAILS))
7554 tree use;
7555 ssa_op_iter i;
7557 fprintf (dump_file, "\nVisiting conditional with predicate: ");
7558 print_gimple_stmt (dump_file, stmt, 0, 0);
7559 fprintf (dump_file, "\nWith known ranges\n");
7561 FOR_EACH_SSA_TREE_OPERAND (use, stmt, i, SSA_OP_USE)
7563 fprintf (dump_file, "\t");
7564 print_generic_expr (dump_file, use, 0);
7565 fprintf (dump_file, ": ");
7566 dump_value_range (dump_file, vr_value[SSA_NAME_VERSION (use)]);
7569 fprintf (dump_file, "\n");
7572 /* Compute the value of the predicate COND by checking the known
7573 ranges of each of its operands.
7575 Note that we cannot evaluate all the equivalent ranges here
7576 because those ranges may not yet be final and with the current
7577 propagation strategy, we cannot determine when the value ranges
7578 of the names in the equivalence set have changed.
7580 For instance, given the following code fragment
7582 i_5 = PHI <8, i_13>
7584 i_14 = ASSERT_EXPR <i_5, i_5 != 0>
7585 if (i_14 == 1)
7588 Assume that on the first visit to i_14, i_5 has the temporary
7589 range [8, 8] because the second argument to the PHI function is
7590 not yet executable. We derive the range ~[0, 0] for i_14 and the
7591 equivalence set { i_5 }. So, when we visit 'if (i_14 == 1)' for
7592 the first time, since i_14 is equivalent to the range [8, 8], we
7593 determine that the predicate is always false.
7595 On the next round of propagation, i_13 is determined to be
7596 VARYING, which causes i_5 to drop down to VARYING. So, another
7597 visit to i_14 is scheduled. In this second visit, we compute the
7598 exact same range and equivalence set for i_14, namely ~[0, 0] and
7599 { i_5 }. But we did not have the previous range for i_5
7600 registered, so vrp_visit_assignment thinks that the range for
7601 i_14 has not changed. Therefore, the predicate 'if (i_14 == 1)'
7602 is not visited again, which stops propagation from visiting
7603 statements in the THEN clause of that if().
7605 To properly fix this we would need to keep the previous range
7606 value for the names in the equivalence set. This way we would've
7607 discovered that from one visit to the other i_5 changed from
7608 range [8, 8] to VR_VARYING.
7610 However, fixing this apparent limitation may not be worth the
7611 additional checking. Testing on several code bases (GCC, DLV,
7612 MICO, TRAMP3D and SPEC2000) showed that doing this results in
7613 4 more predicates folded in SPEC. */
7614 sop = false;
7616 val = vrp_evaluate_conditional_warnv_with_ops (gimple_cond_code (stmt),
7617 gimple_cond_lhs (stmt),
7618 gimple_cond_rhs (stmt),
7619 false, &sop, NULL);
7620 if (val)
7622 if (!sop)
7623 *taken_edge_p = find_taken_edge (gimple_bb (stmt), val);
7624 else
7626 if (dump_file && (dump_flags & TDF_DETAILS))
7627 fprintf (dump_file,
7628 "\nIgnoring predicate evaluation because "
7629 "it assumes that signed overflow is undefined");
7630 val = NULL_TREE;
7634 if (dump_file && (dump_flags & TDF_DETAILS))
7636 fprintf (dump_file, "\nPredicate evaluates to: ");
7637 if (val == NULL_TREE)
7638 fprintf (dump_file, "DON'T KNOW\n");
7639 else
7640 print_generic_stmt (dump_file, val, 0);
7644 /* Searches the case label vector VEC for the index *IDX of the CASE_LABEL
7645 that includes the value VAL. The search is restricted to the range
7646 [START_IDX, n - 1] where n is the size of VEC.
7648 If there is a CASE_LABEL for VAL, its index is placed in IDX and true is
7649 returned.
7651 If there is no CASE_LABEL for VAL and there is one that is larger than VAL,
7652 it is placed in IDX and false is returned.
7654 If VAL is larger than any CASE_LABEL, n is placed on IDX and false is
7655 returned. */
7657 static bool
7658 find_case_label_index (gswitch *stmt, size_t start_idx, tree val, size_t *idx)
7660 size_t n = gimple_switch_num_labels (stmt);
7661 size_t low, high;
7663 /* Find case label for minimum of the value range or the next one.
7664 At each iteration we are searching in [low, high - 1]. */
7666 for (low = start_idx, high = n; high != low; )
7668 tree t;
7669 int cmp;
7670 /* Note that i != high, so we never ask for n. */
7671 size_t i = (high + low) / 2;
7672 t = gimple_switch_label (stmt, i);
7674 /* Cache the result of comparing CASE_LOW and val. */
7675 cmp = tree_int_cst_compare (CASE_LOW (t), val);
7677 if (cmp == 0)
7679 /* Ranges cannot be empty. */
7680 *idx = i;
7681 return true;
7683 else if (cmp > 0)
7684 high = i;
7685 else
7687 low = i + 1;
7688 if (CASE_HIGH (t) != NULL
7689 && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
7691 *idx = i;
7692 return true;
7697 *idx = high;
7698 return false;
7701 /* Searches the case label vector VEC for the range of CASE_LABELs that is used
7702 for values between MIN and MAX. The first index is placed in MIN_IDX. The
7703 last index is placed in MAX_IDX. If the range of CASE_LABELs is empty
7704 then MAX_IDX < MIN_IDX.
7705 Returns true if the default label is not needed. */
7707 static bool
7708 find_case_label_range (gswitch *stmt, tree min, tree max, size_t *min_idx,
7709 size_t *max_idx)
7711 size_t i, j;
7712 bool min_take_default = !find_case_label_index (stmt, 1, min, &i);
7713 bool max_take_default = !find_case_label_index (stmt, i, max, &j);
7715 if (i == j
7716 && min_take_default
7717 && max_take_default)
7719 /* Only the default case label reached.
7720 Return an empty range. */
7721 *min_idx = 1;
7722 *max_idx = 0;
7723 return false;
7725 else
7727 bool take_default = min_take_default || max_take_default;
7728 tree low, high;
7729 size_t k;
7731 if (max_take_default)
7732 j--;
7734 /* If the case label range is continuous, we do not need
7735 the default case label. Verify that. */
7736 high = CASE_LOW (gimple_switch_label (stmt, i));
7737 if (CASE_HIGH (gimple_switch_label (stmt, i)))
7738 high = CASE_HIGH (gimple_switch_label (stmt, i));
7739 for (k = i + 1; k <= j; ++k)
7741 low = CASE_LOW (gimple_switch_label (stmt, k));
7742 if (!integer_onep (int_const_binop (MINUS_EXPR, low, high)))
7744 take_default = true;
7745 break;
7747 high = low;
7748 if (CASE_HIGH (gimple_switch_label (stmt, k)))
7749 high = CASE_HIGH (gimple_switch_label (stmt, k));
7752 *min_idx = i;
7753 *max_idx = j;
7754 return !take_default;
7758 /* Searches the case label vector VEC for the ranges of CASE_LABELs that are
7759 used in range VR. The indices are placed in MIN_IDX1, MAX_IDX, MIN_IDX2 and
7760 MAX_IDX2. If the ranges of CASE_LABELs are empty then MAX_IDX1 < MIN_IDX1.
7761 Returns true if the default label is not needed. */
7763 static bool
7764 find_case_label_ranges (gswitch *stmt, value_range *vr, size_t *min_idx1,
7765 size_t *max_idx1, size_t *min_idx2,
7766 size_t *max_idx2)
7768 size_t i, j, k, l;
7769 unsigned int n = gimple_switch_num_labels (stmt);
7770 bool take_default;
7771 tree case_low, case_high;
7772 tree min = vr->min, max = vr->max;
7774 gcc_checking_assert (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE);
7776 take_default = !find_case_label_range (stmt, min, max, &i, &j);
7778 /* Set second range to emtpy. */
7779 *min_idx2 = 1;
7780 *max_idx2 = 0;
7782 if (vr->type == VR_RANGE)
7784 *min_idx1 = i;
7785 *max_idx1 = j;
7786 return !take_default;
7789 /* Set first range to all case labels. */
7790 *min_idx1 = 1;
7791 *max_idx1 = n - 1;
7793 if (i > j)
7794 return false;
7796 /* Make sure all the values of case labels [i , j] are contained in
7797 range [MIN, MAX]. */
7798 case_low = CASE_LOW (gimple_switch_label (stmt, i));
7799 case_high = CASE_HIGH (gimple_switch_label (stmt, j));
7800 if (tree_int_cst_compare (case_low, min) < 0)
7801 i += 1;
7802 if (case_high != NULL_TREE
7803 && tree_int_cst_compare (max, case_high) < 0)
7804 j -= 1;
7806 if (i > j)
7807 return false;
7809 /* If the range spans case labels [i, j], the corresponding anti-range spans
7810 the labels [1, i - 1] and [j + 1, n - 1]. */
7811 k = j + 1;
7812 l = n - 1;
7813 if (k > l)
7815 k = 1;
7816 l = 0;
7819 j = i - 1;
7820 i = 1;
7821 if (i > j)
7823 i = k;
7824 j = l;
7825 k = 1;
7826 l = 0;
7829 *min_idx1 = i;
7830 *max_idx1 = j;
7831 *min_idx2 = k;
7832 *max_idx2 = l;
7833 return false;
7836 /* Visit switch statement STMT. If we can determine which edge
7837 will be taken out of STMT's basic block, record it in
7838 *TAKEN_EDGE_P. Otherwise, *TAKEN_EDGE_P set to NULL. */
7840 static void
7841 vrp_visit_switch_stmt (gswitch *stmt, edge *taken_edge_p)
7843 tree op, val;
7844 value_range *vr;
7845 size_t i = 0, j = 0, k, l;
7846 bool take_default;
7848 *taken_edge_p = NULL;
7849 op = gimple_switch_index (stmt);
7850 if (TREE_CODE (op) != SSA_NAME)
7851 return;
7853 vr = get_value_range (op);
7854 if (dump_file && (dump_flags & TDF_DETAILS))
7856 fprintf (dump_file, "\nVisiting switch expression with operand ");
7857 print_generic_expr (dump_file, op, 0);
7858 fprintf (dump_file, " with known range ");
7859 dump_value_range (dump_file, vr);
7860 fprintf (dump_file, "\n");
7863 if ((vr->type != VR_RANGE
7864 && vr->type != VR_ANTI_RANGE)
7865 || symbolic_range_p (vr))
7866 return;
7868 /* Find the single edge that is taken from the switch expression. */
7869 take_default = !find_case_label_ranges (stmt, vr, &i, &j, &k, &l);
7871 /* Check if the range spans no CASE_LABEL. If so, we only reach the default
7872 label */
7873 if (j < i)
7875 gcc_assert (take_default);
7876 val = gimple_switch_default_label (stmt);
7878 else
7880 /* Check if labels with index i to j and maybe the default label
7881 are all reaching the same label. */
7883 val = gimple_switch_label (stmt, i);
7884 if (take_default
7885 && CASE_LABEL (gimple_switch_default_label (stmt))
7886 != CASE_LABEL (val))
7888 if (dump_file && (dump_flags & TDF_DETAILS))
7889 fprintf (dump_file, " not a single destination for this "
7890 "range\n");
7891 return;
7893 for (++i; i <= j; ++i)
7895 if (CASE_LABEL (gimple_switch_label (stmt, i)) != CASE_LABEL (val))
7897 if (dump_file && (dump_flags & TDF_DETAILS))
7898 fprintf (dump_file, " not a single destination for this "
7899 "range\n");
7900 return;
7903 for (; k <= l; ++k)
7905 if (CASE_LABEL (gimple_switch_label (stmt, k)) != CASE_LABEL (val))
7907 if (dump_file && (dump_flags & TDF_DETAILS))
7908 fprintf (dump_file, " not a single destination for this "
7909 "range\n");
7910 return;
7915 *taken_edge_p = find_edge (gimple_bb (stmt),
7916 label_to_block (CASE_LABEL (val)));
7918 if (dump_file && (dump_flags & TDF_DETAILS))
7920 fprintf (dump_file, " will take edge to ");
7921 print_generic_stmt (dump_file, CASE_LABEL (val), 0);
7926 /* Evaluate statement STMT. If the statement produces a useful range,
7927 set VR and corepsponding OUTPUT_P.
7929 If STMT is a conditional branch and we can determine its truth
7930 value, the taken edge is recorded in *TAKEN_EDGE_P. */
7932 static void
7933 extract_range_from_stmt (gimple *stmt, edge *taken_edge_p,
7934 tree *output_p, value_range *vr)
7937 if (dump_file && (dump_flags & TDF_DETAILS))
7939 fprintf (dump_file, "\nVisiting statement:\n");
7940 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
7943 if (!stmt_interesting_for_vrp (stmt))
7944 gcc_assert (stmt_ends_bb_p (stmt));
7945 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
7946 vrp_visit_assignment_or_call (stmt, output_p, vr);
7947 else if (gimple_code (stmt) == GIMPLE_COND)
7948 vrp_visit_cond_stmt (as_a <gcond *> (stmt), taken_edge_p);
7949 else if (gimple_code (stmt) == GIMPLE_SWITCH)
7950 vrp_visit_switch_stmt (as_a <gswitch *> (stmt), taken_edge_p);
7953 /* Evaluate statement STMT. If the statement produces a useful range,
7954 return SSA_PROP_INTERESTING and record the SSA name with the
7955 interesting range into *OUTPUT_P.
7957 If STMT is a conditional branch and we can determine its truth
7958 value, the taken edge is recorded in *TAKEN_EDGE_P.
7960 If STMT produces a varying value, return SSA_PROP_VARYING. */
7962 static enum ssa_prop_result
7963 vrp_visit_stmt (gimple *stmt, edge *taken_edge_p, tree *output_p)
7965 value_range vr = VR_INITIALIZER;
7966 tree lhs = gimple_get_lhs (stmt);
7967 extract_range_from_stmt (stmt, taken_edge_p, output_p, &vr);
7969 if (*output_p)
7971 if (update_value_range (*output_p, &vr))
7973 if (dump_file && (dump_flags & TDF_DETAILS))
7975 fprintf (dump_file, "Found new range for ");
7976 print_generic_expr (dump_file, *output_p, 0);
7977 fprintf (dump_file, ": ");
7978 dump_value_range (dump_file, &vr);
7979 fprintf (dump_file, "\n");
7982 if (vr.type == VR_VARYING)
7983 return SSA_PROP_VARYING;
7985 return SSA_PROP_INTERESTING;
7987 return SSA_PROP_NOT_INTERESTING;
7990 if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
7991 switch (gimple_call_internal_fn (stmt))
7993 case IFN_ADD_OVERFLOW:
7994 case IFN_SUB_OVERFLOW:
7995 case IFN_MUL_OVERFLOW:
7996 /* These internal calls return _Complex integer type,
7997 which VRP does not track, but the immediate uses
7998 thereof might be interesting. */
7999 if (lhs && TREE_CODE (lhs) == SSA_NAME)
8001 imm_use_iterator iter;
8002 use_operand_p use_p;
8003 enum ssa_prop_result res = SSA_PROP_VARYING;
8005 set_value_range_to_varying (get_value_range (lhs));
8007 FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
8009 gimple *use_stmt = USE_STMT (use_p);
8010 if (!is_gimple_assign (use_stmt))
8011 continue;
8012 enum tree_code rhs_code = gimple_assign_rhs_code (use_stmt);
8013 if (rhs_code != REALPART_EXPR && rhs_code != IMAGPART_EXPR)
8014 continue;
8015 tree rhs1 = gimple_assign_rhs1 (use_stmt);
8016 tree use_lhs = gimple_assign_lhs (use_stmt);
8017 if (TREE_CODE (rhs1) != rhs_code
8018 || TREE_OPERAND (rhs1, 0) != lhs
8019 || TREE_CODE (use_lhs) != SSA_NAME
8020 || !stmt_interesting_for_vrp (use_stmt)
8021 || (!INTEGRAL_TYPE_P (TREE_TYPE (use_lhs))
8022 || !TYPE_MIN_VALUE (TREE_TYPE (use_lhs))
8023 || !TYPE_MAX_VALUE (TREE_TYPE (use_lhs))))
8024 continue;
8026 /* If there is a change in the value range for any of the
8027 REALPART_EXPR/IMAGPART_EXPR immediate uses, return
8028 SSA_PROP_INTERESTING. If there are any REALPART_EXPR
8029 or IMAGPART_EXPR immediate uses, but none of them have
8030 a change in their value ranges, return
8031 SSA_PROP_NOT_INTERESTING. If there are no
8032 {REAL,IMAG}PART_EXPR uses at all,
8033 return SSA_PROP_VARYING. */
8034 value_range new_vr = VR_INITIALIZER;
8035 extract_range_basic (&new_vr, use_stmt);
8036 value_range *old_vr = get_value_range (use_lhs);
8037 if (old_vr->type != new_vr.type
8038 || !vrp_operand_equal_p (old_vr->min, new_vr.min)
8039 || !vrp_operand_equal_p (old_vr->max, new_vr.max)
8040 || !vrp_bitmap_equal_p (old_vr->equiv, new_vr.equiv))
8041 res = SSA_PROP_INTERESTING;
8042 else
8043 res = SSA_PROP_NOT_INTERESTING;
8044 BITMAP_FREE (new_vr.equiv);
8045 if (res == SSA_PROP_INTERESTING)
8047 *output_p = lhs;
8048 return res;
8052 return res;
8054 break;
8055 default:
8056 break;
8059 /* All other statements produce nothing of interest for VRP, so mark
8060 their outputs varying and prevent further simulation. */
8061 set_defs_to_varying (stmt);
8063 return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
8066 /* Union the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
8067 { VR1TYPE, VR0MIN, VR0MAX } and store the result
8068 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
8069 possible such range. The resulting range is not canonicalized. */
8071 static void
8072 union_ranges (enum value_range_type *vr0type,
8073 tree *vr0min, tree *vr0max,
8074 enum value_range_type vr1type,
8075 tree vr1min, tree vr1max)
8077 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
8078 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
8080 /* [] is vr0, () is vr1 in the following classification comments. */
8081 if (mineq && maxeq)
8083 /* [( )] */
8084 if (*vr0type == vr1type)
8085 /* Nothing to do for equal ranges. */
8087 else if ((*vr0type == VR_RANGE
8088 && vr1type == VR_ANTI_RANGE)
8089 || (*vr0type == VR_ANTI_RANGE
8090 && vr1type == VR_RANGE))
8092 /* For anti-range with range union the result is varying. */
8093 goto give_up;
8095 else
8096 gcc_unreachable ();
8098 else if (operand_less_p (*vr0max, vr1min) == 1
8099 || operand_less_p (vr1max, *vr0min) == 1)
8101 /* [ ] ( ) or ( ) [ ]
8102 If the ranges have an empty intersection, result of the union
8103 operation is the anti-range or if both are anti-ranges
8104 it covers all. */
8105 if (*vr0type == VR_ANTI_RANGE
8106 && vr1type == VR_ANTI_RANGE)
8107 goto give_up;
8108 else if (*vr0type == VR_ANTI_RANGE
8109 && vr1type == VR_RANGE)
8111 else if (*vr0type == VR_RANGE
8112 && vr1type == VR_ANTI_RANGE)
8114 *vr0type = vr1type;
8115 *vr0min = vr1min;
8116 *vr0max = vr1max;
8118 else if (*vr0type == VR_RANGE
8119 && vr1type == VR_RANGE)
8121 /* The result is the convex hull of both ranges. */
8122 if (operand_less_p (*vr0max, vr1min) == 1)
8124 /* If the result can be an anti-range, create one. */
8125 if (TREE_CODE (*vr0max) == INTEGER_CST
8126 && TREE_CODE (vr1min) == INTEGER_CST
8127 && vrp_val_is_min (*vr0min)
8128 && vrp_val_is_max (vr1max))
8130 tree min = int_const_binop (PLUS_EXPR,
8131 *vr0max,
8132 build_int_cst (TREE_TYPE (*vr0max), 1));
8133 tree max = int_const_binop (MINUS_EXPR,
8134 vr1min,
8135 build_int_cst (TREE_TYPE (vr1min), 1));
8136 if (!operand_less_p (max, min))
8138 *vr0type = VR_ANTI_RANGE;
8139 *vr0min = min;
8140 *vr0max = max;
8142 else
8143 *vr0max = vr1max;
8145 else
8146 *vr0max = vr1max;
8148 else
8150 /* If the result can be an anti-range, create one. */
8151 if (TREE_CODE (vr1max) == INTEGER_CST
8152 && TREE_CODE (*vr0min) == INTEGER_CST
8153 && vrp_val_is_min (vr1min)
8154 && vrp_val_is_max (*vr0max))
8156 tree min = int_const_binop (PLUS_EXPR,
8157 vr1max,
8158 build_int_cst (TREE_TYPE (vr1max), 1));
8159 tree max = int_const_binop (MINUS_EXPR,
8160 *vr0min,
8161 build_int_cst (TREE_TYPE (*vr0min), 1));
8162 if (!operand_less_p (max, min))
8164 *vr0type = VR_ANTI_RANGE;
8165 *vr0min = min;
8166 *vr0max = max;
8168 else
8169 *vr0min = vr1min;
8171 else
8172 *vr0min = vr1min;
8175 else
8176 gcc_unreachable ();
8178 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
8179 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
8181 /* [ ( ) ] or [( ) ] or [ ( )] */
8182 if (*vr0type == VR_RANGE
8183 && vr1type == VR_RANGE)
8185 else if (*vr0type == VR_ANTI_RANGE
8186 && vr1type == VR_ANTI_RANGE)
8188 *vr0type = vr1type;
8189 *vr0min = vr1min;
8190 *vr0max = vr1max;
8192 else if (*vr0type == VR_ANTI_RANGE
8193 && vr1type == VR_RANGE)
8195 /* Arbitrarily choose the right or left gap. */
8196 if (!mineq && TREE_CODE (vr1min) == INTEGER_CST)
8197 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8198 build_int_cst (TREE_TYPE (vr1min), 1));
8199 else if (!maxeq && TREE_CODE (vr1max) == INTEGER_CST)
8200 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
8201 build_int_cst (TREE_TYPE (vr1max), 1));
8202 else
8203 goto give_up;
8205 else if (*vr0type == VR_RANGE
8206 && vr1type == VR_ANTI_RANGE)
8207 /* The result covers everything. */
8208 goto give_up;
8209 else
8210 gcc_unreachable ();
8212 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
8213 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
8215 /* ( [ ] ) or ([ ] ) or ( [ ]) */
8216 if (*vr0type == VR_RANGE
8217 && vr1type == VR_RANGE)
8219 *vr0type = vr1type;
8220 *vr0min = vr1min;
8221 *vr0max = vr1max;
8223 else if (*vr0type == VR_ANTI_RANGE
8224 && vr1type == VR_ANTI_RANGE)
8226 else if (*vr0type == VR_RANGE
8227 && vr1type == VR_ANTI_RANGE)
8229 *vr0type = VR_ANTI_RANGE;
8230 if (!mineq && TREE_CODE (*vr0min) == INTEGER_CST)
8232 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
8233 build_int_cst (TREE_TYPE (*vr0min), 1));
8234 *vr0min = vr1min;
8236 else if (!maxeq && TREE_CODE (*vr0max) == INTEGER_CST)
8238 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8239 build_int_cst (TREE_TYPE (*vr0max), 1));
8240 *vr0max = vr1max;
8242 else
8243 goto give_up;
8245 else if (*vr0type == VR_ANTI_RANGE
8246 && vr1type == VR_RANGE)
8247 /* The result covers everything. */
8248 goto give_up;
8249 else
8250 gcc_unreachable ();
8252 else if ((operand_less_p (vr1min, *vr0max) == 1
8253 || operand_equal_p (vr1min, *vr0max, 0))
8254 && operand_less_p (*vr0min, vr1min) == 1
8255 && operand_less_p (*vr0max, vr1max) == 1)
8257 /* [ ( ] ) or [ ]( ) */
8258 if (*vr0type == VR_RANGE
8259 && vr1type == VR_RANGE)
8260 *vr0max = vr1max;
8261 else if (*vr0type == VR_ANTI_RANGE
8262 && vr1type == VR_ANTI_RANGE)
8263 *vr0min = vr1min;
8264 else if (*vr0type == VR_ANTI_RANGE
8265 && vr1type == VR_RANGE)
8267 if (TREE_CODE (vr1min) == INTEGER_CST)
8268 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8269 build_int_cst (TREE_TYPE (vr1min), 1));
8270 else
8271 goto give_up;
8273 else if (*vr0type == VR_RANGE
8274 && vr1type == VR_ANTI_RANGE)
8276 if (TREE_CODE (*vr0max) == INTEGER_CST)
8278 *vr0type = vr1type;
8279 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8280 build_int_cst (TREE_TYPE (*vr0max), 1));
8281 *vr0max = vr1max;
8283 else
8284 goto give_up;
8286 else
8287 gcc_unreachable ();
8289 else if ((operand_less_p (*vr0min, vr1max) == 1
8290 || operand_equal_p (*vr0min, vr1max, 0))
8291 && operand_less_p (vr1min, *vr0min) == 1
8292 && operand_less_p (vr1max, *vr0max) == 1)
8294 /* ( [ ) ] or ( )[ ] */
8295 if (*vr0type == VR_RANGE
8296 && vr1type == VR_RANGE)
8297 *vr0min = vr1min;
8298 else if (*vr0type == VR_ANTI_RANGE
8299 && vr1type == VR_ANTI_RANGE)
8300 *vr0max = vr1max;
8301 else if (*vr0type == VR_ANTI_RANGE
8302 && vr1type == VR_RANGE)
8304 if (TREE_CODE (vr1max) == INTEGER_CST)
8305 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
8306 build_int_cst (TREE_TYPE (vr1max), 1));
8307 else
8308 goto give_up;
8310 else if (*vr0type == VR_RANGE
8311 && vr1type == VR_ANTI_RANGE)
8313 if (TREE_CODE (*vr0min) == INTEGER_CST)
8315 *vr0type = vr1type;
8316 *vr0min = vr1min;
8317 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
8318 build_int_cst (TREE_TYPE (*vr0min), 1));
8320 else
8321 goto give_up;
8323 else
8324 gcc_unreachable ();
8326 else
8327 goto give_up;
8329 return;
8331 give_up:
8332 *vr0type = VR_VARYING;
8333 *vr0min = NULL_TREE;
8334 *vr0max = NULL_TREE;
8337 /* Intersect the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
8338 { VR1TYPE, VR0MIN, VR0MAX } and store the result
8339 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
8340 possible such range. The resulting range is not canonicalized. */
8342 static void
8343 intersect_ranges (enum value_range_type *vr0type,
8344 tree *vr0min, tree *vr0max,
8345 enum value_range_type vr1type,
8346 tree vr1min, tree vr1max)
8348 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
8349 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
8351 /* [] is vr0, () is vr1 in the following classification comments. */
8352 if (mineq && maxeq)
8354 /* [( )] */
8355 if (*vr0type == vr1type)
8356 /* Nothing to do for equal ranges. */
8358 else if ((*vr0type == VR_RANGE
8359 && vr1type == VR_ANTI_RANGE)
8360 || (*vr0type == VR_ANTI_RANGE
8361 && vr1type == VR_RANGE))
8363 /* For anti-range with range intersection the result is empty. */
8364 *vr0type = VR_UNDEFINED;
8365 *vr0min = NULL_TREE;
8366 *vr0max = NULL_TREE;
8368 else
8369 gcc_unreachable ();
8371 else if (operand_less_p (*vr0max, vr1min) == 1
8372 || operand_less_p (vr1max, *vr0min) == 1)
8374 /* [ ] ( ) or ( ) [ ]
8375 If the ranges have an empty intersection, the result of the
8376 intersect operation is the range for intersecting an
8377 anti-range with a range or empty when intersecting two ranges. */
8378 if (*vr0type == VR_RANGE
8379 && vr1type == VR_ANTI_RANGE)
8381 else if (*vr0type == VR_ANTI_RANGE
8382 && vr1type == VR_RANGE)
8384 *vr0type = vr1type;
8385 *vr0min = vr1min;
8386 *vr0max = vr1max;
8388 else if (*vr0type == VR_RANGE
8389 && vr1type == VR_RANGE)
8391 *vr0type = VR_UNDEFINED;
8392 *vr0min = NULL_TREE;
8393 *vr0max = NULL_TREE;
8395 else if (*vr0type == VR_ANTI_RANGE
8396 && vr1type == VR_ANTI_RANGE)
8398 /* If the anti-ranges are adjacent to each other merge them. */
8399 if (TREE_CODE (*vr0max) == INTEGER_CST
8400 && TREE_CODE (vr1min) == INTEGER_CST
8401 && operand_less_p (*vr0max, vr1min) == 1
8402 && integer_onep (int_const_binop (MINUS_EXPR,
8403 vr1min, *vr0max)))
8404 *vr0max = vr1max;
8405 else if (TREE_CODE (vr1max) == INTEGER_CST
8406 && TREE_CODE (*vr0min) == INTEGER_CST
8407 && operand_less_p (vr1max, *vr0min) == 1
8408 && integer_onep (int_const_binop (MINUS_EXPR,
8409 *vr0min, vr1max)))
8410 *vr0min = vr1min;
8411 /* Else arbitrarily take VR0. */
8414 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
8415 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
8417 /* [ ( ) ] or [( ) ] or [ ( )] */
8418 if (*vr0type == VR_RANGE
8419 && vr1type == VR_RANGE)
8421 /* If both are ranges the result is the inner one. */
8422 *vr0type = vr1type;
8423 *vr0min = vr1min;
8424 *vr0max = vr1max;
8426 else if (*vr0type == VR_RANGE
8427 && vr1type == VR_ANTI_RANGE)
8429 /* Choose the right gap if the left one is empty. */
8430 if (mineq)
8432 if (TREE_CODE (vr1max) == INTEGER_CST)
8433 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
8434 build_int_cst (TREE_TYPE (vr1max), 1));
8435 else
8436 *vr0min = vr1max;
8438 /* Choose the left gap if the right one is empty. */
8439 else if (maxeq)
8441 if (TREE_CODE (vr1min) == INTEGER_CST)
8442 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8443 build_int_cst (TREE_TYPE (vr1min), 1));
8444 else
8445 *vr0max = vr1min;
8447 /* Choose the anti-range if the range is effectively varying. */
8448 else if (vrp_val_is_min (*vr0min)
8449 && vrp_val_is_max (*vr0max))
8451 *vr0type = vr1type;
8452 *vr0min = vr1min;
8453 *vr0max = vr1max;
8455 /* Else choose the range. */
8457 else if (*vr0type == VR_ANTI_RANGE
8458 && vr1type == VR_ANTI_RANGE)
8459 /* If both are anti-ranges the result is the outer one. */
8461 else if (*vr0type == VR_ANTI_RANGE
8462 && vr1type == VR_RANGE)
8464 /* The intersection is empty. */
8465 *vr0type = VR_UNDEFINED;
8466 *vr0min = NULL_TREE;
8467 *vr0max = NULL_TREE;
8469 else
8470 gcc_unreachable ();
8472 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
8473 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
8475 /* ( [ ] ) or ([ ] ) or ( [ ]) */
8476 if (*vr0type == VR_RANGE
8477 && vr1type == VR_RANGE)
8478 /* Choose the inner range. */
8480 else if (*vr0type == VR_ANTI_RANGE
8481 && vr1type == VR_RANGE)
8483 /* Choose the right gap if the left is empty. */
8484 if (mineq)
8486 *vr0type = VR_RANGE;
8487 if (TREE_CODE (*vr0max) == INTEGER_CST)
8488 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8489 build_int_cst (TREE_TYPE (*vr0max), 1));
8490 else
8491 *vr0min = *vr0max;
8492 *vr0max = vr1max;
8494 /* Choose the left gap if the right is empty. */
8495 else if (maxeq)
8497 *vr0type = VR_RANGE;
8498 if (TREE_CODE (*vr0min) == INTEGER_CST)
8499 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
8500 build_int_cst (TREE_TYPE (*vr0min), 1));
8501 else
8502 *vr0max = *vr0min;
8503 *vr0min = vr1min;
8505 /* Choose the anti-range if the range is effectively varying. */
8506 else if (vrp_val_is_min (vr1min)
8507 && vrp_val_is_max (vr1max))
8509 /* Else choose the range. */
8510 else
8512 *vr0type = vr1type;
8513 *vr0min = vr1min;
8514 *vr0max = vr1max;
8517 else if (*vr0type == VR_ANTI_RANGE
8518 && vr1type == VR_ANTI_RANGE)
8520 /* If both are anti-ranges the result is the outer one. */
8521 *vr0type = vr1type;
8522 *vr0min = vr1min;
8523 *vr0max = vr1max;
8525 else if (vr1type == VR_ANTI_RANGE
8526 && *vr0type == VR_RANGE)
8528 /* The intersection is empty. */
8529 *vr0type = VR_UNDEFINED;
8530 *vr0min = NULL_TREE;
8531 *vr0max = NULL_TREE;
8533 else
8534 gcc_unreachable ();
8536 else if ((operand_less_p (vr1min, *vr0max) == 1
8537 || operand_equal_p (vr1min, *vr0max, 0))
8538 && operand_less_p (*vr0min, vr1min) == 1)
8540 /* [ ( ] ) or [ ]( ) */
8541 if (*vr0type == VR_ANTI_RANGE
8542 && vr1type == VR_ANTI_RANGE)
8543 *vr0max = vr1max;
8544 else if (*vr0type == VR_RANGE
8545 && vr1type == VR_RANGE)
8546 *vr0min = vr1min;
8547 else if (*vr0type == VR_RANGE
8548 && vr1type == VR_ANTI_RANGE)
8550 if (TREE_CODE (vr1min) == INTEGER_CST)
8551 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8552 build_int_cst (TREE_TYPE (vr1min), 1));
8553 else
8554 *vr0max = vr1min;
8556 else if (*vr0type == VR_ANTI_RANGE
8557 && vr1type == VR_RANGE)
8559 *vr0type = VR_RANGE;
8560 if (TREE_CODE (*vr0max) == INTEGER_CST)
8561 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8562 build_int_cst (TREE_TYPE (*vr0max), 1));
8563 else
8564 *vr0min = *vr0max;
8565 *vr0max = vr1max;
8567 else
8568 gcc_unreachable ();
8570 else if ((operand_less_p (*vr0min, vr1max) == 1
8571 || operand_equal_p (*vr0min, vr1max, 0))
8572 && operand_less_p (vr1min, *vr0min) == 1)
8574 /* ( [ ) ] or ( )[ ] */
8575 if (*vr0type == VR_ANTI_RANGE
8576 && vr1type == VR_ANTI_RANGE)
8577 *vr0min = vr1min;
8578 else if (*vr0type == VR_RANGE
8579 && vr1type == VR_RANGE)
8580 *vr0max = vr1max;
8581 else if (*vr0type == VR_RANGE
8582 && vr1type == VR_ANTI_RANGE)
8584 if (TREE_CODE (vr1max) == INTEGER_CST)
8585 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
8586 build_int_cst (TREE_TYPE (vr1max), 1));
8587 else
8588 *vr0min = vr1max;
8590 else if (*vr0type == VR_ANTI_RANGE
8591 && vr1type == VR_RANGE)
8593 *vr0type = VR_RANGE;
8594 if (TREE_CODE (*vr0min) == INTEGER_CST)
8595 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
8596 build_int_cst (TREE_TYPE (*vr0min), 1));
8597 else
8598 *vr0max = *vr0min;
8599 *vr0min = vr1min;
8601 else
8602 gcc_unreachable ();
8605 /* As a fallback simply use { *VRTYPE, *VR0MIN, *VR0MAX } as
8606 result for the intersection. That's always a conservative
8607 correct estimate unless VR1 is a constant singleton range
8608 in which case we choose that. */
8609 if (vr1type == VR_RANGE
8610 && is_gimple_min_invariant (vr1min)
8611 && vrp_operand_equal_p (vr1min, vr1max))
8613 *vr0type = vr1type;
8614 *vr0min = vr1min;
8615 *vr0max = vr1max;
8618 return;
8622 /* Intersect the two value-ranges *VR0 and *VR1 and store the result
8623 in *VR0. This may not be the smallest possible such range. */
8625 static void
8626 vrp_intersect_ranges_1 (value_range *vr0, value_range *vr1)
8628 value_range saved;
8630 /* If either range is VR_VARYING the other one wins. */
8631 if (vr1->type == VR_VARYING)
8632 return;
8633 if (vr0->type == VR_VARYING)
8635 copy_value_range (vr0, vr1);
8636 return;
8639 /* When either range is VR_UNDEFINED the resulting range is
8640 VR_UNDEFINED, too. */
8641 if (vr0->type == VR_UNDEFINED)
8642 return;
8643 if (vr1->type == VR_UNDEFINED)
8645 set_value_range_to_undefined (vr0);
8646 return;
8649 /* Save the original vr0 so we can return it as conservative intersection
8650 result when our worker turns things to varying. */
8651 saved = *vr0;
8652 intersect_ranges (&vr0->type, &vr0->min, &vr0->max,
8653 vr1->type, vr1->min, vr1->max);
8654 /* Make sure to canonicalize the result though as the inversion of a
8655 VR_RANGE can still be a VR_RANGE. */
8656 set_and_canonicalize_value_range (vr0, vr0->type,
8657 vr0->min, vr0->max, vr0->equiv);
8658 /* If that failed, use the saved original VR0. */
8659 if (vr0->type == VR_VARYING)
8661 *vr0 = saved;
8662 return;
8664 /* If the result is VR_UNDEFINED there is no need to mess with
8665 the equivalencies. */
8666 if (vr0->type == VR_UNDEFINED)
8667 return;
8669 /* The resulting set of equivalences for range intersection is the union of
8670 the two sets. */
8671 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
8672 bitmap_ior_into (vr0->equiv, vr1->equiv);
8673 else if (vr1->equiv && !vr0->equiv)
8675 vr0->equiv = BITMAP_ALLOC (&vrp_equiv_obstack);
8676 bitmap_copy (vr0->equiv, vr1->equiv);
8680 void
8681 vrp_intersect_ranges (value_range *vr0, value_range *vr1)
8683 if (dump_file && (dump_flags & TDF_DETAILS))
8685 fprintf (dump_file, "Intersecting\n ");
8686 dump_value_range (dump_file, vr0);
8687 fprintf (dump_file, "\nand\n ");
8688 dump_value_range (dump_file, vr1);
8689 fprintf (dump_file, "\n");
8691 vrp_intersect_ranges_1 (vr0, vr1);
8692 if (dump_file && (dump_flags & TDF_DETAILS))
8694 fprintf (dump_file, "to\n ");
8695 dump_value_range (dump_file, vr0);
8696 fprintf (dump_file, "\n");
8700 /* Meet operation for value ranges. Given two value ranges VR0 and
8701 VR1, store in VR0 a range that contains both VR0 and VR1. This
8702 may not be the smallest possible such range. */
8704 static void
8705 vrp_meet_1 (value_range *vr0, const value_range *vr1)
8707 value_range saved;
8709 if (vr0->type == VR_UNDEFINED)
8711 set_value_range (vr0, vr1->type, vr1->min, vr1->max, vr1->equiv);
8712 return;
8715 if (vr1->type == VR_UNDEFINED)
8717 /* VR0 already has the resulting range. */
8718 return;
8721 if (vr0->type == VR_VARYING)
8723 /* Nothing to do. VR0 already has the resulting range. */
8724 return;
8727 if (vr1->type == VR_VARYING)
8729 set_value_range_to_varying (vr0);
8730 return;
8733 saved = *vr0;
8734 union_ranges (&vr0->type, &vr0->min, &vr0->max,
8735 vr1->type, vr1->min, vr1->max);
8736 if (vr0->type == VR_VARYING)
8738 /* Failed to find an efficient meet. Before giving up and setting
8739 the result to VARYING, see if we can at least derive a useful
8740 anti-range. FIXME, all this nonsense about distinguishing
8741 anti-ranges from ranges is necessary because of the odd
8742 semantics of range_includes_zero_p and friends. */
8743 if (((saved.type == VR_RANGE
8744 && range_includes_zero_p (saved.min, saved.max) == 0)
8745 || (saved.type == VR_ANTI_RANGE
8746 && range_includes_zero_p (saved.min, saved.max) == 1))
8747 && ((vr1->type == VR_RANGE
8748 && range_includes_zero_p (vr1->min, vr1->max) == 0)
8749 || (vr1->type == VR_ANTI_RANGE
8750 && range_includes_zero_p (vr1->min, vr1->max) == 1)))
8752 set_value_range_to_nonnull (vr0, TREE_TYPE (saved.min));
8754 /* Since this meet operation did not result from the meeting of
8755 two equivalent names, VR0 cannot have any equivalences. */
8756 if (vr0->equiv)
8757 bitmap_clear (vr0->equiv);
8758 return;
8761 set_value_range_to_varying (vr0);
8762 return;
8764 set_and_canonicalize_value_range (vr0, vr0->type, vr0->min, vr0->max,
8765 vr0->equiv);
8766 if (vr0->type == VR_VARYING)
8767 return;
8769 /* The resulting set of equivalences is always the intersection of
8770 the two sets. */
8771 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
8772 bitmap_and_into (vr0->equiv, vr1->equiv);
8773 else if (vr0->equiv && !vr1->equiv)
8774 bitmap_clear (vr0->equiv);
8777 void
8778 vrp_meet (value_range *vr0, const value_range *vr1)
8780 if (dump_file && (dump_flags & TDF_DETAILS))
8782 fprintf (dump_file, "Meeting\n ");
8783 dump_value_range (dump_file, vr0);
8784 fprintf (dump_file, "\nand\n ");
8785 dump_value_range (dump_file, vr1);
8786 fprintf (dump_file, "\n");
8788 vrp_meet_1 (vr0, vr1);
8789 if (dump_file && (dump_flags & TDF_DETAILS))
8791 fprintf (dump_file, "to\n ");
8792 dump_value_range (dump_file, vr0);
8793 fprintf (dump_file, "\n");
8798 /* Visit all arguments for PHI node PHI that flow through executable
8799 edges. If a valid value range can be derived from all the incoming
8800 value ranges, set a new range in VR_RESULT. */
8802 static void
8803 extract_range_from_phi_node (gphi *phi, value_range *vr_result)
8805 size_t i;
8806 tree lhs = PHI_RESULT (phi);
8807 value_range *lhs_vr = get_value_range (lhs);
8808 bool first = true;
8809 int edges, old_edges;
8810 struct loop *l;
8812 if (dump_file && (dump_flags & TDF_DETAILS))
8814 fprintf (dump_file, "\nVisiting PHI node: ");
8815 print_gimple_stmt (dump_file, phi, 0, dump_flags);
8818 bool may_simulate_backedge_again = false;
8819 edges = 0;
8820 for (i = 0; i < gimple_phi_num_args (phi); i++)
8822 edge e = gimple_phi_arg_edge (phi, i);
8824 if (dump_file && (dump_flags & TDF_DETAILS))
8826 fprintf (dump_file,
8827 " Argument #%d (%d -> %d %sexecutable)\n",
8828 (int) i, e->src->index, e->dest->index,
8829 (e->flags & EDGE_EXECUTABLE) ? "" : "not ");
8832 if (e->flags & EDGE_EXECUTABLE)
8834 tree arg = PHI_ARG_DEF (phi, i);
8835 value_range vr_arg;
8837 ++edges;
8839 if (TREE_CODE (arg) == SSA_NAME)
8841 /* See if we are eventually going to change one of the args. */
8842 gimple *def_stmt = SSA_NAME_DEF_STMT (arg);
8843 if (! gimple_nop_p (def_stmt)
8844 && prop_simulate_again_p (def_stmt)
8845 && e->flags & EDGE_DFS_BACK)
8846 may_simulate_backedge_again = true;
8848 vr_arg = *(get_value_range (arg));
8849 /* Do not allow equivalences or symbolic ranges to leak in from
8850 backedges. That creates invalid equivalencies.
8851 See PR53465 and PR54767. */
8852 if (e->flags & EDGE_DFS_BACK)
8854 if (vr_arg.type == VR_RANGE
8855 || vr_arg.type == VR_ANTI_RANGE)
8857 vr_arg.equiv = NULL;
8858 if (symbolic_range_p (&vr_arg))
8860 vr_arg.type = VR_VARYING;
8861 vr_arg.min = NULL_TREE;
8862 vr_arg.max = NULL_TREE;
8866 else
8868 /* If the non-backedge arguments range is VR_VARYING then
8869 we can still try recording a simple equivalence. */
8870 if (vr_arg.type == VR_VARYING)
8872 vr_arg.type = VR_RANGE;
8873 vr_arg.min = arg;
8874 vr_arg.max = arg;
8875 vr_arg.equiv = NULL;
8879 else
8881 if (TREE_OVERFLOW_P (arg))
8882 arg = drop_tree_overflow (arg);
8884 vr_arg.type = VR_RANGE;
8885 vr_arg.min = arg;
8886 vr_arg.max = arg;
8887 vr_arg.equiv = NULL;
8890 if (dump_file && (dump_flags & TDF_DETAILS))
8892 fprintf (dump_file, "\t");
8893 print_generic_expr (dump_file, arg, dump_flags);
8894 fprintf (dump_file, ": ");
8895 dump_value_range (dump_file, &vr_arg);
8896 fprintf (dump_file, "\n");
8899 if (first)
8900 copy_value_range (vr_result, &vr_arg);
8901 else
8902 vrp_meet (vr_result, &vr_arg);
8903 first = false;
8905 if (vr_result->type == VR_VARYING)
8906 break;
8910 if (vr_result->type == VR_VARYING)
8911 goto varying;
8912 else if (vr_result->type == VR_UNDEFINED)
8913 goto update_range;
8915 old_edges = vr_phi_edge_counts[SSA_NAME_VERSION (lhs)];
8916 vr_phi_edge_counts[SSA_NAME_VERSION (lhs)] = edges;
8918 /* To prevent infinite iterations in the algorithm, derive ranges
8919 when the new value is slightly bigger or smaller than the
8920 previous one. We don't do this if we have seen a new executable
8921 edge; this helps us avoid an overflow infinity for conditionals
8922 which are not in a loop. If the old value-range was VR_UNDEFINED
8923 use the updated range and iterate one more time. If we will not
8924 simulate this PHI again via the backedge allow us to iterate. */
8925 if (edges > 0
8926 && gimple_phi_num_args (phi) > 1
8927 && edges == old_edges
8928 && lhs_vr->type != VR_UNDEFINED
8929 && may_simulate_backedge_again)
8931 /* Compare old and new ranges, fall back to varying if the
8932 values are not comparable. */
8933 int cmp_min = compare_values (lhs_vr->min, vr_result->min);
8934 if (cmp_min == -2)
8935 goto varying;
8936 int cmp_max = compare_values (lhs_vr->max, vr_result->max);
8937 if (cmp_max == -2)
8938 goto varying;
8940 /* For non VR_RANGE or for pointers fall back to varying if
8941 the range changed. */
8942 if ((lhs_vr->type != VR_RANGE || vr_result->type != VR_RANGE
8943 || POINTER_TYPE_P (TREE_TYPE (lhs)))
8944 && (cmp_min != 0 || cmp_max != 0))
8945 goto varying;
8947 /* If the new minimum is larger than the previous one
8948 retain the old value. If the new minimum value is smaller
8949 than the previous one and not -INF go all the way to -INF + 1.
8950 In the first case, to avoid infinite bouncing between different
8951 minimums, and in the other case to avoid iterating millions of
8952 times to reach -INF. Going to -INF + 1 also lets the following
8953 iteration compute whether there will be any overflow, at the
8954 expense of one additional iteration. */
8955 if (cmp_min < 0)
8956 vr_result->min = lhs_vr->min;
8957 else if (cmp_min > 0
8958 && !vrp_val_is_min (vr_result->min))
8959 vr_result->min
8960 = int_const_binop (PLUS_EXPR,
8961 vrp_val_min (TREE_TYPE (vr_result->min)),
8962 build_int_cst (TREE_TYPE (vr_result->min), 1));
8964 /* Similarly for the maximum value. */
8965 if (cmp_max > 0)
8966 vr_result->max = lhs_vr->max;
8967 else if (cmp_max < 0
8968 && !vrp_val_is_max (vr_result->max))
8969 vr_result->max
8970 = int_const_binop (MINUS_EXPR,
8971 vrp_val_max (TREE_TYPE (vr_result->min)),
8972 build_int_cst (TREE_TYPE (vr_result->min), 1));
8974 /* If we dropped either bound to +-INF then if this is a loop
8975 PHI node SCEV may known more about its value-range. */
8976 if (cmp_min > 0 || cmp_min < 0
8977 || cmp_max < 0 || cmp_max > 0)
8978 goto scev_check;
8980 goto infinite_check;
8983 goto update_range;
8985 varying:
8986 set_value_range_to_varying (vr_result);
8988 scev_check:
8989 /* If this is a loop PHI node SCEV may known more about its value-range.
8990 scev_check can be reached from two paths, one is a fall through from above
8991 "varying" label, the other is direct goto from code block which tries to
8992 avoid infinite simulation. */
8993 if ((l = loop_containing_stmt (phi))
8994 && l->header == gimple_bb (phi))
8995 adjust_range_with_scev (vr_result, l, phi, lhs);
8997 infinite_check:
8998 /* If we will end up with a (-INF, +INF) range, set it to
8999 VARYING. Same if the previous max value was invalid for
9000 the type and we end up with vr_result.min > vr_result.max. */
9001 if ((vr_result->type == VR_RANGE || vr_result->type == VR_ANTI_RANGE)
9002 && !((vrp_val_is_max (vr_result->max) && vrp_val_is_min (vr_result->min))
9003 || compare_values (vr_result->min, vr_result->max) > 0))
9005 else
9006 set_value_range_to_varying (vr_result);
9008 /* If the new range is different than the previous value, keep
9009 iterating. */
9010 update_range:
9011 return;
9014 /* Visit all arguments for PHI node PHI that flow through executable
9015 edges. If a valid value range can be derived from all the incoming
9016 value ranges, set a new range for the LHS of PHI. */
9018 static enum ssa_prop_result
9019 vrp_visit_phi_node (gphi *phi)
9021 tree lhs = PHI_RESULT (phi);
9022 value_range vr_result = VR_INITIALIZER;
9023 extract_range_from_phi_node (phi, &vr_result);
9024 if (update_value_range (lhs, &vr_result))
9026 if (dump_file && (dump_flags & TDF_DETAILS))
9028 fprintf (dump_file, "Found new range for ");
9029 print_generic_expr (dump_file, lhs, 0);
9030 fprintf (dump_file, ": ");
9031 dump_value_range (dump_file, &vr_result);
9032 fprintf (dump_file, "\n");
9035 if (vr_result.type == VR_VARYING)
9036 return SSA_PROP_VARYING;
9038 return SSA_PROP_INTERESTING;
9041 /* Nothing changed, don't add outgoing edges. */
9042 return SSA_PROP_NOT_INTERESTING;
9045 /* Simplify boolean operations if the source is known
9046 to be already a boolean. */
9047 static bool
9048 simplify_truth_ops_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9050 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
9051 tree lhs, op0, op1;
9052 bool need_conversion;
9054 /* We handle only !=/== case here. */
9055 gcc_assert (rhs_code == EQ_EXPR || rhs_code == NE_EXPR);
9057 op0 = gimple_assign_rhs1 (stmt);
9058 if (!op_with_boolean_value_range_p (op0))
9059 return false;
9061 op1 = gimple_assign_rhs2 (stmt);
9062 if (!op_with_boolean_value_range_p (op1))
9063 return false;
9065 /* Reduce number of cases to handle to NE_EXPR. As there is no
9066 BIT_XNOR_EXPR we cannot replace A == B with a single statement. */
9067 if (rhs_code == EQ_EXPR)
9069 if (TREE_CODE (op1) == INTEGER_CST)
9070 op1 = int_const_binop (BIT_XOR_EXPR, op1,
9071 build_int_cst (TREE_TYPE (op1), 1));
9072 else
9073 return false;
9076 lhs = gimple_assign_lhs (stmt);
9077 need_conversion
9078 = !useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (op0));
9080 /* Make sure to not sign-extend a 1-bit 1 when converting the result. */
9081 if (need_conversion
9082 && !TYPE_UNSIGNED (TREE_TYPE (op0))
9083 && TYPE_PRECISION (TREE_TYPE (op0)) == 1
9084 && TYPE_PRECISION (TREE_TYPE (lhs)) > 1)
9085 return false;
9087 /* For A != 0 we can substitute A itself. */
9088 if (integer_zerop (op1))
9089 gimple_assign_set_rhs_with_ops (gsi,
9090 need_conversion
9091 ? NOP_EXPR : TREE_CODE (op0), op0);
9092 /* For A != B we substitute A ^ B. Either with conversion. */
9093 else if (need_conversion)
9095 tree tem = make_ssa_name (TREE_TYPE (op0));
9096 gassign *newop
9097 = gimple_build_assign (tem, BIT_XOR_EXPR, op0, op1);
9098 gsi_insert_before (gsi, newop, GSI_SAME_STMT);
9099 if (INTEGRAL_TYPE_P (TREE_TYPE (tem))
9100 && TYPE_PRECISION (TREE_TYPE (tem)) > 1)
9101 set_range_info (tem, VR_RANGE,
9102 wi::zero (TYPE_PRECISION (TREE_TYPE (tem))),
9103 wi::one (TYPE_PRECISION (TREE_TYPE (tem))));
9104 gimple_assign_set_rhs_with_ops (gsi, NOP_EXPR, tem);
9106 /* Or without. */
9107 else
9108 gimple_assign_set_rhs_with_ops (gsi, BIT_XOR_EXPR, op0, op1);
9109 update_stmt (gsi_stmt (*gsi));
9110 fold_stmt (gsi, follow_single_use_edges);
9112 return true;
9115 /* Simplify a division or modulo operator to a right shift or
9116 bitwise and if the first operand is unsigned or is greater
9117 than zero and the second operand is an exact power of two.
9118 For TRUNC_MOD_EXPR op0 % op1 with constant op1, optimize it
9119 into just op0 if op0's range is known to be a subset of
9120 [-op1 + 1, op1 - 1] for signed and [0, op1 - 1] for unsigned
9121 modulo. */
9123 static bool
9124 simplify_div_or_mod_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9126 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
9127 tree val = NULL;
9128 tree op0 = gimple_assign_rhs1 (stmt);
9129 tree op1 = gimple_assign_rhs2 (stmt);
9130 value_range *vr = get_value_range (op0);
9132 if (rhs_code == TRUNC_MOD_EXPR
9133 && TREE_CODE (op1) == INTEGER_CST
9134 && tree_int_cst_sgn (op1) == 1
9135 && range_int_cst_p (vr)
9136 && tree_int_cst_lt (vr->max, op1))
9138 if (TYPE_UNSIGNED (TREE_TYPE (op0))
9139 || tree_int_cst_sgn (vr->min) >= 0
9140 || tree_int_cst_lt (fold_unary (NEGATE_EXPR, TREE_TYPE (op1), op1),
9141 vr->min))
9143 /* If op0 already has the range op0 % op1 has,
9144 then TRUNC_MOD_EXPR won't change anything. */
9145 gimple_assign_set_rhs_from_tree (gsi, op0);
9146 return true;
9150 if (!integer_pow2p (op1))
9152 /* X % -Y can be only optimized into X % Y either if
9153 X is not INT_MIN, or Y is not -1. Fold it now, as after
9154 remove_range_assertions the range info might be not available
9155 anymore. */
9156 if (rhs_code == TRUNC_MOD_EXPR
9157 && fold_stmt (gsi, follow_single_use_edges))
9158 return true;
9159 return false;
9162 if (TYPE_UNSIGNED (TREE_TYPE (op0)))
9163 val = integer_one_node;
9164 else
9166 bool sop = false;
9168 val = compare_range_with_value (GE_EXPR, vr, integer_zero_node, &sop);
9170 if (val
9171 && sop
9172 && integer_onep (val)
9173 && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
9175 location_t location;
9177 if (!gimple_has_location (stmt))
9178 location = input_location;
9179 else
9180 location = gimple_location (stmt);
9181 warning_at (location, OPT_Wstrict_overflow,
9182 "assuming signed overflow does not occur when "
9183 "simplifying %</%> or %<%%%> to %<>>%> or %<&%>");
9187 if (val && integer_onep (val))
9189 tree t;
9191 if (rhs_code == TRUNC_DIV_EXPR)
9193 t = build_int_cst (integer_type_node, tree_log2 (op1));
9194 gimple_assign_set_rhs_code (stmt, RSHIFT_EXPR);
9195 gimple_assign_set_rhs1 (stmt, op0);
9196 gimple_assign_set_rhs2 (stmt, t);
9198 else
9200 t = build_int_cst (TREE_TYPE (op1), 1);
9201 t = int_const_binop (MINUS_EXPR, op1, t);
9202 t = fold_convert (TREE_TYPE (op0), t);
9204 gimple_assign_set_rhs_code (stmt, BIT_AND_EXPR);
9205 gimple_assign_set_rhs1 (stmt, op0);
9206 gimple_assign_set_rhs2 (stmt, t);
9209 update_stmt (stmt);
9210 fold_stmt (gsi, follow_single_use_edges);
9211 return true;
9214 return false;
9217 /* Simplify a min or max if the ranges of the two operands are
9218 disjoint. Return true if we do simplify. */
9220 static bool
9221 simplify_min_or_max_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9223 tree op0 = gimple_assign_rhs1 (stmt);
9224 tree op1 = gimple_assign_rhs2 (stmt);
9225 bool sop = false;
9226 tree val;
9228 val = (vrp_evaluate_conditional_warnv_with_ops_using_ranges
9229 (LE_EXPR, op0, op1, &sop));
9230 if (!val)
9232 sop = false;
9233 val = (vrp_evaluate_conditional_warnv_with_ops_using_ranges
9234 (LT_EXPR, op0, op1, &sop));
9237 if (val)
9239 if (sop && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
9241 location_t location;
9243 if (!gimple_has_location (stmt))
9244 location = input_location;
9245 else
9246 location = gimple_location (stmt);
9247 warning_at (location, OPT_Wstrict_overflow,
9248 "assuming signed overflow does not occur when "
9249 "simplifying %<min/max (X,Y)%> to %<X%> or %<Y%>");
9252 /* VAL == TRUE -> OP0 < or <= op1
9253 VAL == FALSE -> OP0 > or >= op1. */
9254 tree res = ((gimple_assign_rhs_code (stmt) == MAX_EXPR)
9255 == integer_zerop (val)) ? op0 : op1;
9256 gimple_assign_set_rhs_from_tree (gsi, res);
9257 return true;
9260 return false;
9263 /* If the operand to an ABS_EXPR is >= 0, then eliminate the
9264 ABS_EXPR. If the operand is <= 0, then simplify the
9265 ABS_EXPR into a NEGATE_EXPR. */
9267 static bool
9268 simplify_abs_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9270 tree op = gimple_assign_rhs1 (stmt);
9271 value_range *vr = get_value_range (op);
9273 if (vr)
9275 tree val = NULL;
9276 bool sop = false;
9278 val = compare_range_with_value (LE_EXPR, vr, integer_zero_node, &sop);
9279 if (!val)
9281 /* The range is neither <= 0 nor > 0. Now see if it is
9282 either < 0 or >= 0. */
9283 sop = false;
9284 val = compare_range_with_value (LT_EXPR, vr, integer_zero_node,
9285 &sop);
9288 if (val)
9290 if (sop && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
9292 location_t location;
9294 if (!gimple_has_location (stmt))
9295 location = input_location;
9296 else
9297 location = gimple_location (stmt);
9298 warning_at (location, OPT_Wstrict_overflow,
9299 "assuming signed overflow does not occur when "
9300 "simplifying %<abs (X)%> to %<X%> or %<-X%>");
9303 gimple_assign_set_rhs1 (stmt, op);
9304 if (integer_zerop (val))
9305 gimple_assign_set_rhs_code (stmt, SSA_NAME);
9306 else
9307 gimple_assign_set_rhs_code (stmt, NEGATE_EXPR);
9308 update_stmt (stmt);
9309 fold_stmt (gsi, follow_single_use_edges);
9310 return true;
9314 return false;
9317 /* Optimize away redundant BIT_AND_EXPR and BIT_IOR_EXPR.
9318 If all the bits that are being cleared by & are already
9319 known to be zero from VR, or all the bits that are being
9320 set by | are already known to be one from VR, the bit
9321 operation is redundant. */
9323 static bool
9324 simplify_bit_ops_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9326 tree op0 = gimple_assign_rhs1 (stmt);
9327 tree op1 = gimple_assign_rhs2 (stmt);
9328 tree op = NULL_TREE;
9329 value_range vr0 = VR_INITIALIZER;
9330 value_range vr1 = VR_INITIALIZER;
9331 wide_int may_be_nonzero0, may_be_nonzero1;
9332 wide_int must_be_nonzero0, must_be_nonzero1;
9333 wide_int mask;
9335 if (TREE_CODE (op0) == SSA_NAME)
9336 vr0 = *(get_value_range (op0));
9337 else if (is_gimple_min_invariant (op0))
9338 set_value_range_to_value (&vr0, op0, NULL);
9339 else
9340 return false;
9342 if (TREE_CODE (op1) == SSA_NAME)
9343 vr1 = *(get_value_range (op1));
9344 else if (is_gimple_min_invariant (op1))
9345 set_value_range_to_value (&vr1, op1, NULL);
9346 else
9347 return false;
9349 if (!zero_nonzero_bits_from_vr (TREE_TYPE (op0), &vr0, &may_be_nonzero0,
9350 &must_be_nonzero0))
9351 return false;
9352 if (!zero_nonzero_bits_from_vr (TREE_TYPE (op1), &vr1, &may_be_nonzero1,
9353 &must_be_nonzero1))
9354 return false;
9356 switch (gimple_assign_rhs_code (stmt))
9358 case BIT_AND_EXPR:
9359 mask = may_be_nonzero0.and_not (must_be_nonzero1);
9360 if (mask == 0)
9362 op = op0;
9363 break;
9365 mask = may_be_nonzero1.and_not (must_be_nonzero0);
9366 if (mask == 0)
9368 op = op1;
9369 break;
9371 break;
9372 case BIT_IOR_EXPR:
9373 mask = may_be_nonzero0.and_not (must_be_nonzero1);
9374 if (mask == 0)
9376 op = op1;
9377 break;
9379 mask = may_be_nonzero1.and_not (must_be_nonzero0);
9380 if (mask == 0)
9382 op = op0;
9383 break;
9385 break;
9386 default:
9387 gcc_unreachable ();
9390 if (op == NULL_TREE)
9391 return false;
9393 gimple_assign_set_rhs_with_ops (gsi, TREE_CODE (op), op);
9394 update_stmt (gsi_stmt (*gsi));
9395 return true;
9398 /* We are comparing trees OP0 and OP1 using COND_CODE. OP0 has
9399 a known value range VR.
9401 If there is one and only one value which will satisfy the
9402 conditional, then return that value. Else return NULL.
9404 If signed overflow must be undefined for the value to satisfy
9405 the conditional, then set *STRICT_OVERFLOW_P to true. */
9407 static tree
9408 test_for_singularity (enum tree_code cond_code, tree op0,
9409 tree op1, value_range *vr,
9410 bool *strict_overflow_p)
9412 tree min = NULL;
9413 tree max = NULL;
9415 /* Extract minimum/maximum values which satisfy the conditional as it was
9416 written. */
9417 if (cond_code == LE_EXPR || cond_code == LT_EXPR)
9419 /* This should not be negative infinity; there is no overflow
9420 here. */
9421 min = TYPE_MIN_VALUE (TREE_TYPE (op0));
9423 max = op1;
9424 if (cond_code == LT_EXPR && !is_overflow_infinity (max))
9426 tree one = build_int_cst (TREE_TYPE (op0), 1);
9427 max = fold_build2 (MINUS_EXPR, TREE_TYPE (op0), max, one);
9428 if (EXPR_P (max))
9429 TREE_NO_WARNING (max) = 1;
9432 else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
9434 /* This should not be positive infinity; there is no overflow
9435 here. */
9436 max = TYPE_MAX_VALUE (TREE_TYPE (op0));
9438 min = op1;
9439 if (cond_code == GT_EXPR && !is_overflow_infinity (min))
9441 tree one = build_int_cst (TREE_TYPE (op0), 1);
9442 min = fold_build2 (PLUS_EXPR, TREE_TYPE (op0), min, one);
9443 if (EXPR_P (min))
9444 TREE_NO_WARNING (min) = 1;
9448 /* Now refine the minimum and maximum values using any
9449 value range information we have for op0. */
9450 if (min && max)
9452 if (compare_values (vr->min, min) == 1)
9453 min = vr->min;
9454 if (compare_values (vr->max, max) == -1)
9455 max = vr->max;
9457 /* If the new min/max values have converged to a single value,
9458 then there is only one value which can satisfy the condition,
9459 return that value. */
9460 if (operand_equal_p (min, max, 0) && is_gimple_min_invariant (min))
9462 if ((cond_code == LE_EXPR || cond_code == LT_EXPR)
9463 && is_overflow_infinity (vr->max))
9464 *strict_overflow_p = true;
9465 if ((cond_code == GE_EXPR || cond_code == GT_EXPR)
9466 && is_overflow_infinity (vr->min))
9467 *strict_overflow_p = true;
9469 return min;
9472 return NULL;
9475 /* Return whether the value range *VR fits in an integer type specified
9476 by PRECISION and UNSIGNED_P. */
9478 static bool
9479 range_fits_type_p (value_range *vr, unsigned dest_precision, signop dest_sgn)
9481 tree src_type;
9482 unsigned src_precision;
9483 widest_int tem;
9484 signop src_sgn;
9486 /* We can only handle integral and pointer types. */
9487 src_type = TREE_TYPE (vr->min);
9488 if (!INTEGRAL_TYPE_P (src_type)
9489 && !POINTER_TYPE_P (src_type))
9490 return false;
9492 /* An extension is fine unless VR is SIGNED and dest_sgn is UNSIGNED,
9493 and so is an identity transform. */
9494 src_precision = TYPE_PRECISION (TREE_TYPE (vr->min));
9495 src_sgn = TYPE_SIGN (src_type);
9496 if ((src_precision < dest_precision
9497 && !(dest_sgn == UNSIGNED && src_sgn == SIGNED))
9498 || (src_precision == dest_precision && src_sgn == dest_sgn))
9499 return true;
9501 /* Now we can only handle ranges with constant bounds. */
9502 if (vr->type != VR_RANGE
9503 || TREE_CODE (vr->min) != INTEGER_CST
9504 || TREE_CODE (vr->max) != INTEGER_CST)
9505 return false;
9507 /* For sign changes, the MSB of the wide_int has to be clear.
9508 An unsigned value with its MSB set cannot be represented by
9509 a signed wide_int, while a negative value cannot be represented
9510 by an unsigned wide_int. */
9511 if (src_sgn != dest_sgn
9512 && (wi::lts_p (vr->min, 0) || wi::lts_p (vr->max, 0)))
9513 return false;
9515 /* Then we can perform the conversion on both ends and compare
9516 the result for equality. */
9517 tem = wi::ext (wi::to_widest (vr->min), dest_precision, dest_sgn);
9518 if (tem != wi::to_widest (vr->min))
9519 return false;
9520 tem = wi::ext (wi::to_widest (vr->max), dest_precision, dest_sgn);
9521 if (tem != wi::to_widest (vr->max))
9522 return false;
9524 return true;
9527 /* Simplify a conditional using a relational operator to an equality
9528 test if the range information indicates only one value can satisfy
9529 the original conditional. */
9531 static bool
9532 simplify_cond_using_ranges (gcond *stmt)
9534 tree op0 = gimple_cond_lhs (stmt);
9535 tree op1 = gimple_cond_rhs (stmt);
9536 enum tree_code cond_code = gimple_cond_code (stmt);
9538 if (cond_code != NE_EXPR
9539 && cond_code != EQ_EXPR
9540 && TREE_CODE (op0) == SSA_NAME
9541 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
9542 && is_gimple_min_invariant (op1))
9544 value_range *vr = get_value_range (op0);
9546 /* If we have range information for OP0, then we might be
9547 able to simplify this conditional. */
9548 if (vr->type == VR_RANGE)
9550 enum warn_strict_overflow_code wc = WARN_STRICT_OVERFLOW_COMPARISON;
9551 bool sop = false;
9552 tree new_tree = test_for_singularity (cond_code, op0, op1, vr, &sop);
9554 if (new_tree
9555 && (!sop || TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (op0))))
9557 if (dump_file)
9559 fprintf (dump_file, "Simplified relational ");
9560 print_gimple_stmt (dump_file, stmt, 0, 0);
9561 fprintf (dump_file, " into ");
9564 gimple_cond_set_code (stmt, EQ_EXPR);
9565 gimple_cond_set_lhs (stmt, op0);
9566 gimple_cond_set_rhs (stmt, new_tree);
9568 update_stmt (stmt);
9570 if (dump_file)
9572 print_gimple_stmt (dump_file, stmt, 0, 0);
9573 fprintf (dump_file, "\n");
9576 if (sop && issue_strict_overflow_warning (wc))
9578 location_t location = input_location;
9579 if (gimple_has_location (stmt))
9580 location = gimple_location (stmt);
9582 warning_at (location, OPT_Wstrict_overflow,
9583 "assuming signed overflow does not occur when "
9584 "simplifying conditional");
9587 return true;
9590 /* Try again after inverting the condition. We only deal
9591 with integral types here, so no need to worry about
9592 issues with inverting FP comparisons. */
9593 sop = false;
9594 new_tree = test_for_singularity
9595 (invert_tree_comparison (cond_code, false),
9596 op0, op1, vr, &sop);
9598 if (new_tree
9599 && (!sop || TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (op0))))
9601 if (dump_file)
9603 fprintf (dump_file, "Simplified relational ");
9604 print_gimple_stmt (dump_file, stmt, 0, 0);
9605 fprintf (dump_file, " into ");
9608 gimple_cond_set_code (stmt, NE_EXPR);
9609 gimple_cond_set_lhs (stmt, op0);
9610 gimple_cond_set_rhs (stmt, new_tree);
9612 update_stmt (stmt);
9614 if (dump_file)
9616 print_gimple_stmt (dump_file, stmt, 0, 0);
9617 fprintf (dump_file, "\n");
9620 if (sop && issue_strict_overflow_warning (wc))
9622 location_t location = input_location;
9623 if (gimple_has_location (stmt))
9624 location = gimple_location (stmt);
9626 warning_at (location, OPT_Wstrict_overflow,
9627 "assuming signed overflow does not occur when "
9628 "simplifying conditional");
9631 return true;
9636 /* If we have a comparison of an SSA_NAME (OP0) against a constant,
9637 see if OP0 was set by a type conversion where the source of
9638 the conversion is another SSA_NAME with a range that fits
9639 into the range of OP0's type.
9641 If so, the conversion is redundant as the earlier SSA_NAME can be
9642 used for the comparison directly if we just massage the constant in the
9643 comparison. */
9644 if (TREE_CODE (op0) == SSA_NAME
9645 && TREE_CODE (op1) == INTEGER_CST)
9647 gimple *def_stmt = SSA_NAME_DEF_STMT (op0);
9648 tree innerop;
9650 if (!is_gimple_assign (def_stmt)
9651 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)))
9652 return false;
9654 innerop = gimple_assign_rhs1 (def_stmt);
9656 if (TREE_CODE (innerop) == SSA_NAME
9657 && !POINTER_TYPE_P (TREE_TYPE (innerop))
9658 && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (innerop)
9659 && desired_pro_or_demotion_p (TREE_TYPE (innerop), TREE_TYPE (op0)))
9661 value_range *vr = get_value_range (innerop);
9663 if (range_int_cst_p (vr)
9664 && range_fits_type_p (vr,
9665 TYPE_PRECISION (TREE_TYPE (op0)),
9666 TYPE_SIGN (TREE_TYPE (op0)))
9667 && int_fits_type_p (op1, TREE_TYPE (innerop))
9668 /* The range must not have overflowed, or if it did overflow
9669 we must not be wrapping/trapping overflow and optimizing
9670 with strict overflow semantics. */
9671 && ((!is_negative_overflow_infinity (vr->min)
9672 && !is_positive_overflow_infinity (vr->max))
9673 || TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (innerop))))
9675 /* If the range overflowed and the user has asked for warnings
9676 when strict overflow semantics were used to optimize code,
9677 issue an appropriate warning. */
9678 if (cond_code != EQ_EXPR && cond_code != NE_EXPR
9679 && (is_negative_overflow_infinity (vr->min)
9680 || is_positive_overflow_infinity (vr->max))
9681 && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_CONDITIONAL))
9683 location_t location;
9685 if (!gimple_has_location (stmt))
9686 location = input_location;
9687 else
9688 location = gimple_location (stmt);
9689 warning_at (location, OPT_Wstrict_overflow,
9690 "assuming signed overflow does not occur when "
9691 "simplifying conditional");
9694 tree newconst = fold_convert (TREE_TYPE (innerop), op1);
9695 gimple_cond_set_lhs (stmt, innerop);
9696 gimple_cond_set_rhs (stmt, newconst);
9697 return true;
9702 return false;
9705 /* Simplify a switch statement using the value range of the switch
9706 argument. */
9708 static bool
9709 simplify_switch_using_ranges (gswitch *stmt)
9711 tree op = gimple_switch_index (stmt);
9712 value_range *vr = NULL;
9713 bool take_default;
9714 edge e;
9715 edge_iterator ei;
9716 size_t i = 0, j = 0, n, n2;
9717 tree vec2;
9718 switch_update su;
9719 size_t k = 1, l = 0;
9721 if (TREE_CODE (op) == SSA_NAME)
9723 vr = get_value_range (op);
9725 /* We can only handle integer ranges. */
9726 if ((vr->type != VR_RANGE
9727 && vr->type != VR_ANTI_RANGE)
9728 || symbolic_range_p (vr))
9729 return false;
9731 /* Find case label for min/max of the value range. */
9732 take_default = !find_case_label_ranges (stmt, vr, &i, &j, &k, &l);
9734 else if (TREE_CODE (op) == INTEGER_CST)
9736 take_default = !find_case_label_index (stmt, 1, op, &i);
9737 if (take_default)
9739 i = 1;
9740 j = 0;
9742 else
9744 j = i;
9747 else
9748 return false;
9750 n = gimple_switch_num_labels (stmt);
9752 /* We can truncate the case label ranges that partially overlap with OP's
9753 value range. */
9754 size_t min_idx = 1, max_idx = 0;
9755 if (vr != NULL)
9756 find_case_label_range (stmt, vr->min, vr->max, &min_idx, &max_idx);
9757 if (min_idx <= max_idx)
9759 tree min_label = gimple_switch_label (stmt, min_idx);
9760 tree max_label = gimple_switch_label (stmt, max_idx);
9762 /* Avoid changing the type of the case labels when truncating. */
9763 tree case_label_type = TREE_TYPE (CASE_LOW (min_label));
9764 tree vr_min = fold_convert (case_label_type, vr->min);
9765 tree vr_max = fold_convert (case_label_type, vr->max);
9767 if (vr->type == VR_RANGE)
9769 /* If OP's value range is [2,8] and the low label range is
9770 0 ... 3, truncate the label's range to 2 .. 3. */
9771 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
9772 && CASE_HIGH (min_label) != NULL_TREE
9773 && tree_int_cst_compare (CASE_HIGH (min_label), vr_min) >= 0)
9774 CASE_LOW (min_label) = vr_min;
9776 /* If OP's value range is [2,8] and the high label range is
9777 7 ... 10, truncate the label's range to 7 .. 8. */
9778 if (tree_int_cst_compare (CASE_LOW (max_label), vr_max) <= 0
9779 && CASE_HIGH (max_label) != NULL_TREE
9780 && tree_int_cst_compare (CASE_HIGH (max_label), vr_max) > 0)
9781 CASE_HIGH (max_label) = vr_max;
9783 else if (vr->type == VR_ANTI_RANGE)
9785 tree one_cst = build_one_cst (case_label_type);
9787 if (min_label == max_label)
9789 /* If OP's value range is ~[7,8] and the label's range is
9790 7 ... 10, truncate the label's range to 9 ... 10. */
9791 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) == 0
9792 && CASE_HIGH (min_label) != NULL_TREE
9793 && tree_int_cst_compare (CASE_HIGH (min_label), vr_max) > 0)
9794 CASE_LOW (min_label)
9795 = int_const_binop (PLUS_EXPR, vr_max, one_cst);
9797 /* If OP's value range is ~[7,8] and the label's range is
9798 5 ... 8, truncate the label's range to 5 ... 6. */
9799 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
9800 && CASE_HIGH (min_label) != NULL_TREE
9801 && tree_int_cst_compare (CASE_HIGH (min_label), vr_max) == 0)
9802 CASE_HIGH (min_label)
9803 = int_const_binop (MINUS_EXPR, vr_min, one_cst);
9805 else
9807 /* If OP's value range is ~[2,8] and the low label range is
9808 0 ... 3, truncate the label's range to 0 ... 1. */
9809 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
9810 && CASE_HIGH (min_label) != NULL_TREE
9811 && tree_int_cst_compare (CASE_HIGH (min_label), vr_min) >= 0)
9812 CASE_HIGH (min_label)
9813 = int_const_binop (MINUS_EXPR, vr_min, one_cst);
9815 /* If OP's value range is ~[2,8] and the high label range is
9816 7 ... 10, truncate the label's range to 9 ... 10. */
9817 if (tree_int_cst_compare (CASE_LOW (max_label), vr_max) <= 0
9818 && CASE_HIGH (max_label) != NULL_TREE
9819 && tree_int_cst_compare (CASE_HIGH (max_label), vr_max) > 0)
9820 CASE_LOW (max_label)
9821 = int_const_binop (PLUS_EXPR, vr_max, one_cst);
9825 /* Canonicalize singleton case ranges. */
9826 if (tree_int_cst_equal (CASE_LOW (min_label), CASE_HIGH (min_label)))
9827 CASE_HIGH (min_label) = NULL_TREE;
9828 if (tree_int_cst_equal (CASE_LOW (max_label), CASE_HIGH (max_label)))
9829 CASE_HIGH (max_label) = NULL_TREE;
9832 /* We can also eliminate case labels that lie completely outside OP's value
9833 range. */
9835 /* Bail out if this is just all edges taken. */
9836 if (i == 1
9837 && j == n - 1
9838 && take_default)
9839 return false;
9841 /* Build a new vector of taken case labels. */
9842 vec2 = make_tree_vec (j - i + 1 + l - k + 1 + (int)take_default);
9843 n2 = 0;
9845 /* Add the default edge, if necessary. */
9846 if (take_default)
9847 TREE_VEC_ELT (vec2, n2++) = gimple_switch_default_label (stmt);
9849 for (; i <= j; ++i, ++n2)
9850 TREE_VEC_ELT (vec2, n2) = gimple_switch_label (stmt, i);
9852 for (; k <= l; ++k, ++n2)
9853 TREE_VEC_ELT (vec2, n2) = gimple_switch_label (stmt, k);
9855 /* Mark needed edges. */
9856 for (i = 0; i < n2; ++i)
9858 e = find_edge (gimple_bb (stmt),
9859 label_to_block (CASE_LABEL (TREE_VEC_ELT (vec2, i))));
9860 e->aux = (void *)-1;
9863 /* Queue not needed edges for later removal. */
9864 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
9866 if (e->aux == (void *)-1)
9868 e->aux = NULL;
9869 continue;
9872 if (dump_file && (dump_flags & TDF_DETAILS))
9874 fprintf (dump_file, "removing unreachable case label\n");
9876 to_remove_edges.safe_push (e);
9877 e->flags &= ~EDGE_EXECUTABLE;
9880 /* And queue an update for the stmt. */
9881 su.stmt = stmt;
9882 su.vec = vec2;
9883 to_update_switch_stmts.safe_push (su);
9884 return false;
9887 /* Simplify an integral conversion from an SSA name in STMT. */
9889 static bool
9890 simplify_conversion_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9892 tree innerop, middleop, finaltype;
9893 gimple *def_stmt;
9894 signop inner_sgn, middle_sgn, final_sgn;
9895 unsigned inner_prec, middle_prec, final_prec;
9896 widest_int innermin, innermed, innermax, middlemin, middlemed, middlemax;
9898 finaltype = TREE_TYPE (gimple_assign_lhs (stmt));
9899 if (!INTEGRAL_TYPE_P (finaltype))
9900 return false;
9901 middleop = gimple_assign_rhs1 (stmt);
9902 def_stmt = SSA_NAME_DEF_STMT (middleop);
9903 if (!is_gimple_assign (def_stmt)
9904 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)))
9905 return false;
9906 innerop = gimple_assign_rhs1 (def_stmt);
9907 if (TREE_CODE (innerop) != SSA_NAME
9908 || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (innerop))
9909 return false;
9911 /* Get the value-range of the inner operand. Use get_range_info in
9912 case innerop was created during substitute-and-fold. */
9913 wide_int imin, imax;
9914 if (!INTEGRAL_TYPE_P (TREE_TYPE (innerop))
9915 || get_range_info (innerop, &imin, &imax) != VR_RANGE)
9916 return false;
9917 innermin = widest_int::from (imin, TYPE_SIGN (TREE_TYPE (innerop)));
9918 innermax = widest_int::from (imax, TYPE_SIGN (TREE_TYPE (innerop)));
9920 /* Simulate the conversion chain to check if the result is equal if
9921 the middle conversion is removed. */
9922 inner_prec = TYPE_PRECISION (TREE_TYPE (innerop));
9923 middle_prec = TYPE_PRECISION (TREE_TYPE (middleop));
9924 final_prec = TYPE_PRECISION (finaltype);
9926 /* If the first conversion is not injective, the second must not
9927 be widening. */
9928 if (wi::gtu_p (innermax - innermin,
9929 wi::mask <widest_int> (middle_prec, false))
9930 && middle_prec < final_prec)
9931 return false;
9932 /* We also want a medium value so that we can track the effect that
9933 narrowing conversions with sign change have. */
9934 inner_sgn = TYPE_SIGN (TREE_TYPE (innerop));
9935 if (inner_sgn == UNSIGNED)
9936 innermed = wi::shifted_mask <widest_int> (1, inner_prec - 1, false);
9937 else
9938 innermed = 0;
9939 if (wi::cmp (innermin, innermed, inner_sgn) >= 0
9940 || wi::cmp (innermed, innermax, inner_sgn) >= 0)
9941 innermed = innermin;
9943 middle_sgn = TYPE_SIGN (TREE_TYPE (middleop));
9944 middlemin = wi::ext (innermin, middle_prec, middle_sgn);
9945 middlemed = wi::ext (innermed, middle_prec, middle_sgn);
9946 middlemax = wi::ext (innermax, middle_prec, middle_sgn);
9948 /* Require that the final conversion applied to both the original
9949 and the intermediate range produces the same result. */
9950 final_sgn = TYPE_SIGN (finaltype);
9951 if (wi::ext (middlemin, final_prec, final_sgn)
9952 != wi::ext (innermin, final_prec, final_sgn)
9953 || wi::ext (middlemed, final_prec, final_sgn)
9954 != wi::ext (innermed, final_prec, final_sgn)
9955 || wi::ext (middlemax, final_prec, final_sgn)
9956 != wi::ext (innermax, final_prec, final_sgn))
9957 return false;
9959 gimple_assign_set_rhs1 (stmt, innerop);
9960 fold_stmt (gsi, follow_single_use_edges);
9961 return true;
9964 /* Simplify a conversion from integral SSA name to float in STMT. */
9966 static bool
9967 simplify_float_conversion_using_ranges (gimple_stmt_iterator *gsi,
9968 gimple *stmt)
9970 tree rhs1 = gimple_assign_rhs1 (stmt);
9971 value_range *vr = get_value_range (rhs1);
9972 machine_mode fltmode = TYPE_MODE (TREE_TYPE (gimple_assign_lhs (stmt)));
9973 machine_mode mode;
9974 tree tem;
9975 gassign *conv;
9977 /* We can only handle constant ranges. */
9978 if (vr->type != VR_RANGE
9979 || TREE_CODE (vr->min) != INTEGER_CST
9980 || TREE_CODE (vr->max) != INTEGER_CST)
9981 return false;
9983 /* First check if we can use a signed type in place of an unsigned. */
9984 if (TYPE_UNSIGNED (TREE_TYPE (rhs1))
9985 && (can_float_p (fltmode, TYPE_MODE (TREE_TYPE (rhs1)), 0)
9986 != CODE_FOR_nothing)
9987 && range_fits_type_p (vr, TYPE_PRECISION (TREE_TYPE (rhs1)), SIGNED))
9988 mode = TYPE_MODE (TREE_TYPE (rhs1));
9989 /* If we can do the conversion in the current input mode do nothing. */
9990 else if (can_float_p (fltmode, TYPE_MODE (TREE_TYPE (rhs1)),
9991 TYPE_UNSIGNED (TREE_TYPE (rhs1))) != CODE_FOR_nothing)
9992 return false;
9993 /* Otherwise search for a mode we can use, starting from the narrowest
9994 integer mode available. */
9995 else
9997 mode = GET_CLASS_NARROWEST_MODE (MODE_INT);
10000 /* If we cannot do a signed conversion to float from mode
10001 or if the value-range does not fit in the signed type
10002 try with a wider mode. */
10003 if (can_float_p (fltmode, mode, 0) != CODE_FOR_nothing
10004 && range_fits_type_p (vr, GET_MODE_PRECISION (mode), SIGNED))
10005 break;
10007 mode = GET_MODE_WIDER_MODE (mode);
10008 /* But do not widen the input. Instead leave that to the
10009 optabs expansion code. */
10010 if (GET_MODE_PRECISION (mode) > TYPE_PRECISION (TREE_TYPE (rhs1)))
10011 return false;
10013 while (mode != VOIDmode);
10014 if (mode == VOIDmode)
10015 return false;
10018 /* It works, insert a truncation or sign-change before the
10019 float conversion. */
10020 tem = make_ssa_name (build_nonstandard_integer_type
10021 (GET_MODE_PRECISION (mode), 0));
10022 conv = gimple_build_assign (tem, NOP_EXPR, rhs1);
10023 gsi_insert_before (gsi, conv, GSI_SAME_STMT);
10024 gimple_assign_set_rhs1 (stmt, tem);
10025 fold_stmt (gsi, follow_single_use_edges);
10027 return true;
10030 /* Simplify an internal fn call using ranges if possible. */
10032 static bool
10033 simplify_internal_call_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
10035 enum tree_code subcode;
10036 bool is_ubsan = false;
10037 bool ovf = false;
10038 switch (gimple_call_internal_fn (stmt))
10040 case IFN_UBSAN_CHECK_ADD:
10041 subcode = PLUS_EXPR;
10042 is_ubsan = true;
10043 break;
10044 case IFN_UBSAN_CHECK_SUB:
10045 subcode = MINUS_EXPR;
10046 is_ubsan = true;
10047 break;
10048 case IFN_UBSAN_CHECK_MUL:
10049 subcode = MULT_EXPR;
10050 is_ubsan = true;
10051 break;
10052 case IFN_ADD_OVERFLOW:
10053 subcode = PLUS_EXPR;
10054 break;
10055 case IFN_SUB_OVERFLOW:
10056 subcode = MINUS_EXPR;
10057 break;
10058 case IFN_MUL_OVERFLOW:
10059 subcode = MULT_EXPR;
10060 break;
10061 default:
10062 return false;
10065 tree op0 = gimple_call_arg (stmt, 0);
10066 tree op1 = gimple_call_arg (stmt, 1);
10067 tree type;
10068 if (is_ubsan)
10070 type = TREE_TYPE (op0);
10071 if (VECTOR_TYPE_P (type))
10072 return false;
10074 else if (gimple_call_lhs (stmt) == NULL_TREE)
10075 return false;
10076 else
10077 type = TREE_TYPE (TREE_TYPE (gimple_call_lhs (stmt)));
10078 if (!check_for_binary_op_overflow (subcode, type, op0, op1, &ovf)
10079 || (is_ubsan && ovf))
10080 return false;
10082 gimple *g;
10083 location_t loc = gimple_location (stmt);
10084 if (is_ubsan)
10085 g = gimple_build_assign (gimple_call_lhs (stmt), subcode, op0, op1);
10086 else
10088 int prec = TYPE_PRECISION (type);
10089 tree utype = type;
10090 if (ovf
10091 || !useless_type_conversion_p (type, TREE_TYPE (op0))
10092 || !useless_type_conversion_p (type, TREE_TYPE (op1)))
10093 utype = build_nonstandard_integer_type (prec, 1);
10094 if (TREE_CODE (op0) == INTEGER_CST)
10095 op0 = fold_convert (utype, op0);
10096 else if (!useless_type_conversion_p (utype, TREE_TYPE (op0)))
10098 g = gimple_build_assign (make_ssa_name (utype), NOP_EXPR, op0);
10099 gimple_set_location (g, loc);
10100 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10101 op0 = gimple_assign_lhs (g);
10103 if (TREE_CODE (op1) == INTEGER_CST)
10104 op1 = fold_convert (utype, op1);
10105 else if (!useless_type_conversion_p (utype, TREE_TYPE (op1)))
10107 g = gimple_build_assign (make_ssa_name (utype), NOP_EXPR, op1);
10108 gimple_set_location (g, loc);
10109 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10110 op1 = gimple_assign_lhs (g);
10112 g = gimple_build_assign (make_ssa_name (utype), subcode, op0, op1);
10113 gimple_set_location (g, loc);
10114 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10115 if (utype != type)
10117 g = gimple_build_assign (make_ssa_name (type), NOP_EXPR,
10118 gimple_assign_lhs (g));
10119 gimple_set_location (g, loc);
10120 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10122 g = gimple_build_assign (gimple_call_lhs (stmt), COMPLEX_EXPR,
10123 gimple_assign_lhs (g),
10124 build_int_cst (type, ovf));
10126 gimple_set_location (g, loc);
10127 gsi_replace (gsi, g, false);
10128 return true;
10131 /* Return true if VAR is a two-valued variable. Set a and b with the
10132 two-values when it is true. Return false otherwise. */
10134 static bool
10135 two_valued_val_range_p (tree var, tree *a, tree *b)
10137 value_range *vr = get_value_range (var);
10138 if ((vr->type != VR_RANGE
10139 && vr->type != VR_ANTI_RANGE)
10140 || TREE_CODE (vr->min) != INTEGER_CST
10141 || TREE_CODE (vr->max) != INTEGER_CST)
10142 return false;
10144 if (vr->type == VR_RANGE
10145 && wi::sub (vr->max, vr->min) == 1)
10147 *a = vr->min;
10148 *b = vr->max;
10149 return true;
10152 /* ~[TYPE_MIN + 1, TYPE_MAX - 1] */
10153 if (vr->type == VR_ANTI_RANGE
10154 && wi::sub (vr->min, vrp_val_min (TREE_TYPE (var))) == 1
10155 && wi::sub (vrp_val_max (TREE_TYPE (var)), vr->max) == 1)
10157 *a = vrp_val_min (TREE_TYPE (var));
10158 *b = vrp_val_max (TREE_TYPE (var));
10159 return true;
10162 return false;
10165 /* Simplify STMT using ranges if possible. */
10167 static bool
10168 simplify_stmt_using_ranges (gimple_stmt_iterator *gsi)
10170 gimple *stmt = gsi_stmt (*gsi);
10171 if (is_gimple_assign (stmt))
10173 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
10174 tree rhs1 = gimple_assign_rhs1 (stmt);
10175 tree rhs2 = gimple_assign_rhs2 (stmt);
10176 tree lhs = gimple_assign_lhs (stmt);
10177 tree val1 = NULL_TREE, val2 = NULL_TREE;
10178 use_operand_p use_p;
10179 gimple *use_stmt;
10181 /* Convert:
10182 LHS = CST BINOP VAR
10183 Where VAR is two-valued and LHS is used in GIMPLE_COND only
10185 LHS = VAR == VAL1 ? (CST BINOP VAL1) : (CST BINOP VAL2)
10187 Also handles:
10188 LHS = VAR BINOP CST
10189 Where VAR is two-valued and LHS is used in GIMPLE_COND only
10191 LHS = VAR == VAL1 ? (VAL1 BINOP CST) : (VAL2 BINOP CST) */
10193 if (TREE_CODE_CLASS (rhs_code) == tcc_binary
10194 && INTEGRAL_TYPE_P (TREE_TYPE (lhs))
10195 && ((TREE_CODE (rhs1) == INTEGER_CST
10196 && TREE_CODE (rhs2) == SSA_NAME)
10197 || (TREE_CODE (rhs2) == INTEGER_CST
10198 && TREE_CODE (rhs1) == SSA_NAME))
10199 && single_imm_use (lhs, &use_p, &use_stmt)
10200 && gimple_code (use_stmt) == GIMPLE_COND)
10203 tree new_rhs1 = NULL_TREE;
10204 tree new_rhs2 = NULL_TREE;
10205 tree cmp_var = NULL_TREE;
10207 if (TREE_CODE (rhs2) == SSA_NAME
10208 && two_valued_val_range_p (rhs2, &val1, &val2))
10210 /* Optimize RHS1 OP [VAL1, VAL2]. */
10211 new_rhs1 = int_const_binop (rhs_code, rhs1, val1);
10212 new_rhs2 = int_const_binop (rhs_code, rhs1, val2);
10213 cmp_var = rhs2;
10215 else if (TREE_CODE (rhs1) == SSA_NAME
10216 && two_valued_val_range_p (rhs1, &val1, &val2))
10218 /* Optimize [VAL1, VAL2] OP RHS2. */
10219 new_rhs1 = int_const_binop (rhs_code, val1, rhs2);
10220 new_rhs2 = int_const_binop (rhs_code, val2, rhs2);
10221 cmp_var = rhs1;
10224 /* If we could not find two-vals or the optimzation is invalid as
10225 in divide by zero, new_rhs1 / new_rhs will be NULL_TREE. */
10226 if (new_rhs1 && new_rhs2)
10228 tree cond = build2 (EQ_EXPR, boolean_type_node, cmp_var, val1);
10229 gimple_assign_set_rhs_with_ops (gsi,
10230 COND_EXPR, cond,
10231 new_rhs1,
10232 new_rhs2);
10233 update_stmt (gsi_stmt (*gsi));
10234 fold_stmt (gsi, follow_single_use_edges);
10235 return true;
10239 switch (rhs_code)
10241 case EQ_EXPR:
10242 case NE_EXPR:
10243 /* Transform EQ_EXPR, NE_EXPR into BIT_XOR_EXPR or identity
10244 if the RHS is zero or one, and the LHS are known to be boolean
10245 values. */
10246 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10247 return simplify_truth_ops_using_ranges (gsi, stmt);
10248 break;
10250 /* Transform TRUNC_DIV_EXPR and TRUNC_MOD_EXPR into RSHIFT_EXPR
10251 and BIT_AND_EXPR respectively if the first operand is greater
10252 than zero and the second operand is an exact power of two.
10253 Also optimize TRUNC_MOD_EXPR away if the second operand is
10254 constant and the first operand already has the right value
10255 range. */
10256 case TRUNC_DIV_EXPR:
10257 case TRUNC_MOD_EXPR:
10258 if (TREE_CODE (rhs1) == SSA_NAME
10259 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10260 return simplify_div_or_mod_using_ranges (gsi, stmt);
10261 break;
10263 /* Transform ABS (X) into X or -X as appropriate. */
10264 case ABS_EXPR:
10265 if (TREE_CODE (rhs1) == SSA_NAME
10266 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10267 return simplify_abs_using_ranges (gsi, stmt);
10268 break;
10270 case BIT_AND_EXPR:
10271 case BIT_IOR_EXPR:
10272 /* Optimize away BIT_AND_EXPR and BIT_IOR_EXPR
10273 if all the bits being cleared are already cleared or
10274 all the bits being set are already set. */
10275 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10276 return simplify_bit_ops_using_ranges (gsi, stmt);
10277 break;
10279 CASE_CONVERT:
10280 if (TREE_CODE (rhs1) == SSA_NAME
10281 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10282 return simplify_conversion_using_ranges (gsi, stmt);
10283 break;
10285 case FLOAT_EXPR:
10286 if (TREE_CODE (rhs1) == SSA_NAME
10287 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10288 return simplify_float_conversion_using_ranges (gsi, stmt);
10289 break;
10291 case MIN_EXPR:
10292 case MAX_EXPR:
10293 return simplify_min_or_max_using_ranges (gsi, stmt);
10295 default:
10296 break;
10299 else if (gimple_code (stmt) == GIMPLE_COND)
10300 return simplify_cond_using_ranges (as_a <gcond *> (stmt));
10301 else if (gimple_code (stmt) == GIMPLE_SWITCH)
10302 return simplify_switch_using_ranges (as_a <gswitch *> (stmt));
10303 else if (is_gimple_call (stmt)
10304 && gimple_call_internal_p (stmt))
10305 return simplify_internal_call_using_ranges (gsi, stmt);
10307 return false;
10310 /* If the statement pointed by SI has a predicate whose value can be
10311 computed using the value range information computed by VRP, compute
10312 its value and return true. Otherwise, return false. */
10314 static bool
10315 fold_predicate_in (gimple_stmt_iterator *si)
10317 bool assignment_p = false;
10318 tree val;
10319 gimple *stmt = gsi_stmt (*si);
10321 if (is_gimple_assign (stmt)
10322 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
10324 assignment_p = true;
10325 val = vrp_evaluate_conditional (gimple_assign_rhs_code (stmt),
10326 gimple_assign_rhs1 (stmt),
10327 gimple_assign_rhs2 (stmt),
10328 stmt);
10330 else if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
10331 val = vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
10332 gimple_cond_lhs (cond_stmt),
10333 gimple_cond_rhs (cond_stmt),
10334 stmt);
10335 else
10336 return false;
10338 if (val)
10340 if (assignment_p)
10341 val = fold_convert (gimple_expr_type (stmt), val);
10343 if (dump_file)
10345 fprintf (dump_file, "Folding predicate ");
10346 print_gimple_expr (dump_file, stmt, 0, 0);
10347 fprintf (dump_file, " to ");
10348 print_generic_expr (dump_file, val, 0);
10349 fprintf (dump_file, "\n");
10352 if (is_gimple_assign (stmt))
10353 gimple_assign_set_rhs_from_tree (si, val);
10354 else
10356 gcc_assert (gimple_code (stmt) == GIMPLE_COND);
10357 gcond *cond_stmt = as_a <gcond *> (stmt);
10358 if (integer_zerop (val))
10359 gimple_cond_make_false (cond_stmt);
10360 else if (integer_onep (val))
10361 gimple_cond_make_true (cond_stmt);
10362 else
10363 gcc_unreachable ();
10366 return true;
10369 return false;
10372 /* Callback for substitute_and_fold folding the stmt at *SI. */
10374 static bool
10375 vrp_fold_stmt (gimple_stmt_iterator *si)
10377 if (fold_predicate_in (si))
10378 return true;
10380 return simplify_stmt_using_ranges (si);
10383 /* Unwindable const/copy equivalences. */
10384 const_and_copies *equiv_stack;
10386 /* A trivial wrapper so that we can present the generic jump threading
10387 code with a simple API for simplifying statements. STMT is the
10388 statement we want to simplify, WITHIN_STMT provides the location
10389 for any overflow warnings. */
10391 static tree
10392 simplify_stmt_for_jump_threading (gimple *stmt, gimple *within_stmt,
10393 class avail_exprs_stack *avail_exprs_stack ATTRIBUTE_UNUSED)
10395 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
10396 return vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
10397 gimple_cond_lhs (cond_stmt),
10398 gimple_cond_rhs (cond_stmt),
10399 within_stmt);
10401 /* We simplify a switch statement by trying to determine which case label
10402 will be taken. If we are successful then we return the corresponding
10403 CASE_LABEL_EXPR. */
10404 if (gswitch *switch_stmt = dyn_cast <gswitch *> (stmt))
10406 tree op = gimple_switch_index (switch_stmt);
10407 if (TREE_CODE (op) != SSA_NAME)
10408 return NULL_TREE;
10410 value_range *vr = get_value_range (op);
10411 if ((vr->type != VR_RANGE && vr->type != VR_ANTI_RANGE)
10412 || symbolic_range_p (vr))
10413 return NULL_TREE;
10415 if (vr->type == VR_RANGE)
10417 size_t i, j;
10418 /* Get the range of labels that contain a part of the operand's
10419 value range. */
10420 find_case_label_range (switch_stmt, vr->min, vr->max, &i, &j);
10422 /* Is there only one such label? */
10423 if (i == j)
10425 tree label = gimple_switch_label (switch_stmt, i);
10427 /* The i'th label will be taken only if the value range of the
10428 operand is entirely within the bounds of this label. */
10429 if (CASE_HIGH (label) != NULL_TREE
10430 ? (tree_int_cst_compare (CASE_LOW (label), vr->min) <= 0
10431 && tree_int_cst_compare (CASE_HIGH (label), vr->max) >= 0)
10432 : (tree_int_cst_equal (CASE_LOW (label), vr->min)
10433 && tree_int_cst_equal (vr->min, vr->max)))
10434 return label;
10437 /* If there are no such labels then the default label will be
10438 taken. */
10439 if (i > j)
10440 return gimple_switch_label (switch_stmt, 0);
10443 if (vr->type == VR_ANTI_RANGE)
10445 unsigned n = gimple_switch_num_labels (switch_stmt);
10446 tree min_label = gimple_switch_label (switch_stmt, 1);
10447 tree max_label = gimple_switch_label (switch_stmt, n - 1);
10449 /* The default label will be taken only if the anti-range of the
10450 operand is entirely outside the bounds of all the (non-default)
10451 case labels. */
10452 if (tree_int_cst_compare (vr->min, CASE_LOW (min_label)) <= 0
10453 && (CASE_HIGH (max_label) != NULL_TREE
10454 ? tree_int_cst_compare (vr->max, CASE_HIGH (max_label)) >= 0
10455 : tree_int_cst_compare (vr->max, CASE_LOW (max_label)) >= 0))
10456 return gimple_switch_label (switch_stmt, 0);
10459 return NULL_TREE;
10462 if (gassign *assign_stmt = dyn_cast <gassign *> (stmt))
10464 value_range new_vr = VR_INITIALIZER;
10465 tree lhs = gimple_assign_lhs (assign_stmt);
10467 if (TREE_CODE (lhs) == SSA_NAME
10468 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
10469 || POINTER_TYPE_P (TREE_TYPE (lhs))))
10471 extract_range_from_assignment (&new_vr, assign_stmt);
10472 if (range_int_cst_singleton_p (&new_vr))
10473 return new_vr.min;
10477 return NULL_TREE;
10480 /* Blocks which have more than one predecessor and more than
10481 one successor present jump threading opportunities, i.e.,
10482 when the block is reached from a specific predecessor, we
10483 may be able to determine which of the outgoing edges will
10484 be traversed. When this optimization applies, we are able
10485 to avoid conditionals at runtime and we may expose secondary
10486 optimization opportunities.
10488 This routine is effectively a driver for the generic jump
10489 threading code. It basically just presents the generic code
10490 with edges that may be suitable for jump threading.
10492 Unlike DOM, we do not iterate VRP if jump threading was successful.
10493 While iterating may expose new opportunities for VRP, it is expected
10494 those opportunities would be very limited and the compile time cost
10495 to expose those opportunities would be significant.
10497 As jump threading opportunities are discovered, they are registered
10498 for later realization. */
10500 static void
10501 identify_jump_threads (void)
10503 basic_block bb;
10504 gcond *dummy;
10505 int i;
10506 edge e;
10508 /* Ugh. When substituting values earlier in this pass we can
10509 wipe the dominance information. So rebuild the dominator
10510 information as we need it within the jump threading code. */
10511 calculate_dominance_info (CDI_DOMINATORS);
10513 /* We do not allow VRP information to be used for jump threading
10514 across a back edge in the CFG. Otherwise it becomes too
10515 difficult to avoid eliminating loop exit tests. Of course
10516 EDGE_DFS_BACK is not accurate at this time so we have to
10517 recompute it. */
10518 mark_dfs_back_edges ();
10520 /* Do not thread across edges we are about to remove. Just marking
10521 them as EDGE_IGNORE will do. */
10522 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
10523 e->flags |= EDGE_IGNORE;
10525 /* Allocate our unwinder stack to unwind any temporary equivalences
10526 that might be recorded. */
10527 equiv_stack = new const_and_copies ();
10529 /* To avoid lots of silly node creation, we create a single
10530 conditional and just modify it in-place when attempting to
10531 thread jumps. */
10532 dummy = gimple_build_cond (EQ_EXPR,
10533 integer_zero_node, integer_zero_node,
10534 NULL, NULL);
10536 /* Walk through all the blocks finding those which present a
10537 potential jump threading opportunity. We could set this up
10538 as a dominator walker and record data during the walk, but
10539 I doubt it's worth the effort for the classes of jump
10540 threading opportunities we are trying to identify at this
10541 point in compilation. */
10542 FOR_EACH_BB_FN (bb, cfun)
10544 gimple *last;
10546 /* If the generic jump threading code does not find this block
10547 interesting, then there is nothing to do. */
10548 if (! potentially_threadable_block (bb))
10549 continue;
10551 last = last_stmt (bb);
10553 /* We're basically looking for a switch or any kind of conditional with
10554 integral or pointer type arguments. Note the type of the second
10555 argument will be the same as the first argument, so no need to
10556 check it explicitly.
10558 We also handle the case where there are no statements in the
10559 block. This come up with forwarder blocks that are not
10560 optimized away because they lead to a loop header. But we do
10561 want to thread through them as we can sometimes thread to the
10562 loop exit which is obviously profitable. */
10563 if (!last
10564 || gimple_code (last) == GIMPLE_SWITCH
10565 || (gimple_code (last) == GIMPLE_COND
10566 && TREE_CODE (gimple_cond_lhs (last)) == SSA_NAME
10567 && (INTEGRAL_TYPE_P (TREE_TYPE (gimple_cond_lhs (last)))
10568 || POINTER_TYPE_P (TREE_TYPE (gimple_cond_lhs (last))))
10569 && (TREE_CODE (gimple_cond_rhs (last)) == SSA_NAME
10570 || is_gimple_min_invariant (gimple_cond_rhs (last)))))
10572 edge_iterator ei;
10574 /* We've got a block with multiple predecessors and multiple
10575 successors which also ends in a suitable conditional or
10576 switch statement. For each predecessor, see if we can thread
10577 it to a specific successor. */
10578 FOR_EACH_EDGE (e, ei, bb->preds)
10580 /* Do not thread across edges marked to ignoreor abnormal
10581 edges in the CFG. */
10582 if (e->flags & (EDGE_IGNORE | EDGE_COMPLEX))
10583 continue;
10585 thread_across_edge (dummy, e, true, equiv_stack, NULL,
10586 simplify_stmt_for_jump_threading);
10591 /* Clear EDGE_IGNORE. */
10592 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
10593 e->flags &= ~EDGE_IGNORE;
10595 /* We do not actually update the CFG or SSA graphs at this point as
10596 ASSERT_EXPRs are still in the IL and cfg cleanup code does not yet
10597 handle ASSERT_EXPRs gracefully. */
10600 /* We identified all the jump threading opportunities earlier, but could
10601 not transform the CFG at that time. This routine transforms the
10602 CFG and arranges for the dominator tree to be rebuilt if necessary.
10604 Note the SSA graph update will occur during the normal TODO
10605 processing by the pass manager. */
10606 static void
10607 finalize_jump_threads (void)
10609 thread_through_all_blocks (false);
10610 delete equiv_stack;
10613 /* Free VRP lattice. */
10615 static void
10616 vrp_free_lattice ()
10618 /* Free allocated memory. */
10619 free (vr_value);
10620 free (vr_phi_edge_counts);
10621 bitmap_obstack_release (&vrp_equiv_obstack);
10622 vrp_value_range_pool.release ();
10624 /* So that we can distinguish between VRP data being available
10625 and not available. */
10626 vr_value = NULL;
10627 vr_phi_edge_counts = NULL;
10630 /* Traverse all the blocks folding conditionals with known ranges. */
10632 static void
10633 vrp_finalize (bool warn_array_bounds_p)
10635 size_t i;
10637 values_propagated = true;
10639 if (dump_file)
10641 fprintf (dump_file, "\nValue ranges after VRP:\n\n");
10642 dump_all_value_ranges (dump_file);
10643 fprintf (dump_file, "\n");
10646 /* Set value range to non pointer SSA_NAMEs. */
10647 for (i = 0; i < num_vr_values; i++)
10648 if (vr_value[i])
10650 tree name = ssa_name (i);
10652 if (!name
10653 || (vr_value[i]->type == VR_VARYING)
10654 || (vr_value[i]->type == VR_UNDEFINED)
10655 || (TREE_CODE (vr_value[i]->min) != INTEGER_CST)
10656 || (TREE_CODE (vr_value[i]->max) != INTEGER_CST))
10657 continue;
10659 if (POINTER_TYPE_P (TREE_TYPE (name))
10660 && ((vr_value[i]->type == VR_RANGE
10661 && range_includes_zero_p (vr_value[i]->min,
10662 vr_value[i]->max) == 0)
10663 || (vr_value[i]->type == VR_ANTI_RANGE
10664 && range_includes_zero_p (vr_value[i]->min,
10665 vr_value[i]->max) == 1)))
10666 set_ptr_nonnull (name);
10667 else if (!POINTER_TYPE_P (TREE_TYPE (name)))
10668 set_range_info (name, vr_value[i]->type, vr_value[i]->min,
10669 vr_value[i]->max);
10672 substitute_and_fold (op_with_constant_singleton_value_range, vrp_fold_stmt);
10674 if (warn_array_bounds && warn_array_bounds_p)
10675 check_all_array_refs ();
10677 /* We must identify jump threading opportunities before we release
10678 the datastructures built by VRP. */
10679 identify_jump_threads ();
10682 /* evrp_dom_walker visits the basic blocks in the dominance order and set
10683 the Value Ranges (VR) for SSA_NAMEs in the scope. Use this VR to
10684 discover more VRs. */
10686 class evrp_dom_walker : public dom_walker
10688 public:
10689 evrp_dom_walker ()
10690 : dom_walker (CDI_DOMINATORS), stack (10)
10692 need_eh_cleanup = BITMAP_ALLOC (NULL);
10694 ~evrp_dom_walker ()
10696 BITMAP_FREE (need_eh_cleanup);
10698 virtual edge before_dom_children (basic_block);
10699 virtual void after_dom_children (basic_block);
10700 void push_value_range (tree var, value_range *vr);
10701 value_range *pop_value_range (tree var);
10702 value_range *try_find_new_range (tree op, tree_code code, tree limit);
10704 /* Cond_stack holds the old VR. */
10705 auto_vec<std::pair <tree, value_range*> > stack;
10706 bitmap need_eh_cleanup;
10707 auto_vec<gimple *> stmts_to_fixup;
10708 auto_vec<gimple *> stmts_to_remove;
10711 /* Find new range for OP such that (OP CODE LIMIT) is true. */
10713 value_range *
10714 evrp_dom_walker::try_find_new_range (tree op, tree_code code, tree limit)
10716 value_range vr = VR_INITIALIZER;
10717 value_range *old_vr = get_value_range (op);
10719 /* Discover VR when condition is true. */
10720 extract_range_for_var_from_comparison_expr (op, code, op,
10721 limit, &vr);
10722 if (old_vr->type == VR_RANGE || old_vr->type == VR_ANTI_RANGE)
10723 vrp_intersect_ranges (&vr, old_vr);
10724 /* If we found any usable VR, set the VR to ssa_name and create a
10725 PUSH old value in the stack with the old VR. */
10726 if (vr.type == VR_RANGE || vr.type == VR_ANTI_RANGE)
10728 if (old_vr->type == vr.type
10729 && vrp_operand_equal_p (old_vr->min, vr.min)
10730 && vrp_operand_equal_p (old_vr->max, vr.max))
10731 return NULL;
10732 value_range *new_vr = vrp_value_range_pool.allocate ();
10733 *new_vr = vr;
10734 return new_vr;
10736 return NULL;
10739 /* See if there is any new scope is entered with new VR and set that VR to
10740 ssa_name before visiting the statements in the scope. */
10742 edge
10743 evrp_dom_walker::before_dom_children (basic_block bb)
10745 tree op0 = NULL_TREE;
10746 edge_iterator ei;
10747 edge e;
10749 if (dump_file && (dump_flags & TDF_DETAILS))
10750 fprintf (dump_file, "Visiting BB%d\n", bb->index);
10752 stack.safe_push (std::make_pair (NULL_TREE, (value_range *)NULL));
10754 edge pred_e = NULL;
10755 FOR_EACH_EDGE (e, ei, bb->preds)
10757 /* Ignore simple backedges from this to allow recording conditions
10758 in loop headers. */
10759 if (dominated_by_p (CDI_DOMINATORS, e->src, e->dest))
10760 continue;
10761 if (! pred_e)
10762 pred_e = e;
10763 else
10765 pred_e = NULL;
10766 break;
10769 if (pred_e)
10771 gimple *stmt = last_stmt (pred_e->src);
10772 if (stmt
10773 && gimple_code (stmt) == GIMPLE_COND
10774 && (op0 = gimple_cond_lhs (stmt))
10775 && TREE_CODE (op0) == SSA_NAME
10776 && (INTEGRAL_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)))
10777 || POINTER_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)))))
10779 if (dump_file && (dump_flags & TDF_DETAILS))
10781 fprintf (dump_file, "Visiting controlling predicate ");
10782 print_gimple_stmt (dump_file, stmt, 0, 0);
10784 /* Entering a new scope. Try to see if we can find a VR
10785 here. */
10786 tree op1 = gimple_cond_rhs (stmt);
10787 tree_code code = gimple_cond_code (stmt);
10789 if (TREE_OVERFLOW_P (op1))
10790 op1 = drop_tree_overflow (op1);
10792 /* If condition is false, invert the cond. */
10793 if (pred_e->flags & EDGE_FALSE_VALUE)
10794 code = invert_tree_comparison (gimple_cond_code (stmt),
10795 HONOR_NANS (op0));
10796 /* Add VR when (OP0 CODE OP1) condition is true. */
10797 value_range *op0_range = try_find_new_range (op0, code, op1);
10799 /* Register ranges for y in x < y where
10800 y might have ranges that are useful. */
10801 tree limit;
10802 tree_code new_code;
10803 if (TREE_CODE (op1) == SSA_NAME
10804 && extract_code_and_val_from_cond_with_ops (op1, code,
10805 op0, op1,
10806 false,
10807 &new_code, &limit))
10809 /* Add VR when (OP1 NEW_CODE LIMIT) condition is true. */
10810 value_range *op1_range = try_find_new_range (op1, new_code, limit);
10811 if (op1_range)
10812 push_value_range (op1, op1_range);
10815 if (op0_range)
10816 push_value_range (op0, op0_range);
10820 /* Visit PHI stmts and discover any new VRs possible. */
10821 bool has_unvisited_preds = false;
10822 FOR_EACH_EDGE (e, ei, bb->preds)
10823 if (e->flags & EDGE_EXECUTABLE
10824 && !(e->src->flags & BB_VISITED))
10826 has_unvisited_preds = true;
10827 break;
10830 for (gphi_iterator gpi = gsi_start_phis (bb);
10831 !gsi_end_p (gpi); gsi_next (&gpi))
10833 gphi *phi = gpi.phi ();
10834 tree lhs = PHI_RESULT (phi);
10835 if (virtual_operand_p (lhs))
10836 continue;
10837 value_range vr_result = VR_INITIALIZER;
10838 bool interesting = stmt_interesting_for_vrp (phi);
10839 if (interesting && dump_file && (dump_flags & TDF_DETAILS))
10841 fprintf (dump_file, "Visiting PHI node ");
10842 print_gimple_stmt (dump_file, phi, 0, 0);
10844 if (!has_unvisited_preds
10845 && interesting)
10846 extract_range_from_phi_node (phi, &vr_result);
10847 else
10849 set_value_range_to_varying (&vr_result);
10850 /* When we have an unvisited executable predecessor we can't
10851 use PHI arg ranges which may be still UNDEFINED but have
10852 to use VARYING for them. But we can still resort to
10853 SCEV for loop header PHIs. */
10854 struct loop *l;
10855 if (interesting
10856 && (l = loop_containing_stmt (phi))
10857 && l->header == gimple_bb (phi))
10858 adjust_range_with_scev (&vr_result, l, phi, lhs);
10860 update_value_range (lhs, &vr_result);
10862 /* Mark PHIs whose lhs we fully propagate for removal. */
10863 tree val = op_with_constant_singleton_value_range (lhs);
10864 if (val && may_propagate_copy (lhs, val))
10865 stmts_to_remove.safe_push (phi);
10868 edge taken_edge = NULL;
10870 /* Visit all other stmts and discover any new VRs possible. */
10871 for (gimple_stmt_iterator gsi = gsi_start_bb (bb);
10872 !gsi_end_p (gsi); gsi_next (&gsi))
10874 gimple *stmt = gsi_stmt (gsi);
10875 tree output = NULL_TREE;
10876 gimple *old_stmt = stmt;
10877 bool was_noreturn = (is_gimple_call (stmt)
10878 && gimple_call_noreturn_p (stmt));
10880 if (dump_file && (dump_flags & TDF_DETAILS))
10882 fprintf (dump_file, "Visiting stmt ");
10883 print_gimple_stmt (dump_file, stmt, 0, 0);
10886 if (gcond *cond = dyn_cast <gcond *> (stmt))
10888 vrp_visit_cond_stmt (cond, &taken_edge);
10889 if (taken_edge)
10891 if (taken_edge->flags & EDGE_TRUE_VALUE)
10892 gimple_cond_make_true (cond);
10893 else if (taken_edge->flags & EDGE_FALSE_VALUE)
10894 gimple_cond_make_false (cond);
10895 else
10896 gcc_unreachable ();
10897 update_stmt (stmt);
10900 else if (stmt_interesting_for_vrp (stmt))
10902 edge taken_edge;
10903 value_range vr = VR_INITIALIZER;
10904 extract_range_from_stmt (stmt, &taken_edge, &output, &vr);
10905 if (output
10906 && (vr.type == VR_RANGE || vr.type == VR_ANTI_RANGE))
10908 update_value_range (output, &vr);
10909 vr = *get_value_range (output);
10911 /* Set the SSA with the value range. */
10912 if (INTEGRAL_TYPE_P (TREE_TYPE (output)))
10914 if ((vr.type == VR_RANGE
10915 || vr.type == VR_ANTI_RANGE)
10916 && (TREE_CODE (vr.min) == INTEGER_CST)
10917 && (TREE_CODE (vr.max) == INTEGER_CST))
10918 set_range_info (output, vr.type, vr.min, vr.max);
10920 else if (POINTER_TYPE_P (TREE_TYPE (output))
10921 && ((vr.type == VR_RANGE
10922 && range_includes_zero_p (vr.min,
10923 vr.max) == 0)
10924 || (vr.type == VR_ANTI_RANGE
10925 && range_includes_zero_p (vr.min,
10926 vr.max) == 1)))
10927 set_ptr_nonnull (output);
10929 /* Mark stmts whose output we fully propagate for removal. */
10930 tree val;
10931 if ((val = op_with_constant_singleton_value_range (output))
10932 && may_propagate_copy (output, val)
10933 && !stmt_could_throw_p (stmt)
10934 && !gimple_has_side_effects (stmt))
10936 stmts_to_remove.safe_push (stmt);
10937 continue;
10940 else
10941 set_defs_to_varying (stmt);
10943 else
10944 set_defs_to_varying (stmt);
10946 /* See if we can derive a range for any of STMT's operands. */
10947 tree op;
10948 ssa_op_iter i;
10949 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
10951 tree value;
10952 enum tree_code comp_code;
10954 /* If OP is used in such a way that we can infer a value
10955 range for it, and we don't find a previous assertion for
10956 it, create a new assertion location node for OP. */
10957 if (infer_value_range (stmt, op, &comp_code, &value))
10959 /* If we are able to infer a nonzero value range for OP,
10960 then walk backwards through the use-def chain to see if OP
10961 was set via a typecast.
10962 If so, then we can also infer a nonzero value range
10963 for the operand of the NOP_EXPR. */
10964 if (comp_code == NE_EXPR && integer_zerop (value))
10966 tree t = op;
10967 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
10968 while (is_gimple_assign (def_stmt)
10969 && CONVERT_EXPR_CODE_P
10970 (gimple_assign_rhs_code (def_stmt))
10971 && TREE_CODE
10972 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
10973 && POINTER_TYPE_P
10974 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
10976 t = gimple_assign_rhs1 (def_stmt);
10977 def_stmt = SSA_NAME_DEF_STMT (t);
10979 /* Add VR when (T COMP_CODE value) condition is
10980 true. */
10981 value_range *op_range
10982 = try_find_new_range (t, comp_code, value);
10983 if (op_range)
10984 push_value_range (t, op_range);
10987 /* Add VR when (OP COMP_CODE value) condition is true. */
10988 value_range *op_range = try_find_new_range (op,
10989 comp_code, value);
10990 if (op_range)
10991 push_value_range (op, op_range);
10995 /* Try folding stmts with the VR discovered. */
10996 bool did_replace
10997 = replace_uses_in (stmt, op_with_constant_singleton_value_range);
10998 if (fold_stmt (&gsi, follow_single_use_edges)
10999 || did_replace)
11001 stmt = gsi_stmt (gsi);
11002 update_stmt (stmt);
11003 did_replace = true;
11006 if (did_replace)
11008 /* If we cleaned up EH information from the statement,
11009 remove EH edges. */
11010 if (maybe_clean_or_replace_eh_stmt (old_stmt, stmt))
11011 bitmap_set_bit (need_eh_cleanup, bb->index);
11013 /* If we turned a not noreturn call into a noreturn one
11014 schedule it for fixup. */
11015 if (!was_noreturn
11016 && is_gimple_call (stmt)
11017 && gimple_call_noreturn_p (stmt))
11018 stmts_to_fixup.safe_push (stmt);
11020 if (gimple_assign_single_p (stmt))
11022 tree rhs = gimple_assign_rhs1 (stmt);
11023 if (TREE_CODE (rhs) == ADDR_EXPR)
11024 recompute_tree_invariant_for_addr_expr (rhs);
11029 /* Visit BB successor PHI nodes and replace PHI args. */
11030 FOR_EACH_EDGE (e, ei, bb->succs)
11032 for (gphi_iterator gpi = gsi_start_phis (e->dest);
11033 !gsi_end_p (gpi); gsi_next (&gpi))
11035 gphi *phi = gpi.phi ();
11036 use_operand_p use_p = PHI_ARG_DEF_PTR_FROM_EDGE (phi, e);
11037 tree arg = USE_FROM_PTR (use_p);
11038 if (TREE_CODE (arg) != SSA_NAME
11039 || virtual_operand_p (arg))
11040 continue;
11041 tree val = op_with_constant_singleton_value_range (arg);
11042 if (val && may_propagate_copy (arg, val))
11043 propagate_value (use_p, val);
11047 bb->flags |= BB_VISITED;
11049 return taken_edge;
11052 /* Restore/pop VRs valid only for BB when we leave BB. */
11054 void
11055 evrp_dom_walker::after_dom_children (basic_block bb ATTRIBUTE_UNUSED)
11057 gcc_checking_assert (!stack.is_empty ());
11058 while (stack.last ().first != NULL_TREE)
11059 pop_value_range (stack.last ().first);
11060 stack.pop ();
11063 /* Push the Value Range of VAR to the stack and update it with new VR. */
11065 void
11066 evrp_dom_walker::push_value_range (tree var, value_range *vr)
11068 if (SSA_NAME_VERSION (var) >= num_vr_values)
11069 return;
11070 if (dump_file && (dump_flags & TDF_DETAILS))
11072 fprintf (dump_file, "pushing new range for ");
11073 print_generic_expr (dump_file, var, 0);
11074 fprintf (dump_file, ": ");
11075 dump_value_range (dump_file, vr);
11076 fprintf (dump_file, "\n");
11078 stack.safe_push (std::make_pair (var, get_value_range (var)));
11079 vr_value[SSA_NAME_VERSION (var)] = vr;
11082 /* Pop the Value Range from the vrp_stack and update VAR with it. */
11084 value_range *
11085 evrp_dom_walker::pop_value_range (tree var)
11087 value_range *vr = stack.last ().second;
11088 gcc_checking_assert (var == stack.last ().first);
11089 if (dump_file && (dump_flags & TDF_DETAILS))
11091 fprintf (dump_file, "popping range for ");
11092 print_generic_expr (dump_file, var, 0);
11093 fprintf (dump_file, ", restoring ");
11094 dump_value_range (dump_file, vr);
11095 fprintf (dump_file, "\n");
11097 vr_value[SSA_NAME_VERSION (var)] = vr;
11098 stack.pop ();
11099 return vr;
11103 /* Main entry point for the early vrp pass which is a simplified non-iterative
11104 version of vrp where basic blocks are visited in dominance order. Value
11105 ranges discovered in early vrp will also be used by ipa-vrp. */
11107 static unsigned int
11108 execute_early_vrp ()
11110 edge e;
11111 edge_iterator ei;
11112 basic_block bb;
11114 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
11115 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
11116 scev_initialize ();
11117 calculate_dominance_info (CDI_DOMINATORS);
11118 FOR_EACH_BB_FN (bb, cfun)
11120 bb->flags &= ~BB_VISITED;
11121 FOR_EACH_EDGE (e, ei, bb->preds)
11122 e->flags |= EDGE_EXECUTABLE;
11124 vrp_initialize_lattice ();
11126 /* Walk stmts in dominance order and propagate VRP. */
11127 evrp_dom_walker walker;
11128 walker.walk (ENTRY_BLOCK_PTR_FOR_FN (cfun));
11130 if (dump_file)
11132 fprintf (dump_file, "\nValue ranges after Early VRP:\n\n");
11133 dump_all_value_ranges (dump_file);
11134 fprintf (dump_file, "\n");
11137 /* Remove stmts in reverse order to make debug stmt creation possible. */
11138 while (! walker.stmts_to_remove.is_empty ())
11140 gimple *stmt = walker.stmts_to_remove.pop ();
11141 if (dump_file && dump_flags & TDF_DETAILS)
11143 fprintf (dump_file, "Removing dead stmt ");
11144 print_gimple_stmt (dump_file, stmt, 0, 0);
11145 fprintf (dump_file, "\n");
11147 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
11148 if (gimple_code (stmt) == GIMPLE_PHI)
11149 remove_phi_node (&gsi, true);
11150 else
11152 unlink_stmt_vdef (stmt);
11153 gsi_remove (&gsi, true);
11154 release_defs (stmt);
11158 if (!bitmap_empty_p (walker.need_eh_cleanup))
11159 gimple_purge_all_dead_eh_edges (walker.need_eh_cleanup);
11161 /* Fixup stmts that became noreturn calls. This may require splitting
11162 blocks and thus isn't possible during the dominator walk. Do this
11163 in reverse order so we don't inadvertedly remove a stmt we want to
11164 fixup by visiting a dominating now noreturn call first. */
11165 while (!walker.stmts_to_fixup.is_empty ())
11167 gimple *stmt = walker.stmts_to_fixup.pop ();
11168 fixup_noreturn_call (stmt);
11171 vrp_free_lattice ();
11172 scev_finalize ();
11173 loop_optimizer_finalize ();
11174 return 0;
11178 /* Main entry point to VRP (Value Range Propagation). This pass is
11179 loosely based on J. R. C. Patterson, ``Accurate Static Branch
11180 Prediction by Value Range Propagation,'' in SIGPLAN Conference on
11181 Programming Language Design and Implementation, pp. 67-78, 1995.
11182 Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
11184 This is essentially an SSA-CCP pass modified to deal with ranges
11185 instead of constants.
11187 While propagating ranges, we may find that two or more SSA name
11188 have equivalent, though distinct ranges. For instance,
11190 1 x_9 = p_3->a;
11191 2 p_4 = ASSERT_EXPR <p_3, p_3 != 0>
11192 3 if (p_4 == q_2)
11193 4 p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
11194 5 endif
11195 6 if (q_2)
11197 In the code above, pointer p_5 has range [q_2, q_2], but from the
11198 code we can also determine that p_5 cannot be NULL and, if q_2 had
11199 a non-varying range, p_5's range should also be compatible with it.
11201 These equivalences are created by two expressions: ASSERT_EXPR and
11202 copy operations. Since p_5 is an assertion on p_4, and p_4 was the
11203 result of another assertion, then we can use the fact that p_5 and
11204 p_4 are equivalent when evaluating p_5's range.
11206 Together with value ranges, we also propagate these equivalences
11207 between names so that we can take advantage of information from
11208 multiple ranges when doing final replacement. Note that this
11209 equivalency relation is transitive but not symmetric.
11211 In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
11212 cannot assert that q_2 is equivalent to p_5 because q_2 may be used
11213 in contexts where that assertion does not hold (e.g., in line 6).
11215 TODO, the main difference between this pass and Patterson's is that
11216 we do not propagate edge probabilities. We only compute whether
11217 edges can be taken or not. That is, instead of having a spectrum
11218 of jump probabilities between 0 and 1, we only deal with 0, 1 and
11219 DON'T KNOW. In the future, it may be worthwhile to propagate
11220 probabilities to aid branch prediction. */
11222 static unsigned int
11223 execute_vrp (bool warn_array_bounds_p)
11225 int i;
11226 edge e;
11227 switch_update *su;
11229 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
11230 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
11231 scev_initialize ();
11233 /* ??? This ends up using stale EDGE_DFS_BACK for liveness computation.
11234 Inserting assertions may split edges which will invalidate
11235 EDGE_DFS_BACK. */
11236 insert_range_assertions ();
11238 to_remove_edges.create (10);
11239 to_update_switch_stmts.create (5);
11240 threadedge_initialize_values ();
11242 /* For visiting PHI nodes we need EDGE_DFS_BACK computed. */
11243 mark_dfs_back_edges ();
11245 vrp_initialize_lattice ();
11246 vrp_initialize ();
11247 ssa_propagate (vrp_visit_stmt, vrp_visit_phi_node);
11248 vrp_finalize (warn_array_bounds_p);
11249 vrp_free_lattice ();
11251 free_numbers_of_iterations_estimates (cfun);
11253 /* ASSERT_EXPRs must be removed before finalizing jump threads
11254 as finalizing jump threads calls the CFG cleanup code which
11255 does not properly handle ASSERT_EXPRs. */
11256 remove_range_assertions ();
11258 /* If we exposed any new variables, go ahead and put them into
11259 SSA form now, before we handle jump threading. This simplifies
11260 interactions between rewriting of _DECL nodes into SSA form
11261 and rewriting SSA_NAME nodes into SSA form after block
11262 duplication and CFG manipulation. */
11263 update_ssa (TODO_update_ssa);
11265 finalize_jump_threads ();
11267 /* Remove dead edges from SWITCH_EXPR optimization. This leaves the
11268 CFG in a broken state and requires a cfg_cleanup run. */
11269 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
11270 remove_edge (e);
11271 /* Update SWITCH_EXPR case label vector. */
11272 FOR_EACH_VEC_ELT (to_update_switch_stmts, i, su)
11274 size_t j;
11275 size_t n = TREE_VEC_LENGTH (su->vec);
11276 tree label;
11277 gimple_switch_set_num_labels (su->stmt, n);
11278 for (j = 0; j < n; j++)
11279 gimple_switch_set_label (su->stmt, j, TREE_VEC_ELT (su->vec, j));
11280 /* As we may have replaced the default label with a regular one
11281 make sure to make it a real default label again. This ensures
11282 optimal expansion. */
11283 label = gimple_switch_label (su->stmt, 0);
11284 CASE_LOW (label) = NULL_TREE;
11285 CASE_HIGH (label) = NULL_TREE;
11288 if (to_remove_edges.length () > 0)
11290 free_dominance_info (CDI_DOMINATORS);
11291 loops_state_set (LOOPS_NEED_FIXUP);
11294 to_remove_edges.release ();
11295 to_update_switch_stmts.release ();
11296 threadedge_finalize_values ();
11298 scev_finalize ();
11299 loop_optimizer_finalize ();
11300 return 0;
11303 namespace {
11305 const pass_data pass_data_vrp =
11307 GIMPLE_PASS, /* type */
11308 "vrp", /* name */
11309 OPTGROUP_NONE, /* optinfo_flags */
11310 TV_TREE_VRP, /* tv_id */
11311 PROP_ssa, /* properties_required */
11312 0, /* properties_provided */
11313 0, /* properties_destroyed */
11314 0, /* todo_flags_start */
11315 ( TODO_cleanup_cfg | TODO_update_ssa ), /* todo_flags_finish */
11318 class pass_vrp : public gimple_opt_pass
11320 public:
11321 pass_vrp (gcc::context *ctxt)
11322 : gimple_opt_pass (pass_data_vrp, ctxt), warn_array_bounds_p (false)
11325 /* opt_pass methods: */
11326 opt_pass * clone () { return new pass_vrp (m_ctxt); }
11327 void set_pass_param (unsigned int n, bool param)
11329 gcc_assert (n == 0);
11330 warn_array_bounds_p = param;
11332 virtual bool gate (function *) { return flag_tree_vrp != 0; }
11333 virtual unsigned int execute (function *)
11334 { return execute_vrp (warn_array_bounds_p); }
11336 private:
11337 bool warn_array_bounds_p;
11338 }; // class pass_vrp
11340 } // anon namespace
11342 gimple_opt_pass *
11343 make_pass_vrp (gcc::context *ctxt)
11345 return new pass_vrp (ctxt);
11348 namespace {
11350 const pass_data pass_data_early_vrp =
11352 GIMPLE_PASS, /* type */
11353 "evrp", /* name */
11354 OPTGROUP_NONE, /* optinfo_flags */
11355 TV_TREE_EARLY_VRP, /* tv_id */
11356 PROP_ssa, /* properties_required */
11357 0, /* properties_provided */
11358 0, /* properties_destroyed */
11359 0, /* todo_flags_start */
11360 ( TODO_cleanup_cfg | TODO_update_ssa | TODO_verify_all ),
11363 class pass_early_vrp : public gimple_opt_pass
11365 public:
11366 pass_early_vrp (gcc::context *ctxt)
11367 : gimple_opt_pass (pass_data_early_vrp, ctxt)
11370 /* opt_pass methods: */
11371 opt_pass * clone () { return new pass_early_vrp (m_ctxt); }
11372 virtual bool gate (function *)
11374 return flag_tree_vrp != 0;
11376 virtual unsigned int execute (function *)
11377 { return execute_early_vrp (); }
11379 }; // class pass_vrp
11380 } // anon namespace
11382 gimple_opt_pass *
11383 make_pass_early_vrp (gcc::context *ctxt)
11385 return new pass_early_vrp (ctxt);