PR tree-optimization/78496
[official-gcc.git] / gcc / tree-vrp.c
blob6a4035dc9247bff74b6c2fb906bfecb29225d8c9
1 /* Support routines for Value Range Propagation (VRP).
2 Copyright (C) 2005-2017 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-general.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 struct assert_info
94 /* Predicate code for the ASSERT_EXPR. Must be COMPARISON_CLASS_P. */
95 enum tree_code comp_code;
97 /* Name to register the assert for. */
98 tree name;
100 /* Value being compared against. */
101 tree val;
103 /* Expression to compare. */
104 tree expr;
107 /* Location information for ASSERT_EXPRs. Each instance of this
108 structure describes an ASSERT_EXPR for an SSA name. Since a single
109 SSA name may have more than one assertion associated with it, these
110 locations are kept in a linked list attached to the corresponding
111 SSA name. */
112 struct assert_locus
114 /* Basic block where the assertion would be inserted. */
115 basic_block bb;
117 /* Some assertions need to be inserted on an edge (e.g., assertions
118 generated by COND_EXPRs). In those cases, BB will be NULL. */
119 edge e;
121 /* Pointer to the statement that generated this assertion. */
122 gimple_stmt_iterator si;
124 /* Predicate code for the ASSERT_EXPR. Must be COMPARISON_CLASS_P. */
125 enum tree_code comp_code;
127 /* Value being compared against. */
128 tree val;
130 /* Expression to compare. */
131 tree expr;
133 /* Next node in the linked list. */
134 assert_locus *next;
137 /* If bit I is present, it means that SSA name N_i has a list of
138 assertions that should be inserted in the IL. */
139 static bitmap need_assert_for;
141 /* Array of locations lists where to insert assertions. ASSERTS_FOR[I]
142 holds a list of ASSERT_LOCUS_T nodes that describe where
143 ASSERT_EXPRs for SSA name N_I should be inserted. */
144 static assert_locus **asserts_for;
146 /* Value range array. After propagation, VR_VALUE[I] holds the range
147 of values that SSA name N_I may take. */
148 static unsigned num_vr_values;
149 static value_range **vr_value;
150 static bool values_propagated;
152 /* For a PHI node which sets SSA name N_I, VR_COUNTS[I] holds the
153 number of executable edges we saw the last time we visited the
154 node. */
155 static int *vr_phi_edge_counts;
157 struct switch_update {
158 gswitch *stmt;
159 tree vec;
162 static vec<edge> to_remove_edges;
163 static vec<switch_update> to_update_switch_stmts;
166 /* Return the maximum value for TYPE. */
168 static inline tree
169 vrp_val_max (const_tree type)
171 if (!INTEGRAL_TYPE_P (type))
172 return NULL_TREE;
174 return TYPE_MAX_VALUE (type);
177 /* Return the minimum value for TYPE. */
179 static inline tree
180 vrp_val_min (const_tree type)
182 if (!INTEGRAL_TYPE_P (type))
183 return NULL_TREE;
185 return TYPE_MIN_VALUE (type);
188 /* Return whether VAL is equal to the maximum value of its type. This
189 will be true for a positive overflow infinity. We can't do a
190 simple equality comparison with TYPE_MAX_VALUE because C typedefs
191 and Ada subtypes can produce types whose TYPE_MAX_VALUE is not ==
192 to the integer constant with the same value in the type. */
194 static inline bool
195 vrp_val_is_max (const_tree val)
197 tree type_max = vrp_val_max (TREE_TYPE (val));
198 return (val == type_max
199 || (type_max != NULL_TREE
200 && operand_equal_p (val, type_max, 0)));
203 /* Return whether VAL is equal to the minimum value of its type. This
204 will be true for a negative overflow infinity. */
206 static inline bool
207 vrp_val_is_min (const_tree val)
209 tree type_min = vrp_val_min (TREE_TYPE (val));
210 return (val == type_min
211 || (type_min != NULL_TREE
212 && operand_equal_p (val, type_min, 0)));
216 /* Return whether TYPE should use an overflow infinity distinct from
217 TYPE_{MIN,MAX}_VALUE. We use an overflow infinity value to
218 represent a signed overflow during VRP computations. An infinity
219 is distinct from a half-range, which will go from some number to
220 TYPE_{MIN,MAX}_VALUE. */
222 static inline bool
223 needs_overflow_infinity (const_tree type)
225 return INTEGRAL_TYPE_P (type) && !TYPE_OVERFLOW_WRAPS (type);
228 /* Return whether TYPE can support our overflow infinity
229 representation: we use the TREE_OVERFLOW flag, which only exists
230 for constants. If TYPE doesn't support this, we don't optimize
231 cases which would require signed overflow--we drop them to
232 VARYING. */
234 static inline bool
235 supports_overflow_infinity (const_tree type)
237 tree min = vrp_val_min (type), max = vrp_val_max (type);
238 gcc_checking_assert (needs_overflow_infinity (type));
239 return (min != NULL_TREE
240 && CONSTANT_CLASS_P (min)
241 && max != NULL_TREE
242 && CONSTANT_CLASS_P (max));
245 /* VAL is the maximum or minimum value of a type. Return a
246 corresponding overflow infinity. */
248 static inline tree
249 make_overflow_infinity (tree val)
251 gcc_checking_assert (val != NULL_TREE && CONSTANT_CLASS_P (val));
252 val = copy_node (val);
253 TREE_OVERFLOW (val) = 1;
254 return val;
257 /* Return a negative overflow infinity for TYPE. */
259 static inline tree
260 negative_overflow_infinity (tree type)
262 gcc_checking_assert (supports_overflow_infinity (type));
263 return make_overflow_infinity (vrp_val_min (type));
266 /* Return a positive overflow infinity for TYPE. */
268 static inline tree
269 positive_overflow_infinity (tree type)
271 gcc_checking_assert (supports_overflow_infinity (type));
272 return make_overflow_infinity (vrp_val_max (type));
275 /* Return whether VAL is a negative overflow infinity. */
277 static inline bool
278 is_negative_overflow_infinity (const_tree val)
280 return (TREE_OVERFLOW_P (val)
281 && needs_overflow_infinity (TREE_TYPE (val))
282 && vrp_val_is_min (val));
285 /* Return whether VAL is a positive overflow infinity. */
287 static inline bool
288 is_positive_overflow_infinity (const_tree val)
290 return (TREE_OVERFLOW_P (val)
291 && needs_overflow_infinity (TREE_TYPE (val))
292 && vrp_val_is_max (val));
295 /* Return whether VAL is a positive or negative overflow infinity. */
297 static inline bool
298 is_overflow_infinity (const_tree val)
300 return (TREE_OVERFLOW_P (val)
301 && needs_overflow_infinity (TREE_TYPE (val))
302 && (vrp_val_is_min (val) || vrp_val_is_max (val)));
305 /* Return whether STMT has a constant rhs that is_overflow_infinity. */
307 static inline bool
308 stmt_overflow_infinity (gimple *stmt)
310 if (is_gimple_assign (stmt)
311 && get_gimple_rhs_class (gimple_assign_rhs_code (stmt)) ==
312 GIMPLE_SINGLE_RHS)
313 return is_overflow_infinity (gimple_assign_rhs1 (stmt));
314 return false;
317 /* If VAL is now an overflow infinity, return VAL. Otherwise, return
318 the same value with TREE_OVERFLOW clear. This can be used to avoid
319 confusing a regular value with an overflow value. */
321 static inline tree
322 avoid_overflow_infinity (tree val)
324 if (!is_overflow_infinity (val))
325 return val;
327 if (vrp_val_is_max (val))
328 return vrp_val_max (TREE_TYPE (val));
329 else
331 gcc_checking_assert (vrp_val_is_min (val));
332 return vrp_val_min (TREE_TYPE (val));
337 /* Set value range VR to VR_UNDEFINED. */
339 static inline void
340 set_value_range_to_undefined (value_range *vr)
342 vr->type = VR_UNDEFINED;
343 vr->min = vr->max = NULL_TREE;
344 if (vr->equiv)
345 bitmap_clear (vr->equiv);
349 /* Set value range VR to VR_VARYING. */
351 static inline void
352 set_value_range_to_varying (value_range *vr)
354 vr->type = VR_VARYING;
355 vr->min = vr->max = NULL_TREE;
356 if (vr->equiv)
357 bitmap_clear (vr->equiv);
361 /* Set value range VR to {T, MIN, MAX, EQUIV}. */
363 static void
364 set_value_range (value_range *vr, enum value_range_type t, tree min,
365 tree max, bitmap equiv)
367 /* Check the validity of the range. */
368 if (flag_checking
369 && (t == VR_RANGE || t == VR_ANTI_RANGE))
371 int cmp;
373 gcc_assert (min && max);
375 gcc_assert ((!TREE_OVERFLOW_P (min) || is_overflow_infinity (min))
376 && (!TREE_OVERFLOW_P (max) || is_overflow_infinity (max)));
378 if (INTEGRAL_TYPE_P (TREE_TYPE (min)) && t == VR_ANTI_RANGE)
379 gcc_assert (!vrp_val_is_min (min) || !vrp_val_is_max (max));
381 cmp = compare_values (min, max);
382 gcc_assert (cmp == 0 || cmp == -1 || cmp == -2);
385 if (flag_checking
386 && (t == VR_UNDEFINED || t == VR_VARYING))
388 gcc_assert (min == NULL_TREE && max == NULL_TREE);
389 gcc_assert (equiv == NULL || bitmap_empty_p (equiv));
392 vr->type = t;
393 vr->min = min;
394 vr->max = max;
396 /* Since updating the equivalence set involves deep copying the
397 bitmaps, only do it if absolutely necessary. */
398 if (vr->equiv == NULL
399 && equiv != NULL)
400 vr->equiv = BITMAP_ALLOC (&vrp_equiv_obstack);
402 if (equiv != vr->equiv)
404 if (equiv && !bitmap_empty_p (equiv))
405 bitmap_copy (vr->equiv, equiv);
406 else
407 bitmap_clear (vr->equiv);
412 /* Set value range VR to the canonical form of {T, MIN, MAX, EQUIV}.
413 This means adjusting T, MIN and MAX representing the case of a
414 wrapping range with MAX < MIN covering [MIN, type_max] U [type_min, MAX]
415 as anti-rage ~[MAX+1, MIN-1]. Likewise for wrapping anti-ranges.
416 In corner cases where MAX+1 or MIN-1 wraps this will fall back
417 to varying.
418 This routine exists to ease canonicalization in the case where we
419 extract ranges from var + CST op limit. */
421 static void
422 set_and_canonicalize_value_range (value_range *vr, enum value_range_type t,
423 tree min, tree max, bitmap equiv)
425 /* Use the canonical setters for VR_UNDEFINED and VR_VARYING. */
426 if (t == VR_UNDEFINED)
428 set_value_range_to_undefined (vr);
429 return;
431 else if (t == VR_VARYING)
433 set_value_range_to_varying (vr);
434 return;
437 /* Nothing to canonicalize for symbolic ranges. */
438 if (TREE_CODE (min) != INTEGER_CST
439 || TREE_CODE (max) != INTEGER_CST)
441 set_value_range (vr, t, min, max, equiv);
442 return;
445 /* Wrong order for min and max, to swap them and the VR type we need
446 to adjust them. */
447 if (tree_int_cst_lt (max, min))
449 tree one, tmp;
451 /* For one bit precision if max < min, then the swapped
452 range covers all values, so for VR_RANGE it is varying and
453 for VR_ANTI_RANGE empty range, so drop to varying as well. */
454 if (TYPE_PRECISION (TREE_TYPE (min)) == 1)
456 set_value_range_to_varying (vr);
457 return;
460 one = build_int_cst (TREE_TYPE (min), 1);
461 tmp = int_const_binop (PLUS_EXPR, max, one);
462 max = int_const_binop (MINUS_EXPR, min, one);
463 min = tmp;
465 /* There's one corner case, if we had [C+1, C] before we now have
466 that again. But this represents an empty value range, so drop
467 to varying in this case. */
468 if (tree_int_cst_lt (max, min))
470 set_value_range_to_varying (vr);
471 return;
474 t = t == VR_RANGE ? VR_ANTI_RANGE : VR_RANGE;
477 /* Anti-ranges that can be represented as ranges should be so. */
478 if (t == VR_ANTI_RANGE)
480 bool is_min = vrp_val_is_min (min);
481 bool is_max = vrp_val_is_max (max);
483 if (is_min && is_max)
485 /* We cannot deal with empty ranges, drop to varying.
486 ??? This could be VR_UNDEFINED instead. */
487 set_value_range_to_varying (vr);
488 return;
490 else if (TYPE_PRECISION (TREE_TYPE (min)) == 1
491 && (is_min || is_max))
493 /* Non-empty boolean ranges can always be represented
494 as a singleton range. */
495 if (is_min)
496 min = max = vrp_val_max (TREE_TYPE (min));
497 else
498 min = max = vrp_val_min (TREE_TYPE (min));
499 t = VR_RANGE;
501 else if (is_min
502 /* As a special exception preserve non-null ranges. */
503 && !(TYPE_UNSIGNED (TREE_TYPE (min))
504 && integer_zerop (max)))
506 tree one = build_int_cst (TREE_TYPE (max), 1);
507 min = int_const_binop (PLUS_EXPR, max, one);
508 max = vrp_val_max (TREE_TYPE (max));
509 t = VR_RANGE;
511 else if (is_max)
513 tree one = build_int_cst (TREE_TYPE (min), 1);
514 max = int_const_binop (MINUS_EXPR, min, one);
515 min = vrp_val_min (TREE_TYPE (min));
516 t = VR_RANGE;
520 /* Do not drop [-INF(OVF), +INF(OVF)] to varying. (OVF) has to be sticky
521 to make sure VRP iteration terminates, otherwise we can get into
522 oscillations. */
524 set_value_range (vr, t, min, max, equiv);
527 /* Copy value range FROM into value range TO. */
529 static inline void
530 copy_value_range (value_range *to, value_range *from)
532 set_value_range (to, from->type, from->min, from->max, from->equiv);
535 /* Set value range VR to a single value. This function is only called
536 with values we get from statements, and exists to clear the
537 TREE_OVERFLOW flag so that we don't think we have an overflow
538 infinity when we shouldn't. */
540 static inline void
541 set_value_range_to_value (value_range *vr, tree val, bitmap equiv)
543 gcc_assert (is_gimple_min_invariant (val));
544 if (TREE_OVERFLOW_P (val))
545 val = drop_tree_overflow (val);
546 set_value_range (vr, VR_RANGE, val, val, equiv);
549 /* Set value range VR to a non-negative range of type TYPE.
550 OVERFLOW_INFINITY indicates whether to use an overflow infinity
551 rather than TYPE_MAX_VALUE; this should be true if we determine
552 that the range is nonnegative based on the assumption that signed
553 overflow does not occur. */
555 static inline void
556 set_value_range_to_nonnegative (value_range *vr, tree type,
557 bool overflow_infinity)
559 tree zero;
561 if (overflow_infinity && !supports_overflow_infinity (type))
563 set_value_range_to_varying (vr);
564 return;
567 zero = build_int_cst (type, 0);
568 set_value_range (vr, VR_RANGE, zero,
569 (overflow_infinity
570 ? positive_overflow_infinity (type)
571 : TYPE_MAX_VALUE (type)),
572 vr->equiv);
575 /* Set value range VR to a non-NULL range of type TYPE. */
577 static inline void
578 set_value_range_to_nonnull (value_range *vr, tree type)
580 tree zero = build_int_cst (type, 0);
581 set_value_range (vr, VR_ANTI_RANGE, zero, zero, vr->equiv);
585 /* Set value range VR to a NULL range of type TYPE. */
587 static inline void
588 set_value_range_to_null (value_range *vr, tree type)
590 set_value_range_to_value (vr, build_int_cst (type, 0), vr->equiv);
594 /* Set value range VR to a range of a truthvalue of type TYPE. */
596 static inline void
597 set_value_range_to_truthvalue (value_range *vr, tree type)
599 if (TYPE_PRECISION (type) == 1)
600 set_value_range_to_varying (vr);
601 else
602 set_value_range (vr, VR_RANGE,
603 build_int_cst (type, 0), build_int_cst (type, 1),
604 vr->equiv);
608 /* If abs (min) < abs (max), set VR to [-max, max], if
609 abs (min) >= abs (max), set VR to [-min, min]. */
611 static void
612 abs_extent_range (value_range *vr, tree min, tree max)
614 int cmp;
616 gcc_assert (TREE_CODE (min) == INTEGER_CST);
617 gcc_assert (TREE_CODE (max) == INTEGER_CST);
618 gcc_assert (INTEGRAL_TYPE_P (TREE_TYPE (min)));
619 gcc_assert (!TYPE_UNSIGNED (TREE_TYPE (min)));
620 min = fold_unary (ABS_EXPR, TREE_TYPE (min), min);
621 max = fold_unary (ABS_EXPR, TREE_TYPE (max), max);
622 if (TREE_OVERFLOW (min) || TREE_OVERFLOW (max))
624 set_value_range_to_varying (vr);
625 return;
627 cmp = compare_values (min, max);
628 if (cmp == -1)
629 min = fold_unary (NEGATE_EXPR, TREE_TYPE (min), max);
630 else if (cmp == 0 || cmp == 1)
632 max = min;
633 min = fold_unary (NEGATE_EXPR, TREE_TYPE (min), min);
635 else
637 set_value_range_to_varying (vr);
638 return;
640 set_and_canonicalize_value_range (vr, VR_RANGE, min, max, NULL);
644 /* Return value range information for VAR.
646 If we have no values ranges recorded (ie, VRP is not running), then
647 return NULL. Otherwise create an empty range if none existed for VAR. */
649 static value_range *
650 get_value_range (const_tree var)
652 static const value_range vr_const_varying
653 = { VR_VARYING, NULL_TREE, NULL_TREE, NULL };
654 value_range *vr;
655 tree sym;
656 unsigned ver = SSA_NAME_VERSION (var);
658 /* If we have no recorded ranges, then return NULL. */
659 if (! vr_value)
660 return NULL;
662 /* If we query the range for a new SSA name return an unmodifiable VARYING.
663 We should get here at most from the substitute-and-fold stage which
664 will never try to change values. */
665 if (ver >= num_vr_values)
666 return CONST_CAST (value_range *, &vr_const_varying);
668 vr = vr_value[ver];
669 if (vr)
670 return vr;
672 /* After propagation finished do not allocate new value-ranges. */
673 if (values_propagated)
674 return CONST_CAST (value_range *, &vr_const_varying);
676 /* Create a default value range. */
677 vr_value[ver] = vr = vrp_value_range_pool.allocate ();
678 memset (vr, 0, sizeof (*vr));
680 /* Defer allocating the equivalence set. */
681 vr->equiv = NULL;
683 /* If VAR is a default definition of a parameter, the variable can
684 take any value in VAR's type. */
685 if (SSA_NAME_IS_DEFAULT_DEF (var))
687 sym = SSA_NAME_VAR (var);
688 if (TREE_CODE (sym) == PARM_DECL)
690 /* Try to use the "nonnull" attribute to create ~[0, 0]
691 anti-ranges for pointers. Note that this is only valid with
692 default definitions of PARM_DECLs. */
693 if (POINTER_TYPE_P (TREE_TYPE (sym))
694 && (nonnull_arg_p (sym)
695 || get_ptr_nonnull (var)))
696 set_value_range_to_nonnull (vr, TREE_TYPE (sym));
697 else if (INTEGRAL_TYPE_P (TREE_TYPE (sym)))
699 wide_int min, max;
700 value_range_type rtype = get_range_info (var, &min, &max);
701 if (rtype == VR_RANGE || rtype == VR_ANTI_RANGE)
702 set_value_range (vr, rtype,
703 wide_int_to_tree (TREE_TYPE (var), min),
704 wide_int_to_tree (TREE_TYPE (var), max),
705 NULL);
706 else
707 set_value_range_to_varying (vr);
709 else
710 set_value_range_to_varying (vr);
712 else if (TREE_CODE (sym) == RESULT_DECL
713 && DECL_BY_REFERENCE (sym))
714 set_value_range_to_nonnull (vr, TREE_TYPE (sym));
717 return vr;
720 /* Set value-ranges of all SSA names defined by STMT to varying. */
722 static void
723 set_defs_to_varying (gimple *stmt)
725 ssa_op_iter i;
726 tree def;
727 FOR_EACH_SSA_TREE_OPERAND (def, stmt, i, SSA_OP_DEF)
729 value_range *vr = get_value_range (def);
730 /* Avoid writing to vr_const_varying get_value_range may return. */
731 if (vr->type != VR_VARYING)
732 set_value_range_to_varying (vr);
737 /* Return true, if VAL1 and VAL2 are equal values for VRP purposes. */
739 static inline bool
740 vrp_operand_equal_p (const_tree val1, const_tree val2)
742 if (val1 == val2)
743 return true;
744 if (!val1 || !val2 || !operand_equal_p (val1, val2, 0))
745 return false;
746 return is_overflow_infinity (val1) == is_overflow_infinity (val2);
749 /* Return true, if the bitmaps B1 and B2 are equal. */
751 static inline bool
752 vrp_bitmap_equal_p (const_bitmap b1, const_bitmap b2)
754 return (b1 == b2
755 || ((!b1 || bitmap_empty_p (b1))
756 && (!b2 || bitmap_empty_p (b2)))
757 || (b1 && b2
758 && bitmap_equal_p (b1, b2)));
761 /* Update the value range and equivalence set for variable VAR to
762 NEW_VR. Return true if NEW_VR is different from VAR's previous
763 value.
765 NOTE: This function assumes that NEW_VR is a temporary value range
766 object created for the sole purpose of updating VAR's range. The
767 storage used by the equivalence set from NEW_VR will be freed by
768 this function. Do not call update_value_range when NEW_VR
769 is the range object associated with another SSA name. */
771 static inline bool
772 update_value_range (const_tree var, value_range *new_vr)
774 value_range *old_vr;
775 bool is_new;
777 /* If there is a value-range on the SSA name from earlier analysis
778 factor that in. */
779 if (INTEGRAL_TYPE_P (TREE_TYPE (var)))
781 wide_int min, max;
782 value_range_type rtype = get_range_info (var, &min, &max);
783 if (rtype == VR_RANGE || rtype == VR_ANTI_RANGE)
785 tree nr_min, nr_max;
786 /* Range info on SSA names doesn't carry overflow information
787 so make sure to preserve the overflow bit on the lattice. */
788 if (rtype == VR_RANGE
789 && needs_overflow_infinity (TREE_TYPE (var))
790 && (new_vr->type == VR_VARYING
791 || (new_vr->type == VR_RANGE
792 && is_negative_overflow_infinity (new_vr->min)))
793 && wi::eq_p (vrp_val_min (TREE_TYPE (var)), min))
794 nr_min = negative_overflow_infinity (TREE_TYPE (var));
795 else
796 nr_min = wide_int_to_tree (TREE_TYPE (var), min);
797 if (rtype == VR_RANGE
798 && needs_overflow_infinity (TREE_TYPE (var))
799 && (new_vr->type == VR_VARYING
800 || (new_vr->type == VR_RANGE
801 && is_positive_overflow_infinity (new_vr->max)))
802 && wi::eq_p (vrp_val_max (TREE_TYPE (var)), max))
803 nr_max = positive_overflow_infinity (TREE_TYPE (var));
804 else
805 nr_max = wide_int_to_tree (TREE_TYPE (var), max);
806 value_range nr = VR_INITIALIZER;
807 set_and_canonicalize_value_range (&nr, rtype, nr_min, nr_max, NULL);
808 vrp_intersect_ranges (new_vr, &nr);
812 /* Update the value range, if necessary. */
813 old_vr = get_value_range (var);
814 is_new = old_vr->type != new_vr->type
815 || !vrp_operand_equal_p (old_vr->min, new_vr->min)
816 || !vrp_operand_equal_p (old_vr->max, new_vr->max)
817 || !vrp_bitmap_equal_p (old_vr->equiv, new_vr->equiv);
819 if (is_new)
821 /* Do not allow transitions up the lattice. The following
822 is slightly more awkward than just new_vr->type < old_vr->type
823 because VR_RANGE and VR_ANTI_RANGE need to be considered
824 the same. We may not have is_new when transitioning to
825 UNDEFINED. If old_vr->type is VARYING, we shouldn't be
826 called. */
827 if (new_vr->type == VR_UNDEFINED)
829 BITMAP_FREE (new_vr->equiv);
830 set_value_range_to_varying (old_vr);
831 set_value_range_to_varying (new_vr);
832 return true;
834 else
835 set_value_range (old_vr, new_vr->type, new_vr->min, new_vr->max,
836 new_vr->equiv);
839 BITMAP_FREE (new_vr->equiv);
841 return is_new;
845 /* Add VAR and VAR's equivalence set to EQUIV. This is the central
846 point where equivalence processing can be turned on/off. */
848 static void
849 add_equivalence (bitmap *equiv, const_tree var)
851 unsigned ver = SSA_NAME_VERSION (var);
852 value_range *vr = get_value_range (var);
854 if (*equiv == NULL)
855 *equiv = BITMAP_ALLOC (&vrp_equiv_obstack);
856 bitmap_set_bit (*equiv, ver);
857 if (vr && vr->equiv)
858 bitmap_ior_into (*equiv, vr->equiv);
862 /* Return true if VR is ~[0, 0]. */
864 static inline bool
865 range_is_nonnull (value_range *vr)
867 return vr->type == VR_ANTI_RANGE
868 && integer_zerop (vr->min)
869 && integer_zerop (vr->max);
873 /* Return true if VR is [0, 0]. */
875 static inline bool
876 range_is_null (value_range *vr)
878 return vr->type == VR_RANGE
879 && integer_zerop (vr->min)
880 && integer_zerop (vr->max);
883 /* Return true if max and min of VR are INTEGER_CST. It's not necessary
884 a singleton. */
886 static inline bool
887 range_int_cst_p (value_range *vr)
889 return (vr->type == VR_RANGE
890 && TREE_CODE (vr->max) == INTEGER_CST
891 && TREE_CODE (vr->min) == INTEGER_CST);
894 /* Return true if VR is a INTEGER_CST singleton. */
896 static inline bool
897 range_int_cst_singleton_p (value_range *vr)
899 return (range_int_cst_p (vr)
900 && !is_overflow_infinity (vr->min)
901 && !is_overflow_infinity (vr->max)
902 && tree_int_cst_equal (vr->min, vr->max));
905 /* Return true if value range VR involves at least one symbol. */
907 static inline bool
908 symbolic_range_p (value_range *vr)
910 return (!is_gimple_min_invariant (vr->min)
911 || !is_gimple_min_invariant (vr->max));
914 /* Return the single symbol (an SSA_NAME) contained in T if any, or NULL_TREE
915 otherwise. We only handle additive operations and set NEG to true if the
916 symbol is negated and INV to the invariant part, if any. */
918 static tree
919 get_single_symbol (tree t, bool *neg, tree *inv)
921 bool neg_;
922 tree inv_;
924 *inv = NULL_TREE;
925 *neg = false;
927 if (TREE_CODE (t) == PLUS_EXPR
928 || TREE_CODE (t) == POINTER_PLUS_EXPR
929 || TREE_CODE (t) == MINUS_EXPR)
931 if (is_gimple_min_invariant (TREE_OPERAND (t, 0)))
933 neg_ = (TREE_CODE (t) == MINUS_EXPR);
934 inv_ = TREE_OPERAND (t, 0);
935 t = TREE_OPERAND (t, 1);
937 else if (is_gimple_min_invariant (TREE_OPERAND (t, 1)))
939 neg_ = false;
940 inv_ = TREE_OPERAND (t, 1);
941 t = TREE_OPERAND (t, 0);
943 else
944 return NULL_TREE;
946 else
948 neg_ = false;
949 inv_ = NULL_TREE;
952 if (TREE_CODE (t) == NEGATE_EXPR)
954 t = TREE_OPERAND (t, 0);
955 neg_ = !neg_;
958 if (TREE_CODE (t) != SSA_NAME)
959 return NULL_TREE;
961 *neg = neg_;
962 *inv = inv_;
963 return t;
966 /* The reverse operation: build a symbolic expression with TYPE
967 from symbol SYM, negated according to NEG, and invariant INV. */
969 static tree
970 build_symbolic_expr (tree type, tree sym, bool neg, tree inv)
972 const bool pointer_p = POINTER_TYPE_P (type);
973 tree t = sym;
975 if (neg)
976 t = build1 (NEGATE_EXPR, type, t);
978 if (integer_zerop (inv))
979 return t;
981 return build2 (pointer_p ? POINTER_PLUS_EXPR : PLUS_EXPR, type, t, inv);
984 /* Return true if value range VR involves exactly one symbol SYM. */
986 static bool
987 symbolic_range_based_on_p (value_range *vr, const_tree sym)
989 bool neg, min_has_symbol, max_has_symbol;
990 tree inv;
992 if (is_gimple_min_invariant (vr->min))
993 min_has_symbol = false;
994 else if (get_single_symbol (vr->min, &neg, &inv) == sym)
995 min_has_symbol = true;
996 else
997 return false;
999 if (is_gimple_min_invariant (vr->max))
1000 max_has_symbol = false;
1001 else if (get_single_symbol (vr->max, &neg, &inv) == sym)
1002 max_has_symbol = true;
1003 else
1004 return false;
1006 return (min_has_symbol || max_has_symbol);
1009 /* Return true if value range VR uses an overflow infinity. */
1011 static inline bool
1012 overflow_infinity_range_p (value_range *vr)
1014 return (vr->type == VR_RANGE
1015 && (is_overflow_infinity (vr->min)
1016 || is_overflow_infinity (vr->max)));
1019 /* Return false if we can not make a valid comparison based on VR;
1020 this will be the case if it uses an overflow infinity and overflow
1021 is not undefined (i.e., -fno-strict-overflow is in effect).
1022 Otherwise return true, and set *STRICT_OVERFLOW_P to true if VR
1023 uses an overflow infinity. */
1025 static bool
1026 usable_range_p (value_range *vr, bool *strict_overflow_p)
1028 gcc_assert (vr->type == VR_RANGE);
1029 if (is_overflow_infinity (vr->min))
1031 *strict_overflow_p = true;
1032 if (!TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (vr->min)))
1033 return false;
1035 if (is_overflow_infinity (vr->max))
1037 *strict_overflow_p = true;
1038 if (!TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (vr->max)))
1039 return false;
1041 return true;
1044 /* Return true if the result of assignment STMT is know to be non-zero.
1045 If the return value is based on the assumption that signed overflow is
1046 undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
1047 *STRICT_OVERFLOW_P.*/
1049 static bool
1050 gimple_assign_nonzero_warnv_p (gimple *stmt, bool *strict_overflow_p)
1052 enum tree_code code = gimple_assign_rhs_code (stmt);
1053 switch (get_gimple_rhs_class (code))
1055 case GIMPLE_UNARY_RHS:
1056 return tree_unary_nonzero_warnv_p (gimple_assign_rhs_code (stmt),
1057 gimple_expr_type (stmt),
1058 gimple_assign_rhs1 (stmt),
1059 strict_overflow_p);
1060 case GIMPLE_BINARY_RHS:
1061 return tree_binary_nonzero_warnv_p (gimple_assign_rhs_code (stmt),
1062 gimple_expr_type (stmt),
1063 gimple_assign_rhs1 (stmt),
1064 gimple_assign_rhs2 (stmt),
1065 strict_overflow_p);
1066 case GIMPLE_TERNARY_RHS:
1067 return false;
1068 case GIMPLE_SINGLE_RHS:
1069 return tree_single_nonzero_warnv_p (gimple_assign_rhs1 (stmt),
1070 strict_overflow_p);
1071 case GIMPLE_INVALID_RHS:
1072 gcc_unreachable ();
1073 default:
1074 gcc_unreachable ();
1078 /* Return true if STMT is known to compute a non-zero value.
1079 If the return value is based on the assumption that signed overflow is
1080 undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
1081 *STRICT_OVERFLOW_P.*/
1083 static bool
1084 gimple_stmt_nonzero_warnv_p (gimple *stmt, bool *strict_overflow_p)
1086 switch (gimple_code (stmt))
1088 case GIMPLE_ASSIGN:
1089 return gimple_assign_nonzero_warnv_p (stmt, strict_overflow_p);
1090 case GIMPLE_CALL:
1092 tree fndecl = gimple_call_fndecl (stmt);
1093 if (!fndecl) return false;
1094 if (flag_delete_null_pointer_checks && !flag_check_new
1095 && DECL_IS_OPERATOR_NEW (fndecl)
1096 && !TREE_NOTHROW (fndecl))
1097 return true;
1098 /* References are always non-NULL. */
1099 if (flag_delete_null_pointer_checks
1100 && TREE_CODE (TREE_TYPE (fndecl)) == REFERENCE_TYPE)
1101 return true;
1102 if (flag_delete_null_pointer_checks &&
1103 lookup_attribute ("returns_nonnull",
1104 TYPE_ATTRIBUTES (gimple_call_fntype (stmt))))
1105 return true;
1107 gcall *call_stmt = as_a<gcall *> (stmt);
1108 unsigned rf = gimple_call_return_flags (call_stmt);
1109 if (rf & ERF_RETURNS_ARG)
1111 unsigned argnum = rf & ERF_RETURN_ARG_MASK;
1112 if (argnum < gimple_call_num_args (call_stmt))
1114 tree arg = gimple_call_arg (call_stmt, argnum);
1115 if (SSA_VAR_P (arg)
1116 && infer_nonnull_range_by_attribute (stmt, arg))
1117 return true;
1120 return gimple_alloca_call_p (stmt);
1122 default:
1123 gcc_unreachable ();
1127 /* Like tree_expr_nonzero_warnv_p, but this function uses value ranges
1128 obtained so far. */
1130 static bool
1131 vrp_stmt_computes_nonzero (gimple *stmt, bool *strict_overflow_p)
1133 if (gimple_stmt_nonzero_warnv_p (stmt, strict_overflow_p))
1134 return true;
1136 /* If we have an expression of the form &X->a, then the expression
1137 is nonnull if X is nonnull. */
1138 if (is_gimple_assign (stmt)
1139 && gimple_assign_rhs_code (stmt) == ADDR_EXPR)
1141 tree expr = gimple_assign_rhs1 (stmt);
1142 tree base = get_base_address (TREE_OPERAND (expr, 0));
1144 if (base != NULL_TREE
1145 && TREE_CODE (base) == MEM_REF
1146 && TREE_CODE (TREE_OPERAND (base, 0)) == SSA_NAME)
1148 value_range *vr = get_value_range (TREE_OPERAND (base, 0));
1149 if (range_is_nonnull (vr))
1150 return true;
1154 return false;
1157 /* Returns true if EXPR is a valid value (as expected by compare_values) --
1158 a gimple invariant, or SSA_NAME +- CST. */
1160 static bool
1161 valid_value_p (tree expr)
1163 if (TREE_CODE (expr) == SSA_NAME)
1164 return true;
1166 if (TREE_CODE (expr) == PLUS_EXPR
1167 || TREE_CODE (expr) == MINUS_EXPR)
1168 return (TREE_CODE (TREE_OPERAND (expr, 0)) == SSA_NAME
1169 && TREE_CODE (TREE_OPERAND (expr, 1)) == INTEGER_CST);
1171 return is_gimple_min_invariant (expr);
1174 /* Return
1175 1 if VAL < VAL2
1176 0 if !(VAL < VAL2)
1177 -2 if those are incomparable. */
1178 static inline int
1179 operand_less_p (tree val, tree val2)
1181 /* LT is folded faster than GE and others. Inline the common case. */
1182 if (TREE_CODE (val) == INTEGER_CST && TREE_CODE (val2) == INTEGER_CST)
1184 if (! is_positive_overflow_infinity (val2))
1185 return tree_int_cst_lt (val, val2);
1187 else
1189 tree tcmp;
1191 fold_defer_overflow_warnings ();
1193 tcmp = fold_binary_to_constant (LT_EXPR, boolean_type_node, val, val2);
1195 fold_undefer_and_ignore_overflow_warnings ();
1197 if (!tcmp
1198 || TREE_CODE (tcmp) != INTEGER_CST)
1199 return -2;
1201 if (!integer_zerop (tcmp))
1202 return 1;
1205 /* val >= val2, not considering overflow infinity. */
1206 if (is_negative_overflow_infinity (val))
1207 return is_negative_overflow_infinity (val2) ? 0 : 1;
1208 else if (is_positive_overflow_infinity (val2))
1209 return is_positive_overflow_infinity (val) ? 0 : 1;
1211 return 0;
1214 /* Compare two values VAL1 and VAL2. Return
1216 -2 if VAL1 and VAL2 cannot be compared at compile-time,
1217 -1 if VAL1 < VAL2,
1218 0 if VAL1 == VAL2,
1219 +1 if VAL1 > VAL2, and
1220 +2 if VAL1 != VAL2
1222 This is similar to tree_int_cst_compare but supports pointer values
1223 and values that cannot be compared at compile time.
1225 If STRICT_OVERFLOW_P is not NULL, then set *STRICT_OVERFLOW_P to
1226 true if the return value is only valid if we assume that signed
1227 overflow is undefined. */
1229 static int
1230 compare_values_warnv (tree val1, tree val2, bool *strict_overflow_p)
1232 if (val1 == val2)
1233 return 0;
1235 /* Below we rely on the fact that VAL1 and VAL2 are both pointers or
1236 both integers. */
1237 gcc_assert (POINTER_TYPE_P (TREE_TYPE (val1))
1238 == POINTER_TYPE_P (TREE_TYPE (val2)));
1240 /* Convert the two values into the same type. This is needed because
1241 sizetype causes sign extension even for unsigned types. */
1242 val2 = fold_convert (TREE_TYPE (val1), val2);
1243 STRIP_USELESS_TYPE_CONVERSION (val2);
1245 const bool overflow_undefined
1246 = INTEGRAL_TYPE_P (TREE_TYPE (val1))
1247 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1));
1248 tree inv1, inv2;
1249 bool neg1, neg2;
1250 tree sym1 = get_single_symbol (val1, &neg1, &inv1);
1251 tree sym2 = get_single_symbol (val2, &neg2, &inv2);
1253 /* If VAL1 and VAL2 are of the form '[-]NAME [+ CST]', return -1 or +1
1254 accordingly. If VAL1 and VAL2 don't use the same name, return -2. */
1255 if (sym1 && sym2)
1257 /* Both values must use the same name with the same sign. */
1258 if (sym1 != sym2 || neg1 != neg2)
1259 return -2;
1261 /* [-]NAME + CST == [-]NAME + CST. */
1262 if (inv1 == inv2)
1263 return 0;
1265 /* If overflow is defined we cannot simplify more. */
1266 if (!overflow_undefined)
1267 return -2;
1269 if (strict_overflow_p != NULL
1270 && (!inv1 || !TREE_NO_WARNING (val1))
1271 && (!inv2 || !TREE_NO_WARNING (val2)))
1272 *strict_overflow_p = true;
1274 if (!inv1)
1275 inv1 = build_int_cst (TREE_TYPE (val1), 0);
1276 if (!inv2)
1277 inv2 = build_int_cst (TREE_TYPE (val2), 0);
1279 return compare_values_warnv (inv1, inv2, strict_overflow_p);
1282 const bool cst1 = is_gimple_min_invariant (val1);
1283 const bool cst2 = is_gimple_min_invariant (val2);
1285 /* If one is of the form '[-]NAME + CST' and the other is constant, then
1286 it might be possible to say something depending on the constants. */
1287 if ((sym1 && inv1 && cst2) || (sym2 && inv2 && cst1))
1289 if (!overflow_undefined)
1290 return -2;
1292 if (strict_overflow_p != NULL
1293 && (!sym1 || !TREE_NO_WARNING (val1))
1294 && (!sym2 || !TREE_NO_WARNING (val2)))
1295 *strict_overflow_p = true;
1297 const signop sgn = TYPE_SIGN (TREE_TYPE (val1));
1298 tree cst = cst1 ? val1 : val2;
1299 tree inv = cst1 ? inv2 : inv1;
1301 /* Compute the difference between the constants. If it overflows or
1302 underflows, this means that we can trivially compare the NAME with
1303 it and, consequently, the two values with each other. */
1304 wide_int diff = wi::sub (cst, inv);
1305 if (wi::cmp (0, inv, sgn) != wi::cmp (diff, cst, sgn))
1307 const int res = wi::cmp (cst, inv, sgn);
1308 return cst1 ? res : -res;
1311 return -2;
1314 /* We cannot say anything more for non-constants. */
1315 if (!cst1 || !cst2)
1316 return -2;
1318 if (!POINTER_TYPE_P (TREE_TYPE (val1)))
1320 /* We cannot compare overflowed values, except for overflow
1321 infinities. */
1322 if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
1324 if (strict_overflow_p != NULL)
1325 *strict_overflow_p = true;
1326 if (is_negative_overflow_infinity (val1))
1327 return is_negative_overflow_infinity (val2) ? 0 : -1;
1328 else if (is_negative_overflow_infinity (val2))
1329 return 1;
1330 else if (is_positive_overflow_infinity (val1))
1331 return is_positive_overflow_infinity (val2) ? 0 : 1;
1332 else if (is_positive_overflow_infinity (val2))
1333 return -1;
1334 return -2;
1337 return tree_int_cst_compare (val1, val2);
1339 else
1341 tree t;
1343 /* First see if VAL1 and VAL2 are not the same. */
1344 if (val1 == val2 || operand_equal_p (val1, val2, 0))
1345 return 0;
1347 /* If VAL1 is a lower address than VAL2, return -1. */
1348 if (operand_less_p (val1, val2) == 1)
1349 return -1;
1351 /* If VAL1 is a higher address than VAL2, return +1. */
1352 if (operand_less_p (val2, val1) == 1)
1353 return 1;
1355 /* If VAL1 is different than VAL2, return +2.
1356 For integer constants we either have already returned -1 or 1
1357 or they are equivalent. We still might succeed in proving
1358 something about non-trivial operands. */
1359 if (TREE_CODE (val1) != INTEGER_CST
1360 || TREE_CODE (val2) != INTEGER_CST)
1362 t = fold_binary_to_constant (NE_EXPR, boolean_type_node, val1, val2);
1363 if (t && integer_onep (t))
1364 return 2;
1367 return -2;
1371 /* Compare values like compare_values_warnv, but treat comparisons of
1372 nonconstants which rely on undefined overflow as incomparable. */
1374 static int
1375 compare_values (tree val1, tree val2)
1377 bool sop;
1378 int ret;
1380 sop = false;
1381 ret = compare_values_warnv (val1, val2, &sop);
1382 if (sop
1383 && (!is_gimple_min_invariant (val1) || !is_gimple_min_invariant (val2)))
1384 ret = -2;
1385 return ret;
1389 /* Return 1 if VAL is inside value range MIN <= VAL <= MAX,
1390 0 if VAL is not inside [MIN, MAX],
1391 -2 if we cannot tell either way.
1393 Benchmark compile/20001226-1.c compilation time after changing this
1394 function. */
1396 static inline int
1397 value_inside_range (tree val, tree min, tree max)
1399 int cmp1, cmp2;
1401 cmp1 = operand_less_p (val, min);
1402 if (cmp1 == -2)
1403 return -2;
1404 if (cmp1 == 1)
1405 return 0;
1407 cmp2 = operand_less_p (max, val);
1408 if (cmp2 == -2)
1409 return -2;
1411 return !cmp2;
1415 /* Return true if value ranges VR0 and VR1 have a non-empty
1416 intersection.
1418 Benchmark compile/20001226-1.c compilation time after changing this
1419 function.
1422 static inline bool
1423 value_ranges_intersect_p (value_range *vr0, value_range *vr1)
1425 /* The value ranges do not intersect if the maximum of the first range is
1426 less than the minimum of the second range or vice versa.
1427 When those relations are unknown, we can't do any better. */
1428 if (operand_less_p (vr0->max, vr1->min) != 0)
1429 return false;
1430 if (operand_less_p (vr1->max, vr0->min) != 0)
1431 return false;
1432 return true;
1436 /* Return 1 if [MIN, MAX] includes the value zero, 0 if it does not
1437 include the value zero, -2 if we cannot tell. */
1439 static inline int
1440 range_includes_zero_p (tree min, tree max)
1442 tree zero = build_int_cst (TREE_TYPE (min), 0);
1443 return value_inside_range (zero, min, max);
1446 /* Return true if *VR is know to only contain nonnegative values. */
1448 static inline bool
1449 value_range_nonnegative_p (value_range *vr)
1451 /* Testing for VR_ANTI_RANGE is not useful here as any anti-range
1452 which would return a useful value should be encoded as a
1453 VR_RANGE. */
1454 if (vr->type == VR_RANGE)
1456 int result = compare_values (vr->min, integer_zero_node);
1457 return (result == 0 || result == 1);
1460 return false;
1463 /* If *VR has a value rante that is a single constant value return that,
1464 otherwise return NULL_TREE. */
1466 static tree
1467 value_range_constant_singleton (value_range *vr)
1469 if (vr->type == VR_RANGE
1470 && vrp_operand_equal_p (vr->min, vr->max)
1471 && is_gimple_min_invariant (vr->min))
1472 return vr->min;
1474 return NULL_TREE;
1477 /* If OP has a value range with a single constant value return that,
1478 otherwise return NULL_TREE. This returns OP itself if OP is a
1479 constant. */
1481 static tree
1482 op_with_constant_singleton_value_range (tree op)
1484 if (is_gimple_min_invariant (op))
1485 return op;
1487 if (TREE_CODE (op) != SSA_NAME)
1488 return NULL_TREE;
1490 return value_range_constant_singleton (get_value_range (op));
1493 /* Return true if op is in a boolean [0, 1] value-range. */
1495 static bool
1496 op_with_boolean_value_range_p (tree op)
1498 value_range *vr;
1500 if (TYPE_PRECISION (TREE_TYPE (op)) == 1)
1501 return true;
1503 if (integer_zerop (op)
1504 || integer_onep (op))
1505 return true;
1507 if (TREE_CODE (op) != SSA_NAME)
1508 return false;
1510 vr = get_value_range (op);
1511 return (vr->type == VR_RANGE
1512 && integer_zerop (vr->min)
1513 && integer_onep (vr->max));
1516 /* Extract value range information for VAR when (OP COND_CODE LIMIT) is
1517 true and store it in *VR_P. */
1519 static void
1520 extract_range_for_var_from_comparison_expr (tree var, enum tree_code cond_code,
1521 tree op, tree limit,
1522 value_range *vr_p)
1524 tree min, max, type;
1525 value_range *limit_vr;
1526 limit = avoid_overflow_infinity (limit);
1527 type = TREE_TYPE (var);
1528 gcc_assert (limit != var);
1530 /* For pointer arithmetic, we only keep track of pointer equality
1531 and inequality. */
1532 if (POINTER_TYPE_P (type) && cond_code != NE_EXPR && cond_code != EQ_EXPR)
1534 set_value_range_to_varying (vr_p);
1535 return;
1538 /* If LIMIT is another SSA name and LIMIT has a range of its own,
1539 try to use LIMIT's range to avoid creating symbolic ranges
1540 unnecessarily. */
1541 limit_vr = (TREE_CODE (limit) == SSA_NAME) ? get_value_range (limit) : NULL;
1543 /* LIMIT's range is only interesting if it has any useful information. */
1544 if (! limit_vr
1545 || limit_vr->type == VR_UNDEFINED
1546 || limit_vr->type == VR_VARYING
1547 || (symbolic_range_p (limit_vr)
1548 && ! (limit_vr->type == VR_RANGE
1549 && (limit_vr->min == limit_vr->max
1550 || operand_equal_p (limit_vr->min, limit_vr->max, 0)))))
1551 limit_vr = NULL;
1553 /* Initially, the new range has the same set of equivalences of
1554 VAR's range. This will be revised before returning the final
1555 value. Since assertions may be chained via mutually exclusive
1556 predicates, we will need to trim the set of equivalences before
1557 we are done. */
1558 gcc_assert (vr_p->equiv == NULL);
1559 add_equivalence (&vr_p->equiv, var);
1561 /* Extract a new range based on the asserted comparison for VAR and
1562 LIMIT's value range. Notice that if LIMIT has an anti-range, we
1563 will only use it for equality comparisons (EQ_EXPR). For any
1564 other kind of assertion, we cannot derive a range from LIMIT's
1565 anti-range that can be used to describe the new range. For
1566 instance, ASSERT_EXPR <x_2, x_2 <= b_4>. If b_4 is ~[2, 10],
1567 then b_4 takes on the ranges [-INF, 1] and [11, +INF]. There is
1568 no single range for x_2 that could describe LE_EXPR, so we might
1569 as well build the range [b_4, +INF] for it.
1570 One special case we handle is extracting a range from a
1571 range test encoded as (unsigned)var + CST <= limit. */
1572 if (TREE_CODE (op) == NOP_EXPR
1573 || TREE_CODE (op) == PLUS_EXPR)
1575 if (TREE_CODE (op) == PLUS_EXPR)
1577 min = fold_build1 (NEGATE_EXPR, TREE_TYPE (TREE_OPERAND (op, 1)),
1578 TREE_OPERAND (op, 1));
1579 max = int_const_binop (PLUS_EXPR, limit, min);
1580 op = TREE_OPERAND (op, 0);
1582 else
1584 min = build_int_cst (TREE_TYPE (var), 0);
1585 max = limit;
1588 /* Make sure to not set TREE_OVERFLOW on the final type
1589 conversion. We are willingly interpreting large positive
1590 unsigned values as negative signed values here. */
1591 min = force_fit_type (TREE_TYPE (var), wi::to_widest (min), 0, false);
1592 max = force_fit_type (TREE_TYPE (var), wi::to_widest (max), 0, false);
1594 /* We can transform a max, min range to an anti-range or
1595 vice-versa. Use set_and_canonicalize_value_range which does
1596 this for us. */
1597 if (cond_code == LE_EXPR)
1598 set_and_canonicalize_value_range (vr_p, VR_RANGE,
1599 min, max, vr_p->equiv);
1600 else if (cond_code == GT_EXPR)
1601 set_and_canonicalize_value_range (vr_p, VR_ANTI_RANGE,
1602 min, max, vr_p->equiv);
1603 else
1604 gcc_unreachable ();
1606 else if (cond_code == EQ_EXPR)
1608 enum value_range_type range_type;
1610 if (limit_vr)
1612 range_type = limit_vr->type;
1613 min = limit_vr->min;
1614 max = limit_vr->max;
1616 else
1618 range_type = VR_RANGE;
1619 min = limit;
1620 max = limit;
1623 set_value_range (vr_p, range_type, min, max, vr_p->equiv);
1625 /* When asserting the equality VAR == LIMIT and LIMIT is another
1626 SSA name, the new range will also inherit the equivalence set
1627 from LIMIT. */
1628 if (TREE_CODE (limit) == SSA_NAME)
1629 add_equivalence (&vr_p->equiv, limit);
1631 else if (cond_code == NE_EXPR)
1633 /* As described above, when LIMIT's range is an anti-range and
1634 this assertion is an inequality (NE_EXPR), then we cannot
1635 derive anything from the anti-range. For instance, if
1636 LIMIT's range was ~[0, 0], the assertion 'VAR != LIMIT' does
1637 not imply that VAR's range is [0, 0]. So, in the case of
1638 anti-ranges, we just assert the inequality using LIMIT and
1639 not its anti-range.
1641 If LIMIT_VR is a range, we can only use it to build a new
1642 anti-range if LIMIT_VR is a single-valued range. For
1643 instance, if LIMIT_VR is [0, 1], the predicate
1644 VAR != [0, 1] does not mean that VAR's range is ~[0, 1].
1645 Rather, it means that for value 0 VAR should be ~[0, 0]
1646 and for value 1, VAR should be ~[1, 1]. We cannot
1647 represent these ranges.
1649 The only situation in which we can build a valid
1650 anti-range is when LIMIT_VR is a single-valued range
1651 (i.e., LIMIT_VR->MIN == LIMIT_VR->MAX). In that case,
1652 build the anti-range ~[LIMIT_VR->MIN, LIMIT_VR->MAX]. */
1653 if (limit_vr
1654 && limit_vr->type == VR_RANGE
1655 && compare_values (limit_vr->min, limit_vr->max) == 0)
1657 min = limit_vr->min;
1658 max = limit_vr->max;
1660 else
1662 /* In any other case, we cannot use LIMIT's range to build a
1663 valid anti-range. */
1664 min = max = limit;
1667 /* If MIN and MAX cover the whole range for their type, then
1668 just use the original LIMIT. */
1669 if (INTEGRAL_TYPE_P (type)
1670 && vrp_val_is_min (min)
1671 && vrp_val_is_max (max))
1672 min = max = limit;
1674 set_and_canonicalize_value_range (vr_p, VR_ANTI_RANGE,
1675 min, max, vr_p->equiv);
1677 else if (cond_code == LE_EXPR || cond_code == LT_EXPR)
1679 min = TYPE_MIN_VALUE (type);
1681 if (limit_vr == NULL || limit_vr->type == VR_ANTI_RANGE)
1682 max = limit;
1683 else
1685 /* If LIMIT_VR is of the form [N1, N2], we need to build the
1686 range [MIN, N2] for LE_EXPR and [MIN, N2 - 1] for
1687 LT_EXPR. */
1688 max = limit_vr->max;
1691 /* If the maximum value forces us to be out of bounds, simply punt.
1692 It would be pointless to try and do anything more since this
1693 all should be optimized away above us. */
1694 if ((cond_code == LT_EXPR
1695 && compare_values (max, min) == 0)
1696 || is_overflow_infinity (max))
1697 set_value_range_to_varying (vr_p);
1698 else
1700 /* For LT_EXPR, we create the range [MIN, MAX - 1]. */
1701 if (cond_code == LT_EXPR)
1703 if (TYPE_PRECISION (TREE_TYPE (max)) == 1
1704 && !TYPE_UNSIGNED (TREE_TYPE (max)))
1705 max = fold_build2 (PLUS_EXPR, TREE_TYPE (max), max,
1706 build_int_cst (TREE_TYPE (max), -1));
1707 else
1708 max = fold_build2 (MINUS_EXPR, TREE_TYPE (max), max,
1709 build_int_cst (TREE_TYPE (max), 1));
1710 if (EXPR_P (max))
1711 TREE_NO_WARNING (max) = 1;
1714 set_value_range (vr_p, VR_RANGE, min, max, vr_p->equiv);
1717 else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
1719 max = TYPE_MAX_VALUE (type);
1721 if (limit_vr == NULL || limit_vr->type == VR_ANTI_RANGE)
1722 min = limit;
1723 else
1725 /* If LIMIT_VR is of the form [N1, N2], we need to build the
1726 range [N1, MAX] for GE_EXPR and [N1 + 1, MAX] for
1727 GT_EXPR. */
1728 min = limit_vr->min;
1731 /* If the minimum value forces us to be out of bounds, simply punt.
1732 It would be pointless to try and do anything more since this
1733 all should be optimized away above us. */
1734 if ((cond_code == GT_EXPR
1735 && compare_values (min, max) == 0)
1736 || is_overflow_infinity (min))
1737 set_value_range_to_varying (vr_p);
1738 else
1740 /* For GT_EXPR, we create the range [MIN + 1, MAX]. */
1741 if (cond_code == GT_EXPR)
1743 if (TYPE_PRECISION (TREE_TYPE (min)) == 1
1744 && !TYPE_UNSIGNED (TREE_TYPE (min)))
1745 min = fold_build2 (MINUS_EXPR, TREE_TYPE (min), min,
1746 build_int_cst (TREE_TYPE (min), -1));
1747 else
1748 min = fold_build2 (PLUS_EXPR, TREE_TYPE (min), min,
1749 build_int_cst (TREE_TYPE (min), 1));
1750 if (EXPR_P (min))
1751 TREE_NO_WARNING (min) = 1;
1754 set_value_range (vr_p, VR_RANGE, min, max, vr_p->equiv);
1757 else
1758 gcc_unreachable ();
1760 /* Finally intersect the new range with what we already know about var. */
1761 vrp_intersect_ranges (vr_p, get_value_range (var));
1764 /* Extract value range information from an ASSERT_EXPR EXPR and store
1765 it in *VR_P. */
1767 static void
1768 extract_range_from_assert (value_range *vr_p, tree expr)
1770 tree var = ASSERT_EXPR_VAR (expr);
1771 tree cond = ASSERT_EXPR_COND (expr);
1772 tree limit, op;
1773 enum tree_code cond_code;
1774 gcc_assert (COMPARISON_CLASS_P (cond));
1776 /* Find VAR in the ASSERT_EXPR conditional. */
1777 if (var == TREE_OPERAND (cond, 0)
1778 || TREE_CODE (TREE_OPERAND (cond, 0)) == PLUS_EXPR
1779 || TREE_CODE (TREE_OPERAND (cond, 0)) == NOP_EXPR)
1781 /* If the predicate is of the form VAR COMP LIMIT, then we just
1782 take LIMIT from the RHS and use the same comparison code. */
1783 cond_code = TREE_CODE (cond);
1784 limit = TREE_OPERAND (cond, 1);
1785 op = TREE_OPERAND (cond, 0);
1787 else
1789 /* If the predicate is of the form LIMIT COMP VAR, then we need
1790 to flip around the comparison code to create the proper range
1791 for VAR. */
1792 cond_code = swap_tree_comparison (TREE_CODE (cond));
1793 limit = TREE_OPERAND (cond, 0);
1794 op = TREE_OPERAND (cond, 1);
1796 extract_range_for_var_from_comparison_expr (var, cond_code, op,
1797 limit, vr_p);
1800 /* Extract range information from SSA name VAR and store it in VR. If
1801 VAR has an interesting range, use it. Otherwise, create the
1802 range [VAR, VAR] and return it. This is useful in situations where
1803 we may have conditionals testing values of VARYING names. For
1804 instance,
1806 x_3 = y_5;
1807 if (x_3 > y_5)
1810 Even if y_5 is deemed VARYING, we can determine that x_3 > y_5 is
1811 always false. */
1813 static void
1814 extract_range_from_ssa_name (value_range *vr, tree var)
1816 value_range *var_vr = get_value_range (var);
1818 if (var_vr->type != VR_VARYING)
1819 copy_value_range (vr, var_vr);
1820 else
1821 set_value_range (vr, VR_RANGE, var, var, NULL);
1823 add_equivalence (&vr->equiv, var);
1827 /* Wrapper around int_const_binop. If the operation overflows and we
1828 are not using wrapping arithmetic, then adjust the result to be
1829 -INF or +INF depending on CODE, VAL1 and VAL2. This can return
1830 NULL_TREE if we need to use an overflow infinity representation but
1831 the type does not support it. */
1833 static tree
1834 vrp_int_const_binop (enum tree_code code, tree val1, tree val2)
1836 tree res;
1838 res = int_const_binop (code, val1, val2);
1840 /* If we are using unsigned arithmetic, operate symbolically
1841 on -INF and +INF as int_const_binop only handles signed overflow. */
1842 if (TYPE_UNSIGNED (TREE_TYPE (val1)))
1844 int checkz = compare_values (res, val1);
1845 bool overflow = false;
1847 /* Ensure that res = val1 [+*] val2 >= val1
1848 or that res = val1 - val2 <= val1. */
1849 if ((code == PLUS_EXPR
1850 && !(checkz == 1 || checkz == 0))
1851 || (code == MINUS_EXPR
1852 && !(checkz == 0 || checkz == -1)))
1854 overflow = true;
1856 /* Checking for multiplication overflow is done by dividing the
1857 output of the multiplication by the first input of the
1858 multiplication. If the result of that division operation is
1859 not equal to the second input of the multiplication, then the
1860 multiplication overflowed. */
1861 else if (code == MULT_EXPR && !integer_zerop (val1))
1863 tree tmp = int_const_binop (TRUNC_DIV_EXPR,
1864 res,
1865 val1);
1866 int check = compare_values (tmp, val2);
1868 if (check != 0)
1869 overflow = true;
1872 if (overflow)
1874 res = copy_node (res);
1875 TREE_OVERFLOW (res) = 1;
1879 else if (TYPE_OVERFLOW_WRAPS (TREE_TYPE (val1)))
1880 /* If the singed operation wraps then int_const_binop has done
1881 everything we want. */
1883 /* Signed division of -1/0 overflows and by the time it gets here
1884 returns NULL_TREE. */
1885 else if (!res)
1886 return NULL_TREE;
1887 else if ((TREE_OVERFLOW (res)
1888 && !TREE_OVERFLOW (val1)
1889 && !TREE_OVERFLOW (val2))
1890 || is_overflow_infinity (val1)
1891 || is_overflow_infinity (val2))
1893 /* If the operation overflowed but neither VAL1 nor VAL2 are
1894 overflown, return -INF or +INF depending on the operation
1895 and the combination of signs of the operands. */
1896 int sgn1 = tree_int_cst_sgn (val1);
1897 int sgn2 = tree_int_cst_sgn (val2);
1899 if (needs_overflow_infinity (TREE_TYPE (res))
1900 && !supports_overflow_infinity (TREE_TYPE (res)))
1901 return NULL_TREE;
1903 /* We have to punt on adding infinities of different signs,
1904 since we can't tell what the sign of the result should be.
1905 Likewise for subtracting infinities of the same sign. */
1906 if (((code == PLUS_EXPR && sgn1 != sgn2)
1907 || (code == MINUS_EXPR && sgn1 == sgn2))
1908 && is_overflow_infinity (val1)
1909 && is_overflow_infinity (val2))
1910 return NULL_TREE;
1912 /* Don't try to handle division or shifting of infinities. */
1913 if ((code == TRUNC_DIV_EXPR
1914 || code == FLOOR_DIV_EXPR
1915 || code == CEIL_DIV_EXPR
1916 || code == EXACT_DIV_EXPR
1917 || code == ROUND_DIV_EXPR
1918 || code == RSHIFT_EXPR)
1919 && (is_overflow_infinity (val1)
1920 || is_overflow_infinity (val2)))
1921 return NULL_TREE;
1923 /* Notice that we only need to handle the restricted set of
1924 operations handled by extract_range_from_binary_expr.
1925 Among them, only multiplication, addition and subtraction
1926 can yield overflow without overflown operands because we
1927 are working with integral types only... except in the
1928 case VAL1 = -INF and VAL2 = -1 which overflows to +INF
1929 for division too. */
1931 /* For multiplication, the sign of the overflow is given
1932 by the comparison of the signs of the operands. */
1933 if ((code == MULT_EXPR && sgn1 == sgn2)
1934 /* For addition, the operands must be of the same sign
1935 to yield an overflow. Its sign is therefore that
1936 of one of the operands, for example the first. For
1937 infinite operands X + -INF is negative, not positive. */
1938 || (code == PLUS_EXPR
1939 && (sgn1 >= 0
1940 ? !is_negative_overflow_infinity (val2)
1941 : is_positive_overflow_infinity (val2)))
1942 /* For subtraction, non-infinite operands must be of
1943 different signs to yield an overflow. Its sign is
1944 therefore that of the first operand or the opposite of
1945 that of the second operand. A first operand of 0 counts
1946 as positive here, for the corner case 0 - (-INF), which
1947 overflows, but must yield +INF. For infinite operands 0
1948 - INF is negative, not positive. */
1949 || (code == MINUS_EXPR
1950 && (sgn1 >= 0
1951 ? !is_positive_overflow_infinity (val2)
1952 : is_negative_overflow_infinity (val2)))
1953 /* We only get in here with positive shift count, so the
1954 overflow direction is the same as the sign of val1.
1955 Actually rshift does not overflow at all, but we only
1956 handle the case of shifting overflowed -INF and +INF. */
1957 || (code == RSHIFT_EXPR
1958 && sgn1 >= 0)
1959 /* For division, the only case is -INF / -1 = +INF. */
1960 || code == TRUNC_DIV_EXPR
1961 || code == FLOOR_DIV_EXPR
1962 || code == CEIL_DIV_EXPR
1963 || code == EXACT_DIV_EXPR
1964 || code == ROUND_DIV_EXPR)
1965 return (needs_overflow_infinity (TREE_TYPE (res))
1966 ? positive_overflow_infinity (TREE_TYPE (res))
1967 : TYPE_MAX_VALUE (TREE_TYPE (res)));
1968 else
1969 return (needs_overflow_infinity (TREE_TYPE (res))
1970 ? negative_overflow_infinity (TREE_TYPE (res))
1971 : TYPE_MIN_VALUE (TREE_TYPE (res)));
1974 return res;
1978 /* For range VR compute two wide_int bitmasks. In *MAY_BE_NONZERO
1979 bitmask if some bit is unset, it means for all numbers in the range
1980 the bit is 0, otherwise it might be 0 or 1. In *MUST_BE_NONZERO
1981 bitmask if some bit is set, it means for all numbers in the range
1982 the bit is 1, otherwise it might be 0 or 1. */
1984 static bool
1985 zero_nonzero_bits_from_vr (const tree expr_type,
1986 value_range *vr,
1987 wide_int *may_be_nonzero,
1988 wide_int *must_be_nonzero)
1990 *may_be_nonzero = wi::minus_one (TYPE_PRECISION (expr_type));
1991 *must_be_nonzero = wi::zero (TYPE_PRECISION (expr_type));
1992 if (!range_int_cst_p (vr)
1993 || is_overflow_infinity (vr->min)
1994 || is_overflow_infinity (vr->max))
1995 return false;
1997 if (range_int_cst_singleton_p (vr))
1999 *may_be_nonzero = vr->min;
2000 *must_be_nonzero = *may_be_nonzero;
2002 else if (tree_int_cst_sgn (vr->min) >= 0
2003 || tree_int_cst_sgn (vr->max) < 0)
2005 wide_int xor_mask = wi::bit_xor (vr->min, vr->max);
2006 *may_be_nonzero = wi::bit_or (vr->min, vr->max);
2007 *must_be_nonzero = wi::bit_and (vr->min, vr->max);
2008 if (xor_mask != 0)
2010 wide_int mask = wi::mask (wi::floor_log2 (xor_mask), false,
2011 may_be_nonzero->get_precision ());
2012 *may_be_nonzero = *may_be_nonzero | mask;
2013 *must_be_nonzero = must_be_nonzero->and_not (mask);
2017 return true;
2020 /* Create two value-ranges in *VR0 and *VR1 from the anti-range *AR
2021 so that *VR0 U *VR1 == *AR. Returns true if that is possible,
2022 false otherwise. If *AR can be represented with a single range
2023 *VR1 will be VR_UNDEFINED. */
2025 static bool
2026 ranges_from_anti_range (value_range *ar,
2027 value_range *vr0, value_range *vr1)
2029 tree type = TREE_TYPE (ar->min);
2031 vr0->type = VR_UNDEFINED;
2032 vr1->type = VR_UNDEFINED;
2034 if (ar->type != VR_ANTI_RANGE
2035 || TREE_CODE (ar->min) != INTEGER_CST
2036 || TREE_CODE (ar->max) != INTEGER_CST
2037 || !vrp_val_min (type)
2038 || !vrp_val_max (type))
2039 return false;
2041 if (!vrp_val_is_min (ar->min))
2043 vr0->type = VR_RANGE;
2044 vr0->min = vrp_val_min (type);
2045 vr0->max = wide_int_to_tree (type, wi::sub (ar->min, 1));
2047 if (!vrp_val_is_max (ar->max))
2049 vr1->type = VR_RANGE;
2050 vr1->min = wide_int_to_tree (type, wi::add (ar->max, 1));
2051 vr1->max = vrp_val_max (type);
2053 if (vr0->type == VR_UNDEFINED)
2055 *vr0 = *vr1;
2056 vr1->type = VR_UNDEFINED;
2059 return vr0->type != VR_UNDEFINED;
2062 /* Helper to extract a value-range *VR for a multiplicative operation
2063 *VR0 CODE *VR1. */
2065 static void
2066 extract_range_from_multiplicative_op_1 (value_range *vr,
2067 enum tree_code code,
2068 value_range *vr0, value_range *vr1)
2070 enum value_range_type type;
2071 tree val[4];
2072 size_t i;
2073 tree min, max;
2074 bool sop;
2075 int cmp;
2077 /* Multiplications, divisions and shifts are a bit tricky to handle,
2078 depending on the mix of signs we have in the two ranges, we
2079 need to operate on different values to get the minimum and
2080 maximum values for the new range. One approach is to figure
2081 out all the variations of range combinations and do the
2082 operations.
2084 However, this involves several calls to compare_values and it
2085 is pretty convoluted. It's simpler to do the 4 operations
2086 (MIN0 OP MIN1, MIN0 OP MAX1, MAX0 OP MIN1 and MAX0 OP MAX0 OP
2087 MAX1) and then figure the smallest and largest values to form
2088 the new range. */
2089 gcc_assert (code == MULT_EXPR
2090 || code == TRUNC_DIV_EXPR
2091 || code == FLOOR_DIV_EXPR
2092 || code == CEIL_DIV_EXPR
2093 || code == EXACT_DIV_EXPR
2094 || code == ROUND_DIV_EXPR
2095 || code == RSHIFT_EXPR
2096 || code == LSHIFT_EXPR);
2097 gcc_assert ((vr0->type == VR_RANGE
2098 || (code == MULT_EXPR && vr0->type == VR_ANTI_RANGE))
2099 && vr0->type == vr1->type);
2101 type = vr0->type;
2103 /* Compute the 4 cross operations. */
2104 sop = false;
2105 val[0] = vrp_int_const_binop (code, vr0->min, vr1->min);
2106 if (val[0] == NULL_TREE)
2107 sop = true;
2109 if (vr1->max == vr1->min)
2110 val[1] = NULL_TREE;
2111 else
2113 val[1] = vrp_int_const_binop (code, vr0->min, vr1->max);
2114 if (val[1] == NULL_TREE)
2115 sop = true;
2118 if (vr0->max == vr0->min)
2119 val[2] = NULL_TREE;
2120 else
2122 val[2] = vrp_int_const_binop (code, vr0->max, vr1->min);
2123 if (val[2] == NULL_TREE)
2124 sop = true;
2127 if (vr0->min == vr0->max || vr1->min == vr1->max)
2128 val[3] = NULL_TREE;
2129 else
2131 val[3] = vrp_int_const_binop (code, vr0->max, vr1->max);
2132 if (val[3] == NULL_TREE)
2133 sop = true;
2136 if (sop)
2138 set_value_range_to_varying (vr);
2139 return;
2142 /* Set MIN to the minimum of VAL[i] and MAX to the maximum
2143 of VAL[i]. */
2144 min = val[0];
2145 max = val[0];
2146 for (i = 1; i < 4; i++)
2148 if (!is_gimple_min_invariant (min)
2149 || (TREE_OVERFLOW (min) && !is_overflow_infinity (min))
2150 || !is_gimple_min_invariant (max)
2151 || (TREE_OVERFLOW (max) && !is_overflow_infinity (max)))
2152 break;
2154 if (val[i])
2156 if (!is_gimple_min_invariant (val[i])
2157 || (TREE_OVERFLOW (val[i])
2158 && !is_overflow_infinity (val[i])))
2160 /* If we found an overflowed value, set MIN and MAX
2161 to it so that we set the resulting range to
2162 VARYING. */
2163 min = max = val[i];
2164 break;
2167 if (compare_values (val[i], min) == -1)
2168 min = val[i];
2170 if (compare_values (val[i], max) == 1)
2171 max = val[i];
2175 /* If either MIN or MAX overflowed, then set the resulting range to
2176 VARYING. But we do accept an overflow infinity
2177 representation. */
2178 if (min == NULL_TREE
2179 || !is_gimple_min_invariant (min)
2180 || (TREE_OVERFLOW (min) && !is_overflow_infinity (min))
2181 || max == NULL_TREE
2182 || !is_gimple_min_invariant (max)
2183 || (TREE_OVERFLOW (max) && !is_overflow_infinity (max)))
2185 set_value_range_to_varying (vr);
2186 return;
2189 /* We punt if:
2190 1) [-INF, +INF]
2191 2) [-INF, +-INF(OVF)]
2192 3) [+-INF(OVF), +INF]
2193 4) [+-INF(OVF), +-INF(OVF)]
2194 We learn nothing when we have INF and INF(OVF) on both sides.
2195 Note that we do accept [-INF, -INF] and [+INF, +INF] without
2196 overflow. */
2197 if ((vrp_val_is_min (min) || is_overflow_infinity (min))
2198 && (vrp_val_is_max (max) || is_overflow_infinity (max)))
2200 set_value_range_to_varying (vr);
2201 return;
2204 cmp = compare_values (min, max);
2205 if (cmp == -2 || cmp == 1)
2207 /* If the new range has its limits swapped around (MIN > MAX),
2208 then the operation caused one of them to wrap around, mark
2209 the new range VARYING. */
2210 set_value_range_to_varying (vr);
2212 else
2213 set_value_range (vr, type, min, max, NULL);
2216 /* Extract range information from a binary operation CODE based on
2217 the ranges of each of its operands *VR0 and *VR1 with resulting
2218 type EXPR_TYPE. The resulting range is stored in *VR. */
2220 static void
2221 extract_range_from_binary_expr_1 (value_range *vr,
2222 enum tree_code code, tree expr_type,
2223 value_range *vr0_, value_range *vr1_)
2225 value_range vr0 = *vr0_, vr1 = *vr1_;
2226 value_range vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
2227 enum value_range_type type;
2228 tree min = NULL_TREE, max = NULL_TREE;
2229 int cmp;
2231 if (!INTEGRAL_TYPE_P (expr_type)
2232 && !POINTER_TYPE_P (expr_type))
2234 set_value_range_to_varying (vr);
2235 return;
2238 /* Not all binary expressions can be applied to ranges in a
2239 meaningful way. Handle only arithmetic operations. */
2240 if (code != PLUS_EXPR
2241 && code != MINUS_EXPR
2242 && code != POINTER_PLUS_EXPR
2243 && code != MULT_EXPR
2244 && code != TRUNC_DIV_EXPR
2245 && code != FLOOR_DIV_EXPR
2246 && code != CEIL_DIV_EXPR
2247 && code != EXACT_DIV_EXPR
2248 && code != ROUND_DIV_EXPR
2249 && code != TRUNC_MOD_EXPR
2250 && code != RSHIFT_EXPR
2251 && code != LSHIFT_EXPR
2252 && code != MIN_EXPR
2253 && code != MAX_EXPR
2254 && code != BIT_AND_EXPR
2255 && code != BIT_IOR_EXPR
2256 && code != BIT_XOR_EXPR)
2258 set_value_range_to_varying (vr);
2259 return;
2262 /* If both ranges are UNDEFINED, so is the result. */
2263 if (vr0.type == VR_UNDEFINED && vr1.type == VR_UNDEFINED)
2265 set_value_range_to_undefined (vr);
2266 return;
2268 /* If one of the ranges is UNDEFINED drop it to VARYING for the following
2269 code. At some point we may want to special-case operations that
2270 have UNDEFINED result for all or some value-ranges of the not UNDEFINED
2271 operand. */
2272 else if (vr0.type == VR_UNDEFINED)
2273 set_value_range_to_varying (&vr0);
2274 else if (vr1.type == VR_UNDEFINED)
2275 set_value_range_to_varying (&vr1);
2277 /* We get imprecise results from ranges_from_anti_range when
2278 code is EXACT_DIV_EXPR. We could mask out bits in the resulting
2279 range, but then we also need to hack up vrp_meet. It's just
2280 easier to special case when vr0 is ~[0,0] for EXACT_DIV_EXPR. */
2281 if (code == EXACT_DIV_EXPR
2282 && vr0.type == VR_ANTI_RANGE
2283 && vr0.min == vr0.max
2284 && integer_zerop (vr0.min))
2286 set_value_range_to_nonnull (vr, expr_type);
2287 return;
2290 /* Now canonicalize anti-ranges to ranges when they are not symbolic
2291 and express ~[] op X as ([]' op X) U ([]'' op X). */
2292 if (vr0.type == VR_ANTI_RANGE
2293 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
2295 extract_range_from_binary_expr_1 (vr, code, expr_type, &vrtem0, vr1_);
2296 if (vrtem1.type != VR_UNDEFINED)
2298 value_range vrres = VR_INITIALIZER;
2299 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
2300 &vrtem1, vr1_);
2301 vrp_meet (vr, &vrres);
2303 return;
2305 /* Likewise for X op ~[]. */
2306 if (vr1.type == VR_ANTI_RANGE
2307 && ranges_from_anti_range (&vr1, &vrtem0, &vrtem1))
2309 extract_range_from_binary_expr_1 (vr, code, expr_type, vr0_, &vrtem0);
2310 if (vrtem1.type != VR_UNDEFINED)
2312 value_range vrres = VR_INITIALIZER;
2313 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
2314 vr0_, &vrtem1);
2315 vrp_meet (vr, &vrres);
2317 return;
2320 /* The type of the resulting value range defaults to VR0.TYPE. */
2321 type = vr0.type;
2323 /* Refuse to operate on VARYING ranges, ranges of different kinds
2324 and symbolic ranges. As an exception, we allow BIT_{AND,IOR}
2325 because we may be able to derive a useful range even if one of
2326 the operands is VR_VARYING or symbolic range. Similarly for
2327 divisions, MIN/MAX and PLUS/MINUS.
2329 TODO, we may be able to derive anti-ranges in some cases. */
2330 if (code != BIT_AND_EXPR
2331 && code != BIT_IOR_EXPR
2332 && code != TRUNC_DIV_EXPR
2333 && code != FLOOR_DIV_EXPR
2334 && code != CEIL_DIV_EXPR
2335 && code != EXACT_DIV_EXPR
2336 && code != ROUND_DIV_EXPR
2337 && code != TRUNC_MOD_EXPR
2338 && code != MIN_EXPR
2339 && code != MAX_EXPR
2340 && code != PLUS_EXPR
2341 && code != MINUS_EXPR
2342 && code != RSHIFT_EXPR
2343 && (vr0.type == VR_VARYING
2344 || vr1.type == VR_VARYING
2345 || vr0.type != vr1.type
2346 || symbolic_range_p (&vr0)
2347 || symbolic_range_p (&vr1)))
2349 set_value_range_to_varying (vr);
2350 return;
2353 /* Now evaluate the expression to determine the new range. */
2354 if (POINTER_TYPE_P (expr_type))
2356 if (code == MIN_EXPR || code == MAX_EXPR)
2358 /* For MIN/MAX expressions with pointers, we only care about
2359 nullness, if both are non null, then the result is nonnull.
2360 If both are null, then the result is null. Otherwise they
2361 are varying. */
2362 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
2363 set_value_range_to_nonnull (vr, expr_type);
2364 else if (range_is_null (&vr0) && range_is_null (&vr1))
2365 set_value_range_to_null (vr, expr_type);
2366 else
2367 set_value_range_to_varying (vr);
2369 else if (code == POINTER_PLUS_EXPR)
2371 /* For pointer types, we are really only interested in asserting
2372 whether the expression evaluates to non-NULL. */
2373 if (range_is_nonnull (&vr0) || range_is_nonnull (&vr1))
2374 set_value_range_to_nonnull (vr, expr_type);
2375 else if (range_is_null (&vr0) && range_is_null (&vr1))
2376 set_value_range_to_null (vr, expr_type);
2377 else
2378 set_value_range_to_varying (vr);
2380 else if (code == BIT_AND_EXPR)
2382 /* For pointer types, we are really only interested in asserting
2383 whether the expression evaluates to non-NULL. */
2384 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
2385 set_value_range_to_nonnull (vr, expr_type);
2386 else if (range_is_null (&vr0) || range_is_null (&vr1))
2387 set_value_range_to_null (vr, expr_type);
2388 else
2389 set_value_range_to_varying (vr);
2391 else
2392 set_value_range_to_varying (vr);
2394 return;
2397 /* For integer ranges, apply the operation to each end of the
2398 range and see what we end up with. */
2399 if (code == PLUS_EXPR || code == MINUS_EXPR)
2401 const bool minus_p = (code == MINUS_EXPR);
2402 tree min_op0 = vr0.min;
2403 tree min_op1 = minus_p ? vr1.max : vr1.min;
2404 tree max_op0 = vr0.max;
2405 tree max_op1 = minus_p ? vr1.min : vr1.max;
2406 tree sym_min_op0 = NULL_TREE;
2407 tree sym_min_op1 = NULL_TREE;
2408 tree sym_max_op0 = NULL_TREE;
2409 tree sym_max_op1 = NULL_TREE;
2410 bool neg_min_op0, neg_min_op1, neg_max_op0, neg_max_op1;
2412 /* If we have a PLUS or MINUS with two VR_RANGEs, either constant or
2413 single-symbolic ranges, try to compute the precise resulting range,
2414 but only if we know that this resulting range will also be constant
2415 or single-symbolic. */
2416 if (vr0.type == VR_RANGE && vr1.type == VR_RANGE
2417 && (TREE_CODE (min_op0) == INTEGER_CST
2418 || (sym_min_op0
2419 = get_single_symbol (min_op0, &neg_min_op0, &min_op0)))
2420 && (TREE_CODE (min_op1) == INTEGER_CST
2421 || (sym_min_op1
2422 = get_single_symbol (min_op1, &neg_min_op1, &min_op1)))
2423 && (!(sym_min_op0 && sym_min_op1)
2424 || (sym_min_op0 == sym_min_op1
2425 && neg_min_op0 == (minus_p ? neg_min_op1 : !neg_min_op1)))
2426 && (TREE_CODE (max_op0) == INTEGER_CST
2427 || (sym_max_op0
2428 = get_single_symbol (max_op0, &neg_max_op0, &max_op0)))
2429 && (TREE_CODE (max_op1) == INTEGER_CST
2430 || (sym_max_op1
2431 = get_single_symbol (max_op1, &neg_max_op1, &max_op1)))
2432 && (!(sym_max_op0 && sym_max_op1)
2433 || (sym_max_op0 == sym_max_op1
2434 && neg_max_op0 == (minus_p ? neg_max_op1 : !neg_max_op1))))
2436 const signop sgn = TYPE_SIGN (expr_type);
2437 const unsigned int prec = TYPE_PRECISION (expr_type);
2438 wide_int type_min, type_max, wmin, wmax;
2439 int min_ovf = 0;
2440 int max_ovf = 0;
2442 /* Get the lower and upper bounds of the type. */
2443 if (TYPE_OVERFLOW_WRAPS (expr_type))
2445 type_min = wi::min_value (prec, sgn);
2446 type_max = wi::max_value (prec, sgn);
2448 else
2450 type_min = vrp_val_min (expr_type);
2451 type_max = vrp_val_max (expr_type);
2454 /* Combine the lower bounds, if any. */
2455 if (min_op0 && min_op1)
2457 if (minus_p)
2459 wmin = wi::sub (min_op0, min_op1);
2461 /* Check for overflow. */
2462 if (wi::cmp (0, min_op1, sgn)
2463 != wi::cmp (wmin, min_op0, sgn))
2464 min_ovf = wi::cmp (min_op0, min_op1, sgn);
2466 else
2468 wmin = wi::add (min_op0, min_op1);
2470 /* Check for overflow. */
2471 if (wi::cmp (min_op1, 0, sgn)
2472 != wi::cmp (wmin, min_op0, sgn))
2473 min_ovf = wi::cmp (min_op0, wmin, sgn);
2476 else if (min_op0)
2477 wmin = min_op0;
2478 else if (min_op1)
2480 if (minus_p)
2482 wmin = wi::neg (min_op1);
2484 /* Check for overflow. */
2485 if (sgn == SIGNED && wi::neg_p (min_op1) && wi::neg_p (wmin))
2486 min_ovf = 1;
2487 else if (sgn == UNSIGNED && wi::ne_p (min_op1, 0))
2488 min_ovf = -1;
2490 else
2491 wmin = min_op1;
2493 else
2494 wmin = wi::shwi (0, prec);
2496 /* Combine the upper bounds, if any. */
2497 if (max_op0 && max_op1)
2499 if (minus_p)
2501 wmax = wi::sub (max_op0, max_op1);
2503 /* Check for overflow. */
2504 if (wi::cmp (0, max_op1, sgn)
2505 != wi::cmp (wmax, max_op0, sgn))
2506 max_ovf = wi::cmp (max_op0, max_op1, sgn);
2508 else
2510 wmax = wi::add (max_op0, max_op1);
2512 if (wi::cmp (max_op1, 0, sgn)
2513 != wi::cmp (wmax, max_op0, sgn))
2514 max_ovf = wi::cmp (max_op0, wmax, sgn);
2517 else if (max_op0)
2518 wmax = max_op0;
2519 else if (max_op1)
2521 if (minus_p)
2523 wmax = wi::neg (max_op1);
2525 /* Check for overflow. */
2526 if (sgn == SIGNED && wi::neg_p (max_op1) && wi::neg_p (wmax))
2527 max_ovf = 1;
2528 else if (sgn == UNSIGNED && wi::ne_p (max_op1, 0))
2529 max_ovf = -1;
2531 else
2532 wmax = max_op1;
2534 else
2535 wmax = wi::shwi (0, prec);
2537 /* Check for type overflow. */
2538 if (min_ovf == 0)
2540 if (wi::cmp (wmin, type_min, sgn) == -1)
2541 min_ovf = -1;
2542 else if (wi::cmp (wmin, type_max, sgn) == 1)
2543 min_ovf = 1;
2545 if (max_ovf == 0)
2547 if (wi::cmp (wmax, type_min, sgn) == -1)
2548 max_ovf = -1;
2549 else if (wi::cmp (wmax, type_max, sgn) == 1)
2550 max_ovf = 1;
2553 /* If we have overflow for the constant part and the resulting
2554 range will be symbolic, drop to VR_VARYING. */
2555 if ((min_ovf && sym_min_op0 != sym_min_op1)
2556 || (max_ovf && sym_max_op0 != sym_max_op1))
2558 set_value_range_to_varying (vr);
2559 return;
2562 if (TYPE_OVERFLOW_WRAPS (expr_type))
2564 /* If overflow wraps, truncate the values and adjust the
2565 range kind and bounds appropriately. */
2566 wide_int tmin = wide_int::from (wmin, prec, sgn);
2567 wide_int tmax = wide_int::from (wmax, prec, sgn);
2568 if (min_ovf == max_ovf)
2570 /* No overflow or both overflow or underflow. The
2571 range kind stays VR_RANGE. */
2572 min = wide_int_to_tree (expr_type, tmin);
2573 max = wide_int_to_tree (expr_type, tmax);
2575 else if ((min_ovf == -1 && max_ovf == 0)
2576 || (max_ovf == 1 && min_ovf == 0))
2578 /* Min underflow or max overflow. The range kind
2579 changes to VR_ANTI_RANGE. */
2580 bool covers = false;
2581 wide_int tem = tmin;
2582 type = VR_ANTI_RANGE;
2583 tmin = tmax + 1;
2584 if (wi::cmp (tmin, tmax, sgn) < 0)
2585 covers = true;
2586 tmax = tem - 1;
2587 if (wi::cmp (tmax, tem, sgn) > 0)
2588 covers = true;
2589 /* If the anti-range would cover nothing, drop to varying.
2590 Likewise if the anti-range bounds are outside of the
2591 types values. */
2592 if (covers || wi::cmp (tmin, tmax, sgn) > 0)
2594 set_value_range_to_varying (vr);
2595 return;
2597 min = wide_int_to_tree (expr_type, tmin);
2598 max = wide_int_to_tree (expr_type, tmax);
2600 else
2602 /* Other underflow and/or overflow, drop to VR_VARYING. */
2603 set_value_range_to_varying (vr);
2604 return;
2607 else
2609 /* If overflow does not wrap, saturate to the types min/max
2610 value. */
2611 if (min_ovf == -1)
2613 if (needs_overflow_infinity (expr_type)
2614 && supports_overflow_infinity (expr_type))
2615 min = negative_overflow_infinity (expr_type);
2616 else
2617 min = wide_int_to_tree (expr_type, type_min);
2619 else if (min_ovf == 1)
2621 if (needs_overflow_infinity (expr_type)
2622 && supports_overflow_infinity (expr_type))
2623 min = positive_overflow_infinity (expr_type);
2624 else
2625 min = wide_int_to_tree (expr_type, type_max);
2627 else
2628 min = wide_int_to_tree (expr_type, wmin);
2630 if (max_ovf == -1)
2632 if (needs_overflow_infinity (expr_type)
2633 && supports_overflow_infinity (expr_type))
2634 max = negative_overflow_infinity (expr_type);
2635 else
2636 max = wide_int_to_tree (expr_type, type_min);
2638 else if (max_ovf == 1)
2640 if (needs_overflow_infinity (expr_type)
2641 && supports_overflow_infinity (expr_type))
2642 max = positive_overflow_infinity (expr_type);
2643 else
2644 max = wide_int_to_tree (expr_type, type_max);
2646 else
2647 max = wide_int_to_tree (expr_type, wmax);
2650 if (needs_overflow_infinity (expr_type)
2651 && supports_overflow_infinity (expr_type))
2653 if ((min_op0 && is_negative_overflow_infinity (min_op0))
2654 || (min_op1
2655 && (minus_p
2656 ? is_positive_overflow_infinity (min_op1)
2657 : is_negative_overflow_infinity (min_op1))))
2658 min = negative_overflow_infinity (expr_type);
2659 if ((max_op0 && is_positive_overflow_infinity (max_op0))
2660 || (max_op1
2661 && (minus_p
2662 ? is_negative_overflow_infinity (max_op1)
2663 : is_positive_overflow_infinity (max_op1))))
2664 max = positive_overflow_infinity (expr_type);
2667 /* If the result lower bound is constant, we're done;
2668 otherwise, build the symbolic lower bound. */
2669 if (sym_min_op0 == sym_min_op1)
2671 else if (sym_min_op0)
2672 min = build_symbolic_expr (expr_type, sym_min_op0,
2673 neg_min_op0, min);
2674 else if (sym_min_op1)
2676 /* We may not negate if that might introduce
2677 undefined overflow. */
2678 if (! minus_p
2679 || neg_min_op1
2680 || TYPE_OVERFLOW_WRAPS (expr_type))
2681 min = build_symbolic_expr (expr_type, sym_min_op1,
2682 neg_min_op1 ^ minus_p, min);
2683 else
2684 min = NULL_TREE;
2687 /* Likewise for the upper bound. */
2688 if (sym_max_op0 == sym_max_op1)
2690 else if (sym_max_op0)
2691 max = build_symbolic_expr (expr_type, sym_max_op0,
2692 neg_max_op0, max);
2693 else if (sym_max_op1)
2695 /* We may not negate if that might introduce
2696 undefined overflow. */
2697 if (! minus_p
2698 || neg_max_op1
2699 || TYPE_OVERFLOW_WRAPS (expr_type))
2700 max = build_symbolic_expr (expr_type, sym_max_op1,
2701 neg_max_op1 ^ minus_p, max);
2702 else
2703 max = NULL_TREE;
2706 else
2708 /* For other cases, for example if we have a PLUS_EXPR with two
2709 VR_ANTI_RANGEs, drop to VR_VARYING. It would take more effort
2710 to compute a precise range for such a case.
2711 ??? General even mixed range kind operations can be expressed
2712 by for example transforming ~[3, 5] + [1, 2] to range-only
2713 operations and a union primitive:
2714 [-INF, 2] + [1, 2] U [5, +INF] + [1, 2]
2715 [-INF+1, 4] U [6, +INF(OVF)]
2716 though usually the union is not exactly representable with
2717 a single range or anti-range as the above is
2718 [-INF+1, +INF(OVF)] intersected with ~[5, 5]
2719 but one could use a scheme similar to equivalences for this. */
2720 set_value_range_to_varying (vr);
2721 return;
2724 else if (code == MIN_EXPR
2725 || code == MAX_EXPR)
2727 if (vr0.type == VR_RANGE
2728 && !symbolic_range_p (&vr0))
2730 type = VR_RANGE;
2731 if (vr1.type == VR_RANGE
2732 && !symbolic_range_p (&vr1))
2734 /* For operations that make the resulting range directly
2735 proportional to the original ranges, apply the operation to
2736 the same end of each range. */
2737 min = vrp_int_const_binop (code, vr0.min, vr1.min);
2738 max = vrp_int_const_binop (code, vr0.max, vr1.max);
2740 else if (code == MIN_EXPR)
2742 min = vrp_val_min (expr_type);
2743 max = vr0.max;
2745 else if (code == MAX_EXPR)
2747 min = vr0.min;
2748 max = vrp_val_max (expr_type);
2751 else if (vr1.type == VR_RANGE
2752 && !symbolic_range_p (&vr1))
2754 type = VR_RANGE;
2755 if (code == MIN_EXPR)
2757 min = vrp_val_min (expr_type);
2758 max = vr1.max;
2760 else if (code == MAX_EXPR)
2762 min = vr1.min;
2763 max = vrp_val_max (expr_type);
2766 else
2768 set_value_range_to_varying (vr);
2769 return;
2772 else if (code == MULT_EXPR)
2774 /* Fancy code so that with unsigned, [-3,-1]*[-3,-1] does not
2775 drop to varying. This test requires 2*prec bits if both
2776 operands are signed and 2*prec + 2 bits if either is not. */
2778 signop sign = TYPE_SIGN (expr_type);
2779 unsigned int prec = TYPE_PRECISION (expr_type);
2781 if (range_int_cst_p (&vr0)
2782 && range_int_cst_p (&vr1)
2783 && TYPE_OVERFLOW_WRAPS (expr_type))
2785 typedef FIXED_WIDE_INT (WIDE_INT_MAX_PRECISION * 2) vrp_int;
2786 typedef generic_wide_int
2787 <wi::extended_tree <WIDE_INT_MAX_PRECISION * 2> > vrp_int_cst;
2788 vrp_int sizem1 = wi::mask <vrp_int> (prec, false);
2789 vrp_int size = sizem1 + 1;
2791 /* Extend the values using the sign of the result to PREC2.
2792 From here on out, everthing is just signed math no matter
2793 what the input types were. */
2794 vrp_int min0 = vrp_int_cst (vr0.min);
2795 vrp_int max0 = vrp_int_cst (vr0.max);
2796 vrp_int min1 = vrp_int_cst (vr1.min);
2797 vrp_int max1 = vrp_int_cst (vr1.max);
2798 /* Canonicalize the intervals. */
2799 if (sign == UNSIGNED)
2801 if (wi::ltu_p (size, min0 + max0))
2803 min0 -= size;
2804 max0 -= size;
2807 if (wi::ltu_p (size, min1 + max1))
2809 min1 -= size;
2810 max1 -= size;
2814 vrp_int prod0 = min0 * min1;
2815 vrp_int prod1 = min0 * max1;
2816 vrp_int prod2 = max0 * min1;
2817 vrp_int prod3 = max0 * max1;
2819 /* Sort the 4 products so that min is in prod0 and max is in
2820 prod3. */
2821 /* min0min1 > max0max1 */
2822 if (prod0 > prod3)
2823 std::swap (prod0, prod3);
2825 /* min0max1 > max0min1 */
2826 if (prod1 > prod2)
2827 std::swap (prod1, prod2);
2829 if (prod0 > prod1)
2830 std::swap (prod0, prod1);
2832 if (prod2 > prod3)
2833 std::swap (prod2, prod3);
2835 /* diff = max - min. */
2836 prod2 = prod3 - prod0;
2837 if (wi::geu_p (prod2, sizem1))
2839 /* the range covers all values. */
2840 set_value_range_to_varying (vr);
2841 return;
2844 /* The following should handle the wrapping and selecting
2845 VR_ANTI_RANGE for us. */
2846 min = wide_int_to_tree (expr_type, prod0);
2847 max = wide_int_to_tree (expr_type, prod3);
2848 set_and_canonicalize_value_range (vr, VR_RANGE, min, max, NULL);
2849 return;
2852 /* If we have an unsigned MULT_EXPR with two VR_ANTI_RANGEs,
2853 drop to VR_VARYING. It would take more effort to compute a
2854 precise range for such a case. For example, if we have
2855 op0 == 65536 and op1 == 65536 with their ranges both being
2856 ~[0,0] on a 32-bit machine, we would have op0 * op1 == 0, so
2857 we cannot claim that the product is in ~[0,0]. Note that we
2858 are guaranteed to have vr0.type == vr1.type at this
2859 point. */
2860 if (vr0.type == VR_ANTI_RANGE
2861 && !TYPE_OVERFLOW_UNDEFINED (expr_type))
2863 set_value_range_to_varying (vr);
2864 return;
2867 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2868 return;
2870 else if (code == RSHIFT_EXPR
2871 || code == LSHIFT_EXPR)
2873 /* If we have a RSHIFT_EXPR with any shift values outside [0..prec-1],
2874 then drop to VR_VARYING. Outside of this range we get undefined
2875 behavior from the shift operation. We cannot even trust
2876 SHIFT_COUNT_TRUNCATED at this stage, because that applies to rtl
2877 shifts, and the operation at the tree level may be widened. */
2878 if (range_int_cst_p (&vr1)
2879 && compare_tree_int (vr1.min, 0) >= 0
2880 && compare_tree_int (vr1.max, TYPE_PRECISION (expr_type)) == -1)
2882 if (code == RSHIFT_EXPR)
2884 /* Even if vr0 is VARYING or otherwise not usable, we can derive
2885 useful ranges just from the shift count. E.g.
2886 x >> 63 for signed 64-bit x is always [-1, 0]. */
2887 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
2889 vr0.type = type = VR_RANGE;
2890 vr0.min = vrp_val_min (expr_type);
2891 vr0.max = vrp_val_max (expr_type);
2893 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2894 return;
2896 /* We can map lshifts by constants to MULT_EXPR handling. */
2897 else if (code == LSHIFT_EXPR
2898 && range_int_cst_singleton_p (&vr1))
2900 bool saved_flag_wrapv;
2901 value_range vr1p = VR_INITIALIZER;
2902 vr1p.type = VR_RANGE;
2903 vr1p.min = (wide_int_to_tree
2904 (expr_type,
2905 wi::set_bit_in_zero (tree_to_shwi (vr1.min),
2906 TYPE_PRECISION (expr_type))));
2907 vr1p.max = vr1p.min;
2908 /* We have to use a wrapping multiply though as signed overflow
2909 on lshifts is implementation defined in C89. */
2910 saved_flag_wrapv = flag_wrapv;
2911 flag_wrapv = 1;
2912 extract_range_from_binary_expr_1 (vr, MULT_EXPR, expr_type,
2913 &vr0, &vr1p);
2914 flag_wrapv = saved_flag_wrapv;
2915 return;
2917 else if (code == LSHIFT_EXPR
2918 && range_int_cst_p (&vr0))
2920 int prec = TYPE_PRECISION (expr_type);
2921 int overflow_pos = prec;
2922 int bound_shift;
2923 wide_int low_bound, high_bound;
2924 bool uns = TYPE_UNSIGNED (expr_type);
2925 bool in_bounds = false;
2927 if (!uns)
2928 overflow_pos -= 1;
2930 bound_shift = overflow_pos - tree_to_shwi (vr1.max);
2931 /* If bound_shift == HOST_BITS_PER_WIDE_INT, the llshift can
2932 overflow. However, for that to happen, vr1.max needs to be
2933 zero, which means vr1 is a singleton range of zero, which
2934 means it should be handled by the previous LSHIFT_EXPR
2935 if-clause. */
2936 wide_int bound = wi::set_bit_in_zero (bound_shift, prec);
2937 wide_int complement = ~(bound - 1);
2939 if (uns)
2941 low_bound = bound;
2942 high_bound = complement;
2943 if (wi::ltu_p (vr0.max, low_bound))
2945 /* [5, 6] << [1, 2] == [10, 24]. */
2946 /* We're shifting out only zeroes, the value increases
2947 monotonically. */
2948 in_bounds = true;
2950 else if (wi::ltu_p (high_bound, vr0.min))
2952 /* [0xffffff00, 0xffffffff] << [1, 2]
2953 == [0xfffffc00, 0xfffffffe]. */
2954 /* We're shifting out only ones, the value decreases
2955 monotonically. */
2956 in_bounds = true;
2959 else
2961 /* [-1, 1] << [1, 2] == [-4, 4]. */
2962 low_bound = complement;
2963 high_bound = bound;
2964 if (wi::lts_p (vr0.max, high_bound)
2965 && wi::lts_p (low_bound, vr0.min))
2967 /* For non-negative numbers, we're shifting out only
2968 zeroes, the value increases monotonically.
2969 For negative numbers, we're shifting out only ones, the
2970 value decreases monotomically. */
2971 in_bounds = true;
2975 if (in_bounds)
2977 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2978 return;
2982 set_value_range_to_varying (vr);
2983 return;
2985 else if (code == TRUNC_DIV_EXPR
2986 || code == FLOOR_DIV_EXPR
2987 || code == CEIL_DIV_EXPR
2988 || code == EXACT_DIV_EXPR
2989 || code == ROUND_DIV_EXPR)
2991 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
2993 /* For division, if op1 has VR_RANGE but op0 does not, something
2994 can be deduced just from that range. Say [min, max] / [4, max]
2995 gives [min / 4, max / 4] range. */
2996 if (vr1.type == VR_RANGE
2997 && !symbolic_range_p (&vr1)
2998 && range_includes_zero_p (vr1.min, vr1.max) == 0)
3000 vr0.type = type = VR_RANGE;
3001 vr0.min = vrp_val_min (expr_type);
3002 vr0.max = vrp_val_max (expr_type);
3004 else
3006 set_value_range_to_varying (vr);
3007 return;
3011 /* For divisions, if flag_non_call_exceptions is true, we must
3012 not eliminate a division by zero. */
3013 if (cfun->can_throw_non_call_exceptions
3014 && (vr1.type != VR_RANGE
3015 || range_includes_zero_p (vr1.min, vr1.max) != 0))
3017 set_value_range_to_varying (vr);
3018 return;
3021 /* For divisions, if op0 is VR_RANGE, we can deduce a range
3022 even if op1 is VR_VARYING, VR_ANTI_RANGE, symbolic or can
3023 include 0. */
3024 if (vr0.type == VR_RANGE
3025 && (vr1.type != VR_RANGE
3026 || range_includes_zero_p (vr1.min, vr1.max) != 0))
3028 tree zero = build_int_cst (TREE_TYPE (vr0.min), 0);
3029 int cmp;
3031 min = NULL_TREE;
3032 max = NULL_TREE;
3033 if (TYPE_UNSIGNED (expr_type)
3034 || value_range_nonnegative_p (&vr1))
3036 /* For unsigned division or when divisor is known
3037 to be non-negative, the range has to cover
3038 all numbers from 0 to max for positive max
3039 and all numbers from min to 0 for negative min. */
3040 cmp = compare_values (vr0.max, zero);
3041 if (cmp == -1)
3043 /* When vr0.max < 0, vr1.min != 0 and value
3044 ranges for dividend and divisor are available. */
3045 if (vr1.type == VR_RANGE
3046 && !symbolic_range_p (&vr0)
3047 && !symbolic_range_p (&vr1)
3048 && compare_values (vr1.min, zero) != 0)
3049 max = int_const_binop (code, vr0.max, vr1.min);
3050 else
3051 max = zero;
3053 else if (cmp == 0 || cmp == 1)
3054 max = vr0.max;
3055 else
3056 type = VR_VARYING;
3057 cmp = compare_values (vr0.min, zero);
3058 if (cmp == 1)
3060 /* For unsigned division when value ranges for dividend
3061 and divisor are available. */
3062 if (vr1.type == VR_RANGE
3063 && !symbolic_range_p (&vr0)
3064 && !symbolic_range_p (&vr1)
3065 && compare_values (vr1.max, zero) != 0)
3066 min = int_const_binop (code, vr0.min, vr1.max);
3067 else
3068 min = zero;
3070 else if (cmp == 0 || cmp == -1)
3071 min = vr0.min;
3072 else
3073 type = VR_VARYING;
3075 else
3077 /* Otherwise the range is -max .. max or min .. -min
3078 depending on which bound is bigger in absolute value,
3079 as the division can change the sign. */
3080 abs_extent_range (vr, vr0.min, vr0.max);
3081 return;
3083 if (type == VR_VARYING)
3085 set_value_range_to_varying (vr);
3086 return;
3089 else if (!symbolic_range_p (&vr0) && !symbolic_range_p (&vr1))
3091 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
3092 return;
3095 else if (code == TRUNC_MOD_EXPR)
3097 if (range_is_null (&vr1))
3099 set_value_range_to_undefined (vr);
3100 return;
3102 /* ABS (A % B) < ABS (B) and either
3103 0 <= A % B <= A or A <= A % B <= 0. */
3104 type = VR_RANGE;
3105 signop sgn = TYPE_SIGN (expr_type);
3106 unsigned int prec = TYPE_PRECISION (expr_type);
3107 wide_int wmin, wmax, tmp;
3108 wide_int zero = wi::zero (prec);
3109 wide_int one = wi::one (prec);
3110 if (vr1.type == VR_RANGE && !symbolic_range_p (&vr1))
3112 wmax = wi::sub (vr1.max, one);
3113 if (sgn == SIGNED)
3115 tmp = wi::sub (wi::minus_one (prec), vr1.min);
3116 wmax = wi::smax (wmax, tmp);
3119 else
3121 wmax = wi::max_value (prec, sgn);
3122 /* X % INT_MIN may be INT_MAX. */
3123 if (sgn == UNSIGNED)
3124 wmax = wmax - one;
3127 if (sgn == UNSIGNED)
3128 wmin = zero;
3129 else
3131 wmin = -wmax;
3132 if (vr0.type == VR_RANGE && TREE_CODE (vr0.min) == INTEGER_CST)
3134 tmp = vr0.min;
3135 if (wi::gts_p (tmp, zero))
3136 tmp = zero;
3137 wmin = wi::smax (wmin, tmp);
3141 if (vr0.type == VR_RANGE && TREE_CODE (vr0.max) == INTEGER_CST)
3143 tmp = vr0.max;
3144 if (sgn == SIGNED && wi::neg_p (tmp))
3145 tmp = zero;
3146 wmax = wi::min (wmax, tmp, sgn);
3149 min = wide_int_to_tree (expr_type, wmin);
3150 max = wide_int_to_tree (expr_type, wmax);
3152 else if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR || code == BIT_XOR_EXPR)
3154 bool int_cst_range0, int_cst_range1;
3155 wide_int may_be_nonzero0, may_be_nonzero1;
3156 wide_int must_be_nonzero0, must_be_nonzero1;
3158 int_cst_range0 = zero_nonzero_bits_from_vr (expr_type, &vr0,
3159 &may_be_nonzero0,
3160 &must_be_nonzero0);
3161 int_cst_range1 = zero_nonzero_bits_from_vr (expr_type, &vr1,
3162 &may_be_nonzero1,
3163 &must_be_nonzero1);
3165 type = VR_RANGE;
3166 if (code == BIT_AND_EXPR)
3168 min = wide_int_to_tree (expr_type,
3169 must_be_nonzero0 & must_be_nonzero1);
3170 wide_int wmax = may_be_nonzero0 & may_be_nonzero1;
3171 /* If both input ranges contain only negative values we can
3172 truncate the result range maximum to the minimum of the
3173 input range maxima. */
3174 if (int_cst_range0 && int_cst_range1
3175 && tree_int_cst_sgn (vr0.max) < 0
3176 && tree_int_cst_sgn (vr1.max) < 0)
3178 wmax = wi::min (wmax, vr0.max, TYPE_SIGN (expr_type));
3179 wmax = wi::min (wmax, vr1.max, TYPE_SIGN (expr_type));
3181 /* If either input range contains only non-negative values
3182 we can truncate the result range maximum to the respective
3183 maximum of the input range. */
3184 if (int_cst_range0 && tree_int_cst_sgn (vr0.min) >= 0)
3185 wmax = wi::min (wmax, vr0.max, TYPE_SIGN (expr_type));
3186 if (int_cst_range1 && tree_int_cst_sgn (vr1.min) >= 0)
3187 wmax = wi::min (wmax, vr1.max, TYPE_SIGN (expr_type));
3188 max = wide_int_to_tree (expr_type, wmax);
3189 cmp = compare_values (min, max);
3190 /* PR68217: In case of signed & sign-bit-CST should
3191 result in [-INF, 0] instead of [-INF, INF]. */
3192 if (cmp == -2 || cmp == 1)
3194 wide_int sign_bit
3195 = wi::set_bit_in_zero (TYPE_PRECISION (expr_type) - 1,
3196 TYPE_PRECISION (expr_type));
3197 if (!TYPE_UNSIGNED (expr_type)
3198 && ((value_range_constant_singleton (&vr0)
3199 && !wi::cmps (vr0.min, sign_bit))
3200 || (value_range_constant_singleton (&vr1)
3201 && !wi::cmps (vr1.min, sign_bit))))
3203 min = TYPE_MIN_VALUE (expr_type);
3204 max = build_int_cst (expr_type, 0);
3208 else if (code == BIT_IOR_EXPR)
3210 max = wide_int_to_tree (expr_type,
3211 may_be_nonzero0 | may_be_nonzero1);
3212 wide_int wmin = must_be_nonzero0 | must_be_nonzero1;
3213 /* If the input ranges contain only positive values we can
3214 truncate the minimum of the result range to the maximum
3215 of the input range minima. */
3216 if (int_cst_range0 && int_cst_range1
3217 && tree_int_cst_sgn (vr0.min) >= 0
3218 && tree_int_cst_sgn (vr1.min) >= 0)
3220 wmin = wi::max (wmin, vr0.min, TYPE_SIGN (expr_type));
3221 wmin = wi::max (wmin, vr1.min, TYPE_SIGN (expr_type));
3223 /* If either input range contains only negative values
3224 we can truncate the minimum of the result range to the
3225 respective minimum range. */
3226 if (int_cst_range0 && tree_int_cst_sgn (vr0.max) < 0)
3227 wmin = wi::max (wmin, vr0.min, TYPE_SIGN (expr_type));
3228 if (int_cst_range1 && tree_int_cst_sgn (vr1.max) < 0)
3229 wmin = wi::max (wmin, vr1.min, TYPE_SIGN (expr_type));
3230 min = wide_int_to_tree (expr_type, wmin);
3232 else if (code == BIT_XOR_EXPR)
3234 wide_int result_zero_bits = ((must_be_nonzero0 & must_be_nonzero1)
3235 | ~(may_be_nonzero0 | may_be_nonzero1));
3236 wide_int result_one_bits
3237 = (must_be_nonzero0.and_not (may_be_nonzero1)
3238 | must_be_nonzero1.and_not (may_be_nonzero0));
3239 max = wide_int_to_tree (expr_type, ~result_zero_bits);
3240 min = wide_int_to_tree (expr_type, result_one_bits);
3241 /* If the range has all positive or all negative values the
3242 result is better than VARYING. */
3243 if (tree_int_cst_sgn (min) < 0
3244 || tree_int_cst_sgn (max) >= 0)
3246 else
3247 max = min = NULL_TREE;
3250 else
3251 gcc_unreachable ();
3253 /* If either MIN or MAX overflowed, then set the resulting range to
3254 VARYING. But we do accept an overflow infinity representation. */
3255 if (min == NULL_TREE
3256 || (TREE_OVERFLOW_P (min) && !is_overflow_infinity (min))
3257 || max == NULL_TREE
3258 || (TREE_OVERFLOW_P (max) && !is_overflow_infinity (max)))
3260 set_value_range_to_varying (vr);
3261 return;
3264 /* We punt if:
3265 1) [-INF, +INF]
3266 2) [-INF, +-INF(OVF)]
3267 3) [+-INF(OVF), +INF]
3268 4) [+-INF(OVF), +-INF(OVF)]
3269 We learn nothing when we have INF and INF(OVF) on both sides.
3270 Note that we do accept [-INF, -INF] and [+INF, +INF] without
3271 overflow. */
3272 if ((vrp_val_is_min (min) || is_overflow_infinity (min))
3273 && (vrp_val_is_max (max) || is_overflow_infinity (max)))
3275 set_value_range_to_varying (vr);
3276 return;
3279 cmp = compare_values (min, max);
3280 if (cmp == -2 || cmp == 1)
3282 /* If the new range has its limits swapped around (MIN > MAX),
3283 then the operation caused one of them to wrap around, mark
3284 the new range VARYING. */
3285 set_value_range_to_varying (vr);
3287 else
3288 set_value_range (vr, type, min, max, NULL);
3291 /* Extract range information from a binary expression OP0 CODE OP1 based on
3292 the ranges of each of its operands with resulting type EXPR_TYPE.
3293 The resulting range is stored in *VR. */
3295 static void
3296 extract_range_from_binary_expr (value_range *vr,
3297 enum tree_code code,
3298 tree expr_type, tree op0, tree op1)
3300 value_range vr0 = VR_INITIALIZER;
3301 value_range vr1 = VR_INITIALIZER;
3303 /* Get value ranges for each operand. For constant operands, create
3304 a new value range with the operand to simplify processing. */
3305 if (TREE_CODE (op0) == SSA_NAME)
3306 vr0 = *(get_value_range (op0));
3307 else if (is_gimple_min_invariant (op0))
3308 set_value_range_to_value (&vr0, op0, NULL);
3309 else
3310 set_value_range_to_varying (&vr0);
3312 if (TREE_CODE (op1) == SSA_NAME)
3313 vr1 = *(get_value_range (op1));
3314 else if (is_gimple_min_invariant (op1))
3315 set_value_range_to_value (&vr1, op1, NULL);
3316 else
3317 set_value_range_to_varying (&vr1);
3319 extract_range_from_binary_expr_1 (vr, code, expr_type, &vr0, &vr1);
3321 /* Try harder for PLUS and MINUS if the range of one operand is symbolic
3322 and based on the other operand, for example if it was deduced from a
3323 symbolic comparison. When a bound of the range of the first operand
3324 is invariant, we set the corresponding bound of the new range to INF
3325 in order to avoid recursing on the range of the second operand. */
3326 if (vr->type == VR_VARYING
3327 && (code == PLUS_EXPR || code == MINUS_EXPR)
3328 && TREE_CODE (op1) == SSA_NAME
3329 && vr0.type == VR_RANGE
3330 && symbolic_range_based_on_p (&vr0, op1))
3332 const bool minus_p = (code == MINUS_EXPR);
3333 value_range n_vr1 = VR_INITIALIZER;
3335 /* Try with VR0 and [-INF, OP1]. */
3336 if (is_gimple_min_invariant (minus_p ? vr0.max : vr0.min))
3337 set_value_range (&n_vr1, VR_RANGE, vrp_val_min (expr_type), op1, NULL);
3339 /* Try with VR0 and [OP1, +INF]. */
3340 else if (is_gimple_min_invariant (minus_p ? vr0.min : vr0.max))
3341 set_value_range (&n_vr1, VR_RANGE, op1, vrp_val_max (expr_type), NULL);
3343 /* Try with VR0 and [OP1, OP1]. */
3344 else
3345 set_value_range (&n_vr1, VR_RANGE, op1, op1, NULL);
3347 extract_range_from_binary_expr_1 (vr, code, expr_type, &vr0, &n_vr1);
3350 if (vr->type == VR_VARYING
3351 && (code == PLUS_EXPR || code == MINUS_EXPR)
3352 && TREE_CODE (op0) == SSA_NAME
3353 && vr1.type == VR_RANGE
3354 && symbolic_range_based_on_p (&vr1, op0))
3356 const bool minus_p = (code == MINUS_EXPR);
3357 value_range n_vr0 = VR_INITIALIZER;
3359 /* Try with [-INF, OP0] and VR1. */
3360 if (is_gimple_min_invariant (minus_p ? vr1.max : vr1.min))
3361 set_value_range (&n_vr0, VR_RANGE, vrp_val_min (expr_type), op0, NULL);
3363 /* Try with [OP0, +INF] and VR1. */
3364 else if (is_gimple_min_invariant (minus_p ? vr1.min : vr1.max))
3365 set_value_range (&n_vr0, VR_RANGE, op0, vrp_val_max (expr_type), NULL);
3367 /* Try with [OP0, OP0] and VR1. */
3368 else
3369 set_value_range (&n_vr0, VR_RANGE, op0, op0, NULL);
3371 extract_range_from_binary_expr_1 (vr, code, expr_type, &n_vr0, &vr1);
3374 /* If we didn't derive a range for MINUS_EXPR, and
3375 op1's range is ~[op0,op0] or vice-versa, then we
3376 can derive a non-null range. This happens often for
3377 pointer subtraction. */
3378 if (vr->type == VR_VARYING
3379 && code == MINUS_EXPR
3380 && TREE_CODE (op0) == SSA_NAME
3381 && ((vr0.type == VR_ANTI_RANGE
3382 && vr0.min == op1
3383 && vr0.min == vr0.max)
3384 || (vr1.type == VR_ANTI_RANGE
3385 && vr1.min == op0
3386 && vr1.min == vr1.max)))
3387 set_value_range_to_nonnull (vr, TREE_TYPE (op0));
3390 /* Extract range information from a unary operation CODE based on
3391 the range of its operand *VR0 with type OP0_TYPE with resulting type TYPE.
3392 The resulting range is stored in *VR. */
3394 void
3395 extract_range_from_unary_expr (value_range *vr,
3396 enum tree_code code, tree type,
3397 value_range *vr0_, tree op0_type)
3399 value_range vr0 = *vr0_, vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
3401 /* VRP only operates on integral and pointer types. */
3402 if (!(INTEGRAL_TYPE_P (op0_type)
3403 || POINTER_TYPE_P (op0_type))
3404 || !(INTEGRAL_TYPE_P (type)
3405 || POINTER_TYPE_P (type)))
3407 set_value_range_to_varying (vr);
3408 return;
3411 /* If VR0 is UNDEFINED, so is the result. */
3412 if (vr0.type == VR_UNDEFINED)
3414 set_value_range_to_undefined (vr);
3415 return;
3418 /* Handle operations that we express in terms of others. */
3419 if (code == PAREN_EXPR || code == OBJ_TYPE_REF)
3421 /* PAREN_EXPR and OBJ_TYPE_REF are simple copies. */
3422 copy_value_range (vr, &vr0);
3423 return;
3425 else if (code == NEGATE_EXPR)
3427 /* -X is simply 0 - X, so re-use existing code that also handles
3428 anti-ranges fine. */
3429 value_range zero = VR_INITIALIZER;
3430 set_value_range_to_value (&zero, build_int_cst (type, 0), NULL);
3431 extract_range_from_binary_expr_1 (vr, MINUS_EXPR, type, &zero, &vr0);
3432 return;
3434 else if (code == BIT_NOT_EXPR)
3436 /* ~X is simply -1 - X, so re-use existing code that also handles
3437 anti-ranges fine. */
3438 value_range minusone = VR_INITIALIZER;
3439 set_value_range_to_value (&minusone, build_int_cst (type, -1), NULL);
3440 extract_range_from_binary_expr_1 (vr, MINUS_EXPR,
3441 type, &minusone, &vr0);
3442 return;
3445 /* Now canonicalize anti-ranges to ranges when they are not symbolic
3446 and express op ~[] as (op []') U (op []''). */
3447 if (vr0.type == VR_ANTI_RANGE
3448 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
3450 extract_range_from_unary_expr (vr, code, type, &vrtem0, op0_type);
3451 if (vrtem1.type != VR_UNDEFINED)
3453 value_range vrres = VR_INITIALIZER;
3454 extract_range_from_unary_expr (&vrres, code, type,
3455 &vrtem1, op0_type);
3456 vrp_meet (vr, &vrres);
3458 return;
3461 if (CONVERT_EXPR_CODE_P (code))
3463 tree inner_type = op0_type;
3464 tree outer_type = type;
3466 /* If the expression evaluates to a pointer, we are only interested in
3467 determining if it evaluates to NULL [0, 0] or non-NULL (~[0, 0]). */
3468 if (POINTER_TYPE_P (type))
3470 if (range_is_nonnull (&vr0))
3471 set_value_range_to_nonnull (vr, type);
3472 else if (range_is_null (&vr0))
3473 set_value_range_to_null (vr, type);
3474 else
3475 set_value_range_to_varying (vr);
3476 return;
3479 /* If VR0 is varying and we increase the type precision, assume
3480 a full range for the following transformation. */
3481 if (vr0.type == VR_VARYING
3482 && INTEGRAL_TYPE_P (inner_type)
3483 && TYPE_PRECISION (inner_type) < TYPE_PRECISION (outer_type))
3485 vr0.type = VR_RANGE;
3486 vr0.min = TYPE_MIN_VALUE (inner_type);
3487 vr0.max = TYPE_MAX_VALUE (inner_type);
3490 /* If VR0 is a constant range or anti-range and the conversion is
3491 not truncating we can convert the min and max values and
3492 canonicalize the resulting range. Otherwise we can do the
3493 conversion if the size of the range is less than what the
3494 precision of the target type can represent and the range is
3495 not an anti-range. */
3496 if ((vr0.type == VR_RANGE
3497 || vr0.type == VR_ANTI_RANGE)
3498 && TREE_CODE (vr0.min) == INTEGER_CST
3499 && TREE_CODE (vr0.max) == INTEGER_CST
3500 && (!is_overflow_infinity (vr0.min)
3501 || (vr0.type == VR_RANGE
3502 && TYPE_PRECISION (outer_type) > TYPE_PRECISION (inner_type)
3503 && needs_overflow_infinity (outer_type)
3504 && supports_overflow_infinity (outer_type)))
3505 && (!is_overflow_infinity (vr0.max)
3506 || (vr0.type == VR_RANGE
3507 && TYPE_PRECISION (outer_type) > TYPE_PRECISION (inner_type)
3508 && needs_overflow_infinity (outer_type)
3509 && supports_overflow_infinity (outer_type)))
3510 && (TYPE_PRECISION (outer_type) >= TYPE_PRECISION (inner_type)
3511 || (vr0.type == VR_RANGE
3512 && integer_zerop (int_const_binop (RSHIFT_EXPR,
3513 int_const_binop (MINUS_EXPR, vr0.max, vr0.min),
3514 size_int (TYPE_PRECISION (outer_type)))))))
3516 tree new_min, new_max;
3517 if (is_overflow_infinity (vr0.min))
3518 new_min = negative_overflow_infinity (outer_type);
3519 else
3520 new_min = force_fit_type (outer_type, wi::to_widest (vr0.min),
3521 0, false);
3522 if (is_overflow_infinity (vr0.max))
3523 new_max = positive_overflow_infinity (outer_type);
3524 else
3525 new_max = force_fit_type (outer_type, wi::to_widest (vr0.max),
3526 0, false);
3527 set_and_canonicalize_value_range (vr, vr0.type,
3528 new_min, new_max, NULL);
3529 return;
3532 set_value_range_to_varying (vr);
3533 return;
3535 else if (code == ABS_EXPR)
3537 tree min, max;
3538 int cmp;
3540 /* Pass through vr0 in the easy cases. */
3541 if (TYPE_UNSIGNED (type)
3542 || value_range_nonnegative_p (&vr0))
3544 copy_value_range (vr, &vr0);
3545 return;
3548 /* For the remaining varying or symbolic ranges we can't do anything
3549 useful. */
3550 if (vr0.type == VR_VARYING
3551 || symbolic_range_p (&vr0))
3553 set_value_range_to_varying (vr);
3554 return;
3557 /* -TYPE_MIN_VALUE = TYPE_MIN_VALUE with flag_wrapv so we can't get a
3558 useful range. */
3559 if (!TYPE_OVERFLOW_UNDEFINED (type)
3560 && ((vr0.type == VR_RANGE
3561 && vrp_val_is_min (vr0.min))
3562 || (vr0.type == VR_ANTI_RANGE
3563 && !vrp_val_is_min (vr0.min))))
3565 set_value_range_to_varying (vr);
3566 return;
3569 /* ABS_EXPR may flip the range around, if the original range
3570 included negative values. */
3571 if (is_overflow_infinity (vr0.min))
3572 min = positive_overflow_infinity (type);
3573 else if (!vrp_val_is_min (vr0.min))
3574 min = fold_unary_to_constant (code, type, vr0.min);
3575 else if (!needs_overflow_infinity (type))
3576 min = TYPE_MAX_VALUE (type);
3577 else if (supports_overflow_infinity (type))
3578 min = positive_overflow_infinity (type);
3579 else
3581 set_value_range_to_varying (vr);
3582 return;
3585 if (is_overflow_infinity (vr0.max))
3586 max = positive_overflow_infinity (type);
3587 else if (!vrp_val_is_min (vr0.max))
3588 max = fold_unary_to_constant (code, type, vr0.max);
3589 else if (!needs_overflow_infinity (type))
3590 max = TYPE_MAX_VALUE (type);
3591 else if (supports_overflow_infinity (type)
3592 /* We shouldn't generate [+INF, +INF] as set_value_range
3593 doesn't like this and ICEs. */
3594 && !is_positive_overflow_infinity (min))
3595 max = positive_overflow_infinity (type);
3596 else
3598 set_value_range_to_varying (vr);
3599 return;
3602 cmp = compare_values (min, max);
3604 /* If a VR_ANTI_RANGEs contains zero, then we have
3605 ~[-INF, min(MIN, MAX)]. */
3606 if (vr0.type == VR_ANTI_RANGE)
3608 if (range_includes_zero_p (vr0.min, vr0.max) == 1)
3610 /* Take the lower of the two values. */
3611 if (cmp != 1)
3612 max = min;
3614 /* Create ~[-INF, min (abs(MIN), abs(MAX))]
3615 or ~[-INF + 1, min (abs(MIN), abs(MAX))] when
3616 flag_wrapv is set and the original anti-range doesn't include
3617 TYPE_MIN_VALUE, remember -TYPE_MIN_VALUE = TYPE_MIN_VALUE. */
3618 if (TYPE_OVERFLOW_WRAPS (type))
3620 tree type_min_value = TYPE_MIN_VALUE (type);
3622 min = (vr0.min != type_min_value
3623 ? int_const_binop (PLUS_EXPR, type_min_value,
3624 build_int_cst (TREE_TYPE (type_min_value), 1))
3625 : type_min_value);
3627 else
3629 if (overflow_infinity_range_p (&vr0))
3630 min = negative_overflow_infinity (type);
3631 else
3632 min = TYPE_MIN_VALUE (type);
3635 else
3637 /* All else has failed, so create the range [0, INF], even for
3638 flag_wrapv since TYPE_MIN_VALUE is in the original
3639 anti-range. */
3640 vr0.type = VR_RANGE;
3641 min = build_int_cst (type, 0);
3642 if (needs_overflow_infinity (type))
3644 if (supports_overflow_infinity (type))
3645 max = positive_overflow_infinity (type);
3646 else
3648 set_value_range_to_varying (vr);
3649 return;
3652 else
3653 max = TYPE_MAX_VALUE (type);
3657 /* If the range contains zero then we know that the minimum value in the
3658 range will be zero. */
3659 else if (range_includes_zero_p (vr0.min, vr0.max) == 1)
3661 if (cmp == 1)
3662 max = min;
3663 min = build_int_cst (type, 0);
3665 else
3667 /* If the range was reversed, swap MIN and MAX. */
3668 if (cmp == 1)
3669 std::swap (min, max);
3672 cmp = compare_values (min, max);
3673 if (cmp == -2 || cmp == 1)
3675 /* If the new range has its limits swapped around (MIN > MAX),
3676 then the operation caused one of them to wrap around, mark
3677 the new range VARYING. */
3678 set_value_range_to_varying (vr);
3680 else
3681 set_value_range (vr, vr0.type, min, max, NULL);
3682 return;
3685 /* For unhandled operations fall back to varying. */
3686 set_value_range_to_varying (vr);
3687 return;
3691 /* Extract range information from a unary expression CODE OP0 based on
3692 the range of its operand with resulting type TYPE.
3693 The resulting range is stored in *VR. */
3695 static void
3696 extract_range_from_unary_expr (value_range *vr, enum tree_code code,
3697 tree type, tree op0)
3699 value_range vr0 = VR_INITIALIZER;
3701 /* Get value ranges for the operand. For constant operands, create
3702 a new value range with the operand to simplify processing. */
3703 if (TREE_CODE (op0) == SSA_NAME)
3704 vr0 = *(get_value_range (op0));
3705 else if (is_gimple_min_invariant (op0))
3706 set_value_range_to_value (&vr0, op0, NULL);
3707 else
3708 set_value_range_to_varying (&vr0);
3710 extract_range_from_unary_expr (vr, code, type, &vr0, TREE_TYPE (op0));
3714 /* Extract range information from a conditional expression STMT based on
3715 the ranges of each of its operands and the expression code. */
3717 static void
3718 extract_range_from_cond_expr (value_range *vr, gassign *stmt)
3720 tree op0, op1;
3721 value_range vr0 = VR_INITIALIZER;
3722 value_range vr1 = VR_INITIALIZER;
3724 /* Get value ranges for each operand. For constant operands, create
3725 a new value range with the operand to simplify processing. */
3726 op0 = gimple_assign_rhs2 (stmt);
3727 if (TREE_CODE (op0) == SSA_NAME)
3728 vr0 = *(get_value_range (op0));
3729 else if (is_gimple_min_invariant (op0))
3730 set_value_range_to_value (&vr0, op0, NULL);
3731 else
3732 set_value_range_to_varying (&vr0);
3734 op1 = gimple_assign_rhs3 (stmt);
3735 if (TREE_CODE (op1) == SSA_NAME)
3736 vr1 = *(get_value_range (op1));
3737 else if (is_gimple_min_invariant (op1))
3738 set_value_range_to_value (&vr1, op1, NULL);
3739 else
3740 set_value_range_to_varying (&vr1);
3742 /* The resulting value range is the union of the operand ranges */
3743 copy_value_range (vr, &vr0);
3744 vrp_meet (vr, &vr1);
3748 /* Extract range information from a comparison expression EXPR based
3749 on the range of its operand and the expression code. */
3751 static void
3752 extract_range_from_comparison (value_range *vr, enum tree_code code,
3753 tree type, tree op0, tree op1)
3755 bool sop = false;
3756 tree val;
3758 val = vrp_evaluate_conditional_warnv_with_ops (code, op0, op1, false, &sop,
3759 NULL);
3761 /* A disadvantage of using a special infinity as an overflow
3762 representation is that we lose the ability to record overflow
3763 when we don't have an infinity. So we have to ignore a result
3764 which relies on overflow. */
3766 if (val && !is_overflow_infinity (val) && !sop)
3768 /* Since this expression was found on the RHS of an assignment,
3769 its type may be different from _Bool. Convert VAL to EXPR's
3770 type. */
3771 val = fold_convert (type, val);
3772 if (is_gimple_min_invariant (val))
3773 set_value_range_to_value (vr, val, vr->equiv);
3774 else
3775 set_value_range (vr, VR_RANGE, val, val, vr->equiv);
3777 else
3778 /* The result of a comparison is always true or false. */
3779 set_value_range_to_truthvalue (vr, type);
3782 /* Helper function for simplify_internal_call_using_ranges and
3783 extract_range_basic. Return true if OP0 SUBCODE OP1 for
3784 SUBCODE {PLUS,MINUS,MULT}_EXPR is known to never overflow or
3785 always overflow. Set *OVF to true if it is known to always
3786 overflow. */
3788 static bool
3789 check_for_binary_op_overflow (enum tree_code subcode, tree type,
3790 tree op0, tree op1, bool *ovf)
3792 value_range vr0 = VR_INITIALIZER;
3793 value_range vr1 = VR_INITIALIZER;
3794 if (TREE_CODE (op0) == SSA_NAME)
3795 vr0 = *get_value_range (op0);
3796 else if (TREE_CODE (op0) == INTEGER_CST)
3797 set_value_range_to_value (&vr0, op0, NULL);
3798 else
3799 set_value_range_to_varying (&vr0);
3801 if (TREE_CODE (op1) == SSA_NAME)
3802 vr1 = *get_value_range (op1);
3803 else if (TREE_CODE (op1) == INTEGER_CST)
3804 set_value_range_to_value (&vr1, op1, NULL);
3805 else
3806 set_value_range_to_varying (&vr1);
3808 if (!range_int_cst_p (&vr0)
3809 || TREE_OVERFLOW (vr0.min)
3810 || TREE_OVERFLOW (vr0.max))
3812 vr0.min = vrp_val_min (TREE_TYPE (op0));
3813 vr0.max = vrp_val_max (TREE_TYPE (op0));
3815 if (!range_int_cst_p (&vr1)
3816 || TREE_OVERFLOW (vr1.min)
3817 || TREE_OVERFLOW (vr1.max))
3819 vr1.min = vrp_val_min (TREE_TYPE (op1));
3820 vr1.max = vrp_val_max (TREE_TYPE (op1));
3822 *ovf = arith_overflowed_p (subcode, type, vr0.min,
3823 subcode == MINUS_EXPR ? vr1.max : vr1.min);
3824 if (arith_overflowed_p (subcode, type, vr0.max,
3825 subcode == MINUS_EXPR ? vr1.min : vr1.max) != *ovf)
3826 return false;
3827 if (subcode == MULT_EXPR)
3829 if (arith_overflowed_p (subcode, type, vr0.min, vr1.max) != *ovf
3830 || arith_overflowed_p (subcode, type, vr0.max, vr1.min) != *ovf)
3831 return false;
3833 if (*ovf)
3835 /* So far we found that there is an overflow on the boundaries.
3836 That doesn't prove that there is an overflow even for all values
3837 in between the boundaries. For that compute widest_int range
3838 of the result and see if it doesn't overlap the range of
3839 type. */
3840 widest_int wmin, wmax;
3841 widest_int w[4];
3842 int i;
3843 w[0] = wi::to_widest (vr0.min);
3844 w[1] = wi::to_widest (vr0.max);
3845 w[2] = wi::to_widest (vr1.min);
3846 w[3] = wi::to_widest (vr1.max);
3847 for (i = 0; i < 4; i++)
3849 widest_int wt;
3850 switch (subcode)
3852 case PLUS_EXPR:
3853 wt = wi::add (w[i & 1], w[2 + (i & 2) / 2]);
3854 break;
3855 case MINUS_EXPR:
3856 wt = wi::sub (w[i & 1], w[2 + (i & 2) / 2]);
3857 break;
3858 case MULT_EXPR:
3859 wt = wi::mul (w[i & 1], w[2 + (i & 2) / 2]);
3860 break;
3861 default:
3862 gcc_unreachable ();
3864 if (i == 0)
3866 wmin = wt;
3867 wmax = wt;
3869 else
3871 wmin = wi::smin (wmin, wt);
3872 wmax = wi::smax (wmax, wt);
3875 /* The result of op0 CODE op1 is known to be in range
3876 [wmin, wmax]. */
3877 widest_int wtmin = wi::to_widest (vrp_val_min (type));
3878 widest_int wtmax = wi::to_widest (vrp_val_max (type));
3879 /* If all values in [wmin, wmax] are smaller than
3880 [wtmin, wtmax] or all are larger than [wtmin, wtmax],
3881 the arithmetic operation will always overflow. */
3882 if (wmax < wtmin || wmin > wtmax)
3883 return true;
3884 return false;
3886 return true;
3889 /* Try to derive a nonnegative or nonzero range out of STMT relying
3890 primarily on generic routines in fold in conjunction with range data.
3891 Store the result in *VR */
3893 static void
3894 extract_range_basic (value_range *vr, gimple *stmt)
3896 bool sop = false;
3897 tree type = gimple_expr_type (stmt);
3899 if (is_gimple_call (stmt))
3901 tree arg;
3902 int mini, maxi, zerov = 0, prec;
3903 enum tree_code subcode = ERROR_MARK;
3904 combined_fn cfn = gimple_call_combined_fn (stmt);
3906 switch (cfn)
3908 case CFN_BUILT_IN_CONSTANT_P:
3909 /* If the call is __builtin_constant_p and the argument is a
3910 function parameter resolve it to false. This avoids bogus
3911 array bound warnings.
3912 ??? We could do this as early as inlining is finished. */
3913 arg = gimple_call_arg (stmt, 0);
3914 if (TREE_CODE (arg) == SSA_NAME
3915 && SSA_NAME_IS_DEFAULT_DEF (arg)
3916 && TREE_CODE (SSA_NAME_VAR (arg)) == PARM_DECL
3917 && cfun->after_inlining)
3919 set_value_range_to_null (vr, type);
3920 return;
3922 break;
3923 /* Both __builtin_ffs* and __builtin_popcount return
3924 [0, prec]. */
3925 CASE_CFN_FFS:
3926 CASE_CFN_POPCOUNT:
3927 arg = gimple_call_arg (stmt, 0);
3928 prec = TYPE_PRECISION (TREE_TYPE (arg));
3929 mini = 0;
3930 maxi = prec;
3931 if (TREE_CODE (arg) == SSA_NAME)
3933 value_range *vr0 = get_value_range (arg);
3934 /* If arg is non-zero, then ffs or popcount
3935 are non-zero. */
3936 if (((vr0->type == VR_RANGE
3937 && range_includes_zero_p (vr0->min, vr0->max) == 0)
3938 || (vr0->type == VR_ANTI_RANGE
3939 && range_includes_zero_p (vr0->min, vr0->max) == 1))
3940 && !is_overflow_infinity (vr0->min)
3941 && !is_overflow_infinity (vr0->max))
3942 mini = 1;
3943 /* If some high bits are known to be zero,
3944 we can decrease the maximum. */
3945 if (vr0->type == VR_RANGE
3946 && TREE_CODE (vr0->max) == INTEGER_CST
3947 && !operand_less_p (vr0->min,
3948 build_zero_cst (TREE_TYPE (vr0->min)))
3949 && !is_overflow_infinity (vr0->max))
3950 maxi = tree_floor_log2 (vr0->max) + 1;
3952 goto bitop_builtin;
3953 /* __builtin_parity* returns [0, 1]. */
3954 CASE_CFN_PARITY:
3955 mini = 0;
3956 maxi = 1;
3957 goto bitop_builtin;
3958 /* __builtin_c[lt]z* return [0, prec-1], except for
3959 when the argument is 0, but that is undefined behavior.
3960 On many targets where the CLZ RTL or optab value is defined
3961 for 0 the value is prec, so include that in the range
3962 by default. */
3963 CASE_CFN_CLZ:
3964 arg = gimple_call_arg (stmt, 0);
3965 prec = TYPE_PRECISION (TREE_TYPE (arg));
3966 mini = 0;
3967 maxi = prec;
3968 if (optab_handler (clz_optab, TYPE_MODE (TREE_TYPE (arg)))
3969 != CODE_FOR_nothing
3970 && CLZ_DEFINED_VALUE_AT_ZERO (TYPE_MODE (TREE_TYPE (arg)),
3971 zerov)
3972 /* Handle only the single common value. */
3973 && zerov != prec)
3974 /* Magic value to give up, unless vr0 proves
3975 arg is non-zero. */
3976 mini = -2;
3977 if (TREE_CODE (arg) == SSA_NAME)
3979 value_range *vr0 = get_value_range (arg);
3980 /* From clz of VR_RANGE minimum we can compute
3981 result maximum. */
3982 if (vr0->type == VR_RANGE
3983 && TREE_CODE (vr0->min) == INTEGER_CST
3984 && !is_overflow_infinity (vr0->min))
3986 maxi = prec - 1 - tree_floor_log2 (vr0->min);
3987 if (maxi != prec)
3988 mini = 0;
3990 else if (vr0->type == VR_ANTI_RANGE
3991 && integer_zerop (vr0->min)
3992 && !is_overflow_infinity (vr0->min))
3994 maxi = prec - 1;
3995 mini = 0;
3997 if (mini == -2)
3998 break;
3999 /* From clz of VR_RANGE maximum we can compute
4000 result minimum. */
4001 if (vr0->type == VR_RANGE
4002 && TREE_CODE (vr0->max) == INTEGER_CST
4003 && !is_overflow_infinity (vr0->max))
4005 mini = prec - 1 - tree_floor_log2 (vr0->max);
4006 if (mini == prec)
4007 break;
4010 if (mini == -2)
4011 break;
4012 goto bitop_builtin;
4013 /* __builtin_ctz* return [0, prec-1], except for
4014 when the argument is 0, but that is undefined behavior.
4015 If there is a ctz optab for this mode and
4016 CTZ_DEFINED_VALUE_AT_ZERO, include that in the range,
4017 otherwise just assume 0 won't be seen. */
4018 CASE_CFN_CTZ:
4019 arg = gimple_call_arg (stmt, 0);
4020 prec = TYPE_PRECISION (TREE_TYPE (arg));
4021 mini = 0;
4022 maxi = prec - 1;
4023 if (optab_handler (ctz_optab, TYPE_MODE (TREE_TYPE (arg)))
4024 != CODE_FOR_nothing
4025 && CTZ_DEFINED_VALUE_AT_ZERO (TYPE_MODE (TREE_TYPE (arg)),
4026 zerov))
4028 /* Handle only the two common values. */
4029 if (zerov == -1)
4030 mini = -1;
4031 else if (zerov == prec)
4032 maxi = prec;
4033 else
4034 /* Magic value to give up, unless vr0 proves
4035 arg is non-zero. */
4036 mini = -2;
4038 if (TREE_CODE (arg) == SSA_NAME)
4040 value_range *vr0 = get_value_range (arg);
4041 /* If arg is non-zero, then use [0, prec - 1]. */
4042 if (((vr0->type == VR_RANGE
4043 && integer_nonzerop (vr0->min))
4044 || (vr0->type == VR_ANTI_RANGE
4045 && integer_zerop (vr0->min)))
4046 && !is_overflow_infinity (vr0->min))
4048 mini = 0;
4049 maxi = prec - 1;
4051 /* If some high bits are known to be zero,
4052 we can decrease the result maximum. */
4053 if (vr0->type == VR_RANGE
4054 && TREE_CODE (vr0->max) == INTEGER_CST
4055 && !is_overflow_infinity (vr0->max))
4057 maxi = tree_floor_log2 (vr0->max);
4058 /* For vr0 [0, 0] give up. */
4059 if (maxi == -1)
4060 break;
4063 if (mini == -2)
4064 break;
4065 goto bitop_builtin;
4066 /* __builtin_clrsb* returns [0, prec-1]. */
4067 CASE_CFN_CLRSB:
4068 arg = gimple_call_arg (stmt, 0);
4069 prec = TYPE_PRECISION (TREE_TYPE (arg));
4070 mini = 0;
4071 maxi = prec - 1;
4072 goto bitop_builtin;
4073 bitop_builtin:
4074 set_value_range (vr, VR_RANGE, build_int_cst (type, mini),
4075 build_int_cst (type, maxi), NULL);
4076 return;
4077 case CFN_UBSAN_CHECK_ADD:
4078 subcode = PLUS_EXPR;
4079 break;
4080 case CFN_UBSAN_CHECK_SUB:
4081 subcode = MINUS_EXPR;
4082 break;
4083 case CFN_UBSAN_CHECK_MUL:
4084 subcode = MULT_EXPR;
4085 break;
4086 case CFN_GOACC_DIM_SIZE:
4087 case CFN_GOACC_DIM_POS:
4088 /* Optimizing these two internal functions helps the loop
4089 optimizer eliminate outer comparisons. Size is [1,N]
4090 and pos is [0,N-1]. */
4092 bool is_pos = cfn == CFN_GOACC_DIM_POS;
4093 int axis = oacc_get_ifn_dim_arg (stmt);
4094 int size = oacc_get_fn_dim_size (current_function_decl, axis);
4096 if (!size)
4097 /* If it's dynamic, the backend might know a hardware
4098 limitation. */
4099 size = targetm.goacc.dim_limit (axis);
4101 tree type = TREE_TYPE (gimple_call_lhs (stmt));
4102 set_value_range (vr, VR_RANGE,
4103 build_int_cst (type, is_pos ? 0 : 1),
4104 size ? build_int_cst (type, size - is_pos)
4105 : vrp_val_max (type), NULL);
4107 return;
4108 case CFN_BUILT_IN_STRLEN:
4109 if (tree lhs = gimple_call_lhs (stmt))
4110 if (ptrdiff_type_node
4111 && (TYPE_PRECISION (ptrdiff_type_node)
4112 == TYPE_PRECISION (TREE_TYPE (lhs))))
4114 tree type = TREE_TYPE (lhs);
4115 tree max = vrp_val_max (ptrdiff_type_node);
4116 wide_int wmax = wi::to_wide (max, TYPE_PRECISION (TREE_TYPE (max)));
4117 tree range_min = build_zero_cst (type);
4118 tree range_max = wide_int_to_tree (type, wmax - 1);
4119 set_value_range (vr, VR_RANGE, range_min, range_max, NULL);
4120 return;
4122 break;
4123 default:
4124 break;
4126 if (subcode != ERROR_MARK)
4128 bool saved_flag_wrapv = flag_wrapv;
4129 /* Pretend the arithmetics is wrapping. If there is
4130 any overflow, we'll complain, but will actually do
4131 wrapping operation. */
4132 flag_wrapv = 1;
4133 extract_range_from_binary_expr (vr, subcode, type,
4134 gimple_call_arg (stmt, 0),
4135 gimple_call_arg (stmt, 1));
4136 flag_wrapv = saved_flag_wrapv;
4138 /* If for both arguments vrp_valueize returned non-NULL,
4139 this should have been already folded and if not, it
4140 wasn't folded because of overflow. Avoid removing the
4141 UBSAN_CHECK_* calls in that case. */
4142 if (vr->type == VR_RANGE
4143 && (vr->min == vr->max
4144 || operand_equal_p (vr->min, vr->max, 0)))
4145 set_value_range_to_varying (vr);
4146 return;
4149 /* Handle extraction of the two results (result of arithmetics and
4150 a flag whether arithmetics overflowed) from {ADD,SUB,MUL}_OVERFLOW
4151 internal function. Similarly from ATOMIC_COMPARE_EXCHANGE. */
4152 else if (is_gimple_assign (stmt)
4153 && (gimple_assign_rhs_code (stmt) == REALPART_EXPR
4154 || gimple_assign_rhs_code (stmt) == IMAGPART_EXPR)
4155 && INTEGRAL_TYPE_P (type))
4157 enum tree_code code = gimple_assign_rhs_code (stmt);
4158 tree op = gimple_assign_rhs1 (stmt);
4159 if (TREE_CODE (op) == code && TREE_CODE (TREE_OPERAND (op, 0)) == SSA_NAME)
4161 gimple *g = SSA_NAME_DEF_STMT (TREE_OPERAND (op, 0));
4162 if (is_gimple_call (g) && gimple_call_internal_p (g))
4164 enum tree_code subcode = ERROR_MARK;
4165 switch (gimple_call_internal_fn (g))
4167 case IFN_ADD_OVERFLOW:
4168 subcode = PLUS_EXPR;
4169 break;
4170 case IFN_SUB_OVERFLOW:
4171 subcode = MINUS_EXPR;
4172 break;
4173 case IFN_MUL_OVERFLOW:
4174 subcode = MULT_EXPR;
4175 break;
4176 case IFN_ATOMIC_COMPARE_EXCHANGE:
4177 if (code == IMAGPART_EXPR)
4179 /* This is the boolean return value whether compare and
4180 exchange changed anything or not. */
4181 set_value_range (vr, VR_RANGE, build_int_cst (type, 0),
4182 build_int_cst (type, 1), NULL);
4183 return;
4185 break;
4186 default:
4187 break;
4189 if (subcode != ERROR_MARK)
4191 tree op0 = gimple_call_arg (g, 0);
4192 tree op1 = gimple_call_arg (g, 1);
4193 if (code == IMAGPART_EXPR)
4195 bool ovf = false;
4196 if (check_for_binary_op_overflow (subcode, type,
4197 op0, op1, &ovf))
4198 set_value_range_to_value (vr,
4199 build_int_cst (type, ovf),
4200 NULL);
4201 else if (TYPE_PRECISION (type) == 1
4202 && !TYPE_UNSIGNED (type))
4203 set_value_range_to_varying (vr);
4204 else
4205 set_value_range (vr, VR_RANGE, build_int_cst (type, 0),
4206 build_int_cst (type, 1), NULL);
4208 else if (types_compatible_p (type, TREE_TYPE (op0))
4209 && types_compatible_p (type, TREE_TYPE (op1)))
4211 bool saved_flag_wrapv = flag_wrapv;
4212 /* Pretend the arithmetics is wrapping. If there is
4213 any overflow, IMAGPART_EXPR will be set. */
4214 flag_wrapv = 1;
4215 extract_range_from_binary_expr (vr, subcode, type,
4216 op0, op1);
4217 flag_wrapv = saved_flag_wrapv;
4219 else
4221 value_range vr0 = VR_INITIALIZER;
4222 value_range vr1 = VR_INITIALIZER;
4223 bool saved_flag_wrapv = flag_wrapv;
4224 /* Pretend the arithmetics is wrapping. If there is
4225 any overflow, IMAGPART_EXPR will be set. */
4226 flag_wrapv = 1;
4227 extract_range_from_unary_expr (&vr0, NOP_EXPR,
4228 type, op0);
4229 extract_range_from_unary_expr (&vr1, NOP_EXPR,
4230 type, op1);
4231 extract_range_from_binary_expr_1 (vr, subcode, type,
4232 &vr0, &vr1);
4233 flag_wrapv = saved_flag_wrapv;
4235 return;
4240 if (INTEGRAL_TYPE_P (type)
4241 && gimple_stmt_nonnegative_warnv_p (stmt, &sop))
4242 set_value_range_to_nonnegative (vr, type,
4243 sop || stmt_overflow_infinity (stmt));
4244 else if (vrp_stmt_computes_nonzero (stmt, &sop)
4245 && !sop)
4246 set_value_range_to_nonnull (vr, type);
4247 else
4248 set_value_range_to_varying (vr);
4252 /* Try to compute a useful range out of assignment STMT and store it
4253 in *VR. */
4255 static void
4256 extract_range_from_assignment (value_range *vr, gassign *stmt)
4258 enum tree_code code = gimple_assign_rhs_code (stmt);
4260 if (code == ASSERT_EXPR)
4261 extract_range_from_assert (vr, gimple_assign_rhs1 (stmt));
4262 else if (code == SSA_NAME)
4263 extract_range_from_ssa_name (vr, gimple_assign_rhs1 (stmt));
4264 else if (TREE_CODE_CLASS (code) == tcc_binary)
4265 extract_range_from_binary_expr (vr, gimple_assign_rhs_code (stmt),
4266 gimple_expr_type (stmt),
4267 gimple_assign_rhs1 (stmt),
4268 gimple_assign_rhs2 (stmt));
4269 else if (TREE_CODE_CLASS (code) == tcc_unary)
4270 extract_range_from_unary_expr (vr, gimple_assign_rhs_code (stmt),
4271 gimple_expr_type (stmt),
4272 gimple_assign_rhs1 (stmt));
4273 else if (code == COND_EXPR)
4274 extract_range_from_cond_expr (vr, stmt);
4275 else if (TREE_CODE_CLASS (code) == tcc_comparison)
4276 extract_range_from_comparison (vr, gimple_assign_rhs_code (stmt),
4277 gimple_expr_type (stmt),
4278 gimple_assign_rhs1 (stmt),
4279 gimple_assign_rhs2 (stmt));
4280 else if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS
4281 && is_gimple_min_invariant (gimple_assign_rhs1 (stmt)))
4282 set_value_range_to_value (vr, gimple_assign_rhs1 (stmt), NULL);
4283 else
4284 set_value_range_to_varying (vr);
4286 if (vr->type == VR_VARYING)
4287 extract_range_basic (vr, stmt);
4290 /* Given a range VR, a LOOP and a variable VAR, determine whether it
4291 would be profitable to adjust VR using scalar evolution information
4292 for VAR. If so, update VR with the new limits. */
4294 static void
4295 adjust_range_with_scev (value_range *vr, struct loop *loop,
4296 gimple *stmt, tree var)
4298 tree init, step, chrec, tmin, tmax, min, max, type, tem;
4299 enum ev_direction dir;
4301 /* TODO. Don't adjust anti-ranges. An anti-range may provide
4302 better opportunities than a regular range, but I'm not sure. */
4303 if (vr->type == VR_ANTI_RANGE)
4304 return;
4306 chrec = instantiate_parameters (loop, analyze_scalar_evolution (loop, var));
4308 /* Like in PR19590, scev can return a constant function. */
4309 if (is_gimple_min_invariant (chrec))
4311 set_value_range_to_value (vr, chrec, vr->equiv);
4312 return;
4315 if (TREE_CODE (chrec) != POLYNOMIAL_CHREC)
4316 return;
4318 init = initial_condition_in_loop_num (chrec, loop->num);
4319 tem = op_with_constant_singleton_value_range (init);
4320 if (tem)
4321 init = tem;
4322 step = evolution_part_in_loop_num (chrec, loop->num);
4323 tem = op_with_constant_singleton_value_range (step);
4324 if (tem)
4325 step = tem;
4327 /* If STEP is symbolic, we can't know whether INIT will be the
4328 minimum or maximum value in the range. Also, unless INIT is
4329 a simple expression, compare_values and possibly other functions
4330 in tree-vrp won't be able to handle it. */
4331 if (step == NULL_TREE
4332 || !is_gimple_min_invariant (step)
4333 || !valid_value_p (init))
4334 return;
4336 dir = scev_direction (chrec);
4337 if (/* Do not adjust ranges if we do not know whether the iv increases
4338 or decreases, ... */
4339 dir == EV_DIR_UNKNOWN
4340 /* ... or if it may wrap. */
4341 || scev_probably_wraps_p (NULL_TREE, init, step, stmt,
4342 get_chrec_loop (chrec), true))
4343 return;
4345 /* We use TYPE_MIN_VALUE and TYPE_MAX_VALUE here instead of
4346 negative_overflow_infinity and positive_overflow_infinity,
4347 because we have concluded that the loop probably does not
4348 wrap. */
4350 type = TREE_TYPE (var);
4351 if (POINTER_TYPE_P (type) || !TYPE_MIN_VALUE (type))
4352 tmin = lower_bound_in_type (type, type);
4353 else
4354 tmin = TYPE_MIN_VALUE (type);
4355 if (POINTER_TYPE_P (type) || !TYPE_MAX_VALUE (type))
4356 tmax = upper_bound_in_type (type, type);
4357 else
4358 tmax = TYPE_MAX_VALUE (type);
4360 /* Try to use estimated number of iterations for the loop to constrain the
4361 final value in the evolution. */
4362 if (TREE_CODE (step) == INTEGER_CST
4363 && is_gimple_val (init)
4364 && (TREE_CODE (init) != SSA_NAME
4365 || get_value_range (init)->type == VR_RANGE))
4367 widest_int nit;
4369 /* We are only entering here for loop header PHI nodes, so using
4370 the number of latch executions is the correct thing to use. */
4371 if (max_loop_iterations (loop, &nit))
4373 value_range maxvr = VR_INITIALIZER;
4374 signop sgn = TYPE_SIGN (TREE_TYPE (step));
4375 bool overflow;
4377 widest_int wtmp = wi::mul (wi::to_widest (step), nit, sgn,
4378 &overflow);
4379 /* If the multiplication overflowed we can't do a meaningful
4380 adjustment. Likewise if the result doesn't fit in the type
4381 of the induction variable. For a signed type we have to
4382 check whether the result has the expected signedness which
4383 is that of the step as number of iterations is unsigned. */
4384 if (!overflow
4385 && wi::fits_to_tree_p (wtmp, TREE_TYPE (init))
4386 && (sgn == UNSIGNED
4387 || wi::gts_p (wtmp, 0) == wi::gts_p (step, 0)))
4389 tem = wide_int_to_tree (TREE_TYPE (init), wtmp);
4390 extract_range_from_binary_expr (&maxvr, PLUS_EXPR,
4391 TREE_TYPE (init), init, tem);
4392 /* Likewise if the addition did. */
4393 if (maxvr.type == VR_RANGE)
4395 value_range initvr = VR_INITIALIZER;
4397 if (TREE_CODE (init) == SSA_NAME)
4398 initvr = *(get_value_range (init));
4399 else if (is_gimple_min_invariant (init))
4400 set_value_range_to_value (&initvr, init, NULL);
4401 else
4402 return;
4404 /* Check if init + nit * step overflows. Though we checked
4405 scev {init, step}_loop doesn't wrap, it is not enough
4406 because the loop may exit immediately. Overflow could
4407 happen in the plus expression in this case. */
4408 if ((dir == EV_DIR_DECREASES
4409 && (is_negative_overflow_infinity (maxvr.min)
4410 || compare_values (maxvr.min, initvr.min) != -1))
4411 || (dir == EV_DIR_GROWS
4412 && (is_positive_overflow_infinity (maxvr.max)
4413 || compare_values (maxvr.max, initvr.max) != 1)))
4414 return;
4416 tmin = maxvr.min;
4417 tmax = maxvr.max;
4423 if (vr->type == VR_VARYING || vr->type == VR_UNDEFINED)
4425 min = tmin;
4426 max = tmax;
4428 /* For VARYING or UNDEFINED ranges, just about anything we get
4429 from scalar evolutions should be better. */
4431 if (dir == EV_DIR_DECREASES)
4432 max = init;
4433 else
4434 min = init;
4436 else if (vr->type == VR_RANGE)
4438 min = vr->min;
4439 max = vr->max;
4441 if (dir == EV_DIR_DECREASES)
4443 /* INIT is the maximum value. If INIT is lower than VR->MAX
4444 but no smaller than VR->MIN, set VR->MAX to INIT. */
4445 if (compare_values (init, max) == -1)
4446 max = init;
4448 /* According to the loop information, the variable does not
4449 overflow. If we think it does, probably because of an
4450 overflow due to arithmetic on a different INF value,
4451 reset now. */
4452 if (is_negative_overflow_infinity (min)
4453 || compare_values (min, tmin) == -1)
4454 min = tmin;
4457 else
4459 /* If INIT is bigger than VR->MIN, set VR->MIN to INIT. */
4460 if (compare_values (init, min) == 1)
4461 min = init;
4463 if (is_positive_overflow_infinity (max)
4464 || compare_values (tmax, max) == -1)
4465 max = tmax;
4468 else
4469 return;
4471 /* If we just created an invalid range with the minimum
4472 greater than the maximum, we fail conservatively.
4473 This should happen only in unreachable
4474 parts of code, or for invalid programs. */
4475 if (compare_values (min, max) == 1
4476 || (is_negative_overflow_infinity (min)
4477 && is_positive_overflow_infinity (max)))
4478 return;
4480 /* Even for valid range info, sometimes overflow flag will leak in.
4481 As GIMPLE IL should have no constants with TREE_OVERFLOW set, we
4482 drop them except for +-overflow_infinity which still need special
4483 handling in vrp pass. */
4484 if (TREE_OVERFLOW_P (min)
4485 && ! is_negative_overflow_infinity (min))
4486 min = drop_tree_overflow (min);
4487 if (TREE_OVERFLOW_P (max)
4488 && ! is_positive_overflow_infinity (max))
4489 max = drop_tree_overflow (max);
4491 set_value_range (vr, VR_RANGE, min, max, vr->equiv);
4495 /* Given two numeric value ranges VR0, VR1 and a comparison code COMP:
4497 - Return BOOLEAN_TRUE_NODE if VR0 COMP VR1 always returns true for
4498 all the values in the ranges.
4500 - Return BOOLEAN_FALSE_NODE if the comparison always returns false.
4502 - Return NULL_TREE if it is not always possible to determine the
4503 value of the comparison.
4505 Also set *STRICT_OVERFLOW_P to indicate whether a range with an
4506 overflow infinity was used in the test. */
4509 static tree
4510 compare_ranges (enum tree_code comp, value_range *vr0, value_range *vr1,
4511 bool *strict_overflow_p)
4513 /* VARYING or UNDEFINED ranges cannot be compared. */
4514 if (vr0->type == VR_VARYING
4515 || vr0->type == VR_UNDEFINED
4516 || vr1->type == VR_VARYING
4517 || vr1->type == VR_UNDEFINED)
4518 return NULL_TREE;
4520 /* Anti-ranges need to be handled separately. */
4521 if (vr0->type == VR_ANTI_RANGE || vr1->type == VR_ANTI_RANGE)
4523 /* If both are anti-ranges, then we cannot compute any
4524 comparison. */
4525 if (vr0->type == VR_ANTI_RANGE && vr1->type == VR_ANTI_RANGE)
4526 return NULL_TREE;
4528 /* These comparisons are never statically computable. */
4529 if (comp == GT_EXPR
4530 || comp == GE_EXPR
4531 || comp == LT_EXPR
4532 || comp == LE_EXPR)
4533 return NULL_TREE;
4535 /* Equality can be computed only between a range and an
4536 anti-range. ~[VAL1, VAL2] == [VAL1, VAL2] is always false. */
4537 if (vr0->type == VR_RANGE)
4539 /* To simplify processing, make VR0 the anti-range. */
4540 value_range *tmp = vr0;
4541 vr0 = vr1;
4542 vr1 = tmp;
4545 gcc_assert (comp == NE_EXPR || comp == EQ_EXPR);
4547 if (compare_values_warnv (vr0->min, vr1->min, strict_overflow_p) == 0
4548 && compare_values_warnv (vr0->max, vr1->max, strict_overflow_p) == 0)
4549 return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
4551 return NULL_TREE;
4554 if (!usable_range_p (vr0, strict_overflow_p)
4555 || !usable_range_p (vr1, strict_overflow_p))
4556 return NULL_TREE;
4558 /* Simplify processing. If COMP is GT_EXPR or GE_EXPR, switch the
4559 operands around and change the comparison code. */
4560 if (comp == GT_EXPR || comp == GE_EXPR)
4562 comp = (comp == GT_EXPR) ? LT_EXPR : LE_EXPR;
4563 std::swap (vr0, vr1);
4566 if (comp == EQ_EXPR)
4568 /* Equality may only be computed if both ranges represent
4569 exactly one value. */
4570 if (compare_values_warnv (vr0->min, vr0->max, strict_overflow_p) == 0
4571 && compare_values_warnv (vr1->min, vr1->max, strict_overflow_p) == 0)
4573 int cmp_min = compare_values_warnv (vr0->min, vr1->min,
4574 strict_overflow_p);
4575 int cmp_max = compare_values_warnv (vr0->max, vr1->max,
4576 strict_overflow_p);
4577 if (cmp_min == 0 && cmp_max == 0)
4578 return boolean_true_node;
4579 else if (cmp_min != -2 && cmp_max != -2)
4580 return boolean_false_node;
4582 /* If [V0_MIN, V1_MAX] < [V1_MIN, V1_MAX] then V0 != V1. */
4583 else if (compare_values_warnv (vr0->min, vr1->max,
4584 strict_overflow_p) == 1
4585 || compare_values_warnv (vr1->min, vr0->max,
4586 strict_overflow_p) == 1)
4587 return boolean_false_node;
4589 return NULL_TREE;
4591 else if (comp == NE_EXPR)
4593 int cmp1, cmp2;
4595 /* If VR0 is completely to the left or completely to the right
4596 of VR1, they are always different. Notice that we need to
4597 make sure that both comparisons yield similar results to
4598 avoid comparing values that cannot be compared at
4599 compile-time. */
4600 cmp1 = compare_values_warnv (vr0->max, vr1->min, strict_overflow_p);
4601 cmp2 = compare_values_warnv (vr0->min, vr1->max, strict_overflow_p);
4602 if ((cmp1 == -1 && cmp2 == -1) || (cmp1 == 1 && cmp2 == 1))
4603 return boolean_true_node;
4605 /* If VR0 and VR1 represent a single value and are identical,
4606 return false. */
4607 else if (compare_values_warnv (vr0->min, vr0->max,
4608 strict_overflow_p) == 0
4609 && compare_values_warnv (vr1->min, vr1->max,
4610 strict_overflow_p) == 0
4611 && compare_values_warnv (vr0->min, vr1->min,
4612 strict_overflow_p) == 0
4613 && compare_values_warnv (vr0->max, vr1->max,
4614 strict_overflow_p) == 0)
4615 return boolean_false_node;
4617 /* Otherwise, they may or may not be different. */
4618 else
4619 return NULL_TREE;
4621 else if (comp == LT_EXPR || comp == LE_EXPR)
4623 int tst;
4625 /* If VR0 is to the left of VR1, return true. */
4626 tst = compare_values_warnv (vr0->max, vr1->min, strict_overflow_p);
4627 if ((comp == LT_EXPR && tst == -1)
4628 || (comp == LE_EXPR && (tst == -1 || tst == 0)))
4630 if (overflow_infinity_range_p (vr0)
4631 || overflow_infinity_range_p (vr1))
4632 *strict_overflow_p = true;
4633 return boolean_true_node;
4636 /* If VR0 is to the right of VR1, return false. */
4637 tst = compare_values_warnv (vr0->min, vr1->max, strict_overflow_p);
4638 if ((comp == LT_EXPR && (tst == 0 || tst == 1))
4639 || (comp == LE_EXPR && tst == 1))
4641 if (overflow_infinity_range_p (vr0)
4642 || overflow_infinity_range_p (vr1))
4643 *strict_overflow_p = true;
4644 return boolean_false_node;
4647 /* Otherwise, we don't know. */
4648 return NULL_TREE;
4651 gcc_unreachable ();
4655 /* Given a value range VR, a value VAL and a comparison code COMP, return
4656 BOOLEAN_TRUE_NODE if VR COMP VAL always returns true for all the
4657 values in VR. Return BOOLEAN_FALSE_NODE if the comparison
4658 always returns false. Return NULL_TREE if it is not always
4659 possible to determine the value of the comparison. Also set
4660 *STRICT_OVERFLOW_P to indicate whether a range with an overflow
4661 infinity was used in the test. */
4663 static tree
4664 compare_range_with_value (enum tree_code comp, value_range *vr, tree val,
4665 bool *strict_overflow_p)
4667 if (vr->type == VR_VARYING || vr->type == VR_UNDEFINED)
4668 return NULL_TREE;
4670 /* Anti-ranges need to be handled separately. */
4671 if (vr->type == VR_ANTI_RANGE)
4673 /* For anti-ranges, the only predicates that we can compute at
4674 compile time are equality and inequality. */
4675 if (comp == GT_EXPR
4676 || comp == GE_EXPR
4677 || comp == LT_EXPR
4678 || comp == LE_EXPR)
4679 return NULL_TREE;
4681 /* ~[VAL_1, VAL_2] OP VAL is known if VAL_1 <= VAL <= VAL_2. */
4682 if (value_inside_range (val, vr->min, vr->max) == 1)
4683 return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
4685 return NULL_TREE;
4688 if (!usable_range_p (vr, strict_overflow_p))
4689 return NULL_TREE;
4691 if (comp == EQ_EXPR)
4693 /* EQ_EXPR may only be computed if VR represents exactly
4694 one value. */
4695 if (compare_values_warnv (vr->min, vr->max, strict_overflow_p) == 0)
4697 int cmp = compare_values_warnv (vr->min, val, strict_overflow_p);
4698 if (cmp == 0)
4699 return boolean_true_node;
4700 else if (cmp == -1 || cmp == 1 || cmp == 2)
4701 return boolean_false_node;
4703 else if (compare_values_warnv (val, vr->min, strict_overflow_p) == -1
4704 || compare_values_warnv (vr->max, val, strict_overflow_p) == -1)
4705 return boolean_false_node;
4707 return NULL_TREE;
4709 else if (comp == NE_EXPR)
4711 /* If VAL is not inside VR, then they are always different. */
4712 if (compare_values_warnv (vr->max, val, strict_overflow_p) == -1
4713 || compare_values_warnv (vr->min, val, strict_overflow_p) == 1)
4714 return boolean_true_node;
4716 /* If VR represents exactly one value equal to VAL, then return
4717 false. */
4718 if (compare_values_warnv (vr->min, vr->max, strict_overflow_p) == 0
4719 && compare_values_warnv (vr->min, val, strict_overflow_p) == 0)
4720 return boolean_false_node;
4722 /* Otherwise, they may or may not be different. */
4723 return NULL_TREE;
4725 else if (comp == LT_EXPR || comp == LE_EXPR)
4727 int tst;
4729 /* If VR is to the left of VAL, return true. */
4730 tst = compare_values_warnv (vr->max, val, strict_overflow_p);
4731 if ((comp == LT_EXPR && tst == -1)
4732 || (comp == LE_EXPR && (tst == -1 || tst == 0)))
4734 if (overflow_infinity_range_p (vr))
4735 *strict_overflow_p = true;
4736 return boolean_true_node;
4739 /* If VR is to the right of VAL, return false. */
4740 tst = compare_values_warnv (vr->min, val, strict_overflow_p);
4741 if ((comp == LT_EXPR && (tst == 0 || tst == 1))
4742 || (comp == LE_EXPR && tst == 1))
4744 if (overflow_infinity_range_p (vr))
4745 *strict_overflow_p = true;
4746 return boolean_false_node;
4749 /* Otherwise, we don't know. */
4750 return NULL_TREE;
4752 else if (comp == GT_EXPR || comp == GE_EXPR)
4754 int tst;
4756 /* If VR is to the right of VAL, return true. */
4757 tst = compare_values_warnv (vr->min, val, strict_overflow_p);
4758 if ((comp == GT_EXPR && tst == 1)
4759 || (comp == GE_EXPR && (tst == 0 || tst == 1)))
4761 if (overflow_infinity_range_p (vr))
4762 *strict_overflow_p = true;
4763 return boolean_true_node;
4766 /* If VR is to the left of VAL, return false. */
4767 tst = compare_values_warnv (vr->max, val, strict_overflow_p);
4768 if ((comp == GT_EXPR && (tst == -1 || tst == 0))
4769 || (comp == GE_EXPR && tst == -1))
4771 if (overflow_infinity_range_p (vr))
4772 *strict_overflow_p = true;
4773 return boolean_false_node;
4776 /* Otherwise, we don't know. */
4777 return NULL_TREE;
4780 gcc_unreachable ();
4784 /* Debugging dumps. */
4786 void dump_value_range (FILE *, const value_range *);
4787 void debug_value_range (value_range *);
4788 void dump_all_value_ranges (FILE *);
4789 void debug_all_value_ranges (void);
4790 void dump_vr_equiv (FILE *, bitmap);
4791 void debug_vr_equiv (bitmap);
4794 /* Dump value range VR to FILE. */
4796 void
4797 dump_value_range (FILE *file, const value_range *vr)
4799 if (vr == NULL)
4800 fprintf (file, "[]");
4801 else if (vr->type == VR_UNDEFINED)
4802 fprintf (file, "UNDEFINED");
4803 else if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
4805 tree type = TREE_TYPE (vr->min);
4807 fprintf (file, "%s[", (vr->type == VR_ANTI_RANGE) ? "~" : "");
4809 if (is_negative_overflow_infinity (vr->min))
4810 fprintf (file, "-INF(OVF)");
4811 else if (INTEGRAL_TYPE_P (type)
4812 && !TYPE_UNSIGNED (type)
4813 && vrp_val_is_min (vr->min))
4814 fprintf (file, "-INF");
4815 else
4816 print_generic_expr (file, vr->min, 0);
4818 fprintf (file, ", ");
4820 if (is_positive_overflow_infinity (vr->max))
4821 fprintf (file, "+INF(OVF)");
4822 else if (INTEGRAL_TYPE_P (type)
4823 && vrp_val_is_max (vr->max))
4824 fprintf (file, "+INF");
4825 else
4826 print_generic_expr (file, vr->max, 0);
4828 fprintf (file, "]");
4830 if (vr->equiv)
4832 bitmap_iterator bi;
4833 unsigned i, c = 0;
4835 fprintf (file, " EQUIVALENCES: { ");
4837 EXECUTE_IF_SET_IN_BITMAP (vr->equiv, 0, i, bi)
4839 print_generic_expr (file, ssa_name (i), 0);
4840 fprintf (file, " ");
4841 c++;
4844 fprintf (file, "} (%u elements)", c);
4847 else if (vr->type == VR_VARYING)
4848 fprintf (file, "VARYING");
4849 else
4850 fprintf (file, "INVALID RANGE");
4854 /* Dump value range VR to stderr. */
4856 DEBUG_FUNCTION void
4857 debug_value_range (value_range *vr)
4859 dump_value_range (stderr, vr);
4860 fprintf (stderr, "\n");
4864 /* Dump value ranges of all SSA_NAMEs to FILE. */
4866 void
4867 dump_all_value_ranges (FILE *file)
4869 size_t i;
4871 for (i = 0; i < num_vr_values; i++)
4873 if (vr_value[i])
4875 print_generic_expr (file, ssa_name (i), 0);
4876 fprintf (file, ": ");
4877 dump_value_range (file, vr_value[i]);
4878 fprintf (file, "\n");
4882 fprintf (file, "\n");
4886 /* Dump all value ranges to stderr. */
4888 DEBUG_FUNCTION void
4889 debug_all_value_ranges (void)
4891 dump_all_value_ranges (stderr);
4895 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
4896 create a new SSA name N and return the assertion assignment
4897 'N = ASSERT_EXPR <V, V OP W>'. */
4899 static gimple *
4900 build_assert_expr_for (tree cond, tree v)
4902 tree a;
4903 gassign *assertion;
4905 gcc_assert (TREE_CODE (v) == SSA_NAME
4906 && COMPARISON_CLASS_P (cond));
4908 a = build2 (ASSERT_EXPR, TREE_TYPE (v), v, cond);
4909 assertion = gimple_build_assign (NULL_TREE, a);
4911 /* The new ASSERT_EXPR, creates a new SSA name that replaces the
4912 operand of the ASSERT_EXPR. Create it so the new name and the old one
4913 are registered in the replacement table so that we can fix the SSA web
4914 after adding all the ASSERT_EXPRs. */
4915 create_new_def_for (v, assertion, NULL);
4917 return assertion;
4921 /* Return false if EXPR is a predicate expression involving floating
4922 point values. */
4924 static inline bool
4925 fp_predicate (gimple *stmt)
4927 GIMPLE_CHECK (stmt, GIMPLE_COND);
4929 return FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)));
4932 /* If the range of values taken by OP can be inferred after STMT executes,
4933 return the comparison code (COMP_CODE_P) and value (VAL_P) that
4934 describes the inferred range. Return true if a range could be
4935 inferred. */
4937 static bool
4938 infer_value_range (gimple *stmt, tree op, tree_code *comp_code_p, tree *val_p)
4940 *val_p = NULL_TREE;
4941 *comp_code_p = ERROR_MARK;
4943 /* Do not attempt to infer anything in names that flow through
4944 abnormal edges. */
4945 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
4946 return false;
4948 /* If STMT is the last statement of a basic block with no normal
4949 successors, there is no point inferring anything about any of its
4950 operands. We would not be able to find a proper insertion point
4951 for the assertion, anyway. */
4952 if (stmt_ends_bb_p (stmt))
4954 edge_iterator ei;
4955 edge e;
4957 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
4958 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
4959 break;
4960 if (e == NULL)
4961 return false;
4964 if (infer_nonnull_range (stmt, op))
4966 *val_p = build_int_cst (TREE_TYPE (op), 0);
4967 *comp_code_p = NE_EXPR;
4968 return true;
4971 return false;
4975 void dump_asserts_for (FILE *, tree);
4976 void debug_asserts_for (tree);
4977 void dump_all_asserts (FILE *);
4978 void debug_all_asserts (void);
4980 /* Dump all the registered assertions for NAME to FILE. */
4982 void
4983 dump_asserts_for (FILE *file, tree name)
4985 assert_locus *loc;
4987 fprintf (file, "Assertions to be inserted for ");
4988 print_generic_expr (file, name, 0);
4989 fprintf (file, "\n");
4991 loc = asserts_for[SSA_NAME_VERSION (name)];
4992 while (loc)
4994 fprintf (file, "\t");
4995 print_gimple_stmt (file, gsi_stmt (loc->si), 0, 0);
4996 fprintf (file, "\n\tBB #%d", loc->bb->index);
4997 if (loc->e)
4999 fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
5000 loc->e->dest->index);
5001 dump_edge_info (file, loc->e, dump_flags, 0);
5003 fprintf (file, "\n\tPREDICATE: ");
5004 print_generic_expr (file, loc->expr, 0);
5005 fprintf (file, " %s ", get_tree_code_name (loc->comp_code));
5006 print_generic_expr (file, loc->val, 0);
5007 fprintf (file, "\n\n");
5008 loc = loc->next;
5011 fprintf (file, "\n");
5015 /* Dump all the registered assertions for NAME to stderr. */
5017 DEBUG_FUNCTION void
5018 debug_asserts_for (tree name)
5020 dump_asserts_for (stderr, name);
5024 /* Dump all the registered assertions for all the names to FILE. */
5026 void
5027 dump_all_asserts (FILE *file)
5029 unsigned i;
5030 bitmap_iterator bi;
5032 fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
5033 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
5034 dump_asserts_for (file, ssa_name (i));
5035 fprintf (file, "\n");
5039 /* Dump all the registered assertions for all the names to stderr. */
5041 DEBUG_FUNCTION void
5042 debug_all_asserts (void)
5044 dump_all_asserts (stderr);
5047 /* Push the assert info for NAME, EXPR, COMP_CODE and VAL to ASSERTS. */
5049 static void
5050 add_assert_info (vec<assert_info> &asserts,
5051 tree name, tree expr, enum tree_code comp_code, tree val)
5053 assert_info info;
5054 info.comp_code = comp_code;
5055 info.name = name;
5056 info.val = val;
5057 info.expr = expr;
5058 asserts.safe_push (info);
5061 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
5062 'EXPR COMP_CODE VAL' at a location that dominates block BB or
5063 E->DEST, then register this location as a possible insertion point
5064 for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
5066 BB, E and SI provide the exact insertion point for the new
5067 ASSERT_EXPR. If BB is NULL, then the ASSERT_EXPR is to be inserted
5068 on edge E. Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
5069 BB. If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
5070 must not be NULL. */
5072 static void
5073 register_new_assert_for (tree name, tree expr,
5074 enum tree_code comp_code,
5075 tree val,
5076 basic_block bb,
5077 edge e,
5078 gimple_stmt_iterator si)
5080 assert_locus *n, *loc, *last_loc;
5081 basic_block dest_bb;
5083 gcc_checking_assert (bb == NULL || e == NULL);
5085 if (e == NULL)
5086 gcc_checking_assert (gimple_code (gsi_stmt (si)) != GIMPLE_COND
5087 && gimple_code (gsi_stmt (si)) != GIMPLE_SWITCH);
5089 /* Never build an assert comparing against an integer constant with
5090 TREE_OVERFLOW set. This confuses our undefined overflow warning
5091 machinery. */
5092 if (TREE_OVERFLOW_P (val))
5093 val = drop_tree_overflow (val);
5095 /* The new assertion A will be inserted at BB or E. We need to
5096 determine if the new location is dominated by a previously
5097 registered location for A. If we are doing an edge insertion,
5098 assume that A will be inserted at E->DEST. Note that this is not
5099 necessarily true.
5101 If E is a critical edge, it will be split. But even if E is
5102 split, the new block will dominate the same set of blocks that
5103 E->DEST dominates.
5105 The reverse, however, is not true, blocks dominated by E->DEST
5106 will not be dominated by the new block created to split E. So,
5107 if the insertion location is on a critical edge, we will not use
5108 the new location to move another assertion previously registered
5109 at a block dominated by E->DEST. */
5110 dest_bb = (bb) ? bb : e->dest;
5112 /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
5113 VAL at a block dominating DEST_BB, then we don't need to insert a new
5114 one. Similarly, if the same assertion already exists at a block
5115 dominated by DEST_BB and the new location is not on a critical
5116 edge, then update the existing location for the assertion (i.e.,
5117 move the assertion up in the dominance tree).
5119 Note, this is implemented as a simple linked list because there
5120 should not be more than a handful of assertions registered per
5121 name. If this becomes a performance problem, a table hashed by
5122 COMP_CODE and VAL could be implemented. */
5123 loc = asserts_for[SSA_NAME_VERSION (name)];
5124 last_loc = loc;
5125 while (loc)
5127 if (loc->comp_code == comp_code
5128 && (loc->val == val
5129 || operand_equal_p (loc->val, val, 0))
5130 && (loc->expr == expr
5131 || operand_equal_p (loc->expr, expr, 0)))
5133 /* If E is not a critical edge and DEST_BB
5134 dominates the existing location for the assertion, move
5135 the assertion up in the dominance tree by updating its
5136 location information. */
5137 if ((e == NULL || !EDGE_CRITICAL_P (e))
5138 && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
5140 loc->bb = dest_bb;
5141 loc->e = e;
5142 loc->si = si;
5143 return;
5147 /* Update the last node of the list and move to the next one. */
5148 last_loc = loc;
5149 loc = loc->next;
5152 /* If we didn't find an assertion already registered for
5153 NAME COMP_CODE VAL, add a new one at the end of the list of
5154 assertions associated with NAME. */
5155 n = XNEW (struct assert_locus);
5156 n->bb = dest_bb;
5157 n->e = e;
5158 n->si = si;
5159 n->comp_code = comp_code;
5160 n->val = val;
5161 n->expr = expr;
5162 n->next = NULL;
5164 if (last_loc)
5165 last_loc->next = n;
5166 else
5167 asserts_for[SSA_NAME_VERSION (name)] = n;
5169 bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
5172 /* (COND_OP0 COND_CODE COND_OP1) is a predicate which uses NAME.
5173 Extract a suitable test code and value and store them into *CODE_P and
5174 *VAL_P so the predicate is normalized to NAME *CODE_P *VAL_P.
5176 If no extraction was possible, return FALSE, otherwise return TRUE.
5178 If INVERT is true, then we invert the result stored into *CODE_P. */
5180 static bool
5181 extract_code_and_val_from_cond_with_ops (tree name, enum tree_code cond_code,
5182 tree cond_op0, tree cond_op1,
5183 bool invert, enum tree_code *code_p,
5184 tree *val_p)
5186 enum tree_code comp_code;
5187 tree val;
5189 /* Otherwise, we have a comparison of the form NAME COMP VAL
5190 or VAL COMP NAME. */
5191 if (name == cond_op1)
5193 /* If the predicate is of the form VAL COMP NAME, flip
5194 COMP around because we need to register NAME as the
5195 first operand in the predicate. */
5196 comp_code = swap_tree_comparison (cond_code);
5197 val = cond_op0;
5199 else if (name == cond_op0)
5201 /* The comparison is of the form NAME COMP VAL, so the
5202 comparison code remains unchanged. */
5203 comp_code = cond_code;
5204 val = cond_op1;
5206 else
5207 gcc_unreachable ();
5209 /* Invert the comparison code as necessary. */
5210 if (invert)
5211 comp_code = invert_tree_comparison (comp_code, 0);
5213 /* VRP only handles integral and pointer types. */
5214 if (! INTEGRAL_TYPE_P (TREE_TYPE (val))
5215 && ! POINTER_TYPE_P (TREE_TYPE (val)))
5216 return false;
5218 /* Do not register always-false predicates.
5219 FIXME: this works around a limitation in fold() when dealing with
5220 enumerations. Given 'enum { N1, N2 } x;', fold will not
5221 fold 'if (x > N2)' to 'if (0)'. */
5222 if ((comp_code == GT_EXPR || comp_code == LT_EXPR)
5223 && INTEGRAL_TYPE_P (TREE_TYPE (val)))
5225 tree min = TYPE_MIN_VALUE (TREE_TYPE (val));
5226 tree max = TYPE_MAX_VALUE (TREE_TYPE (val));
5228 if (comp_code == GT_EXPR
5229 && (!max
5230 || compare_values (val, max) == 0))
5231 return false;
5233 if (comp_code == LT_EXPR
5234 && (!min
5235 || compare_values (val, min) == 0))
5236 return false;
5238 *code_p = comp_code;
5239 *val_p = val;
5240 return true;
5243 /* Find out smallest RES where RES > VAL && (RES & MASK) == RES, if any
5244 (otherwise return VAL). VAL and MASK must be zero-extended for
5245 precision PREC. If SGNBIT is non-zero, first xor VAL with SGNBIT
5246 (to transform signed values into unsigned) and at the end xor
5247 SGNBIT back. */
5249 static wide_int
5250 masked_increment (const wide_int &val_in, const wide_int &mask,
5251 const wide_int &sgnbit, unsigned int prec)
5253 wide_int bit = wi::one (prec), res;
5254 unsigned int i;
5256 wide_int val = val_in ^ sgnbit;
5257 for (i = 0; i < prec; i++, bit += bit)
5259 res = mask;
5260 if ((res & bit) == 0)
5261 continue;
5262 res = bit - 1;
5263 res = (val + bit).and_not (res);
5264 res &= mask;
5265 if (wi::gtu_p (res, val))
5266 return res ^ sgnbit;
5268 return val ^ sgnbit;
5271 /* Helper for overflow_comparison_p
5273 OP0 CODE OP1 is a comparison. Examine the comparison and potentially
5274 OP1's defining statement to see if it ultimately has the form
5275 OP0 CODE (OP0 PLUS INTEGER_CST)
5277 If so, return TRUE indicating this is an overflow test and store into
5278 *NEW_CST an updated constant that can be used in a narrowed range test.
5280 REVERSED indicates if the comparison was originally:
5282 OP1 CODE' OP0.
5284 This affects how we build the updated constant. */
5286 static bool
5287 overflow_comparison_p_1 (enum tree_code code, tree op0, tree op1,
5288 bool follow_assert_exprs, bool reversed, tree *new_cst)
5290 /* See if this is a relational operation between two SSA_NAMES with
5291 unsigned, overflow wrapping values. If so, check it more deeply. */
5292 if ((code == LT_EXPR || code == LE_EXPR
5293 || code == GE_EXPR || code == GT_EXPR)
5294 && TREE_CODE (op0) == SSA_NAME
5295 && TREE_CODE (op1) == SSA_NAME
5296 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
5297 && TYPE_UNSIGNED (TREE_TYPE (op0))
5298 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0)))
5300 gimple *op1_def = SSA_NAME_DEF_STMT (op1);
5302 /* If requested, follow any ASSERT_EXPRs backwards for OP1. */
5303 if (follow_assert_exprs)
5305 while (gimple_assign_single_p (op1_def)
5306 && TREE_CODE (gimple_assign_rhs1 (op1_def)) == ASSERT_EXPR)
5308 op1 = TREE_OPERAND (gimple_assign_rhs1 (op1_def), 0);
5309 if (TREE_CODE (op1) != SSA_NAME)
5310 break;
5311 op1_def = SSA_NAME_DEF_STMT (op1);
5315 /* Now look at the defining statement of OP1 to see if it adds
5316 or subtracts a nonzero constant from another operand. */
5317 if (op1_def
5318 && is_gimple_assign (op1_def)
5319 && gimple_assign_rhs_code (op1_def) == PLUS_EXPR
5320 && TREE_CODE (gimple_assign_rhs2 (op1_def)) == INTEGER_CST
5321 && !integer_zerop (gimple_assign_rhs2 (op1_def)))
5323 tree target = gimple_assign_rhs1 (op1_def);
5325 /* If requested, follow ASSERT_EXPRs backwards for op0 looking
5326 for one where TARGET appears on the RHS. */
5327 if (follow_assert_exprs)
5329 /* Now see if that "other operand" is op0, following the chain
5330 of ASSERT_EXPRs if necessary. */
5331 gimple *op0_def = SSA_NAME_DEF_STMT (op0);
5332 while (op0 != target
5333 && gimple_assign_single_p (op0_def)
5334 && TREE_CODE (gimple_assign_rhs1 (op0_def)) == ASSERT_EXPR)
5336 op0 = TREE_OPERAND (gimple_assign_rhs1 (op0_def), 0);
5337 if (TREE_CODE (op0) != SSA_NAME)
5338 break;
5339 op0_def = SSA_NAME_DEF_STMT (op0);
5343 /* If we did not find our target SSA_NAME, then this is not
5344 an overflow test. */
5345 if (op0 != target)
5346 return false;
5348 tree type = TREE_TYPE (op0);
5349 wide_int max = wi::max_value (TYPE_PRECISION (type), UNSIGNED);
5350 tree inc = gimple_assign_rhs2 (op1_def);
5351 if (reversed)
5352 *new_cst = wide_int_to_tree (type, max + inc);
5353 else
5354 *new_cst = wide_int_to_tree (type, max - inc);
5355 return true;
5358 return false;
5361 /* OP0 CODE OP1 is a comparison. Examine the comparison and potentially
5362 OP1's defining statement to see if it ultimately has the form
5363 OP0 CODE (OP0 PLUS INTEGER_CST)
5365 If so, return TRUE indicating this is an overflow test and store into
5366 *NEW_CST an updated constant that can be used in a narrowed range test.
5368 These statements are left as-is in the IL to facilitate discovery of
5369 {ADD,SUB}_OVERFLOW sequences later in the optimizer pipeline. But
5370 the alternate range representation is often useful within VRP. */
5372 static bool
5373 overflow_comparison_p (tree_code code, tree name, tree val,
5374 bool use_equiv_p, tree *new_cst)
5376 if (overflow_comparison_p_1 (code, name, val, use_equiv_p, false, new_cst))
5377 return true;
5378 return overflow_comparison_p_1 (swap_tree_comparison (code), val, name,
5379 use_equiv_p, true, new_cst);
5383 /* Try to register an edge assertion for SSA name NAME on edge E for
5384 the condition COND contributing to the conditional jump pointed to by BSI.
5385 Invert the condition COND if INVERT is true. */
5387 static void
5388 register_edge_assert_for_2 (tree name, edge e,
5389 enum tree_code cond_code,
5390 tree cond_op0, tree cond_op1, bool invert,
5391 vec<assert_info> &asserts)
5393 tree val;
5394 enum tree_code comp_code;
5396 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
5397 cond_op0,
5398 cond_op1,
5399 invert, &comp_code, &val))
5400 return;
5402 /* Queue the assert. */
5403 tree x;
5404 if (overflow_comparison_p (comp_code, name, val, false, &x))
5406 enum tree_code new_code = ((comp_code == GT_EXPR || comp_code == GE_EXPR)
5407 ? GT_EXPR : LE_EXPR);
5408 add_assert_info (asserts, name, name, new_code, x);
5410 add_assert_info (asserts, name, name, comp_code, val);
5412 /* In the case of NAME <= CST and NAME being defined as
5413 NAME = (unsigned) NAME2 + CST2 we can assert NAME2 >= -CST2
5414 and NAME2 <= CST - CST2. We can do the same for NAME > CST.
5415 This catches range and anti-range tests. */
5416 if ((comp_code == LE_EXPR
5417 || comp_code == GT_EXPR)
5418 && TREE_CODE (val) == INTEGER_CST
5419 && TYPE_UNSIGNED (TREE_TYPE (val)))
5421 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5422 tree cst2 = NULL_TREE, name2 = NULL_TREE, name3 = NULL_TREE;
5424 /* Extract CST2 from the (optional) addition. */
5425 if (is_gimple_assign (def_stmt)
5426 && gimple_assign_rhs_code (def_stmt) == PLUS_EXPR)
5428 name2 = gimple_assign_rhs1 (def_stmt);
5429 cst2 = gimple_assign_rhs2 (def_stmt);
5430 if (TREE_CODE (name2) == SSA_NAME
5431 && TREE_CODE (cst2) == INTEGER_CST)
5432 def_stmt = SSA_NAME_DEF_STMT (name2);
5435 /* Extract NAME2 from the (optional) sign-changing cast. */
5436 if (gimple_assign_cast_p (def_stmt))
5438 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt))
5439 && ! TYPE_UNSIGNED (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
5440 && (TYPE_PRECISION (gimple_expr_type (def_stmt))
5441 == TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))))
5442 name3 = gimple_assign_rhs1 (def_stmt);
5445 /* If name3 is used later, create an ASSERT_EXPR for it. */
5446 if (name3 != NULL_TREE
5447 && TREE_CODE (name3) == SSA_NAME
5448 && (cst2 == NULL_TREE
5449 || TREE_CODE (cst2) == INTEGER_CST)
5450 && INTEGRAL_TYPE_P (TREE_TYPE (name3)))
5452 tree tmp;
5454 /* Build an expression for the range test. */
5455 tmp = build1 (NOP_EXPR, TREE_TYPE (name), name3);
5456 if (cst2 != NULL_TREE)
5457 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
5459 if (dump_file)
5461 fprintf (dump_file, "Adding assert for ");
5462 print_generic_expr (dump_file, name3, 0);
5463 fprintf (dump_file, " from ");
5464 print_generic_expr (dump_file, tmp, 0);
5465 fprintf (dump_file, "\n");
5468 add_assert_info (asserts, name3, tmp, comp_code, val);
5471 /* If name2 is used later, create an ASSERT_EXPR for it. */
5472 if (name2 != NULL_TREE
5473 && TREE_CODE (name2) == SSA_NAME
5474 && TREE_CODE (cst2) == INTEGER_CST
5475 && INTEGRAL_TYPE_P (TREE_TYPE (name2)))
5477 tree tmp;
5479 /* Build an expression for the range test. */
5480 tmp = name2;
5481 if (TREE_TYPE (name) != TREE_TYPE (name2))
5482 tmp = build1 (NOP_EXPR, TREE_TYPE (name), tmp);
5483 if (cst2 != NULL_TREE)
5484 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
5486 if (dump_file)
5488 fprintf (dump_file, "Adding assert for ");
5489 print_generic_expr (dump_file, name2, 0);
5490 fprintf (dump_file, " from ");
5491 print_generic_expr (dump_file, tmp, 0);
5492 fprintf (dump_file, "\n");
5495 add_assert_info (asserts, name2, tmp, comp_code, val);
5499 /* In the case of post-in/decrement tests like if (i++) ... and uses
5500 of the in/decremented value on the edge the extra name we want to
5501 assert for is not on the def chain of the name compared. Instead
5502 it is in the set of use stmts.
5503 Similar cases happen for conversions that were simplified through
5504 fold_{sign_changed,widened}_comparison. */
5505 if ((comp_code == NE_EXPR
5506 || comp_code == EQ_EXPR)
5507 && TREE_CODE (val) == INTEGER_CST)
5509 imm_use_iterator ui;
5510 gimple *use_stmt;
5511 FOR_EACH_IMM_USE_STMT (use_stmt, ui, name)
5513 if (!is_gimple_assign (use_stmt))
5514 continue;
5516 /* Cut off to use-stmts that are dominating the predecessor. */
5517 if (!dominated_by_p (CDI_DOMINATORS, e->src, gimple_bb (use_stmt)))
5518 continue;
5520 tree name2 = gimple_assign_lhs (use_stmt);
5521 if (TREE_CODE (name2) != SSA_NAME)
5522 continue;
5524 enum tree_code code = gimple_assign_rhs_code (use_stmt);
5525 tree cst;
5526 if (code == PLUS_EXPR
5527 || code == MINUS_EXPR)
5529 cst = gimple_assign_rhs2 (use_stmt);
5530 if (TREE_CODE (cst) != INTEGER_CST)
5531 continue;
5532 cst = int_const_binop (code, val, cst);
5534 else if (CONVERT_EXPR_CODE_P (code))
5536 /* For truncating conversions we cannot record
5537 an inequality. */
5538 if (comp_code == NE_EXPR
5539 && (TYPE_PRECISION (TREE_TYPE (name2))
5540 < TYPE_PRECISION (TREE_TYPE (name))))
5541 continue;
5542 cst = fold_convert (TREE_TYPE (name2), val);
5544 else
5545 continue;
5547 if (TREE_OVERFLOW_P (cst))
5548 cst = drop_tree_overflow (cst);
5549 add_assert_info (asserts, name2, name2, comp_code, cst);
5553 if (TREE_CODE_CLASS (comp_code) == tcc_comparison
5554 && TREE_CODE (val) == INTEGER_CST)
5556 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5557 tree name2 = NULL_TREE, names[2], cst2 = NULL_TREE;
5558 tree val2 = NULL_TREE;
5559 unsigned int prec = TYPE_PRECISION (TREE_TYPE (val));
5560 wide_int mask = wi::zero (prec);
5561 unsigned int nprec = prec;
5562 enum tree_code rhs_code = ERROR_MARK;
5564 if (is_gimple_assign (def_stmt))
5565 rhs_code = gimple_assign_rhs_code (def_stmt);
5567 /* In the case of NAME != CST1 where NAME = A +- CST2 we can
5568 assert that A != CST1 -+ CST2. */
5569 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
5570 && (rhs_code == PLUS_EXPR || rhs_code == MINUS_EXPR))
5572 tree op0 = gimple_assign_rhs1 (def_stmt);
5573 tree op1 = gimple_assign_rhs2 (def_stmt);
5574 if (TREE_CODE (op0) == SSA_NAME
5575 && TREE_CODE (op1) == INTEGER_CST)
5577 enum tree_code reverse_op = (rhs_code == PLUS_EXPR
5578 ? MINUS_EXPR : PLUS_EXPR);
5579 op1 = int_const_binop (reverse_op, val, op1);
5580 if (TREE_OVERFLOW (op1))
5581 op1 = drop_tree_overflow (op1);
5582 add_assert_info (asserts, op0, op0, comp_code, op1);
5586 /* Add asserts for NAME cmp CST and NAME being defined
5587 as NAME = (int) NAME2. */
5588 if (!TYPE_UNSIGNED (TREE_TYPE (val))
5589 && (comp_code == LE_EXPR || comp_code == LT_EXPR
5590 || comp_code == GT_EXPR || comp_code == GE_EXPR)
5591 && gimple_assign_cast_p (def_stmt))
5593 name2 = gimple_assign_rhs1 (def_stmt);
5594 if (CONVERT_EXPR_CODE_P (rhs_code)
5595 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
5596 && TYPE_UNSIGNED (TREE_TYPE (name2))
5597 && prec == TYPE_PRECISION (TREE_TYPE (name2))
5598 && (comp_code == LE_EXPR || comp_code == GT_EXPR
5599 || !tree_int_cst_equal (val,
5600 TYPE_MIN_VALUE (TREE_TYPE (val)))))
5602 tree tmp, cst;
5603 enum tree_code new_comp_code = comp_code;
5605 cst = fold_convert (TREE_TYPE (name2),
5606 TYPE_MIN_VALUE (TREE_TYPE (val)));
5607 /* Build an expression for the range test. */
5608 tmp = build2 (PLUS_EXPR, TREE_TYPE (name2), name2, cst);
5609 cst = fold_build2 (PLUS_EXPR, TREE_TYPE (name2), cst,
5610 fold_convert (TREE_TYPE (name2), val));
5611 if (comp_code == LT_EXPR || comp_code == GE_EXPR)
5613 new_comp_code = comp_code == LT_EXPR ? LE_EXPR : GT_EXPR;
5614 cst = fold_build2 (MINUS_EXPR, TREE_TYPE (name2), cst,
5615 build_int_cst (TREE_TYPE (name2), 1));
5618 if (dump_file)
5620 fprintf (dump_file, "Adding assert for ");
5621 print_generic_expr (dump_file, name2, 0);
5622 fprintf (dump_file, " from ");
5623 print_generic_expr (dump_file, tmp, 0);
5624 fprintf (dump_file, "\n");
5627 add_assert_info (asserts, name2, tmp, new_comp_code, cst);
5631 /* Add asserts for NAME cmp CST and NAME being defined as
5632 NAME = NAME2 >> CST2.
5634 Extract CST2 from the right shift. */
5635 if (rhs_code == RSHIFT_EXPR)
5637 name2 = gimple_assign_rhs1 (def_stmt);
5638 cst2 = gimple_assign_rhs2 (def_stmt);
5639 if (TREE_CODE (name2) == SSA_NAME
5640 && tree_fits_uhwi_p (cst2)
5641 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
5642 && IN_RANGE (tree_to_uhwi (cst2), 1, prec - 1)
5643 && prec == GET_MODE_PRECISION (TYPE_MODE (TREE_TYPE (val))))
5645 mask = wi::mask (tree_to_uhwi (cst2), false, prec);
5646 val2 = fold_binary (LSHIFT_EXPR, TREE_TYPE (val), val, cst2);
5649 if (val2 != NULL_TREE
5650 && TREE_CODE (val2) == INTEGER_CST
5651 && simple_cst_equal (fold_build2 (RSHIFT_EXPR,
5652 TREE_TYPE (val),
5653 val2, cst2), val))
5655 enum tree_code new_comp_code = comp_code;
5656 tree tmp, new_val;
5658 tmp = name2;
5659 if (comp_code == EQ_EXPR || comp_code == NE_EXPR)
5661 if (!TYPE_UNSIGNED (TREE_TYPE (val)))
5663 tree type = build_nonstandard_integer_type (prec, 1);
5664 tmp = build1 (NOP_EXPR, type, name2);
5665 val2 = fold_convert (type, val2);
5667 tmp = fold_build2 (MINUS_EXPR, TREE_TYPE (tmp), tmp, val2);
5668 new_val = wide_int_to_tree (TREE_TYPE (tmp), mask);
5669 new_comp_code = comp_code == EQ_EXPR ? LE_EXPR : GT_EXPR;
5671 else if (comp_code == LT_EXPR || comp_code == GE_EXPR)
5673 wide_int minval
5674 = wi::min_value (prec, TYPE_SIGN (TREE_TYPE (val)));
5675 new_val = val2;
5676 if (minval == new_val)
5677 new_val = NULL_TREE;
5679 else
5681 wide_int maxval
5682 = wi::max_value (prec, TYPE_SIGN (TREE_TYPE (val)));
5683 mask |= val2;
5684 if (mask == maxval)
5685 new_val = NULL_TREE;
5686 else
5687 new_val = wide_int_to_tree (TREE_TYPE (val2), mask);
5690 if (new_val)
5692 if (dump_file)
5694 fprintf (dump_file, "Adding assert for ");
5695 print_generic_expr (dump_file, name2, 0);
5696 fprintf (dump_file, " from ");
5697 print_generic_expr (dump_file, tmp, 0);
5698 fprintf (dump_file, "\n");
5701 add_assert_info (asserts, name2, tmp, new_comp_code, new_val);
5705 /* Add asserts for NAME cmp CST and NAME being defined as
5706 NAME = NAME2 & CST2.
5708 Extract CST2 from the and.
5710 Also handle
5711 NAME = (unsigned) NAME2;
5712 casts where NAME's type is unsigned and has smaller precision
5713 than NAME2's type as if it was NAME = NAME2 & MASK. */
5714 names[0] = NULL_TREE;
5715 names[1] = NULL_TREE;
5716 cst2 = NULL_TREE;
5717 if (rhs_code == BIT_AND_EXPR
5718 || (CONVERT_EXPR_CODE_P (rhs_code)
5719 && INTEGRAL_TYPE_P (TREE_TYPE (val))
5720 && TYPE_UNSIGNED (TREE_TYPE (val))
5721 && TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
5722 > prec))
5724 name2 = gimple_assign_rhs1 (def_stmt);
5725 if (rhs_code == BIT_AND_EXPR)
5726 cst2 = gimple_assign_rhs2 (def_stmt);
5727 else
5729 cst2 = TYPE_MAX_VALUE (TREE_TYPE (val));
5730 nprec = TYPE_PRECISION (TREE_TYPE (name2));
5732 if (TREE_CODE (name2) == SSA_NAME
5733 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
5734 && TREE_CODE (cst2) == INTEGER_CST
5735 && !integer_zerop (cst2)
5736 && (nprec > 1
5737 || TYPE_UNSIGNED (TREE_TYPE (val))))
5739 gimple *def_stmt2 = SSA_NAME_DEF_STMT (name2);
5740 if (gimple_assign_cast_p (def_stmt2))
5742 names[1] = gimple_assign_rhs1 (def_stmt2);
5743 if (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt2))
5744 || !INTEGRAL_TYPE_P (TREE_TYPE (names[1]))
5745 || (TYPE_PRECISION (TREE_TYPE (name2))
5746 != TYPE_PRECISION (TREE_TYPE (names[1]))))
5747 names[1] = NULL_TREE;
5749 names[0] = name2;
5752 if (names[0] || names[1])
5754 wide_int minv, maxv, valv, cst2v;
5755 wide_int tem, sgnbit;
5756 bool valid_p = false, valn, cst2n;
5757 enum tree_code ccode = comp_code;
5759 valv = wide_int::from (val, nprec, UNSIGNED);
5760 cst2v = wide_int::from (cst2, nprec, UNSIGNED);
5761 valn = wi::neg_p (valv, TYPE_SIGN (TREE_TYPE (val)));
5762 cst2n = wi::neg_p (cst2v, TYPE_SIGN (TREE_TYPE (val)));
5763 /* If CST2 doesn't have most significant bit set,
5764 but VAL is negative, we have comparison like
5765 if ((x & 0x123) > -4) (always true). Just give up. */
5766 if (!cst2n && valn)
5767 ccode = ERROR_MARK;
5768 if (cst2n)
5769 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
5770 else
5771 sgnbit = wi::zero (nprec);
5772 minv = valv & cst2v;
5773 switch (ccode)
5775 case EQ_EXPR:
5776 /* Minimum unsigned value for equality is VAL & CST2
5777 (should be equal to VAL, otherwise we probably should
5778 have folded the comparison into false) and
5779 maximum unsigned value is VAL | ~CST2. */
5780 maxv = valv | ~cst2v;
5781 valid_p = true;
5782 break;
5784 case NE_EXPR:
5785 tem = valv | ~cst2v;
5786 /* If VAL is 0, handle (X & CST2) != 0 as (X & CST2) > 0U. */
5787 if (valv == 0)
5789 cst2n = false;
5790 sgnbit = wi::zero (nprec);
5791 goto gt_expr;
5793 /* If (VAL | ~CST2) is all ones, handle it as
5794 (X & CST2) < VAL. */
5795 if (tem == -1)
5797 cst2n = false;
5798 valn = false;
5799 sgnbit = wi::zero (nprec);
5800 goto lt_expr;
5802 if (!cst2n && wi::neg_p (cst2v))
5803 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
5804 if (sgnbit != 0)
5806 if (valv == sgnbit)
5808 cst2n = true;
5809 valn = true;
5810 goto gt_expr;
5812 if (tem == wi::mask (nprec - 1, false, nprec))
5814 cst2n = true;
5815 goto lt_expr;
5817 if (!cst2n)
5818 sgnbit = wi::zero (nprec);
5820 break;
5822 case GE_EXPR:
5823 /* Minimum unsigned value for >= if (VAL & CST2) == VAL
5824 is VAL and maximum unsigned value is ~0. For signed
5825 comparison, if CST2 doesn't have most significant bit
5826 set, handle it similarly. If CST2 has MSB set,
5827 the minimum is the same, and maximum is ~0U/2. */
5828 if (minv != valv)
5830 /* If (VAL & CST2) != VAL, X & CST2 can't be equal to
5831 VAL. */
5832 minv = masked_increment (valv, cst2v, sgnbit, nprec);
5833 if (minv == valv)
5834 break;
5836 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
5837 valid_p = true;
5838 break;
5840 case GT_EXPR:
5841 gt_expr:
5842 /* Find out smallest MINV where MINV > VAL
5843 && (MINV & CST2) == MINV, if any. If VAL is signed and
5844 CST2 has MSB set, compute it biased by 1 << (nprec - 1). */
5845 minv = masked_increment (valv, cst2v, sgnbit, nprec);
5846 if (minv == valv)
5847 break;
5848 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
5849 valid_p = true;
5850 break;
5852 case LE_EXPR:
5853 /* Minimum unsigned value for <= is 0 and maximum
5854 unsigned value is VAL | ~CST2 if (VAL & CST2) == VAL.
5855 Otherwise, find smallest VAL2 where VAL2 > VAL
5856 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
5857 as maximum.
5858 For signed comparison, if CST2 doesn't have most
5859 significant bit set, handle it similarly. If CST2 has
5860 MSB set, the maximum is the same and minimum is INT_MIN. */
5861 if (minv == valv)
5862 maxv = valv;
5863 else
5865 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
5866 if (maxv == valv)
5867 break;
5868 maxv -= 1;
5870 maxv |= ~cst2v;
5871 minv = sgnbit;
5872 valid_p = true;
5873 break;
5875 case LT_EXPR:
5876 lt_expr:
5877 /* Minimum unsigned value for < is 0 and maximum
5878 unsigned value is (VAL-1) | ~CST2 if (VAL & CST2) == VAL.
5879 Otherwise, find smallest VAL2 where VAL2 > VAL
5880 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
5881 as maximum.
5882 For signed comparison, if CST2 doesn't have most
5883 significant bit set, handle it similarly. If CST2 has
5884 MSB set, the maximum is the same and minimum is INT_MIN. */
5885 if (minv == valv)
5887 if (valv == sgnbit)
5888 break;
5889 maxv = valv;
5891 else
5893 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
5894 if (maxv == valv)
5895 break;
5897 maxv -= 1;
5898 maxv |= ~cst2v;
5899 minv = sgnbit;
5900 valid_p = true;
5901 break;
5903 default:
5904 break;
5906 if (valid_p
5907 && (maxv - minv) != -1)
5909 tree tmp, new_val, type;
5910 int i;
5912 for (i = 0; i < 2; i++)
5913 if (names[i])
5915 wide_int maxv2 = maxv;
5916 tmp = names[i];
5917 type = TREE_TYPE (names[i]);
5918 if (!TYPE_UNSIGNED (type))
5920 type = build_nonstandard_integer_type (nprec, 1);
5921 tmp = build1 (NOP_EXPR, type, names[i]);
5923 if (minv != 0)
5925 tmp = build2 (PLUS_EXPR, type, tmp,
5926 wide_int_to_tree (type, -minv));
5927 maxv2 = maxv - minv;
5929 new_val = wide_int_to_tree (type, maxv2);
5931 if (dump_file)
5933 fprintf (dump_file, "Adding assert for ");
5934 print_generic_expr (dump_file, names[i], 0);
5935 fprintf (dump_file, " from ");
5936 print_generic_expr (dump_file, tmp, 0);
5937 fprintf (dump_file, "\n");
5940 add_assert_info (asserts, names[i], tmp, LE_EXPR, new_val);
5947 /* OP is an operand of a truth value expression which is known to have
5948 a particular value. Register any asserts for OP and for any
5949 operands in OP's defining statement.
5951 If CODE is EQ_EXPR, then we want to register OP is zero (false),
5952 if CODE is NE_EXPR, then we want to register OP is nonzero (true). */
5954 static void
5955 register_edge_assert_for_1 (tree op, enum tree_code code,
5956 edge e, vec<assert_info> &asserts)
5958 gimple *op_def;
5959 tree val;
5960 enum tree_code rhs_code;
5962 /* We only care about SSA_NAMEs. */
5963 if (TREE_CODE (op) != SSA_NAME)
5964 return;
5966 /* We know that OP will have a zero or nonzero value. */
5967 val = build_int_cst (TREE_TYPE (op), 0);
5968 add_assert_info (asserts, op, op, code, val);
5970 /* Now look at how OP is set. If it's set from a comparison,
5971 a truth operation or some bit operations, then we may be able
5972 to register information about the operands of that assignment. */
5973 op_def = SSA_NAME_DEF_STMT (op);
5974 if (gimple_code (op_def) != GIMPLE_ASSIGN)
5975 return;
5977 rhs_code = gimple_assign_rhs_code (op_def);
5979 if (TREE_CODE_CLASS (rhs_code) == tcc_comparison)
5981 bool invert = (code == EQ_EXPR ? true : false);
5982 tree op0 = gimple_assign_rhs1 (op_def);
5983 tree op1 = gimple_assign_rhs2 (op_def);
5985 if (TREE_CODE (op0) == SSA_NAME)
5986 register_edge_assert_for_2 (op0, e, rhs_code, op0, op1, invert, asserts);
5987 if (TREE_CODE (op1) == SSA_NAME)
5988 register_edge_assert_for_2 (op1, e, rhs_code, op0, op1, invert, asserts);
5990 else if ((code == NE_EXPR
5991 && gimple_assign_rhs_code (op_def) == BIT_AND_EXPR)
5992 || (code == EQ_EXPR
5993 && gimple_assign_rhs_code (op_def) == BIT_IOR_EXPR))
5995 /* Recurse on each operand. */
5996 tree op0 = gimple_assign_rhs1 (op_def);
5997 tree op1 = gimple_assign_rhs2 (op_def);
5998 if (TREE_CODE (op0) == SSA_NAME
5999 && has_single_use (op0))
6000 register_edge_assert_for_1 (op0, code, e, asserts);
6001 if (TREE_CODE (op1) == SSA_NAME
6002 && has_single_use (op1))
6003 register_edge_assert_for_1 (op1, code, e, asserts);
6005 else if (gimple_assign_rhs_code (op_def) == BIT_NOT_EXPR
6006 && TYPE_PRECISION (TREE_TYPE (gimple_assign_lhs (op_def))) == 1)
6008 /* Recurse, flipping CODE. */
6009 code = invert_tree_comparison (code, false);
6010 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
6012 else if (gimple_assign_rhs_code (op_def) == SSA_NAME)
6014 /* Recurse through the copy. */
6015 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
6017 else if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (op_def)))
6019 /* Recurse through the type conversion, unless it is a narrowing
6020 conversion or conversion from non-integral type. */
6021 tree rhs = gimple_assign_rhs1 (op_def);
6022 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs))
6023 && (TYPE_PRECISION (TREE_TYPE (rhs))
6024 <= TYPE_PRECISION (TREE_TYPE (op))))
6025 register_edge_assert_for_1 (rhs, code, e, asserts);
6029 /* Try to register an edge assertion for SSA name NAME on edge E for
6030 the condition COND contributing to the conditional jump pointed to by
6031 SI. */
6033 static void
6034 register_edge_assert_for (tree name, edge e,
6035 enum tree_code cond_code, tree cond_op0,
6036 tree cond_op1, vec<assert_info> &asserts)
6038 tree val;
6039 enum tree_code comp_code;
6040 bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
6042 /* Do not attempt to infer anything in names that flow through
6043 abnormal edges. */
6044 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
6045 return;
6047 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
6048 cond_op0, cond_op1,
6049 is_else_edge,
6050 &comp_code, &val))
6051 return;
6053 /* Register ASSERT_EXPRs for name. */
6054 register_edge_assert_for_2 (name, e, cond_code, cond_op0,
6055 cond_op1, is_else_edge, asserts);
6058 /* If COND is effectively an equality test of an SSA_NAME against
6059 the value zero or one, then we may be able to assert values
6060 for SSA_NAMEs which flow into COND. */
6062 /* In the case of NAME == 1 or NAME != 0, for BIT_AND_EXPR defining
6063 statement of NAME we can assert both operands of the BIT_AND_EXPR
6064 have nonzero value. */
6065 if (((comp_code == EQ_EXPR && integer_onep (val))
6066 || (comp_code == NE_EXPR && integer_zerop (val))))
6068 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
6070 if (is_gimple_assign (def_stmt)
6071 && gimple_assign_rhs_code (def_stmt) == BIT_AND_EXPR)
6073 tree op0 = gimple_assign_rhs1 (def_stmt);
6074 tree op1 = gimple_assign_rhs2 (def_stmt);
6075 register_edge_assert_for_1 (op0, NE_EXPR, e, asserts);
6076 register_edge_assert_for_1 (op1, NE_EXPR, e, asserts);
6080 /* In the case of NAME == 0 or NAME != 1, for BIT_IOR_EXPR defining
6081 statement of NAME we can assert both operands of the BIT_IOR_EXPR
6082 have zero value. */
6083 if (((comp_code == EQ_EXPR && integer_zerop (val))
6084 || (comp_code == NE_EXPR && integer_onep (val))))
6086 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
6088 /* For BIT_IOR_EXPR only if NAME == 0 both operands have
6089 necessarily zero value, or if type-precision is one. */
6090 if (is_gimple_assign (def_stmt)
6091 && (gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR
6092 && (TYPE_PRECISION (TREE_TYPE (name)) == 1
6093 || comp_code == EQ_EXPR)))
6095 tree op0 = gimple_assign_rhs1 (def_stmt);
6096 tree op1 = gimple_assign_rhs2 (def_stmt);
6097 register_edge_assert_for_1 (op0, EQ_EXPR, e, asserts);
6098 register_edge_assert_for_1 (op1, EQ_EXPR, e, asserts);
6103 /* Finish found ASSERTS for E and register them at GSI. */
6105 static void
6106 finish_register_edge_assert_for (edge e, gimple_stmt_iterator gsi,
6107 vec<assert_info> &asserts)
6109 for (unsigned i = 0; i < asserts.length (); ++i)
6110 /* Only register an ASSERT_EXPR if NAME was found in the sub-graph
6111 reachable from E. */
6112 if (live_on_edge (e, asserts[i].name))
6113 register_new_assert_for (asserts[i].name, asserts[i].expr,
6114 asserts[i].comp_code, asserts[i].val,
6115 NULL, e, gsi);
6120 /* Determine whether the outgoing edges of BB should receive an
6121 ASSERT_EXPR for each of the operands of BB's LAST statement.
6122 The last statement of BB must be a COND_EXPR.
6124 If any of the sub-graphs rooted at BB have an interesting use of
6125 the predicate operands, an assert location node is added to the
6126 list of assertions for the corresponding operands. */
6128 static void
6129 find_conditional_asserts (basic_block bb, gcond *last)
6131 gimple_stmt_iterator bsi;
6132 tree op;
6133 edge_iterator ei;
6134 edge e;
6135 ssa_op_iter iter;
6137 bsi = gsi_for_stmt (last);
6139 /* Look for uses of the operands in each of the sub-graphs
6140 rooted at BB. We need to check each of the outgoing edges
6141 separately, so that we know what kind of ASSERT_EXPR to
6142 insert. */
6143 FOR_EACH_EDGE (e, ei, bb->succs)
6145 if (e->dest == bb)
6146 continue;
6148 /* Register the necessary assertions for each operand in the
6149 conditional predicate. */
6150 auto_vec<assert_info, 8> asserts;
6151 FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
6152 register_edge_assert_for (op, e,
6153 gimple_cond_code (last),
6154 gimple_cond_lhs (last),
6155 gimple_cond_rhs (last), asserts);
6156 finish_register_edge_assert_for (e, bsi, asserts);
6160 struct case_info
6162 tree expr;
6163 basic_block bb;
6166 /* Compare two case labels sorting first by the destination bb index
6167 and then by the case value. */
6169 static int
6170 compare_case_labels (const void *p1, const void *p2)
6172 const struct case_info *ci1 = (const struct case_info *) p1;
6173 const struct case_info *ci2 = (const struct case_info *) p2;
6174 int idx1 = ci1->bb->index;
6175 int idx2 = ci2->bb->index;
6177 if (idx1 < idx2)
6178 return -1;
6179 else if (idx1 == idx2)
6181 /* Make sure the default label is first in a group. */
6182 if (!CASE_LOW (ci1->expr))
6183 return -1;
6184 else if (!CASE_LOW (ci2->expr))
6185 return 1;
6186 else
6187 return tree_int_cst_compare (CASE_LOW (ci1->expr),
6188 CASE_LOW (ci2->expr));
6190 else
6191 return 1;
6194 /* Determine whether the outgoing edges of BB should receive an
6195 ASSERT_EXPR for each of the operands of BB's LAST statement.
6196 The last statement of BB must be a SWITCH_EXPR.
6198 If any of the sub-graphs rooted at BB have an interesting use of
6199 the predicate operands, an assert location node is added to the
6200 list of assertions for the corresponding operands. */
6202 static void
6203 find_switch_asserts (basic_block bb, gswitch *last)
6205 gimple_stmt_iterator bsi;
6206 tree op;
6207 edge e;
6208 struct case_info *ci;
6209 size_t n = gimple_switch_num_labels (last);
6210 #if GCC_VERSION >= 4000
6211 unsigned int idx;
6212 #else
6213 /* Work around GCC 3.4 bug (PR 37086). */
6214 volatile unsigned int idx;
6215 #endif
6217 bsi = gsi_for_stmt (last);
6218 op = gimple_switch_index (last);
6219 if (TREE_CODE (op) != SSA_NAME)
6220 return;
6222 /* Build a vector of case labels sorted by destination label. */
6223 ci = XNEWVEC (struct case_info, n);
6224 for (idx = 0; idx < n; ++idx)
6226 ci[idx].expr = gimple_switch_label (last, idx);
6227 ci[idx].bb = label_to_block (CASE_LABEL (ci[idx].expr));
6229 edge default_edge = find_edge (bb, ci[0].bb);
6230 qsort (ci, n, sizeof (struct case_info), compare_case_labels);
6232 for (idx = 0; idx < n; ++idx)
6234 tree min, max;
6235 tree cl = ci[idx].expr;
6236 basic_block cbb = ci[idx].bb;
6238 min = CASE_LOW (cl);
6239 max = CASE_HIGH (cl);
6241 /* If there are multiple case labels with the same destination
6242 we need to combine them to a single value range for the edge. */
6243 if (idx + 1 < n && cbb == ci[idx + 1].bb)
6245 /* Skip labels until the last of the group. */
6246 do {
6247 ++idx;
6248 } while (idx < n && cbb == ci[idx].bb);
6249 --idx;
6251 /* Pick up the maximum of the case label range. */
6252 if (CASE_HIGH (ci[idx].expr))
6253 max = CASE_HIGH (ci[idx].expr);
6254 else
6255 max = CASE_LOW (ci[idx].expr);
6258 /* Can't extract a useful assertion out of a range that includes the
6259 default label. */
6260 if (min == NULL_TREE)
6261 continue;
6263 /* Find the edge to register the assert expr on. */
6264 e = find_edge (bb, cbb);
6266 /* Register the necessary assertions for the operand in the
6267 SWITCH_EXPR. */
6268 auto_vec<assert_info, 8> asserts;
6269 register_edge_assert_for (op, e,
6270 max ? GE_EXPR : EQ_EXPR,
6271 op, fold_convert (TREE_TYPE (op), min),
6272 asserts);
6273 if (max)
6274 register_edge_assert_for (op, e, LE_EXPR, op,
6275 fold_convert (TREE_TYPE (op), max),
6276 asserts);
6277 finish_register_edge_assert_for (e, bsi, asserts);
6280 XDELETEVEC (ci);
6282 if (!live_on_edge (default_edge, op))
6283 return;
6285 /* Now register along the default label assertions that correspond to the
6286 anti-range of each label. */
6287 int insertion_limit = PARAM_VALUE (PARAM_MAX_VRP_SWITCH_ASSERTIONS);
6288 if (insertion_limit == 0)
6289 return;
6291 /* We can't do this if the default case shares a label with another case. */
6292 tree default_cl = gimple_switch_default_label (last);
6293 for (idx = 1; idx < n; idx++)
6295 tree min, max;
6296 tree cl = gimple_switch_label (last, idx);
6297 if (CASE_LABEL (cl) == CASE_LABEL (default_cl))
6298 continue;
6300 min = CASE_LOW (cl);
6301 max = CASE_HIGH (cl);
6303 /* Combine contiguous case ranges to reduce the number of assertions
6304 to insert. */
6305 for (idx = idx + 1; idx < n; idx++)
6307 tree next_min, next_max;
6308 tree next_cl = gimple_switch_label (last, idx);
6309 if (CASE_LABEL (next_cl) == CASE_LABEL (default_cl))
6310 break;
6312 next_min = CASE_LOW (next_cl);
6313 next_max = CASE_HIGH (next_cl);
6315 wide_int difference = wi::sub (next_min, max ? max : min);
6316 if (wi::eq_p (difference, 1))
6317 max = next_max ? next_max : next_min;
6318 else
6319 break;
6321 idx--;
6323 if (max == NULL_TREE)
6325 /* Register the assertion OP != MIN. */
6326 auto_vec<assert_info, 8> asserts;
6327 min = fold_convert (TREE_TYPE (op), min);
6328 register_edge_assert_for (op, default_edge, NE_EXPR, op, min,
6329 asserts);
6330 finish_register_edge_assert_for (default_edge, bsi, asserts);
6332 else
6334 /* Register the assertion (unsigned)OP - MIN > (MAX - MIN),
6335 which will give OP the anti-range ~[MIN,MAX]. */
6336 tree uop = fold_convert (unsigned_type_for (TREE_TYPE (op)), op);
6337 min = fold_convert (TREE_TYPE (uop), min);
6338 max = fold_convert (TREE_TYPE (uop), max);
6340 tree lhs = fold_build2 (MINUS_EXPR, TREE_TYPE (uop), uop, min);
6341 tree rhs = int_const_binop (MINUS_EXPR, max, min);
6342 register_new_assert_for (op, lhs, GT_EXPR, rhs,
6343 NULL, default_edge, bsi);
6346 if (--insertion_limit == 0)
6347 break;
6352 /* Traverse all the statements in block BB looking for statements that
6353 may generate useful assertions for the SSA names in their operand.
6354 If a statement produces a useful assertion A for name N_i, then the
6355 list of assertions already generated for N_i is scanned to
6356 determine if A is actually needed.
6358 If N_i already had the assertion A at a location dominating the
6359 current location, then nothing needs to be done. Otherwise, the
6360 new location for A is recorded instead.
6362 1- For every statement S in BB, all the variables used by S are
6363 added to bitmap FOUND_IN_SUBGRAPH.
6365 2- If statement S uses an operand N in a way that exposes a known
6366 value range for N, then if N was not already generated by an
6367 ASSERT_EXPR, create a new assert location for N. For instance,
6368 if N is a pointer and the statement dereferences it, we can
6369 assume that N is not NULL.
6371 3- COND_EXPRs are a special case of #2. We can derive range
6372 information from the predicate but need to insert different
6373 ASSERT_EXPRs for each of the sub-graphs rooted at the
6374 conditional block. If the last statement of BB is a conditional
6375 expression of the form 'X op Y', then
6377 a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
6379 b) If the conditional is the only entry point to the sub-graph
6380 corresponding to the THEN_CLAUSE, recurse into it. On
6381 return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
6382 an ASSERT_EXPR is added for the corresponding variable.
6384 c) Repeat step (b) on the ELSE_CLAUSE.
6386 d) Mark X and Y in FOUND_IN_SUBGRAPH.
6388 For instance,
6390 if (a == 9)
6391 b = a;
6392 else
6393 b = c + 1;
6395 In this case, an assertion on the THEN clause is useful to
6396 determine that 'a' is always 9 on that edge. However, an assertion
6397 on the ELSE clause would be unnecessary.
6399 4- If BB does not end in a conditional expression, then we recurse
6400 into BB's dominator children.
6402 At the end of the recursive traversal, every SSA name will have a
6403 list of locations where ASSERT_EXPRs should be added. When a new
6404 location for name N is found, it is registered by calling
6405 register_new_assert_for. That function keeps track of all the
6406 registered assertions to prevent adding unnecessary assertions.
6407 For instance, if a pointer P_4 is dereferenced more than once in a
6408 dominator tree, only the location dominating all the dereference of
6409 P_4 will receive an ASSERT_EXPR. */
6411 static void
6412 find_assert_locations_1 (basic_block bb, sbitmap live)
6414 gimple *last;
6416 last = last_stmt (bb);
6418 /* If BB's last statement is a conditional statement involving integer
6419 operands, determine if we need to add ASSERT_EXPRs. */
6420 if (last
6421 && gimple_code (last) == GIMPLE_COND
6422 && !fp_predicate (last)
6423 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
6424 find_conditional_asserts (bb, as_a <gcond *> (last));
6426 /* If BB's last statement is a switch statement involving integer
6427 operands, determine if we need to add ASSERT_EXPRs. */
6428 if (last
6429 && gimple_code (last) == GIMPLE_SWITCH
6430 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
6431 find_switch_asserts (bb, as_a <gswitch *> (last));
6433 /* Traverse all the statements in BB marking used names and looking
6434 for statements that may infer assertions for their used operands. */
6435 for (gimple_stmt_iterator si = gsi_last_bb (bb); !gsi_end_p (si);
6436 gsi_prev (&si))
6438 gimple *stmt;
6439 tree op;
6440 ssa_op_iter i;
6442 stmt = gsi_stmt (si);
6444 if (is_gimple_debug (stmt))
6445 continue;
6447 /* See if we can derive an assertion for any of STMT's operands. */
6448 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
6450 tree value;
6451 enum tree_code comp_code;
6453 /* If op is not live beyond this stmt, do not bother to insert
6454 asserts for it. */
6455 if (!bitmap_bit_p (live, SSA_NAME_VERSION (op)))
6456 continue;
6458 /* If OP is used in such a way that we can infer a value
6459 range for it, and we don't find a previous assertion for
6460 it, create a new assertion location node for OP. */
6461 if (infer_value_range (stmt, op, &comp_code, &value))
6463 /* If we are able to infer a nonzero value range for OP,
6464 then walk backwards through the use-def chain to see if OP
6465 was set via a typecast.
6467 If so, then we can also infer a nonzero value range
6468 for the operand of the NOP_EXPR. */
6469 if (comp_code == NE_EXPR && integer_zerop (value))
6471 tree t = op;
6472 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
6474 while (is_gimple_assign (def_stmt)
6475 && CONVERT_EXPR_CODE_P
6476 (gimple_assign_rhs_code (def_stmt))
6477 && TREE_CODE
6478 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
6479 && POINTER_TYPE_P
6480 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
6482 t = gimple_assign_rhs1 (def_stmt);
6483 def_stmt = SSA_NAME_DEF_STMT (t);
6485 /* Note we want to register the assert for the
6486 operand of the NOP_EXPR after SI, not after the
6487 conversion. */
6488 if (bitmap_bit_p (live, SSA_NAME_VERSION (t)))
6489 register_new_assert_for (t, t, comp_code, value,
6490 bb, NULL, si);
6494 register_new_assert_for (op, op, comp_code, value, bb, NULL, si);
6498 /* Update live. */
6499 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
6500 bitmap_set_bit (live, SSA_NAME_VERSION (op));
6501 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_DEF)
6502 bitmap_clear_bit (live, SSA_NAME_VERSION (op));
6505 /* Traverse all PHI nodes in BB, updating live. */
6506 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
6507 gsi_next (&si))
6509 use_operand_p arg_p;
6510 ssa_op_iter i;
6511 gphi *phi = si.phi ();
6512 tree res = gimple_phi_result (phi);
6514 if (virtual_operand_p (res))
6515 continue;
6517 FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
6519 tree arg = USE_FROM_PTR (arg_p);
6520 if (TREE_CODE (arg) == SSA_NAME)
6521 bitmap_set_bit (live, SSA_NAME_VERSION (arg));
6524 bitmap_clear_bit (live, SSA_NAME_VERSION (res));
6528 /* Do an RPO walk over the function computing SSA name liveness
6529 on-the-fly and deciding on assert expressions to insert. */
6531 static void
6532 find_assert_locations (void)
6534 int *rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
6535 int *bb_rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
6536 int *last_rpo = XCNEWVEC (int, last_basic_block_for_fn (cfun));
6537 int rpo_cnt, i;
6539 live = XCNEWVEC (sbitmap, last_basic_block_for_fn (cfun));
6540 rpo_cnt = pre_and_rev_post_order_compute (NULL, rpo, false);
6541 for (i = 0; i < rpo_cnt; ++i)
6542 bb_rpo[rpo[i]] = i;
6544 /* Pre-seed loop latch liveness from loop header PHI nodes. Due to
6545 the order we compute liveness and insert asserts we otherwise
6546 fail to insert asserts into the loop latch. */
6547 loop_p loop;
6548 FOR_EACH_LOOP (loop, 0)
6550 i = loop->latch->index;
6551 unsigned int j = single_succ_edge (loop->latch)->dest_idx;
6552 for (gphi_iterator gsi = gsi_start_phis (loop->header);
6553 !gsi_end_p (gsi); gsi_next (&gsi))
6555 gphi *phi = gsi.phi ();
6556 if (virtual_operand_p (gimple_phi_result (phi)))
6557 continue;
6558 tree arg = gimple_phi_arg_def (phi, j);
6559 if (TREE_CODE (arg) == SSA_NAME)
6561 if (live[i] == NULL)
6563 live[i] = sbitmap_alloc (num_ssa_names);
6564 bitmap_clear (live[i]);
6566 bitmap_set_bit (live[i], SSA_NAME_VERSION (arg));
6571 for (i = rpo_cnt - 1; i >= 0; --i)
6573 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, rpo[i]);
6574 edge e;
6575 edge_iterator ei;
6577 if (!live[rpo[i]])
6579 live[rpo[i]] = sbitmap_alloc (num_ssa_names);
6580 bitmap_clear (live[rpo[i]]);
6583 /* Process BB and update the live information with uses in
6584 this block. */
6585 find_assert_locations_1 (bb, live[rpo[i]]);
6587 /* Merge liveness into the predecessor blocks and free it. */
6588 if (!bitmap_empty_p (live[rpo[i]]))
6590 int pred_rpo = i;
6591 FOR_EACH_EDGE (e, ei, bb->preds)
6593 int pred = e->src->index;
6594 if ((e->flags & EDGE_DFS_BACK) || pred == ENTRY_BLOCK)
6595 continue;
6597 if (!live[pred])
6599 live[pred] = sbitmap_alloc (num_ssa_names);
6600 bitmap_clear (live[pred]);
6602 bitmap_ior (live[pred], live[pred], live[rpo[i]]);
6604 if (bb_rpo[pred] < pred_rpo)
6605 pred_rpo = bb_rpo[pred];
6608 /* Record the RPO number of the last visited block that needs
6609 live information from this block. */
6610 last_rpo[rpo[i]] = pred_rpo;
6612 else
6614 sbitmap_free (live[rpo[i]]);
6615 live[rpo[i]] = NULL;
6618 /* We can free all successors live bitmaps if all their
6619 predecessors have been visited already. */
6620 FOR_EACH_EDGE (e, ei, bb->succs)
6621 if (last_rpo[e->dest->index] == i
6622 && live[e->dest->index])
6624 sbitmap_free (live[e->dest->index]);
6625 live[e->dest->index] = NULL;
6629 XDELETEVEC (rpo);
6630 XDELETEVEC (bb_rpo);
6631 XDELETEVEC (last_rpo);
6632 for (i = 0; i < last_basic_block_for_fn (cfun); ++i)
6633 if (live[i])
6634 sbitmap_free (live[i]);
6635 XDELETEVEC (live);
6638 /* Create an ASSERT_EXPR for NAME and insert it in the location
6639 indicated by LOC. Return true if we made any edge insertions. */
6641 static bool
6642 process_assert_insertions_for (tree name, assert_locus *loc)
6644 /* Build the comparison expression NAME_i COMP_CODE VAL. */
6645 gimple *stmt;
6646 tree cond;
6647 gimple *assert_stmt;
6648 edge_iterator ei;
6649 edge e;
6651 /* If we have X <=> X do not insert an assert expr for that. */
6652 if (loc->expr == loc->val)
6653 return false;
6655 cond = build2 (loc->comp_code, boolean_type_node, loc->expr, loc->val);
6656 assert_stmt = build_assert_expr_for (cond, name);
6657 if (loc->e)
6659 /* We have been asked to insert the assertion on an edge. This
6660 is used only by COND_EXPR and SWITCH_EXPR assertions. */
6661 gcc_checking_assert (gimple_code (gsi_stmt (loc->si)) == GIMPLE_COND
6662 || (gimple_code (gsi_stmt (loc->si))
6663 == GIMPLE_SWITCH));
6665 gsi_insert_on_edge (loc->e, assert_stmt);
6666 return true;
6669 /* If the stmt iterator points at the end then this is an insertion
6670 at the beginning of a block. */
6671 if (gsi_end_p (loc->si))
6673 gimple_stmt_iterator si = gsi_after_labels (loc->bb);
6674 gsi_insert_before (&si, assert_stmt, GSI_SAME_STMT);
6675 return false;
6678 /* Otherwise, we can insert right after LOC->SI iff the
6679 statement must not be the last statement in the block. */
6680 stmt = gsi_stmt (loc->si);
6681 if (!stmt_ends_bb_p (stmt))
6683 gsi_insert_after (&loc->si, assert_stmt, GSI_SAME_STMT);
6684 return false;
6687 /* If STMT must be the last statement in BB, we can only insert new
6688 assertions on the non-abnormal edge out of BB. Note that since
6689 STMT is not control flow, there may only be one non-abnormal/eh edge
6690 out of BB. */
6691 FOR_EACH_EDGE (e, ei, loc->bb->succs)
6692 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
6694 gsi_insert_on_edge (e, assert_stmt);
6695 return true;
6698 gcc_unreachable ();
6701 /* Qsort helper for sorting assert locations. */
6703 static int
6704 compare_assert_loc (const void *pa, const void *pb)
6706 assert_locus * const a = *(assert_locus * const *)pa;
6707 assert_locus * const b = *(assert_locus * const *)pb;
6708 if (! a->e && b->e)
6709 return 1;
6710 else if (a->e && ! b->e)
6711 return -1;
6713 /* Sort after destination index. */
6714 if (! a->e && ! b->e)
6716 else if (a->e->dest->index > b->e->dest->index)
6717 return 1;
6718 else if (a->e->dest->index < b->e->dest->index)
6719 return -1;
6721 /* Sort after comp_code. */
6722 if (a->comp_code > b->comp_code)
6723 return 1;
6724 else if (a->comp_code < b->comp_code)
6725 return -1;
6727 /* Break the tie using hashing and source/bb index. */
6728 hashval_t ha = iterative_hash_expr (a->expr, iterative_hash_expr (a->val, 0));
6729 hashval_t hb = iterative_hash_expr (b->expr, iterative_hash_expr (b->val, 0));
6730 if (ha == hb)
6731 return (a->e && b->e
6732 ? a->e->src->index - b->e->src->index
6733 : a->bb->index - b->bb->index);
6734 return ha - hb;
6737 /* Process all the insertions registered for every name N_i registered
6738 in NEED_ASSERT_FOR. The list of assertions to be inserted are
6739 found in ASSERTS_FOR[i]. */
6741 static void
6742 process_assert_insertions (void)
6744 unsigned i;
6745 bitmap_iterator bi;
6746 bool update_edges_p = false;
6747 int num_asserts = 0;
6749 if (dump_file && (dump_flags & TDF_DETAILS))
6750 dump_all_asserts (dump_file);
6752 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
6754 assert_locus *loc = asserts_for[i];
6755 gcc_assert (loc);
6757 auto_vec<assert_locus *, 16> asserts;
6758 for (; loc; loc = loc->next)
6759 asserts.safe_push (loc);
6760 asserts.qsort (compare_assert_loc);
6762 /* Push down common asserts to successors and remove redundant ones. */
6763 unsigned ecnt = 0;
6764 assert_locus *common = NULL;
6765 unsigned commonj = 0;
6766 for (unsigned j = 0; j < asserts.length (); ++j)
6768 loc = asserts[j];
6769 if (! loc->e)
6770 common = NULL;
6771 else if (! common
6772 || loc->e->dest != common->e->dest
6773 || loc->comp_code != common->comp_code
6774 || ! operand_equal_p (loc->val, common->val, 0)
6775 || ! operand_equal_p (loc->expr, common->expr, 0))
6777 commonj = j;
6778 common = loc;
6779 ecnt = 1;
6781 else if (loc->e == asserts[j-1]->e)
6783 /* Remove duplicate asserts. */
6784 if (commonj == j - 1)
6786 commonj = j;
6787 common = loc;
6789 free (asserts[j-1]);
6790 asserts[j-1] = NULL;
6792 else
6794 ecnt++;
6795 if (EDGE_COUNT (common->e->dest->preds) == ecnt)
6797 /* We have the same assertion on all incoming edges of a BB.
6798 Insert it at the beginning of that block. */
6799 loc->bb = loc->e->dest;
6800 loc->e = NULL;
6801 loc->si = gsi_none ();
6802 common = NULL;
6803 /* Clear asserts commoned. */
6804 for (; commonj != j; ++commonj)
6805 if (asserts[commonj])
6807 free (asserts[commonj]);
6808 asserts[commonj] = NULL;
6814 for (unsigned j = 0; j < asserts.length (); ++j)
6816 loc = asserts[j];
6817 if (! loc)
6818 continue;
6819 update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
6820 num_asserts++;
6821 free (loc);
6825 if (update_edges_p)
6826 gsi_commit_edge_inserts ();
6828 statistics_counter_event (cfun, "Number of ASSERT_EXPR expressions inserted",
6829 num_asserts);
6833 /* Traverse the flowgraph looking for conditional jumps to insert range
6834 expressions. These range expressions are meant to provide information
6835 to optimizations that need to reason in terms of value ranges. They
6836 will not be expanded into RTL. For instance, given:
6838 x = ...
6839 y = ...
6840 if (x < y)
6841 y = x - 2;
6842 else
6843 x = y + 3;
6845 this pass will transform the code into:
6847 x = ...
6848 y = ...
6849 if (x < y)
6851 x = ASSERT_EXPR <x, x < y>
6852 y = x - 2
6854 else
6856 y = ASSERT_EXPR <y, x >= y>
6857 x = y + 3
6860 The idea is that once copy and constant propagation have run, other
6861 optimizations will be able to determine what ranges of values can 'x'
6862 take in different paths of the code, simply by checking the reaching
6863 definition of 'x'. */
6865 static void
6866 insert_range_assertions (void)
6868 need_assert_for = BITMAP_ALLOC (NULL);
6869 asserts_for = XCNEWVEC (assert_locus *, num_ssa_names);
6871 calculate_dominance_info (CDI_DOMINATORS);
6873 find_assert_locations ();
6874 if (!bitmap_empty_p (need_assert_for))
6876 process_assert_insertions ();
6877 update_ssa (TODO_update_ssa_no_phi);
6880 if (dump_file && (dump_flags & TDF_DETAILS))
6882 fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
6883 dump_function_to_file (current_function_decl, dump_file, dump_flags);
6886 free (asserts_for);
6887 BITMAP_FREE (need_assert_for);
6890 /* Checks one ARRAY_REF in REF, located at LOCUS. Ignores flexible arrays
6891 and "struct" hacks. If VRP can determine that the
6892 array subscript is a constant, check if it is outside valid
6893 range. If the array subscript is a RANGE, warn if it is
6894 non-overlapping with valid range.
6895 IGNORE_OFF_BY_ONE is true if the ARRAY_REF is inside a ADDR_EXPR. */
6897 static void
6898 check_array_ref (location_t location, tree ref, bool ignore_off_by_one)
6900 value_range *vr = NULL;
6901 tree low_sub, up_sub;
6902 tree low_bound, up_bound, up_bound_p1;
6904 if (TREE_NO_WARNING (ref))
6905 return;
6907 low_sub = up_sub = TREE_OPERAND (ref, 1);
6908 up_bound = array_ref_up_bound (ref);
6910 /* Can not check flexible arrays. */
6911 if (!up_bound
6912 || TREE_CODE (up_bound) != INTEGER_CST)
6913 return;
6915 /* Accesses to trailing arrays via pointers may access storage
6916 beyond the types array bounds. */
6917 if (warn_array_bounds < 2
6918 && array_at_struct_end_p (ref))
6919 return;
6921 low_bound = array_ref_low_bound (ref);
6922 up_bound_p1 = int_const_binop (PLUS_EXPR, up_bound,
6923 build_int_cst (TREE_TYPE (up_bound), 1));
6925 /* Empty array. */
6926 if (tree_int_cst_equal (low_bound, up_bound_p1))
6928 warning_at (location, OPT_Warray_bounds,
6929 "array subscript is above array bounds");
6930 TREE_NO_WARNING (ref) = 1;
6933 if (TREE_CODE (low_sub) == SSA_NAME)
6935 vr = get_value_range (low_sub);
6936 if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
6938 low_sub = vr->type == VR_RANGE ? vr->max : vr->min;
6939 up_sub = vr->type == VR_RANGE ? vr->min : vr->max;
6943 if (vr && vr->type == VR_ANTI_RANGE)
6945 if (TREE_CODE (up_sub) == INTEGER_CST
6946 && (ignore_off_by_one
6947 ? tree_int_cst_lt (up_bound, up_sub)
6948 : tree_int_cst_le (up_bound, up_sub))
6949 && TREE_CODE (low_sub) == INTEGER_CST
6950 && tree_int_cst_le (low_sub, low_bound))
6952 warning_at (location, OPT_Warray_bounds,
6953 "array subscript is outside array bounds");
6954 TREE_NO_WARNING (ref) = 1;
6957 else if (TREE_CODE (up_sub) == INTEGER_CST
6958 && (ignore_off_by_one
6959 ? !tree_int_cst_le (up_sub, up_bound_p1)
6960 : !tree_int_cst_le (up_sub, up_bound)))
6962 if (dump_file && (dump_flags & TDF_DETAILS))
6964 fprintf (dump_file, "Array bound warning for ");
6965 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
6966 fprintf (dump_file, "\n");
6968 warning_at (location, OPT_Warray_bounds,
6969 "array subscript is above array bounds");
6970 TREE_NO_WARNING (ref) = 1;
6972 else if (TREE_CODE (low_sub) == INTEGER_CST
6973 && tree_int_cst_lt (low_sub, low_bound))
6975 if (dump_file && (dump_flags & TDF_DETAILS))
6977 fprintf (dump_file, "Array bound warning for ");
6978 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
6979 fprintf (dump_file, "\n");
6981 warning_at (location, OPT_Warray_bounds,
6982 "array subscript is below array bounds");
6983 TREE_NO_WARNING (ref) = 1;
6987 /* Searches if the expr T, located at LOCATION computes
6988 address of an ARRAY_REF, and call check_array_ref on it. */
6990 static void
6991 search_for_addr_array (tree t, location_t location)
6993 /* Check each ARRAY_REFs in the reference chain. */
6996 if (TREE_CODE (t) == ARRAY_REF)
6997 check_array_ref (location, t, true /*ignore_off_by_one*/);
6999 t = TREE_OPERAND (t, 0);
7001 while (handled_component_p (t));
7003 if (TREE_CODE (t) == MEM_REF
7004 && TREE_CODE (TREE_OPERAND (t, 0)) == ADDR_EXPR
7005 && !TREE_NO_WARNING (t))
7007 tree tem = TREE_OPERAND (TREE_OPERAND (t, 0), 0);
7008 tree low_bound, up_bound, el_sz;
7009 offset_int idx;
7010 if (TREE_CODE (TREE_TYPE (tem)) != ARRAY_TYPE
7011 || TREE_CODE (TREE_TYPE (TREE_TYPE (tem))) == ARRAY_TYPE
7012 || !TYPE_DOMAIN (TREE_TYPE (tem)))
7013 return;
7015 low_bound = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
7016 up_bound = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
7017 el_sz = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (tem)));
7018 if (!low_bound
7019 || TREE_CODE (low_bound) != INTEGER_CST
7020 || !up_bound
7021 || TREE_CODE (up_bound) != INTEGER_CST
7022 || !el_sz
7023 || TREE_CODE (el_sz) != INTEGER_CST)
7024 return;
7026 idx = mem_ref_offset (t);
7027 idx = wi::sdiv_trunc (idx, wi::to_offset (el_sz));
7028 if (idx < 0)
7030 if (dump_file && (dump_flags & TDF_DETAILS))
7032 fprintf (dump_file, "Array bound warning for ");
7033 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
7034 fprintf (dump_file, "\n");
7036 warning_at (location, OPT_Warray_bounds,
7037 "array subscript is below array bounds");
7038 TREE_NO_WARNING (t) = 1;
7040 else if (idx > (wi::to_offset (up_bound)
7041 - wi::to_offset (low_bound) + 1))
7043 if (dump_file && (dump_flags & TDF_DETAILS))
7045 fprintf (dump_file, "Array bound warning for ");
7046 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
7047 fprintf (dump_file, "\n");
7049 warning_at (location, OPT_Warray_bounds,
7050 "array subscript is above array bounds");
7051 TREE_NO_WARNING (t) = 1;
7056 /* walk_tree() callback that checks if *TP is
7057 an ARRAY_REF inside an ADDR_EXPR (in which an array
7058 subscript one outside the valid range is allowed). Call
7059 check_array_ref for each ARRAY_REF found. The location is
7060 passed in DATA. */
7062 static tree
7063 check_array_bounds (tree *tp, int *walk_subtree, void *data)
7065 tree t = *tp;
7066 struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
7067 location_t location;
7069 if (EXPR_HAS_LOCATION (t))
7070 location = EXPR_LOCATION (t);
7071 else
7073 location_t *locp = (location_t *) wi->info;
7074 location = *locp;
7077 *walk_subtree = TRUE;
7079 if (TREE_CODE (t) == ARRAY_REF)
7080 check_array_ref (location, t, false /*ignore_off_by_one*/);
7082 else if (TREE_CODE (t) == ADDR_EXPR)
7084 search_for_addr_array (t, location);
7085 *walk_subtree = FALSE;
7088 return NULL_TREE;
7091 /* Walk over all statements of all reachable BBs and call check_array_bounds
7092 on them. */
7094 static void
7095 check_all_array_refs (void)
7097 basic_block bb;
7098 gimple_stmt_iterator si;
7100 FOR_EACH_BB_FN (bb, cfun)
7102 edge_iterator ei;
7103 edge e;
7104 bool executable = false;
7106 /* Skip blocks that were found to be unreachable. */
7107 FOR_EACH_EDGE (e, ei, bb->preds)
7108 executable |= !!(e->flags & EDGE_EXECUTABLE);
7109 if (!executable)
7110 continue;
7112 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
7114 gimple *stmt = gsi_stmt (si);
7115 struct walk_stmt_info wi;
7116 if (!gimple_has_location (stmt)
7117 || is_gimple_debug (stmt))
7118 continue;
7120 memset (&wi, 0, sizeof (wi));
7122 location_t loc = gimple_location (stmt);
7123 wi.info = &loc;
7125 walk_gimple_op (gsi_stmt (si),
7126 check_array_bounds,
7127 &wi);
7132 /* Return true if all imm uses of VAR are either in STMT, or
7133 feed (optionally through a chain of single imm uses) GIMPLE_COND
7134 in basic block COND_BB. */
7136 static bool
7137 all_imm_uses_in_stmt_or_feed_cond (tree var, gimple *stmt, basic_block cond_bb)
7139 use_operand_p use_p, use2_p;
7140 imm_use_iterator iter;
7142 FOR_EACH_IMM_USE_FAST (use_p, iter, var)
7143 if (USE_STMT (use_p) != stmt)
7145 gimple *use_stmt = USE_STMT (use_p), *use_stmt2;
7146 if (is_gimple_debug (use_stmt))
7147 continue;
7148 while (is_gimple_assign (use_stmt)
7149 && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
7150 && single_imm_use (gimple_assign_lhs (use_stmt),
7151 &use2_p, &use_stmt2))
7152 use_stmt = use_stmt2;
7153 if (gimple_code (use_stmt) != GIMPLE_COND
7154 || gimple_bb (use_stmt) != cond_bb)
7155 return false;
7157 return true;
7160 /* Handle
7161 _4 = x_3 & 31;
7162 if (_4 != 0)
7163 goto <bb 6>;
7164 else
7165 goto <bb 7>;
7166 <bb 6>:
7167 __builtin_unreachable ();
7168 <bb 7>:
7169 x_5 = ASSERT_EXPR <x_3, ...>;
7170 If x_3 has no other immediate uses (checked by caller),
7171 var is the x_3 var from ASSERT_EXPR, we can clear low 5 bits
7172 from the non-zero bitmask. */
7174 static void
7175 maybe_set_nonzero_bits (basic_block bb, tree var)
7177 edge e = single_pred_edge (bb);
7178 basic_block cond_bb = e->src;
7179 gimple *stmt = last_stmt (cond_bb);
7180 tree cst;
7182 if (stmt == NULL
7183 || gimple_code (stmt) != GIMPLE_COND
7184 || gimple_cond_code (stmt) != ((e->flags & EDGE_TRUE_VALUE)
7185 ? EQ_EXPR : NE_EXPR)
7186 || TREE_CODE (gimple_cond_lhs (stmt)) != SSA_NAME
7187 || !integer_zerop (gimple_cond_rhs (stmt)))
7188 return;
7190 stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt));
7191 if (!is_gimple_assign (stmt)
7192 || gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
7193 || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
7194 return;
7195 if (gimple_assign_rhs1 (stmt) != var)
7197 gimple *stmt2;
7199 if (TREE_CODE (gimple_assign_rhs1 (stmt)) != SSA_NAME)
7200 return;
7201 stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
7202 if (!gimple_assign_cast_p (stmt2)
7203 || gimple_assign_rhs1 (stmt2) != var
7204 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt2))
7205 || (TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (stmt)))
7206 != TYPE_PRECISION (TREE_TYPE (var))))
7207 return;
7209 cst = gimple_assign_rhs2 (stmt);
7210 set_nonzero_bits (var, wi::bit_and_not (get_nonzero_bits (var), cst));
7213 /* Convert range assertion expressions into the implied copies and
7214 copy propagate away the copies. Doing the trivial copy propagation
7215 here avoids the need to run the full copy propagation pass after
7216 VRP.
7218 FIXME, this will eventually lead to copy propagation removing the
7219 names that had useful range information attached to them. For
7220 instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
7221 then N_i will have the range [3, +INF].
7223 However, by converting the assertion into the implied copy
7224 operation N_i = N_j, we will then copy-propagate N_j into the uses
7225 of N_i and lose the range information. We may want to hold on to
7226 ASSERT_EXPRs a little while longer as the ranges could be used in
7227 things like jump threading.
7229 The problem with keeping ASSERT_EXPRs around is that passes after
7230 VRP need to handle them appropriately.
7232 Another approach would be to make the range information a first
7233 class property of the SSA_NAME so that it can be queried from
7234 any pass. This is made somewhat more complex by the need for
7235 multiple ranges to be associated with one SSA_NAME. */
7237 static void
7238 remove_range_assertions (void)
7240 basic_block bb;
7241 gimple_stmt_iterator si;
7242 /* 1 if looking at ASSERT_EXPRs immediately at the beginning of
7243 a basic block preceeded by GIMPLE_COND branching to it and
7244 __builtin_trap, -1 if not yet checked, 0 otherwise. */
7245 int is_unreachable;
7247 /* Note that the BSI iterator bump happens at the bottom of the
7248 loop and no bump is necessary if we're removing the statement
7249 referenced by the current BSI. */
7250 FOR_EACH_BB_FN (bb, cfun)
7251 for (si = gsi_after_labels (bb), is_unreachable = -1; !gsi_end_p (si);)
7253 gimple *stmt = gsi_stmt (si);
7255 if (is_gimple_assign (stmt)
7256 && gimple_assign_rhs_code (stmt) == ASSERT_EXPR)
7258 tree lhs = gimple_assign_lhs (stmt);
7259 tree rhs = gimple_assign_rhs1 (stmt);
7260 tree var;
7262 var = ASSERT_EXPR_VAR (rhs);
7264 if (TREE_CODE (var) == SSA_NAME
7265 && !POINTER_TYPE_P (TREE_TYPE (lhs))
7266 && SSA_NAME_RANGE_INFO (lhs))
7268 if (is_unreachable == -1)
7270 is_unreachable = 0;
7271 if (single_pred_p (bb)
7272 && assert_unreachable_fallthru_edge_p
7273 (single_pred_edge (bb)))
7274 is_unreachable = 1;
7276 /* Handle
7277 if (x_7 >= 10 && x_7 < 20)
7278 __builtin_unreachable ();
7279 x_8 = ASSERT_EXPR <x_7, ...>;
7280 if the only uses of x_7 are in the ASSERT_EXPR and
7281 in the condition. In that case, we can copy the
7282 range info from x_8 computed in this pass also
7283 for x_7. */
7284 if (is_unreachable
7285 && all_imm_uses_in_stmt_or_feed_cond (var, stmt,
7286 single_pred (bb)))
7288 set_range_info (var, SSA_NAME_RANGE_TYPE (lhs),
7289 SSA_NAME_RANGE_INFO (lhs)->get_min (),
7290 SSA_NAME_RANGE_INFO (lhs)->get_max ());
7291 maybe_set_nonzero_bits (bb, var);
7295 /* Propagate the RHS into every use of the LHS. For SSA names
7296 also propagate abnormals as it merely restores the original
7297 IL in this case (an replace_uses_by would assert). */
7298 if (TREE_CODE (var) == SSA_NAME)
7300 imm_use_iterator iter;
7301 use_operand_p use_p;
7302 gimple *use_stmt;
7303 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
7304 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
7305 SET_USE (use_p, var);
7307 else
7308 replace_uses_by (lhs, var);
7310 /* And finally, remove the copy, it is not needed. */
7311 gsi_remove (&si, true);
7312 release_defs (stmt);
7314 else
7316 if (!is_gimple_debug (gsi_stmt (si)))
7317 is_unreachable = 0;
7318 gsi_next (&si);
7324 /* Return true if STMT is interesting for VRP. */
7326 static bool
7327 stmt_interesting_for_vrp (gimple *stmt)
7329 if (gimple_code (stmt) == GIMPLE_PHI)
7331 tree res = gimple_phi_result (stmt);
7332 return (!virtual_operand_p (res)
7333 && (INTEGRAL_TYPE_P (TREE_TYPE (res))
7334 || POINTER_TYPE_P (TREE_TYPE (res))));
7336 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
7338 tree lhs = gimple_get_lhs (stmt);
7340 /* In general, assignments with virtual operands are not useful
7341 for deriving ranges, with the obvious exception of calls to
7342 builtin functions. */
7343 if (lhs && TREE_CODE (lhs) == SSA_NAME
7344 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
7345 || POINTER_TYPE_P (TREE_TYPE (lhs)))
7346 && (is_gimple_call (stmt)
7347 || !gimple_vuse (stmt)))
7348 return true;
7349 else if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
7350 switch (gimple_call_internal_fn (stmt))
7352 case IFN_ADD_OVERFLOW:
7353 case IFN_SUB_OVERFLOW:
7354 case IFN_MUL_OVERFLOW:
7355 case IFN_ATOMIC_COMPARE_EXCHANGE:
7356 /* These internal calls return _Complex integer type,
7357 but are interesting to VRP nevertheless. */
7358 if (lhs && TREE_CODE (lhs) == SSA_NAME)
7359 return true;
7360 break;
7361 default:
7362 break;
7365 else if (gimple_code (stmt) == GIMPLE_COND
7366 || gimple_code (stmt) == GIMPLE_SWITCH)
7367 return true;
7369 return false;
7372 /* Initialize VRP lattice. */
7374 static void
7375 vrp_initialize_lattice ()
7377 values_propagated = false;
7378 num_vr_values = num_ssa_names;
7379 vr_value = XCNEWVEC (value_range *, num_vr_values);
7380 vr_phi_edge_counts = XCNEWVEC (int, num_ssa_names);
7381 bitmap_obstack_initialize (&vrp_equiv_obstack);
7384 /* Initialization required by ssa_propagate engine. */
7386 static void
7387 vrp_initialize ()
7389 basic_block bb;
7391 FOR_EACH_BB_FN (bb, cfun)
7393 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
7394 gsi_next (&si))
7396 gphi *phi = si.phi ();
7397 if (!stmt_interesting_for_vrp (phi))
7399 tree lhs = PHI_RESULT (phi);
7400 set_value_range_to_varying (get_value_range (lhs));
7401 prop_set_simulate_again (phi, false);
7403 else
7404 prop_set_simulate_again (phi, true);
7407 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
7408 gsi_next (&si))
7410 gimple *stmt = gsi_stmt (si);
7412 /* If the statement is a control insn, then we do not
7413 want to avoid simulating the statement once. Failure
7414 to do so means that those edges will never get added. */
7415 if (stmt_ends_bb_p (stmt))
7416 prop_set_simulate_again (stmt, true);
7417 else if (!stmt_interesting_for_vrp (stmt))
7419 set_defs_to_varying (stmt);
7420 prop_set_simulate_again (stmt, false);
7422 else
7423 prop_set_simulate_again (stmt, true);
7428 /* Return the singleton value-range for NAME or NAME. */
7430 static inline tree
7431 vrp_valueize (tree name)
7433 if (TREE_CODE (name) == SSA_NAME)
7435 value_range *vr = get_value_range (name);
7436 if (vr->type == VR_RANGE
7437 && (TREE_CODE (vr->min) == SSA_NAME
7438 || is_gimple_min_invariant (vr->min))
7439 && vrp_operand_equal_p (vr->min, vr->max))
7440 return vr->min;
7442 return name;
7445 /* Return the singleton value-range for NAME if that is a constant
7446 but signal to not follow SSA edges. */
7448 static inline tree
7449 vrp_valueize_1 (tree name)
7451 if (TREE_CODE (name) == SSA_NAME)
7453 /* If the definition may be simulated again we cannot follow
7454 this SSA edge as the SSA propagator does not necessarily
7455 re-visit the use. */
7456 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
7457 if (!gimple_nop_p (def_stmt)
7458 && prop_simulate_again_p (def_stmt))
7459 return NULL_TREE;
7460 value_range *vr = get_value_range (name);
7461 if (range_int_cst_singleton_p (vr))
7462 return vr->min;
7464 return name;
7467 /* Visit assignment STMT. If it produces an interesting range, record
7468 the range in VR and set LHS to OUTPUT_P. */
7470 static void
7471 vrp_visit_assignment_or_call (gimple *stmt, tree *output_p, value_range *vr)
7473 tree lhs;
7474 enum gimple_code code = gimple_code (stmt);
7475 lhs = gimple_get_lhs (stmt);
7476 *output_p = NULL_TREE;
7478 /* We only keep track of ranges in integral and pointer types. */
7479 if (TREE_CODE (lhs) == SSA_NAME
7480 && ((INTEGRAL_TYPE_P (TREE_TYPE (lhs))
7481 /* It is valid to have NULL MIN/MAX values on a type. See
7482 build_range_type. */
7483 && TYPE_MIN_VALUE (TREE_TYPE (lhs))
7484 && TYPE_MAX_VALUE (TREE_TYPE (lhs)))
7485 || POINTER_TYPE_P (TREE_TYPE (lhs))))
7487 *output_p = lhs;
7489 /* Try folding the statement to a constant first. */
7490 tree tem = gimple_fold_stmt_to_constant_1 (stmt, vrp_valueize,
7491 vrp_valueize_1);
7492 if (tem)
7494 if (TREE_CODE (tem) == SSA_NAME
7495 && (SSA_NAME_IS_DEFAULT_DEF (tem)
7496 || ! prop_simulate_again_p (SSA_NAME_DEF_STMT (tem))))
7498 extract_range_from_ssa_name (vr, tem);
7499 return;
7501 else if (is_gimple_min_invariant (tem))
7503 set_value_range_to_value (vr, tem, NULL);
7504 return;
7507 /* Then dispatch to value-range extracting functions. */
7508 if (code == GIMPLE_CALL)
7509 extract_range_basic (vr, stmt);
7510 else
7511 extract_range_from_assignment (vr, as_a <gassign *> (stmt));
7515 /* Helper that gets the value range of the SSA_NAME with version I
7516 or a symbolic range containing the SSA_NAME only if the value range
7517 is varying or undefined. */
7519 static inline value_range
7520 get_vr_for_comparison (int i)
7522 value_range vr = *get_value_range (ssa_name (i));
7524 /* If name N_i does not have a valid range, use N_i as its own
7525 range. This allows us to compare against names that may
7526 have N_i in their ranges. */
7527 if (vr.type == VR_VARYING || vr.type == VR_UNDEFINED)
7529 vr.type = VR_RANGE;
7530 vr.min = ssa_name (i);
7531 vr.max = ssa_name (i);
7534 return vr;
7537 /* Compare all the value ranges for names equivalent to VAR with VAL
7538 using comparison code COMP. Return the same value returned by
7539 compare_range_with_value, including the setting of
7540 *STRICT_OVERFLOW_P. */
7542 static tree
7543 compare_name_with_value (enum tree_code comp, tree var, tree val,
7544 bool *strict_overflow_p, bool use_equiv_p)
7546 bitmap_iterator bi;
7547 unsigned i;
7548 bitmap e;
7549 tree retval, t;
7550 int used_strict_overflow;
7551 bool sop;
7552 value_range equiv_vr;
7554 /* Get the set of equivalences for VAR. */
7555 e = get_value_range (var)->equiv;
7557 /* Start at -1. Set it to 0 if we do a comparison without relying
7558 on overflow, or 1 if all comparisons rely on overflow. */
7559 used_strict_overflow = -1;
7561 /* Compare vars' value range with val. */
7562 equiv_vr = get_vr_for_comparison (SSA_NAME_VERSION (var));
7563 sop = false;
7564 retval = compare_range_with_value (comp, &equiv_vr, val, &sop);
7565 if (retval)
7566 used_strict_overflow = sop ? 1 : 0;
7568 /* If the equiv set is empty we have done all work we need to do. */
7569 if (e == NULL)
7571 if (retval
7572 && used_strict_overflow > 0)
7573 *strict_overflow_p = true;
7574 return retval;
7577 EXECUTE_IF_SET_IN_BITMAP (e, 0, i, bi)
7579 tree name = ssa_name (i);
7580 if (! name)
7581 continue;
7583 if (! use_equiv_p
7584 && ! SSA_NAME_IS_DEFAULT_DEF (name)
7585 && prop_simulate_again_p (SSA_NAME_DEF_STMT (name)))
7586 continue;
7588 equiv_vr = get_vr_for_comparison (i);
7589 sop = false;
7590 t = compare_range_with_value (comp, &equiv_vr, val, &sop);
7591 if (t)
7593 /* If we get different answers from different members
7594 of the equivalence set this check must be in a dead
7595 code region. Folding it to a trap representation
7596 would be correct here. For now just return don't-know. */
7597 if (retval != NULL
7598 && t != retval)
7600 retval = NULL_TREE;
7601 break;
7603 retval = t;
7605 if (!sop)
7606 used_strict_overflow = 0;
7607 else if (used_strict_overflow < 0)
7608 used_strict_overflow = 1;
7612 if (retval
7613 && used_strict_overflow > 0)
7614 *strict_overflow_p = true;
7616 return retval;
7620 /* Given a comparison code COMP and names N1 and N2, compare all the
7621 ranges equivalent to N1 against all the ranges equivalent to N2
7622 to determine the value of N1 COMP N2. Return the same value
7623 returned by compare_ranges. Set *STRICT_OVERFLOW_P to indicate
7624 whether we relied on an overflow infinity in the comparison. */
7627 static tree
7628 compare_names (enum tree_code comp, tree n1, tree n2,
7629 bool *strict_overflow_p)
7631 tree t, retval;
7632 bitmap e1, e2;
7633 bitmap_iterator bi1, bi2;
7634 unsigned i1, i2;
7635 int used_strict_overflow;
7636 static bitmap_obstack *s_obstack = NULL;
7637 static bitmap s_e1 = NULL, s_e2 = NULL;
7639 /* Compare the ranges of every name equivalent to N1 against the
7640 ranges of every name equivalent to N2. */
7641 e1 = get_value_range (n1)->equiv;
7642 e2 = get_value_range (n2)->equiv;
7644 /* Use the fake bitmaps if e1 or e2 are not available. */
7645 if (s_obstack == NULL)
7647 s_obstack = XNEW (bitmap_obstack);
7648 bitmap_obstack_initialize (s_obstack);
7649 s_e1 = BITMAP_ALLOC (s_obstack);
7650 s_e2 = BITMAP_ALLOC (s_obstack);
7652 if (e1 == NULL)
7653 e1 = s_e1;
7654 if (e2 == NULL)
7655 e2 = s_e2;
7657 /* Add N1 and N2 to their own set of equivalences to avoid
7658 duplicating the body of the loop just to check N1 and N2
7659 ranges. */
7660 bitmap_set_bit (e1, SSA_NAME_VERSION (n1));
7661 bitmap_set_bit (e2, SSA_NAME_VERSION (n2));
7663 /* If the equivalence sets have a common intersection, then the two
7664 names can be compared without checking their ranges. */
7665 if (bitmap_intersect_p (e1, e2))
7667 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7668 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7670 return (comp == EQ_EXPR || comp == GE_EXPR || comp == LE_EXPR)
7671 ? boolean_true_node
7672 : boolean_false_node;
7675 /* Start at -1. Set it to 0 if we do a comparison without relying
7676 on overflow, or 1 if all comparisons rely on overflow. */
7677 used_strict_overflow = -1;
7679 /* Otherwise, compare all the equivalent ranges. First, add N1 and
7680 N2 to their own set of equivalences to avoid duplicating the body
7681 of the loop just to check N1 and N2 ranges. */
7682 EXECUTE_IF_SET_IN_BITMAP (e1, 0, i1, bi1)
7684 if (! ssa_name (i1))
7685 continue;
7687 value_range vr1 = get_vr_for_comparison (i1);
7689 t = retval = NULL_TREE;
7690 EXECUTE_IF_SET_IN_BITMAP (e2, 0, i2, bi2)
7692 if (! ssa_name (i2))
7693 continue;
7695 bool sop = false;
7697 value_range vr2 = get_vr_for_comparison (i2);
7699 t = compare_ranges (comp, &vr1, &vr2, &sop);
7700 if (t)
7702 /* If we get different answers from different members
7703 of the equivalence set this check must be in a dead
7704 code region. Folding it to a trap representation
7705 would be correct here. For now just return don't-know. */
7706 if (retval != NULL
7707 && t != retval)
7709 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7710 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7711 return NULL_TREE;
7713 retval = t;
7715 if (!sop)
7716 used_strict_overflow = 0;
7717 else if (used_strict_overflow < 0)
7718 used_strict_overflow = 1;
7722 if (retval)
7724 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7725 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7726 if (used_strict_overflow > 0)
7727 *strict_overflow_p = true;
7728 return retval;
7732 /* None of the equivalent ranges are useful in computing this
7733 comparison. */
7734 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7735 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7736 return NULL_TREE;
7739 /* Helper function for vrp_evaluate_conditional_warnv & other
7740 optimizers. */
7742 static tree
7743 vrp_evaluate_conditional_warnv_with_ops_using_ranges (enum tree_code code,
7744 tree op0, tree op1,
7745 bool * strict_overflow_p)
7747 value_range *vr0, *vr1;
7749 vr0 = (TREE_CODE (op0) == SSA_NAME) ? get_value_range (op0) : NULL;
7750 vr1 = (TREE_CODE (op1) == SSA_NAME) ? get_value_range (op1) : NULL;
7752 tree res = NULL_TREE;
7753 if (vr0 && vr1)
7754 res = compare_ranges (code, vr0, vr1, strict_overflow_p);
7755 if (!res && vr0)
7756 res = compare_range_with_value (code, vr0, op1, strict_overflow_p);
7757 if (!res && vr1)
7758 res = (compare_range_with_value
7759 (swap_tree_comparison (code), vr1, op0, strict_overflow_p));
7760 return res;
7763 /* Helper function for vrp_evaluate_conditional_warnv. */
7765 static tree
7766 vrp_evaluate_conditional_warnv_with_ops (enum tree_code code, tree op0,
7767 tree op1, bool use_equiv_p,
7768 bool *strict_overflow_p, bool *only_ranges)
7770 tree ret;
7771 if (only_ranges)
7772 *only_ranges = true;
7774 /* We only deal with integral and pointer types. */
7775 if (!INTEGRAL_TYPE_P (TREE_TYPE (op0))
7776 && !POINTER_TYPE_P (TREE_TYPE (op0)))
7777 return NULL_TREE;
7779 /* If OP0 CODE OP1 is an overflow comparison, if it can be expressed
7780 as a simple equality test, then prefer that over its current form
7781 for evaluation.
7783 An overflow test which collapses to an equality test can always be
7784 expressed as a comparison of one argument against zero. Overflow
7785 occurs when the chosen argument is zero and does not occur if the
7786 chosen argument is not zero. */
7787 tree x;
7788 if (overflow_comparison_p (code, op0, op1, use_equiv_p, &x))
7790 wide_int max = wi::max_value (TYPE_PRECISION (TREE_TYPE (op0)), UNSIGNED);
7791 /* B = A - 1; if (A < B) -> B = A - 1; if (A == 0)
7792 B = A - 1; if (A > B) -> B = A - 1; if (A != 0)
7793 B = A + 1; if (B < A) -> B = A + 1; if (B == 0)
7794 B = A + 1; if (B > A) -> B = A + 1; if (B != 0) */
7795 if (integer_zerop (x))
7797 op1 = x;
7798 code = (code == LT_EXPR || code == LE_EXPR) ? EQ_EXPR : NE_EXPR;
7800 /* B = A + 1; if (A > B) -> B = A + 1; if (B == 0)
7801 B = A + 1; if (A < B) -> B = A + 1; if (B != 0)
7802 B = A - 1; if (B > A) -> B = A - 1; if (A == 0)
7803 B = A - 1; if (B < A) -> B = A - 1; if (A != 0) */
7804 else if (wi::eq_p (x, max - 1))
7806 op0 = op1;
7807 op1 = wide_int_to_tree (TREE_TYPE (op0), 0);
7808 code = (code == GT_EXPR || code == GE_EXPR) ? EQ_EXPR : NE_EXPR;
7812 if ((ret = vrp_evaluate_conditional_warnv_with_ops_using_ranges
7813 (code, op0, op1, strict_overflow_p)))
7814 return ret;
7815 if (only_ranges)
7816 *only_ranges = false;
7817 /* Do not use compare_names during propagation, it's quadratic. */
7818 if (TREE_CODE (op0) == SSA_NAME && TREE_CODE (op1) == SSA_NAME
7819 && use_equiv_p)
7820 return compare_names (code, op0, op1, strict_overflow_p);
7821 else if (TREE_CODE (op0) == SSA_NAME)
7822 return compare_name_with_value (code, op0, op1,
7823 strict_overflow_p, use_equiv_p);
7824 else if (TREE_CODE (op1) == SSA_NAME)
7825 return compare_name_with_value (swap_tree_comparison (code), op1, op0,
7826 strict_overflow_p, use_equiv_p);
7827 return NULL_TREE;
7830 /* Given (CODE OP0 OP1) within STMT, try to simplify it based on value range
7831 information. Return NULL if the conditional can not be evaluated.
7832 The ranges of all the names equivalent with the operands in COND
7833 will be used when trying to compute the value. If the result is
7834 based on undefined signed overflow, issue a warning if
7835 appropriate. */
7837 static tree
7838 vrp_evaluate_conditional (tree_code code, tree op0, tree op1, gimple *stmt)
7840 bool sop;
7841 tree ret;
7842 bool only_ranges;
7844 /* Some passes and foldings leak constants with overflow flag set
7845 into the IL. Avoid doing wrong things with these and bail out. */
7846 if ((TREE_CODE (op0) == INTEGER_CST
7847 && TREE_OVERFLOW (op0))
7848 || (TREE_CODE (op1) == INTEGER_CST
7849 && TREE_OVERFLOW (op1)))
7850 return NULL_TREE;
7852 sop = false;
7853 ret = vrp_evaluate_conditional_warnv_with_ops (code, op0, op1, true, &sop,
7854 &only_ranges);
7856 if (ret && sop)
7858 enum warn_strict_overflow_code wc;
7859 const char* warnmsg;
7861 if (is_gimple_min_invariant (ret))
7863 wc = WARN_STRICT_OVERFLOW_CONDITIONAL;
7864 warnmsg = G_("assuming signed overflow does not occur when "
7865 "simplifying conditional to constant");
7867 else
7869 wc = WARN_STRICT_OVERFLOW_COMPARISON;
7870 warnmsg = G_("assuming signed overflow does not occur when "
7871 "simplifying conditional");
7874 if (issue_strict_overflow_warning (wc))
7876 location_t location;
7878 if (!gimple_has_location (stmt))
7879 location = input_location;
7880 else
7881 location = gimple_location (stmt);
7882 warning_at (location, OPT_Wstrict_overflow, "%s", warnmsg);
7886 if (warn_type_limits
7887 && ret && only_ranges
7888 && TREE_CODE_CLASS (code) == tcc_comparison
7889 && TREE_CODE (op0) == SSA_NAME)
7891 /* If the comparison is being folded and the operand on the LHS
7892 is being compared against a constant value that is outside of
7893 the natural range of OP0's type, then the predicate will
7894 always fold regardless of the value of OP0. If -Wtype-limits
7895 was specified, emit a warning. */
7896 tree type = TREE_TYPE (op0);
7897 value_range *vr0 = get_value_range (op0);
7899 if (vr0->type == VR_RANGE
7900 && INTEGRAL_TYPE_P (type)
7901 && vrp_val_is_min (vr0->min)
7902 && vrp_val_is_max (vr0->max)
7903 && is_gimple_min_invariant (op1))
7905 location_t location;
7907 if (!gimple_has_location (stmt))
7908 location = input_location;
7909 else
7910 location = gimple_location (stmt);
7912 warning_at (location, OPT_Wtype_limits,
7913 integer_zerop (ret)
7914 ? G_("comparison always false "
7915 "due to limited range of data type")
7916 : G_("comparison always true "
7917 "due to limited range of data type"));
7921 return ret;
7925 /* Visit conditional statement STMT. If we can determine which edge
7926 will be taken out of STMT's basic block, record it in
7927 *TAKEN_EDGE_P. Otherwise, set *TAKEN_EDGE_P to NULL. */
7929 static void
7930 vrp_visit_cond_stmt (gcond *stmt, edge *taken_edge_p)
7932 tree val;
7933 bool sop;
7935 *taken_edge_p = NULL;
7937 if (dump_file && (dump_flags & TDF_DETAILS))
7939 tree use;
7940 ssa_op_iter i;
7942 fprintf (dump_file, "\nVisiting conditional with predicate: ");
7943 print_gimple_stmt (dump_file, stmt, 0, 0);
7944 fprintf (dump_file, "\nWith known ranges\n");
7946 FOR_EACH_SSA_TREE_OPERAND (use, stmt, i, SSA_OP_USE)
7948 fprintf (dump_file, "\t");
7949 print_generic_expr (dump_file, use, 0);
7950 fprintf (dump_file, ": ");
7951 dump_value_range (dump_file, vr_value[SSA_NAME_VERSION (use)]);
7954 fprintf (dump_file, "\n");
7957 /* Compute the value of the predicate COND by checking the known
7958 ranges of each of its operands.
7960 Note that we cannot evaluate all the equivalent ranges here
7961 because those ranges may not yet be final and with the current
7962 propagation strategy, we cannot determine when the value ranges
7963 of the names in the equivalence set have changed.
7965 For instance, given the following code fragment
7967 i_5 = PHI <8, i_13>
7969 i_14 = ASSERT_EXPR <i_5, i_5 != 0>
7970 if (i_14 == 1)
7973 Assume that on the first visit to i_14, i_5 has the temporary
7974 range [8, 8] because the second argument to the PHI function is
7975 not yet executable. We derive the range ~[0, 0] for i_14 and the
7976 equivalence set { i_5 }. So, when we visit 'if (i_14 == 1)' for
7977 the first time, since i_14 is equivalent to the range [8, 8], we
7978 determine that the predicate is always false.
7980 On the next round of propagation, i_13 is determined to be
7981 VARYING, which causes i_5 to drop down to VARYING. So, another
7982 visit to i_14 is scheduled. In this second visit, we compute the
7983 exact same range and equivalence set for i_14, namely ~[0, 0] and
7984 { i_5 }. But we did not have the previous range for i_5
7985 registered, so vrp_visit_assignment thinks that the range for
7986 i_14 has not changed. Therefore, the predicate 'if (i_14 == 1)'
7987 is not visited again, which stops propagation from visiting
7988 statements in the THEN clause of that if().
7990 To properly fix this we would need to keep the previous range
7991 value for the names in the equivalence set. This way we would've
7992 discovered that from one visit to the other i_5 changed from
7993 range [8, 8] to VR_VARYING.
7995 However, fixing this apparent limitation may not be worth the
7996 additional checking. Testing on several code bases (GCC, DLV,
7997 MICO, TRAMP3D and SPEC2000) showed that doing this results in
7998 4 more predicates folded in SPEC. */
7999 sop = false;
8001 val = vrp_evaluate_conditional_warnv_with_ops (gimple_cond_code (stmt),
8002 gimple_cond_lhs (stmt),
8003 gimple_cond_rhs (stmt),
8004 false, &sop, NULL);
8005 if (val)
8007 if (!sop)
8008 *taken_edge_p = find_taken_edge (gimple_bb (stmt), val);
8009 else
8011 if (dump_file && (dump_flags & TDF_DETAILS))
8012 fprintf (dump_file,
8013 "\nIgnoring predicate evaluation because "
8014 "it assumes that signed overflow is undefined");
8015 val = NULL_TREE;
8019 if (dump_file && (dump_flags & TDF_DETAILS))
8021 fprintf (dump_file, "\nPredicate evaluates to: ");
8022 if (val == NULL_TREE)
8023 fprintf (dump_file, "DON'T KNOW\n");
8024 else
8025 print_generic_stmt (dump_file, val, 0);
8029 /* Searches the case label vector VEC for the index *IDX of the CASE_LABEL
8030 that includes the value VAL. The search is restricted to the range
8031 [START_IDX, n - 1] where n is the size of VEC.
8033 If there is a CASE_LABEL for VAL, its index is placed in IDX and true is
8034 returned.
8036 If there is no CASE_LABEL for VAL and there is one that is larger than VAL,
8037 it is placed in IDX and false is returned.
8039 If VAL is larger than any CASE_LABEL, n is placed on IDX and false is
8040 returned. */
8042 static bool
8043 find_case_label_index (gswitch *stmt, size_t start_idx, tree val, size_t *idx)
8045 size_t n = gimple_switch_num_labels (stmt);
8046 size_t low, high;
8048 /* Find case label for minimum of the value range or the next one.
8049 At each iteration we are searching in [low, high - 1]. */
8051 for (low = start_idx, high = n; high != low; )
8053 tree t;
8054 int cmp;
8055 /* Note that i != high, so we never ask for n. */
8056 size_t i = (high + low) / 2;
8057 t = gimple_switch_label (stmt, i);
8059 /* Cache the result of comparing CASE_LOW and val. */
8060 cmp = tree_int_cst_compare (CASE_LOW (t), val);
8062 if (cmp == 0)
8064 /* Ranges cannot be empty. */
8065 *idx = i;
8066 return true;
8068 else if (cmp > 0)
8069 high = i;
8070 else
8072 low = i + 1;
8073 if (CASE_HIGH (t) != NULL
8074 && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
8076 *idx = i;
8077 return true;
8082 *idx = high;
8083 return false;
8086 /* Searches the case label vector VEC for the range of CASE_LABELs that is used
8087 for values between MIN and MAX. The first index is placed in MIN_IDX. The
8088 last index is placed in MAX_IDX. If the range of CASE_LABELs is empty
8089 then MAX_IDX < MIN_IDX.
8090 Returns true if the default label is not needed. */
8092 static bool
8093 find_case_label_range (gswitch *stmt, tree min, tree max, size_t *min_idx,
8094 size_t *max_idx)
8096 size_t i, j;
8097 bool min_take_default = !find_case_label_index (stmt, 1, min, &i);
8098 bool max_take_default = !find_case_label_index (stmt, i, max, &j);
8100 if (i == j
8101 && min_take_default
8102 && max_take_default)
8104 /* Only the default case label reached.
8105 Return an empty range. */
8106 *min_idx = 1;
8107 *max_idx = 0;
8108 return false;
8110 else
8112 bool take_default = min_take_default || max_take_default;
8113 tree low, high;
8114 size_t k;
8116 if (max_take_default)
8117 j--;
8119 /* If the case label range is continuous, we do not need
8120 the default case label. Verify that. */
8121 high = CASE_LOW (gimple_switch_label (stmt, i));
8122 if (CASE_HIGH (gimple_switch_label (stmt, i)))
8123 high = CASE_HIGH (gimple_switch_label (stmt, i));
8124 for (k = i + 1; k <= j; ++k)
8126 low = CASE_LOW (gimple_switch_label (stmt, k));
8127 if (!integer_onep (int_const_binop (MINUS_EXPR, low, high)))
8129 take_default = true;
8130 break;
8132 high = low;
8133 if (CASE_HIGH (gimple_switch_label (stmt, k)))
8134 high = CASE_HIGH (gimple_switch_label (stmt, k));
8137 *min_idx = i;
8138 *max_idx = j;
8139 return !take_default;
8143 /* Searches the case label vector VEC for the ranges of CASE_LABELs that are
8144 used in range VR. The indices are placed in MIN_IDX1, MAX_IDX, MIN_IDX2 and
8145 MAX_IDX2. If the ranges of CASE_LABELs are empty then MAX_IDX1 < MIN_IDX1.
8146 Returns true if the default label is not needed. */
8148 static bool
8149 find_case_label_ranges (gswitch *stmt, value_range *vr, size_t *min_idx1,
8150 size_t *max_idx1, size_t *min_idx2,
8151 size_t *max_idx2)
8153 size_t i, j, k, l;
8154 unsigned int n = gimple_switch_num_labels (stmt);
8155 bool take_default;
8156 tree case_low, case_high;
8157 tree min = vr->min, max = vr->max;
8159 gcc_checking_assert (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE);
8161 take_default = !find_case_label_range (stmt, min, max, &i, &j);
8163 /* Set second range to emtpy. */
8164 *min_idx2 = 1;
8165 *max_idx2 = 0;
8167 if (vr->type == VR_RANGE)
8169 *min_idx1 = i;
8170 *max_idx1 = j;
8171 return !take_default;
8174 /* Set first range to all case labels. */
8175 *min_idx1 = 1;
8176 *max_idx1 = n - 1;
8178 if (i > j)
8179 return false;
8181 /* Make sure all the values of case labels [i , j] are contained in
8182 range [MIN, MAX]. */
8183 case_low = CASE_LOW (gimple_switch_label (stmt, i));
8184 case_high = CASE_HIGH (gimple_switch_label (stmt, j));
8185 if (tree_int_cst_compare (case_low, min) < 0)
8186 i += 1;
8187 if (case_high != NULL_TREE
8188 && tree_int_cst_compare (max, case_high) < 0)
8189 j -= 1;
8191 if (i > j)
8192 return false;
8194 /* If the range spans case labels [i, j], the corresponding anti-range spans
8195 the labels [1, i - 1] and [j + 1, n - 1]. */
8196 k = j + 1;
8197 l = n - 1;
8198 if (k > l)
8200 k = 1;
8201 l = 0;
8204 j = i - 1;
8205 i = 1;
8206 if (i > j)
8208 i = k;
8209 j = l;
8210 k = 1;
8211 l = 0;
8214 *min_idx1 = i;
8215 *max_idx1 = j;
8216 *min_idx2 = k;
8217 *max_idx2 = l;
8218 return false;
8221 /* Visit switch statement STMT. If we can determine which edge
8222 will be taken out of STMT's basic block, record it in
8223 *TAKEN_EDGE_P. Otherwise, *TAKEN_EDGE_P set to NULL. */
8225 static void
8226 vrp_visit_switch_stmt (gswitch *stmt, edge *taken_edge_p)
8228 tree op, val;
8229 value_range *vr;
8230 size_t i = 0, j = 0, k, l;
8231 bool take_default;
8233 *taken_edge_p = NULL;
8234 op = gimple_switch_index (stmt);
8235 if (TREE_CODE (op) != SSA_NAME)
8236 return;
8238 vr = get_value_range (op);
8239 if (dump_file && (dump_flags & TDF_DETAILS))
8241 fprintf (dump_file, "\nVisiting switch expression with operand ");
8242 print_generic_expr (dump_file, op, 0);
8243 fprintf (dump_file, " with known range ");
8244 dump_value_range (dump_file, vr);
8245 fprintf (dump_file, "\n");
8248 if ((vr->type != VR_RANGE
8249 && vr->type != VR_ANTI_RANGE)
8250 || symbolic_range_p (vr))
8251 return;
8253 /* Find the single edge that is taken from the switch expression. */
8254 take_default = !find_case_label_ranges (stmt, vr, &i, &j, &k, &l);
8256 /* Check if the range spans no CASE_LABEL. If so, we only reach the default
8257 label */
8258 if (j < i)
8260 gcc_assert (take_default);
8261 val = gimple_switch_default_label (stmt);
8263 else
8265 /* Check if labels with index i to j and maybe the default label
8266 are all reaching the same label. */
8268 val = gimple_switch_label (stmt, i);
8269 if (take_default
8270 && CASE_LABEL (gimple_switch_default_label (stmt))
8271 != CASE_LABEL (val))
8273 if (dump_file && (dump_flags & TDF_DETAILS))
8274 fprintf (dump_file, " not a single destination for this "
8275 "range\n");
8276 return;
8278 for (++i; i <= j; ++i)
8280 if (CASE_LABEL (gimple_switch_label (stmt, i)) != CASE_LABEL (val))
8282 if (dump_file && (dump_flags & TDF_DETAILS))
8283 fprintf (dump_file, " not a single destination for this "
8284 "range\n");
8285 return;
8288 for (; k <= l; ++k)
8290 if (CASE_LABEL (gimple_switch_label (stmt, k)) != CASE_LABEL (val))
8292 if (dump_file && (dump_flags & TDF_DETAILS))
8293 fprintf (dump_file, " not a single destination for this "
8294 "range\n");
8295 return;
8300 *taken_edge_p = find_edge (gimple_bb (stmt),
8301 label_to_block (CASE_LABEL (val)));
8303 if (dump_file && (dump_flags & TDF_DETAILS))
8305 fprintf (dump_file, " will take edge to ");
8306 print_generic_stmt (dump_file, CASE_LABEL (val), 0);
8311 /* Evaluate statement STMT. If the statement produces a useful range,
8312 set VR and corepsponding OUTPUT_P.
8314 If STMT is a conditional branch and we can determine its truth
8315 value, the taken edge is recorded in *TAKEN_EDGE_P. */
8317 static void
8318 extract_range_from_stmt (gimple *stmt, edge *taken_edge_p,
8319 tree *output_p, value_range *vr)
8322 if (dump_file && (dump_flags & TDF_DETAILS))
8324 fprintf (dump_file, "\nVisiting statement:\n");
8325 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
8328 if (!stmt_interesting_for_vrp (stmt))
8329 gcc_assert (stmt_ends_bb_p (stmt));
8330 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
8331 vrp_visit_assignment_or_call (stmt, output_p, vr);
8332 else if (gimple_code (stmt) == GIMPLE_COND)
8333 vrp_visit_cond_stmt (as_a <gcond *> (stmt), taken_edge_p);
8334 else if (gimple_code (stmt) == GIMPLE_SWITCH)
8335 vrp_visit_switch_stmt (as_a <gswitch *> (stmt), taken_edge_p);
8338 /* Evaluate statement STMT. If the statement produces a useful range,
8339 return SSA_PROP_INTERESTING and record the SSA name with the
8340 interesting range into *OUTPUT_P.
8342 If STMT is a conditional branch and we can determine its truth
8343 value, the taken edge is recorded in *TAKEN_EDGE_P.
8345 If STMT produces a varying value, return SSA_PROP_VARYING. */
8347 static enum ssa_prop_result
8348 vrp_visit_stmt (gimple *stmt, edge *taken_edge_p, tree *output_p)
8350 value_range vr = VR_INITIALIZER;
8351 tree lhs = gimple_get_lhs (stmt);
8352 extract_range_from_stmt (stmt, taken_edge_p, output_p, &vr);
8354 if (*output_p)
8356 if (update_value_range (*output_p, &vr))
8358 if (dump_file && (dump_flags & TDF_DETAILS))
8360 fprintf (dump_file, "Found new range for ");
8361 print_generic_expr (dump_file, *output_p, 0);
8362 fprintf (dump_file, ": ");
8363 dump_value_range (dump_file, &vr);
8364 fprintf (dump_file, "\n");
8367 if (vr.type == VR_VARYING)
8368 return SSA_PROP_VARYING;
8370 return SSA_PROP_INTERESTING;
8372 return SSA_PROP_NOT_INTERESTING;
8375 if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
8376 switch (gimple_call_internal_fn (stmt))
8378 case IFN_ADD_OVERFLOW:
8379 case IFN_SUB_OVERFLOW:
8380 case IFN_MUL_OVERFLOW:
8381 case IFN_ATOMIC_COMPARE_EXCHANGE:
8382 /* These internal calls return _Complex integer type,
8383 which VRP does not track, but the immediate uses
8384 thereof might be interesting. */
8385 if (lhs && TREE_CODE (lhs) == SSA_NAME)
8387 imm_use_iterator iter;
8388 use_operand_p use_p;
8389 enum ssa_prop_result res = SSA_PROP_VARYING;
8391 set_value_range_to_varying (get_value_range (lhs));
8393 FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
8395 gimple *use_stmt = USE_STMT (use_p);
8396 if (!is_gimple_assign (use_stmt))
8397 continue;
8398 enum tree_code rhs_code = gimple_assign_rhs_code (use_stmt);
8399 if (rhs_code != REALPART_EXPR && rhs_code != IMAGPART_EXPR)
8400 continue;
8401 tree rhs1 = gimple_assign_rhs1 (use_stmt);
8402 tree use_lhs = gimple_assign_lhs (use_stmt);
8403 if (TREE_CODE (rhs1) != rhs_code
8404 || TREE_OPERAND (rhs1, 0) != lhs
8405 || TREE_CODE (use_lhs) != SSA_NAME
8406 || !stmt_interesting_for_vrp (use_stmt)
8407 || (!INTEGRAL_TYPE_P (TREE_TYPE (use_lhs))
8408 || !TYPE_MIN_VALUE (TREE_TYPE (use_lhs))
8409 || !TYPE_MAX_VALUE (TREE_TYPE (use_lhs))))
8410 continue;
8412 /* If there is a change in the value range for any of the
8413 REALPART_EXPR/IMAGPART_EXPR immediate uses, return
8414 SSA_PROP_INTERESTING. If there are any REALPART_EXPR
8415 or IMAGPART_EXPR immediate uses, but none of them have
8416 a change in their value ranges, return
8417 SSA_PROP_NOT_INTERESTING. If there are no
8418 {REAL,IMAG}PART_EXPR uses at all,
8419 return SSA_PROP_VARYING. */
8420 value_range new_vr = VR_INITIALIZER;
8421 extract_range_basic (&new_vr, use_stmt);
8422 value_range *old_vr = get_value_range (use_lhs);
8423 if (old_vr->type != new_vr.type
8424 || !vrp_operand_equal_p (old_vr->min, new_vr.min)
8425 || !vrp_operand_equal_p (old_vr->max, new_vr.max)
8426 || !vrp_bitmap_equal_p (old_vr->equiv, new_vr.equiv))
8427 res = SSA_PROP_INTERESTING;
8428 else
8429 res = SSA_PROP_NOT_INTERESTING;
8430 BITMAP_FREE (new_vr.equiv);
8431 if (res == SSA_PROP_INTERESTING)
8433 *output_p = lhs;
8434 return res;
8438 return res;
8440 break;
8441 default:
8442 break;
8445 /* All other statements produce nothing of interest for VRP, so mark
8446 their outputs varying and prevent further simulation. */
8447 set_defs_to_varying (stmt);
8449 return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
8452 /* Union the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
8453 { VR1TYPE, VR0MIN, VR0MAX } and store the result
8454 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
8455 possible such range. The resulting range is not canonicalized. */
8457 static void
8458 union_ranges (enum value_range_type *vr0type,
8459 tree *vr0min, tree *vr0max,
8460 enum value_range_type vr1type,
8461 tree vr1min, tree vr1max)
8463 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
8464 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
8466 /* [] is vr0, () is vr1 in the following classification comments. */
8467 if (mineq && maxeq)
8469 /* [( )] */
8470 if (*vr0type == vr1type)
8471 /* Nothing to do for equal ranges. */
8473 else if ((*vr0type == VR_RANGE
8474 && vr1type == VR_ANTI_RANGE)
8475 || (*vr0type == VR_ANTI_RANGE
8476 && vr1type == VR_RANGE))
8478 /* For anti-range with range union the result is varying. */
8479 goto give_up;
8481 else
8482 gcc_unreachable ();
8484 else if (operand_less_p (*vr0max, vr1min) == 1
8485 || operand_less_p (vr1max, *vr0min) == 1)
8487 /* [ ] ( ) or ( ) [ ]
8488 If the ranges have an empty intersection, result of the union
8489 operation is the anti-range or if both are anti-ranges
8490 it covers all. */
8491 if (*vr0type == VR_ANTI_RANGE
8492 && vr1type == VR_ANTI_RANGE)
8493 goto give_up;
8494 else if (*vr0type == VR_ANTI_RANGE
8495 && vr1type == VR_RANGE)
8497 else if (*vr0type == VR_RANGE
8498 && vr1type == VR_ANTI_RANGE)
8500 *vr0type = vr1type;
8501 *vr0min = vr1min;
8502 *vr0max = vr1max;
8504 else if (*vr0type == VR_RANGE
8505 && vr1type == VR_RANGE)
8507 /* The result is the convex hull of both ranges. */
8508 if (operand_less_p (*vr0max, vr1min) == 1)
8510 /* If the result can be an anti-range, create one. */
8511 if (TREE_CODE (*vr0max) == INTEGER_CST
8512 && TREE_CODE (vr1min) == INTEGER_CST
8513 && vrp_val_is_min (*vr0min)
8514 && vrp_val_is_max (vr1max))
8516 tree min = int_const_binop (PLUS_EXPR,
8517 *vr0max,
8518 build_int_cst (TREE_TYPE (*vr0max), 1));
8519 tree max = int_const_binop (MINUS_EXPR,
8520 vr1min,
8521 build_int_cst (TREE_TYPE (vr1min), 1));
8522 if (!operand_less_p (max, min))
8524 *vr0type = VR_ANTI_RANGE;
8525 *vr0min = min;
8526 *vr0max = max;
8528 else
8529 *vr0max = vr1max;
8531 else
8532 *vr0max = vr1max;
8534 else
8536 /* If the result can be an anti-range, create one. */
8537 if (TREE_CODE (vr1max) == INTEGER_CST
8538 && TREE_CODE (*vr0min) == INTEGER_CST
8539 && vrp_val_is_min (vr1min)
8540 && vrp_val_is_max (*vr0max))
8542 tree min = int_const_binop (PLUS_EXPR,
8543 vr1max,
8544 build_int_cst (TREE_TYPE (vr1max), 1));
8545 tree max = int_const_binop (MINUS_EXPR,
8546 *vr0min,
8547 build_int_cst (TREE_TYPE (*vr0min), 1));
8548 if (!operand_less_p (max, min))
8550 *vr0type = VR_ANTI_RANGE;
8551 *vr0min = min;
8552 *vr0max = max;
8554 else
8555 *vr0min = vr1min;
8557 else
8558 *vr0min = vr1min;
8561 else
8562 gcc_unreachable ();
8564 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
8565 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
8567 /* [ ( ) ] or [( ) ] or [ ( )] */
8568 if (*vr0type == VR_RANGE
8569 && vr1type == VR_RANGE)
8571 else if (*vr0type == VR_ANTI_RANGE
8572 && vr1type == VR_ANTI_RANGE)
8574 *vr0type = vr1type;
8575 *vr0min = vr1min;
8576 *vr0max = vr1max;
8578 else if (*vr0type == VR_ANTI_RANGE
8579 && vr1type == VR_RANGE)
8581 /* Arbitrarily choose the right or left gap. */
8582 if (!mineq && TREE_CODE (vr1min) == INTEGER_CST)
8583 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8584 build_int_cst (TREE_TYPE (vr1min), 1));
8585 else if (!maxeq && TREE_CODE (vr1max) == INTEGER_CST)
8586 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
8587 build_int_cst (TREE_TYPE (vr1max), 1));
8588 else
8589 goto give_up;
8591 else if (*vr0type == VR_RANGE
8592 && vr1type == VR_ANTI_RANGE)
8593 /* The result covers everything. */
8594 goto give_up;
8595 else
8596 gcc_unreachable ();
8598 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
8599 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
8601 /* ( [ ] ) or ([ ] ) or ( [ ]) */
8602 if (*vr0type == VR_RANGE
8603 && vr1type == VR_RANGE)
8605 *vr0type = vr1type;
8606 *vr0min = vr1min;
8607 *vr0max = vr1max;
8609 else if (*vr0type == VR_ANTI_RANGE
8610 && vr1type == VR_ANTI_RANGE)
8612 else if (*vr0type == VR_RANGE
8613 && vr1type == VR_ANTI_RANGE)
8615 *vr0type = VR_ANTI_RANGE;
8616 if (!mineq && TREE_CODE (*vr0min) == INTEGER_CST)
8618 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
8619 build_int_cst (TREE_TYPE (*vr0min), 1));
8620 *vr0min = vr1min;
8622 else if (!maxeq && TREE_CODE (*vr0max) == INTEGER_CST)
8624 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8625 build_int_cst (TREE_TYPE (*vr0max), 1));
8626 *vr0max = vr1max;
8628 else
8629 goto give_up;
8631 else if (*vr0type == VR_ANTI_RANGE
8632 && vr1type == VR_RANGE)
8633 /* The result covers everything. */
8634 goto give_up;
8635 else
8636 gcc_unreachable ();
8638 else if ((operand_less_p (vr1min, *vr0max) == 1
8639 || operand_equal_p (vr1min, *vr0max, 0))
8640 && operand_less_p (*vr0min, vr1min) == 1
8641 && operand_less_p (*vr0max, vr1max) == 1)
8643 /* [ ( ] ) or [ ]( ) */
8644 if (*vr0type == VR_RANGE
8645 && vr1type == VR_RANGE)
8646 *vr0max = vr1max;
8647 else if (*vr0type == VR_ANTI_RANGE
8648 && vr1type == VR_ANTI_RANGE)
8649 *vr0min = vr1min;
8650 else if (*vr0type == VR_ANTI_RANGE
8651 && vr1type == VR_RANGE)
8653 if (TREE_CODE (vr1min) == INTEGER_CST)
8654 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8655 build_int_cst (TREE_TYPE (vr1min), 1));
8656 else
8657 goto give_up;
8659 else if (*vr0type == VR_RANGE
8660 && vr1type == VR_ANTI_RANGE)
8662 if (TREE_CODE (*vr0max) == INTEGER_CST)
8664 *vr0type = vr1type;
8665 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8666 build_int_cst (TREE_TYPE (*vr0max), 1));
8667 *vr0max = vr1max;
8669 else
8670 goto give_up;
8672 else
8673 gcc_unreachable ();
8675 else if ((operand_less_p (*vr0min, vr1max) == 1
8676 || operand_equal_p (*vr0min, vr1max, 0))
8677 && operand_less_p (vr1min, *vr0min) == 1
8678 && operand_less_p (vr1max, *vr0max) == 1)
8680 /* ( [ ) ] or ( )[ ] */
8681 if (*vr0type == VR_RANGE
8682 && vr1type == VR_RANGE)
8683 *vr0min = vr1min;
8684 else if (*vr0type == VR_ANTI_RANGE
8685 && vr1type == VR_ANTI_RANGE)
8686 *vr0max = vr1max;
8687 else if (*vr0type == VR_ANTI_RANGE
8688 && vr1type == VR_RANGE)
8690 if (TREE_CODE (vr1max) == INTEGER_CST)
8691 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
8692 build_int_cst (TREE_TYPE (vr1max), 1));
8693 else
8694 goto give_up;
8696 else if (*vr0type == VR_RANGE
8697 && vr1type == VR_ANTI_RANGE)
8699 if (TREE_CODE (*vr0min) == INTEGER_CST)
8701 *vr0type = vr1type;
8702 *vr0min = vr1min;
8703 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
8704 build_int_cst (TREE_TYPE (*vr0min), 1));
8706 else
8707 goto give_up;
8709 else
8710 gcc_unreachable ();
8712 else
8713 goto give_up;
8715 return;
8717 give_up:
8718 *vr0type = VR_VARYING;
8719 *vr0min = NULL_TREE;
8720 *vr0max = NULL_TREE;
8723 /* Intersect the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
8724 { VR1TYPE, VR0MIN, VR0MAX } and store the result
8725 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
8726 possible such range. The resulting range is not canonicalized. */
8728 static void
8729 intersect_ranges (enum value_range_type *vr0type,
8730 tree *vr0min, tree *vr0max,
8731 enum value_range_type vr1type,
8732 tree vr1min, tree vr1max)
8734 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
8735 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
8737 /* [] is vr0, () is vr1 in the following classification comments. */
8738 if (mineq && maxeq)
8740 /* [( )] */
8741 if (*vr0type == vr1type)
8742 /* Nothing to do for equal ranges. */
8744 else if ((*vr0type == VR_RANGE
8745 && vr1type == VR_ANTI_RANGE)
8746 || (*vr0type == VR_ANTI_RANGE
8747 && vr1type == VR_RANGE))
8749 /* For anti-range with range intersection the result is empty. */
8750 *vr0type = VR_UNDEFINED;
8751 *vr0min = NULL_TREE;
8752 *vr0max = NULL_TREE;
8754 else
8755 gcc_unreachable ();
8757 else if (operand_less_p (*vr0max, vr1min) == 1
8758 || operand_less_p (vr1max, *vr0min) == 1)
8760 /* [ ] ( ) or ( ) [ ]
8761 If the ranges have an empty intersection, the result of the
8762 intersect operation is the range for intersecting an
8763 anti-range with a range or empty when intersecting two ranges. */
8764 if (*vr0type == VR_RANGE
8765 && vr1type == VR_ANTI_RANGE)
8767 else if (*vr0type == VR_ANTI_RANGE
8768 && vr1type == VR_RANGE)
8770 *vr0type = vr1type;
8771 *vr0min = vr1min;
8772 *vr0max = vr1max;
8774 else if (*vr0type == VR_RANGE
8775 && vr1type == VR_RANGE)
8777 *vr0type = VR_UNDEFINED;
8778 *vr0min = NULL_TREE;
8779 *vr0max = NULL_TREE;
8781 else if (*vr0type == VR_ANTI_RANGE
8782 && vr1type == VR_ANTI_RANGE)
8784 /* If the anti-ranges are adjacent to each other merge them. */
8785 if (TREE_CODE (*vr0max) == INTEGER_CST
8786 && TREE_CODE (vr1min) == INTEGER_CST
8787 && operand_less_p (*vr0max, vr1min) == 1
8788 && integer_onep (int_const_binop (MINUS_EXPR,
8789 vr1min, *vr0max)))
8790 *vr0max = vr1max;
8791 else if (TREE_CODE (vr1max) == INTEGER_CST
8792 && TREE_CODE (*vr0min) == INTEGER_CST
8793 && operand_less_p (vr1max, *vr0min) == 1
8794 && integer_onep (int_const_binop (MINUS_EXPR,
8795 *vr0min, vr1max)))
8796 *vr0min = vr1min;
8797 /* Else arbitrarily take VR0. */
8800 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
8801 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
8803 /* [ ( ) ] or [( ) ] or [ ( )] */
8804 if (*vr0type == VR_RANGE
8805 && vr1type == VR_RANGE)
8807 /* If both are ranges the result is the inner one. */
8808 *vr0type = vr1type;
8809 *vr0min = vr1min;
8810 *vr0max = vr1max;
8812 else if (*vr0type == VR_RANGE
8813 && vr1type == VR_ANTI_RANGE)
8815 /* Choose the right gap if the left one is empty. */
8816 if (mineq)
8818 if (TREE_CODE (vr1max) != INTEGER_CST)
8819 *vr0min = vr1max;
8820 else if (TYPE_PRECISION (TREE_TYPE (vr1max)) == 1
8821 && !TYPE_UNSIGNED (TREE_TYPE (vr1max)))
8822 *vr0min
8823 = int_const_binop (MINUS_EXPR, vr1max,
8824 build_int_cst (TREE_TYPE (vr1max), -1));
8825 else
8826 *vr0min
8827 = int_const_binop (PLUS_EXPR, vr1max,
8828 build_int_cst (TREE_TYPE (vr1max), 1));
8830 /* Choose the left gap if the right one is empty. */
8831 else if (maxeq)
8833 if (TREE_CODE (vr1min) != INTEGER_CST)
8834 *vr0max = vr1min;
8835 else if (TYPE_PRECISION (TREE_TYPE (vr1min)) == 1
8836 && !TYPE_UNSIGNED (TREE_TYPE (vr1min)))
8837 *vr0max
8838 = int_const_binop (PLUS_EXPR, vr1min,
8839 build_int_cst (TREE_TYPE (vr1min), -1));
8840 else
8841 *vr0max
8842 = int_const_binop (MINUS_EXPR, vr1min,
8843 build_int_cst (TREE_TYPE (vr1min), 1));
8845 /* Choose the anti-range if the range is effectively varying. */
8846 else if (vrp_val_is_min (*vr0min)
8847 && vrp_val_is_max (*vr0max))
8849 *vr0type = vr1type;
8850 *vr0min = vr1min;
8851 *vr0max = vr1max;
8853 /* Else choose the range. */
8855 else if (*vr0type == VR_ANTI_RANGE
8856 && vr1type == VR_ANTI_RANGE)
8857 /* If both are anti-ranges the result is the outer one. */
8859 else if (*vr0type == VR_ANTI_RANGE
8860 && vr1type == VR_RANGE)
8862 /* The intersection is empty. */
8863 *vr0type = VR_UNDEFINED;
8864 *vr0min = NULL_TREE;
8865 *vr0max = NULL_TREE;
8867 else
8868 gcc_unreachable ();
8870 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
8871 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
8873 /* ( [ ] ) or ([ ] ) or ( [ ]) */
8874 if (*vr0type == VR_RANGE
8875 && vr1type == VR_RANGE)
8876 /* Choose the inner range. */
8878 else if (*vr0type == VR_ANTI_RANGE
8879 && vr1type == VR_RANGE)
8881 /* Choose the right gap if the left is empty. */
8882 if (mineq)
8884 *vr0type = VR_RANGE;
8885 if (TREE_CODE (*vr0max) != INTEGER_CST)
8886 *vr0min = *vr0max;
8887 else if (TYPE_PRECISION (TREE_TYPE (*vr0max)) == 1
8888 && !TYPE_UNSIGNED (TREE_TYPE (*vr0max)))
8889 *vr0min
8890 = int_const_binop (MINUS_EXPR, *vr0max,
8891 build_int_cst (TREE_TYPE (*vr0max), -1));
8892 else
8893 *vr0min
8894 = int_const_binop (PLUS_EXPR, *vr0max,
8895 build_int_cst (TREE_TYPE (*vr0max), 1));
8896 *vr0max = vr1max;
8898 /* Choose the left gap if the right is empty. */
8899 else if (maxeq)
8901 *vr0type = VR_RANGE;
8902 if (TREE_CODE (*vr0min) != INTEGER_CST)
8903 *vr0max = *vr0min;
8904 else if (TYPE_PRECISION (TREE_TYPE (*vr0min)) == 1
8905 && !TYPE_UNSIGNED (TREE_TYPE (*vr0min)))
8906 *vr0max
8907 = int_const_binop (PLUS_EXPR, *vr0min,
8908 build_int_cst (TREE_TYPE (*vr0min), -1));
8909 else
8910 *vr0max
8911 = int_const_binop (MINUS_EXPR, *vr0min,
8912 build_int_cst (TREE_TYPE (*vr0min), 1));
8913 *vr0min = vr1min;
8915 /* Choose the anti-range if the range is effectively varying. */
8916 else if (vrp_val_is_min (vr1min)
8917 && vrp_val_is_max (vr1max))
8919 /* Choose the anti-range if it is ~[0,0], that range is special
8920 enough to special case when vr1's range is relatively wide. */
8921 else if (*vr0min == *vr0max
8922 && integer_zerop (*vr0min)
8923 && (TYPE_PRECISION (TREE_TYPE (*vr0min))
8924 == TYPE_PRECISION (ptr_type_node))
8925 && TREE_CODE (vr1max) == INTEGER_CST
8926 && TREE_CODE (vr1min) == INTEGER_CST
8927 && (wi::clz (wi::sub (vr1max, vr1min))
8928 < TYPE_PRECISION (TREE_TYPE (*vr0min)) / 2))
8930 /* Else choose the range. */
8931 else
8933 *vr0type = vr1type;
8934 *vr0min = vr1min;
8935 *vr0max = vr1max;
8938 else if (*vr0type == VR_ANTI_RANGE
8939 && vr1type == VR_ANTI_RANGE)
8941 /* If both are anti-ranges the result is the outer one. */
8942 *vr0type = vr1type;
8943 *vr0min = vr1min;
8944 *vr0max = vr1max;
8946 else if (vr1type == VR_ANTI_RANGE
8947 && *vr0type == VR_RANGE)
8949 /* The intersection is empty. */
8950 *vr0type = VR_UNDEFINED;
8951 *vr0min = NULL_TREE;
8952 *vr0max = NULL_TREE;
8954 else
8955 gcc_unreachable ();
8957 else if ((operand_less_p (vr1min, *vr0max) == 1
8958 || operand_equal_p (vr1min, *vr0max, 0))
8959 && operand_less_p (*vr0min, vr1min) == 1)
8961 /* [ ( ] ) or [ ]( ) */
8962 if (*vr0type == VR_ANTI_RANGE
8963 && vr1type == VR_ANTI_RANGE)
8964 *vr0max = vr1max;
8965 else if (*vr0type == VR_RANGE
8966 && vr1type == VR_RANGE)
8967 *vr0min = vr1min;
8968 else if (*vr0type == VR_RANGE
8969 && vr1type == VR_ANTI_RANGE)
8971 if (TREE_CODE (vr1min) == INTEGER_CST)
8972 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8973 build_int_cst (TREE_TYPE (vr1min), 1));
8974 else
8975 *vr0max = vr1min;
8977 else if (*vr0type == VR_ANTI_RANGE
8978 && vr1type == VR_RANGE)
8980 *vr0type = VR_RANGE;
8981 if (TREE_CODE (*vr0max) == INTEGER_CST)
8982 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8983 build_int_cst (TREE_TYPE (*vr0max), 1));
8984 else
8985 *vr0min = *vr0max;
8986 *vr0max = vr1max;
8988 else
8989 gcc_unreachable ();
8991 else if ((operand_less_p (*vr0min, vr1max) == 1
8992 || operand_equal_p (*vr0min, vr1max, 0))
8993 && operand_less_p (vr1min, *vr0min) == 1)
8995 /* ( [ ) ] or ( )[ ] */
8996 if (*vr0type == VR_ANTI_RANGE
8997 && vr1type == VR_ANTI_RANGE)
8998 *vr0min = vr1min;
8999 else if (*vr0type == VR_RANGE
9000 && vr1type == VR_RANGE)
9001 *vr0max = vr1max;
9002 else if (*vr0type == VR_RANGE
9003 && vr1type == VR_ANTI_RANGE)
9005 if (TREE_CODE (vr1max) == INTEGER_CST)
9006 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
9007 build_int_cst (TREE_TYPE (vr1max), 1));
9008 else
9009 *vr0min = vr1max;
9011 else if (*vr0type == VR_ANTI_RANGE
9012 && vr1type == VR_RANGE)
9014 *vr0type = VR_RANGE;
9015 if (TREE_CODE (*vr0min) == INTEGER_CST)
9016 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
9017 build_int_cst (TREE_TYPE (*vr0min), 1));
9018 else
9019 *vr0max = *vr0min;
9020 *vr0min = vr1min;
9022 else
9023 gcc_unreachable ();
9026 /* As a fallback simply use { *VRTYPE, *VR0MIN, *VR0MAX } as
9027 result for the intersection. That's always a conservative
9028 correct estimate unless VR1 is a constant singleton range
9029 in which case we choose that. */
9030 if (vr1type == VR_RANGE
9031 && is_gimple_min_invariant (vr1min)
9032 && vrp_operand_equal_p (vr1min, vr1max))
9034 *vr0type = vr1type;
9035 *vr0min = vr1min;
9036 *vr0max = vr1max;
9039 return;
9043 /* Intersect the two value-ranges *VR0 and *VR1 and store the result
9044 in *VR0. This may not be the smallest possible such range. */
9046 static void
9047 vrp_intersect_ranges_1 (value_range *vr0, value_range *vr1)
9049 value_range saved;
9051 /* If either range is VR_VARYING the other one wins. */
9052 if (vr1->type == VR_VARYING)
9053 return;
9054 if (vr0->type == VR_VARYING)
9056 copy_value_range (vr0, vr1);
9057 return;
9060 /* When either range is VR_UNDEFINED the resulting range is
9061 VR_UNDEFINED, too. */
9062 if (vr0->type == VR_UNDEFINED)
9063 return;
9064 if (vr1->type == VR_UNDEFINED)
9066 set_value_range_to_undefined (vr0);
9067 return;
9070 /* Save the original vr0 so we can return it as conservative intersection
9071 result when our worker turns things to varying. */
9072 saved = *vr0;
9073 intersect_ranges (&vr0->type, &vr0->min, &vr0->max,
9074 vr1->type, vr1->min, vr1->max);
9075 /* Make sure to canonicalize the result though as the inversion of a
9076 VR_RANGE can still be a VR_RANGE. */
9077 set_and_canonicalize_value_range (vr0, vr0->type,
9078 vr0->min, vr0->max, vr0->equiv);
9079 /* If that failed, use the saved original VR0. */
9080 if (vr0->type == VR_VARYING)
9082 *vr0 = saved;
9083 return;
9085 /* If the result is VR_UNDEFINED there is no need to mess with
9086 the equivalencies. */
9087 if (vr0->type == VR_UNDEFINED)
9088 return;
9090 /* The resulting set of equivalences for range intersection is the union of
9091 the two sets. */
9092 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
9093 bitmap_ior_into (vr0->equiv, vr1->equiv);
9094 else if (vr1->equiv && !vr0->equiv)
9096 vr0->equiv = BITMAP_ALLOC (&vrp_equiv_obstack);
9097 bitmap_copy (vr0->equiv, vr1->equiv);
9101 void
9102 vrp_intersect_ranges (value_range *vr0, value_range *vr1)
9104 if (dump_file && (dump_flags & TDF_DETAILS))
9106 fprintf (dump_file, "Intersecting\n ");
9107 dump_value_range (dump_file, vr0);
9108 fprintf (dump_file, "\nand\n ");
9109 dump_value_range (dump_file, vr1);
9110 fprintf (dump_file, "\n");
9112 vrp_intersect_ranges_1 (vr0, vr1);
9113 if (dump_file && (dump_flags & TDF_DETAILS))
9115 fprintf (dump_file, "to\n ");
9116 dump_value_range (dump_file, vr0);
9117 fprintf (dump_file, "\n");
9121 /* Meet operation for value ranges. Given two value ranges VR0 and
9122 VR1, store in VR0 a range that contains both VR0 and VR1. This
9123 may not be the smallest possible such range. */
9125 static void
9126 vrp_meet_1 (value_range *vr0, const value_range *vr1)
9128 value_range saved;
9130 if (vr0->type == VR_UNDEFINED)
9132 set_value_range (vr0, vr1->type, vr1->min, vr1->max, vr1->equiv);
9133 return;
9136 if (vr1->type == VR_UNDEFINED)
9138 /* VR0 already has the resulting range. */
9139 return;
9142 if (vr0->type == VR_VARYING)
9144 /* Nothing to do. VR0 already has the resulting range. */
9145 return;
9148 if (vr1->type == VR_VARYING)
9150 set_value_range_to_varying (vr0);
9151 return;
9154 saved = *vr0;
9155 union_ranges (&vr0->type, &vr0->min, &vr0->max,
9156 vr1->type, vr1->min, vr1->max);
9157 if (vr0->type == VR_VARYING)
9159 /* Failed to find an efficient meet. Before giving up and setting
9160 the result to VARYING, see if we can at least derive a useful
9161 anti-range. FIXME, all this nonsense about distinguishing
9162 anti-ranges from ranges is necessary because of the odd
9163 semantics of range_includes_zero_p and friends. */
9164 if (((saved.type == VR_RANGE
9165 && range_includes_zero_p (saved.min, saved.max) == 0)
9166 || (saved.type == VR_ANTI_RANGE
9167 && range_includes_zero_p (saved.min, saved.max) == 1))
9168 && ((vr1->type == VR_RANGE
9169 && range_includes_zero_p (vr1->min, vr1->max) == 0)
9170 || (vr1->type == VR_ANTI_RANGE
9171 && range_includes_zero_p (vr1->min, vr1->max) == 1)))
9173 set_value_range_to_nonnull (vr0, TREE_TYPE (saved.min));
9175 /* Since this meet operation did not result from the meeting of
9176 two equivalent names, VR0 cannot have any equivalences. */
9177 if (vr0->equiv)
9178 bitmap_clear (vr0->equiv);
9179 return;
9182 set_value_range_to_varying (vr0);
9183 return;
9185 set_and_canonicalize_value_range (vr0, vr0->type, vr0->min, vr0->max,
9186 vr0->equiv);
9187 if (vr0->type == VR_VARYING)
9188 return;
9190 /* The resulting set of equivalences is always the intersection of
9191 the two sets. */
9192 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
9193 bitmap_and_into (vr0->equiv, vr1->equiv);
9194 else if (vr0->equiv && !vr1->equiv)
9195 bitmap_clear (vr0->equiv);
9198 void
9199 vrp_meet (value_range *vr0, const value_range *vr1)
9201 if (dump_file && (dump_flags & TDF_DETAILS))
9203 fprintf (dump_file, "Meeting\n ");
9204 dump_value_range (dump_file, vr0);
9205 fprintf (dump_file, "\nand\n ");
9206 dump_value_range (dump_file, vr1);
9207 fprintf (dump_file, "\n");
9209 vrp_meet_1 (vr0, vr1);
9210 if (dump_file && (dump_flags & TDF_DETAILS))
9212 fprintf (dump_file, "to\n ");
9213 dump_value_range (dump_file, vr0);
9214 fprintf (dump_file, "\n");
9219 /* Visit all arguments for PHI node PHI that flow through executable
9220 edges. If a valid value range can be derived from all the incoming
9221 value ranges, set a new range in VR_RESULT. */
9223 static void
9224 extract_range_from_phi_node (gphi *phi, value_range *vr_result)
9226 size_t i;
9227 tree lhs = PHI_RESULT (phi);
9228 value_range *lhs_vr = get_value_range (lhs);
9229 bool first = true;
9230 int edges, old_edges;
9231 struct loop *l;
9233 if (dump_file && (dump_flags & TDF_DETAILS))
9235 fprintf (dump_file, "\nVisiting PHI node: ");
9236 print_gimple_stmt (dump_file, phi, 0, dump_flags);
9239 bool may_simulate_backedge_again = false;
9240 edges = 0;
9241 for (i = 0; i < gimple_phi_num_args (phi); i++)
9243 edge e = gimple_phi_arg_edge (phi, i);
9245 if (dump_file && (dump_flags & TDF_DETAILS))
9247 fprintf (dump_file,
9248 " Argument #%d (%d -> %d %sexecutable)\n",
9249 (int) i, e->src->index, e->dest->index,
9250 (e->flags & EDGE_EXECUTABLE) ? "" : "not ");
9253 if (e->flags & EDGE_EXECUTABLE)
9255 tree arg = PHI_ARG_DEF (phi, i);
9256 value_range vr_arg;
9258 ++edges;
9260 if (TREE_CODE (arg) == SSA_NAME)
9262 /* See if we are eventually going to change one of the args. */
9263 gimple *def_stmt = SSA_NAME_DEF_STMT (arg);
9264 if (! gimple_nop_p (def_stmt)
9265 && prop_simulate_again_p (def_stmt)
9266 && e->flags & EDGE_DFS_BACK)
9267 may_simulate_backedge_again = true;
9269 vr_arg = *(get_value_range (arg));
9270 /* Do not allow equivalences or symbolic ranges to leak in from
9271 backedges. That creates invalid equivalencies.
9272 See PR53465 and PR54767. */
9273 if (e->flags & EDGE_DFS_BACK)
9275 if (vr_arg.type == VR_RANGE
9276 || vr_arg.type == VR_ANTI_RANGE)
9278 vr_arg.equiv = NULL;
9279 if (symbolic_range_p (&vr_arg))
9281 vr_arg.type = VR_VARYING;
9282 vr_arg.min = NULL_TREE;
9283 vr_arg.max = NULL_TREE;
9287 else
9289 /* If the non-backedge arguments range is VR_VARYING then
9290 we can still try recording a simple equivalence. */
9291 if (vr_arg.type == VR_VARYING)
9293 vr_arg.type = VR_RANGE;
9294 vr_arg.min = arg;
9295 vr_arg.max = arg;
9296 vr_arg.equiv = NULL;
9300 else
9302 if (TREE_OVERFLOW_P (arg))
9303 arg = drop_tree_overflow (arg);
9305 vr_arg.type = VR_RANGE;
9306 vr_arg.min = arg;
9307 vr_arg.max = arg;
9308 vr_arg.equiv = NULL;
9311 if (dump_file && (dump_flags & TDF_DETAILS))
9313 fprintf (dump_file, "\t");
9314 print_generic_expr (dump_file, arg, dump_flags);
9315 fprintf (dump_file, ": ");
9316 dump_value_range (dump_file, &vr_arg);
9317 fprintf (dump_file, "\n");
9320 if (first)
9321 copy_value_range (vr_result, &vr_arg);
9322 else
9323 vrp_meet (vr_result, &vr_arg);
9324 first = false;
9326 if (vr_result->type == VR_VARYING)
9327 break;
9331 if (vr_result->type == VR_VARYING)
9332 goto varying;
9333 else if (vr_result->type == VR_UNDEFINED)
9334 goto update_range;
9336 old_edges = vr_phi_edge_counts[SSA_NAME_VERSION (lhs)];
9337 vr_phi_edge_counts[SSA_NAME_VERSION (lhs)] = edges;
9339 /* To prevent infinite iterations in the algorithm, derive ranges
9340 when the new value is slightly bigger or smaller than the
9341 previous one. We don't do this if we have seen a new executable
9342 edge; this helps us avoid an overflow infinity for conditionals
9343 which are not in a loop. If the old value-range was VR_UNDEFINED
9344 use the updated range and iterate one more time. If we will not
9345 simulate this PHI again via the backedge allow us to iterate. */
9346 if (edges > 0
9347 && gimple_phi_num_args (phi) > 1
9348 && edges == old_edges
9349 && lhs_vr->type != VR_UNDEFINED
9350 && may_simulate_backedge_again)
9352 /* Compare old and new ranges, fall back to varying if the
9353 values are not comparable. */
9354 int cmp_min = compare_values (lhs_vr->min, vr_result->min);
9355 if (cmp_min == -2)
9356 goto varying;
9357 int cmp_max = compare_values (lhs_vr->max, vr_result->max);
9358 if (cmp_max == -2)
9359 goto varying;
9361 /* For non VR_RANGE or for pointers fall back to varying if
9362 the range changed. */
9363 if ((lhs_vr->type != VR_RANGE || vr_result->type != VR_RANGE
9364 || POINTER_TYPE_P (TREE_TYPE (lhs)))
9365 && (cmp_min != 0 || cmp_max != 0))
9366 goto varying;
9368 /* If the new minimum is larger than the previous one
9369 retain the old value. If the new minimum value is smaller
9370 than the previous one and not -INF go all the way to -INF + 1.
9371 In the first case, to avoid infinite bouncing between different
9372 minimums, and in the other case to avoid iterating millions of
9373 times to reach -INF. Going to -INF + 1 also lets the following
9374 iteration compute whether there will be any overflow, at the
9375 expense of one additional iteration. */
9376 if (cmp_min < 0)
9377 vr_result->min = lhs_vr->min;
9378 else if (cmp_min > 0
9379 && !vrp_val_is_min (vr_result->min))
9380 vr_result->min
9381 = int_const_binop (PLUS_EXPR,
9382 vrp_val_min (TREE_TYPE (vr_result->min)),
9383 build_int_cst (TREE_TYPE (vr_result->min), 1));
9385 /* Similarly for the maximum value. */
9386 if (cmp_max > 0)
9387 vr_result->max = lhs_vr->max;
9388 else if (cmp_max < 0
9389 && !vrp_val_is_max (vr_result->max))
9390 vr_result->max
9391 = int_const_binop (MINUS_EXPR,
9392 vrp_val_max (TREE_TYPE (vr_result->min)),
9393 build_int_cst (TREE_TYPE (vr_result->min), 1));
9395 /* If we dropped either bound to +-INF then if this is a loop
9396 PHI node SCEV may known more about its value-range. */
9397 if (cmp_min > 0 || cmp_min < 0
9398 || cmp_max < 0 || cmp_max > 0)
9399 goto scev_check;
9401 goto infinite_check;
9404 goto update_range;
9406 varying:
9407 set_value_range_to_varying (vr_result);
9409 scev_check:
9410 /* If this is a loop PHI node SCEV may known more about its value-range.
9411 scev_check can be reached from two paths, one is a fall through from above
9412 "varying" label, the other is direct goto from code block which tries to
9413 avoid infinite simulation. */
9414 if ((l = loop_containing_stmt (phi))
9415 && l->header == gimple_bb (phi))
9416 adjust_range_with_scev (vr_result, l, phi, lhs);
9418 infinite_check:
9419 /* If we will end up with a (-INF, +INF) range, set it to
9420 VARYING. Same if the previous max value was invalid for
9421 the type and we end up with vr_result.min > vr_result.max. */
9422 if ((vr_result->type == VR_RANGE || vr_result->type == VR_ANTI_RANGE)
9423 && !((vrp_val_is_max (vr_result->max) && vrp_val_is_min (vr_result->min))
9424 || compare_values (vr_result->min, vr_result->max) > 0))
9426 else
9427 set_value_range_to_varying (vr_result);
9429 /* If the new range is different than the previous value, keep
9430 iterating. */
9431 update_range:
9432 return;
9435 /* Visit all arguments for PHI node PHI that flow through executable
9436 edges. If a valid value range can be derived from all the incoming
9437 value ranges, set a new range for the LHS of PHI. */
9439 static enum ssa_prop_result
9440 vrp_visit_phi_node (gphi *phi)
9442 tree lhs = PHI_RESULT (phi);
9443 value_range vr_result = VR_INITIALIZER;
9444 extract_range_from_phi_node (phi, &vr_result);
9445 if (update_value_range (lhs, &vr_result))
9447 if (dump_file && (dump_flags & TDF_DETAILS))
9449 fprintf (dump_file, "Found new range for ");
9450 print_generic_expr (dump_file, lhs, 0);
9451 fprintf (dump_file, ": ");
9452 dump_value_range (dump_file, &vr_result);
9453 fprintf (dump_file, "\n");
9456 if (vr_result.type == VR_VARYING)
9457 return SSA_PROP_VARYING;
9459 return SSA_PROP_INTERESTING;
9462 /* Nothing changed, don't add outgoing edges. */
9463 return SSA_PROP_NOT_INTERESTING;
9466 /* Simplify boolean operations if the source is known
9467 to be already a boolean. */
9468 static bool
9469 simplify_truth_ops_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9471 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
9472 tree lhs, op0, op1;
9473 bool need_conversion;
9475 /* We handle only !=/== case here. */
9476 gcc_assert (rhs_code == EQ_EXPR || rhs_code == NE_EXPR);
9478 op0 = gimple_assign_rhs1 (stmt);
9479 if (!op_with_boolean_value_range_p (op0))
9480 return false;
9482 op1 = gimple_assign_rhs2 (stmt);
9483 if (!op_with_boolean_value_range_p (op1))
9484 return false;
9486 /* Reduce number of cases to handle to NE_EXPR. As there is no
9487 BIT_XNOR_EXPR we cannot replace A == B with a single statement. */
9488 if (rhs_code == EQ_EXPR)
9490 if (TREE_CODE (op1) == INTEGER_CST)
9491 op1 = int_const_binop (BIT_XOR_EXPR, op1,
9492 build_int_cst (TREE_TYPE (op1), 1));
9493 else
9494 return false;
9497 lhs = gimple_assign_lhs (stmt);
9498 need_conversion
9499 = !useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (op0));
9501 /* Make sure to not sign-extend a 1-bit 1 when converting the result. */
9502 if (need_conversion
9503 && !TYPE_UNSIGNED (TREE_TYPE (op0))
9504 && TYPE_PRECISION (TREE_TYPE (op0)) == 1
9505 && TYPE_PRECISION (TREE_TYPE (lhs)) > 1)
9506 return false;
9508 /* For A != 0 we can substitute A itself. */
9509 if (integer_zerop (op1))
9510 gimple_assign_set_rhs_with_ops (gsi,
9511 need_conversion
9512 ? NOP_EXPR : TREE_CODE (op0), op0);
9513 /* For A != B we substitute A ^ B. Either with conversion. */
9514 else if (need_conversion)
9516 tree tem = make_ssa_name (TREE_TYPE (op0));
9517 gassign *newop
9518 = gimple_build_assign (tem, BIT_XOR_EXPR, op0, op1);
9519 gsi_insert_before (gsi, newop, GSI_SAME_STMT);
9520 if (INTEGRAL_TYPE_P (TREE_TYPE (tem))
9521 && TYPE_PRECISION (TREE_TYPE (tem)) > 1)
9522 set_range_info (tem, VR_RANGE,
9523 wi::zero (TYPE_PRECISION (TREE_TYPE (tem))),
9524 wi::one (TYPE_PRECISION (TREE_TYPE (tem))));
9525 gimple_assign_set_rhs_with_ops (gsi, NOP_EXPR, tem);
9527 /* Or without. */
9528 else
9529 gimple_assign_set_rhs_with_ops (gsi, BIT_XOR_EXPR, op0, op1);
9530 update_stmt (gsi_stmt (*gsi));
9531 fold_stmt (gsi, follow_single_use_edges);
9533 return true;
9536 /* Simplify a division or modulo operator to a right shift or bitwise and
9537 if the first operand is unsigned or is greater than zero and the second
9538 operand is an exact power of two. For TRUNC_MOD_EXPR op0 % op1 with
9539 constant op1 (op1min = op1) or with op1 in [op1min, op1max] range,
9540 optimize it into just op0 if op0's range is known to be a subset of
9541 [-op1min + 1, op1min - 1] for signed and [0, op1min - 1] for unsigned
9542 modulo. */
9544 static bool
9545 simplify_div_or_mod_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9547 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
9548 tree val = NULL;
9549 tree op0 = gimple_assign_rhs1 (stmt);
9550 tree op1 = gimple_assign_rhs2 (stmt);
9551 tree op0min = NULL_TREE, op0max = NULL_TREE;
9552 tree op1min = op1;
9553 value_range *vr = NULL;
9555 if (TREE_CODE (op0) == INTEGER_CST)
9557 op0min = op0;
9558 op0max = op0;
9560 else
9562 vr = get_value_range (op0);
9563 if (range_int_cst_p (vr))
9565 op0min = vr->min;
9566 op0max = vr->max;
9570 if (rhs_code == TRUNC_MOD_EXPR
9571 && TREE_CODE (op1) == SSA_NAME)
9573 value_range *vr1 = get_value_range (op1);
9574 if (range_int_cst_p (vr1))
9575 op1min = vr1->min;
9577 if (rhs_code == TRUNC_MOD_EXPR
9578 && TREE_CODE (op1min) == INTEGER_CST
9579 && tree_int_cst_sgn (op1min) == 1
9580 && op0max
9581 && tree_int_cst_lt (op0max, op1min))
9583 if (TYPE_UNSIGNED (TREE_TYPE (op0))
9584 || tree_int_cst_sgn (op0min) >= 0
9585 || tree_int_cst_lt (fold_unary (NEGATE_EXPR, TREE_TYPE (op1min), op1min),
9586 op0min))
9588 /* If op0 already has the range op0 % op1 has,
9589 then TRUNC_MOD_EXPR won't change anything. */
9590 gimple_assign_set_rhs_from_tree (gsi, op0);
9591 return true;
9595 if (TREE_CODE (op0) != SSA_NAME)
9596 return false;
9598 if (!integer_pow2p (op1))
9600 /* X % -Y can be only optimized into X % Y either if
9601 X is not INT_MIN, or Y is not -1. Fold it now, as after
9602 remove_range_assertions the range info might be not available
9603 anymore. */
9604 if (rhs_code == TRUNC_MOD_EXPR
9605 && fold_stmt (gsi, follow_single_use_edges))
9606 return true;
9607 return false;
9610 if (TYPE_UNSIGNED (TREE_TYPE (op0)))
9611 val = integer_one_node;
9612 else
9614 bool sop = false;
9616 val = compare_range_with_value (GE_EXPR, vr, integer_zero_node, &sop);
9618 if (val
9619 && sop
9620 && integer_onep (val)
9621 && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
9623 location_t location;
9625 if (!gimple_has_location (stmt))
9626 location = input_location;
9627 else
9628 location = gimple_location (stmt);
9629 warning_at (location, OPT_Wstrict_overflow,
9630 "assuming signed overflow does not occur when "
9631 "simplifying %</%> or %<%%%> to %<>>%> or %<&%>");
9635 if (val && integer_onep (val))
9637 tree t;
9639 if (rhs_code == TRUNC_DIV_EXPR)
9641 t = build_int_cst (integer_type_node, tree_log2 (op1));
9642 gimple_assign_set_rhs_code (stmt, RSHIFT_EXPR);
9643 gimple_assign_set_rhs1 (stmt, op0);
9644 gimple_assign_set_rhs2 (stmt, t);
9646 else
9648 t = build_int_cst (TREE_TYPE (op1), 1);
9649 t = int_const_binop (MINUS_EXPR, op1, t);
9650 t = fold_convert (TREE_TYPE (op0), t);
9652 gimple_assign_set_rhs_code (stmt, BIT_AND_EXPR);
9653 gimple_assign_set_rhs1 (stmt, op0);
9654 gimple_assign_set_rhs2 (stmt, t);
9657 update_stmt (stmt);
9658 fold_stmt (gsi, follow_single_use_edges);
9659 return true;
9662 return false;
9665 /* Simplify a min or max if the ranges of the two operands are
9666 disjoint. Return true if we do simplify. */
9668 static bool
9669 simplify_min_or_max_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9671 tree op0 = gimple_assign_rhs1 (stmt);
9672 tree op1 = gimple_assign_rhs2 (stmt);
9673 bool sop = false;
9674 tree val;
9676 val = (vrp_evaluate_conditional_warnv_with_ops_using_ranges
9677 (LE_EXPR, op0, op1, &sop));
9678 if (!val)
9680 sop = false;
9681 val = (vrp_evaluate_conditional_warnv_with_ops_using_ranges
9682 (LT_EXPR, op0, op1, &sop));
9685 if (val)
9687 if (sop && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
9689 location_t location;
9691 if (!gimple_has_location (stmt))
9692 location = input_location;
9693 else
9694 location = gimple_location (stmt);
9695 warning_at (location, OPT_Wstrict_overflow,
9696 "assuming signed overflow does not occur when "
9697 "simplifying %<min/max (X,Y)%> to %<X%> or %<Y%>");
9700 /* VAL == TRUE -> OP0 < or <= op1
9701 VAL == FALSE -> OP0 > or >= op1. */
9702 tree res = ((gimple_assign_rhs_code (stmt) == MAX_EXPR)
9703 == integer_zerop (val)) ? op0 : op1;
9704 gimple_assign_set_rhs_from_tree (gsi, res);
9705 return true;
9708 return false;
9711 /* If the operand to an ABS_EXPR is >= 0, then eliminate the
9712 ABS_EXPR. If the operand is <= 0, then simplify the
9713 ABS_EXPR into a NEGATE_EXPR. */
9715 static bool
9716 simplify_abs_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9718 tree op = gimple_assign_rhs1 (stmt);
9719 value_range *vr = get_value_range (op);
9721 if (vr)
9723 tree val = NULL;
9724 bool sop = false;
9726 val = compare_range_with_value (LE_EXPR, vr, integer_zero_node, &sop);
9727 if (!val)
9729 /* The range is neither <= 0 nor > 0. Now see if it is
9730 either < 0 or >= 0. */
9731 sop = false;
9732 val = compare_range_with_value (LT_EXPR, vr, integer_zero_node,
9733 &sop);
9736 if (val)
9738 if (sop && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
9740 location_t location;
9742 if (!gimple_has_location (stmt))
9743 location = input_location;
9744 else
9745 location = gimple_location (stmt);
9746 warning_at (location, OPT_Wstrict_overflow,
9747 "assuming signed overflow does not occur when "
9748 "simplifying %<abs (X)%> to %<X%> or %<-X%>");
9751 gimple_assign_set_rhs1 (stmt, op);
9752 if (integer_zerop (val))
9753 gimple_assign_set_rhs_code (stmt, SSA_NAME);
9754 else
9755 gimple_assign_set_rhs_code (stmt, NEGATE_EXPR);
9756 update_stmt (stmt);
9757 fold_stmt (gsi, follow_single_use_edges);
9758 return true;
9762 return false;
9765 /* Optimize away redundant BIT_AND_EXPR and BIT_IOR_EXPR.
9766 If all the bits that are being cleared by & are already
9767 known to be zero from VR, or all the bits that are being
9768 set by | are already known to be one from VR, the bit
9769 operation is redundant. */
9771 static bool
9772 simplify_bit_ops_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9774 tree op0 = gimple_assign_rhs1 (stmt);
9775 tree op1 = gimple_assign_rhs2 (stmt);
9776 tree op = NULL_TREE;
9777 value_range vr0 = VR_INITIALIZER;
9778 value_range vr1 = VR_INITIALIZER;
9779 wide_int may_be_nonzero0, may_be_nonzero1;
9780 wide_int must_be_nonzero0, must_be_nonzero1;
9781 wide_int mask;
9783 if (TREE_CODE (op0) == SSA_NAME)
9784 vr0 = *(get_value_range (op0));
9785 else if (is_gimple_min_invariant (op0))
9786 set_value_range_to_value (&vr0, op0, NULL);
9787 else
9788 return false;
9790 if (TREE_CODE (op1) == SSA_NAME)
9791 vr1 = *(get_value_range (op1));
9792 else if (is_gimple_min_invariant (op1))
9793 set_value_range_to_value (&vr1, op1, NULL);
9794 else
9795 return false;
9797 if (!zero_nonzero_bits_from_vr (TREE_TYPE (op0), &vr0, &may_be_nonzero0,
9798 &must_be_nonzero0))
9799 return false;
9800 if (!zero_nonzero_bits_from_vr (TREE_TYPE (op1), &vr1, &may_be_nonzero1,
9801 &must_be_nonzero1))
9802 return false;
9804 switch (gimple_assign_rhs_code (stmt))
9806 case BIT_AND_EXPR:
9807 mask = may_be_nonzero0.and_not (must_be_nonzero1);
9808 if (mask == 0)
9810 op = op0;
9811 break;
9813 mask = may_be_nonzero1.and_not (must_be_nonzero0);
9814 if (mask == 0)
9816 op = op1;
9817 break;
9819 break;
9820 case BIT_IOR_EXPR:
9821 mask = may_be_nonzero0.and_not (must_be_nonzero1);
9822 if (mask == 0)
9824 op = op1;
9825 break;
9827 mask = may_be_nonzero1.and_not (must_be_nonzero0);
9828 if (mask == 0)
9830 op = op0;
9831 break;
9833 break;
9834 default:
9835 gcc_unreachable ();
9838 if (op == NULL_TREE)
9839 return false;
9841 gimple_assign_set_rhs_with_ops (gsi, TREE_CODE (op), op);
9842 update_stmt (gsi_stmt (*gsi));
9843 return true;
9846 /* We are comparing trees OP0 and OP1 using COND_CODE. OP0 has
9847 a known value range VR.
9849 If there is one and only one value which will satisfy the
9850 conditional, then return that value. Else return NULL.
9852 If signed overflow must be undefined for the value to satisfy
9853 the conditional, then set *STRICT_OVERFLOW_P to true. */
9855 static tree
9856 test_for_singularity (enum tree_code cond_code, tree op0,
9857 tree op1, value_range *vr,
9858 bool *strict_overflow_p)
9860 tree min = NULL;
9861 tree max = NULL;
9863 /* Extract minimum/maximum values which satisfy the conditional as it was
9864 written. */
9865 if (cond_code == LE_EXPR || cond_code == LT_EXPR)
9867 /* This should not be negative infinity; there is no overflow
9868 here. */
9869 min = TYPE_MIN_VALUE (TREE_TYPE (op0));
9871 max = op1;
9872 if (cond_code == LT_EXPR && !is_overflow_infinity (max))
9874 tree one = build_int_cst (TREE_TYPE (op0), 1);
9875 max = fold_build2 (MINUS_EXPR, TREE_TYPE (op0), max, one);
9876 if (EXPR_P (max))
9877 TREE_NO_WARNING (max) = 1;
9880 else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
9882 /* This should not be positive infinity; there is no overflow
9883 here. */
9884 max = TYPE_MAX_VALUE (TREE_TYPE (op0));
9886 min = op1;
9887 if (cond_code == GT_EXPR && !is_overflow_infinity (min))
9889 tree one = build_int_cst (TREE_TYPE (op0), 1);
9890 min = fold_build2 (PLUS_EXPR, TREE_TYPE (op0), min, one);
9891 if (EXPR_P (min))
9892 TREE_NO_WARNING (min) = 1;
9896 /* Now refine the minimum and maximum values using any
9897 value range information we have for op0. */
9898 if (min && max)
9900 if (compare_values (vr->min, min) == 1)
9901 min = vr->min;
9902 if (compare_values (vr->max, max) == -1)
9903 max = vr->max;
9905 /* If the new min/max values have converged to a single value,
9906 then there is only one value which can satisfy the condition,
9907 return that value. */
9908 if (operand_equal_p (min, max, 0) && is_gimple_min_invariant (min))
9910 if ((cond_code == LE_EXPR || cond_code == LT_EXPR)
9911 && is_overflow_infinity (vr->max))
9912 *strict_overflow_p = true;
9913 if ((cond_code == GE_EXPR || cond_code == GT_EXPR)
9914 && is_overflow_infinity (vr->min))
9915 *strict_overflow_p = true;
9917 return min;
9920 return NULL;
9923 /* Return whether the value range *VR fits in an integer type specified
9924 by PRECISION and UNSIGNED_P. */
9926 static bool
9927 range_fits_type_p (value_range *vr, unsigned dest_precision, signop dest_sgn)
9929 tree src_type;
9930 unsigned src_precision;
9931 widest_int tem;
9932 signop src_sgn;
9934 /* We can only handle integral and pointer types. */
9935 src_type = TREE_TYPE (vr->min);
9936 if (!INTEGRAL_TYPE_P (src_type)
9937 && !POINTER_TYPE_P (src_type))
9938 return false;
9940 /* An extension is fine unless VR is SIGNED and dest_sgn is UNSIGNED,
9941 and so is an identity transform. */
9942 src_precision = TYPE_PRECISION (TREE_TYPE (vr->min));
9943 src_sgn = TYPE_SIGN (src_type);
9944 if ((src_precision < dest_precision
9945 && !(dest_sgn == UNSIGNED && src_sgn == SIGNED))
9946 || (src_precision == dest_precision && src_sgn == dest_sgn))
9947 return true;
9949 /* Now we can only handle ranges with constant bounds. */
9950 if (vr->type != VR_RANGE
9951 || TREE_CODE (vr->min) != INTEGER_CST
9952 || TREE_CODE (vr->max) != INTEGER_CST)
9953 return false;
9955 /* For sign changes, the MSB of the wide_int has to be clear.
9956 An unsigned value with its MSB set cannot be represented by
9957 a signed wide_int, while a negative value cannot be represented
9958 by an unsigned wide_int. */
9959 if (src_sgn != dest_sgn
9960 && (wi::lts_p (vr->min, 0) || wi::lts_p (vr->max, 0)))
9961 return false;
9963 /* Then we can perform the conversion on both ends and compare
9964 the result for equality. */
9965 tem = wi::ext (wi::to_widest (vr->min), dest_precision, dest_sgn);
9966 if (tem != wi::to_widest (vr->min))
9967 return false;
9968 tem = wi::ext (wi::to_widest (vr->max), dest_precision, dest_sgn);
9969 if (tem != wi::to_widest (vr->max))
9970 return false;
9972 return true;
9975 /* Simplify a conditional using a relational operator to an equality
9976 test if the range information indicates only one value can satisfy
9977 the original conditional. */
9979 static bool
9980 simplify_cond_using_ranges_1 (gcond *stmt)
9982 tree op0 = gimple_cond_lhs (stmt);
9983 tree op1 = gimple_cond_rhs (stmt);
9984 enum tree_code cond_code = gimple_cond_code (stmt);
9986 if (cond_code != NE_EXPR
9987 && cond_code != EQ_EXPR
9988 && TREE_CODE (op0) == SSA_NAME
9989 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
9990 && is_gimple_min_invariant (op1))
9992 value_range *vr = get_value_range (op0);
9994 /* If we have range information for OP0, then we might be
9995 able to simplify this conditional. */
9996 if (vr->type == VR_RANGE)
9998 enum warn_strict_overflow_code wc = WARN_STRICT_OVERFLOW_COMPARISON;
9999 bool sop = false;
10000 tree new_tree = test_for_singularity (cond_code, op0, op1, vr, &sop);
10002 if (new_tree
10003 && (!sop || TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (op0))))
10005 if (dump_file)
10007 fprintf (dump_file, "Simplified relational ");
10008 print_gimple_stmt (dump_file, stmt, 0, 0);
10009 fprintf (dump_file, " into ");
10012 gimple_cond_set_code (stmt, EQ_EXPR);
10013 gimple_cond_set_lhs (stmt, op0);
10014 gimple_cond_set_rhs (stmt, new_tree);
10016 update_stmt (stmt);
10018 if (dump_file)
10020 print_gimple_stmt (dump_file, stmt, 0, 0);
10021 fprintf (dump_file, "\n");
10024 if (sop && issue_strict_overflow_warning (wc))
10026 location_t location = input_location;
10027 if (gimple_has_location (stmt))
10028 location = gimple_location (stmt);
10030 warning_at (location, OPT_Wstrict_overflow,
10031 "assuming signed overflow does not occur when "
10032 "simplifying conditional");
10035 return true;
10038 /* Try again after inverting the condition. We only deal
10039 with integral types here, so no need to worry about
10040 issues with inverting FP comparisons. */
10041 sop = false;
10042 new_tree = test_for_singularity
10043 (invert_tree_comparison (cond_code, false),
10044 op0, op1, vr, &sop);
10046 if (new_tree
10047 && (!sop || TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (op0))))
10049 if (dump_file)
10051 fprintf (dump_file, "Simplified relational ");
10052 print_gimple_stmt (dump_file, stmt, 0, 0);
10053 fprintf (dump_file, " into ");
10056 gimple_cond_set_code (stmt, NE_EXPR);
10057 gimple_cond_set_lhs (stmt, op0);
10058 gimple_cond_set_rhs (stmt, new_tree);
10060 update_stmt (stmt);
10062 if (dump_file)
10064 print_gimple_stmt (dump_file, stmt, 0, 0);
10065 fprintf (dump_file, "\n");
10068 if (sop && issue_strict_overflow_warning (wc))
10070 location_t location = input_location;
10071 if (gimple_has_location (stmt))
10072 location = gimple_location (stmt);
10074 warning_at (location, OPT_Wstrict_overflow,
10075 "assuming signed overflow does not occur when "
10076 "simplifying conditional");
10079 return true;
10083 return false;
10086 /* STMT is a conditional at the end of a basic block.
10088 If the conditional is of the form SSA_NAME op constant and the SSA_NAME
10089 was set via a type conversion, try to replace the SSA_NAME with the RHS
10090 of the type conversion. Doing so makes the conversion dead which helps
10091 subsequent passes. */
10093 static void
10094 simplify_cond_using_ranges_2 (gcond *stmt)
10096 tree op0 = gimple_cond_lhs (stmt);
10097 tree op1 = gimple_cond_rhs (stmt);
10098 enum tree_code cond_code = gimple_cond_code (stmt);
10100 /* If we have a comparison of an SSA_NAME (OP0) against a constant,
10101 see if OP0 was set by a type conversion where the source of
10102 the conversion is another SSA_NAME with a range that fits
10103 into the range of OP0's type.
10105 If so, the conversion is redundant as the earlier SSA_NAME can be
10106 used for the comparison directly if we just massage the constant in the
10107 comparison. */
10108 if (TREE_CODE (op0) == SSA_NAME
10109 && TREE_CODE (op1) == INTEGER_CST)
10111 gimple *def_stmt = SSA_NAME_DEF_STMT (op0);
10112 tree innerop;
10114 if (!is_gimple_assign (def_stmt)
10115 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)))
10116 return;
10118 innerop = gimple_assign_rhs1 (def_stmt);
10120 if (TREE_CODE (innerop) == SSA_NAME
10121 && !POINTER_TYPE_P (TREE_TYPE (innerop))
10122 && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (innerop)
10123 && desired_pro_or_demotion_p (TREE_TYPE (innerop), TREE_TYPE (op0)))
10125 value_range *vr = get_value_range (innerop);
10127 if (range_int_cst_p (vr)
10128 && range_fits_type_p (vr,
10129 TYPE_PRECISION (TREE_TYPE (op0)),
10130 TYPE_SIGN (TREE_TYPE (op0)))
10131 && int_fits_type_p (op1, TREE_TYPE (innerop))
10132 /* The range must not have overflowed, or if it did overflow
10133 we must not be wrapping/trapping overflow and optimizing
10134 with strict overflow semantics. */
10135 && ((!is_negative_overflow_infinity (vr->min)
10136 && !is_positive_overflow_infinity (vr->max))
10137 || TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (innerop))))
10139 /* If the range overflowed and the user has asked for warnings
10140 when strict overflow semantics were used to optimize code,
10141 issue an appropriate warning. */
10142 if (cond_code != EQ_EXPR && cond_code != NE_EXPR
10143 && (is_negative_overflow_infinity (vr->min)
10144 || is_positive_overflow_infinity (vr->max))
10145 && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_CONDITIONAL))
10147 location_t location;
10149 if (!gimple_has_location (stmt))
10150 location = input_location;
10151 else
10152 location = gimple_location (stmt);
10153 warning_at (location, OPT_Wstrict_overflow,
10154 "assuming signed overflow does not occur when "
10155 "simplifying conditional");
10158 tree newconst = fold_convert (TREE_TYPE (innerop), op1);
10159 gimple_cond_set_lhs (stmt, innerop);
10160 gimple_cond_set_rhs (stmt, newconst);
10161 update_stmt (stmt);
10162 if (dump_file && (dump_flags & TDF_DETAILS))
10164 fprintf (dump_file, "Folded into: ");
10165 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
10166 fprintf (dump_file, "\n");
10173 /* Simplify a switch statement using the value range of the switch
10174 argument. */
10176 static bool
10177 simplify_switch_using_ranges (gswitch *stmt)
10179 tree op = gimple_switch_index (stmt);
10180 value_range *vr = NULL;
10181 bool take_default;
10182 edge e;
10183 edge_iterator ei;
10184 size_t i = 0, j = 0, n, n2;
10185 tree vec2;
10186 switch_update su;
10187 size_t k = 1, l = 0;
10189 if (TREE_CODE (op) == SSA_NAME)
10191 vr = get_value_range (op);
10193 /* We can only handle integer ranges. */
10194 if ((vr->type != VR_RANGE
10195 && vr->type != VR_ANTI_RANGE)
10196 || symbolic_range_p (vr))
10197 return false;
10199 /* Find case label for min/max of the value range. */
10200 take_default = !find_case_label_ranges (stmt, vr, &i, &j, &k, &l);
10202 else if (TREE_CODE (op) == INTEGER_CST)
10204 take_default = !find_case_label_index (stmt, 1, op, &i);
10205 if (take_default)
10207 i = 1;
10208 j = 0;
10210 else
10212 j = i;
10215 else
10216 return false;
10218 n = gimple_switch_num_labels (stmt);
10220 /* We can truncate the case label ranges that partially overlap with OP's
10221 value range. */
10222 size_t min_idx = 1, max_idx = 0;
10223 if (vr != NULL)
10224 find_case_label_range (stmt, vr->min, vr->max, &min_idx, &max_idx);
10225 if (min_idx <= max_idx)
10227 tree min_label = gimple_switch_label (stmt, min_idx);
10228 tree max_label = gimple_switch_label (stmt, max_idx);
10230 /* Avoid changing the type of the case labels when truncating. */
10231 tree case_label_type = TREE_TYPE (CASE_LOW (min_label));
10232 tree vr_min = fold_convert (case_label_type, vr->min);
10233 tree vr_max = fold_convert (case_label_type, vr->max);
10235 if (vr->type == VR_RANGE)
10237 /* If OP's value range is [2,8] and the low label range is
10238 0 ... 3, truncate the label's range to 2 .. 3. */
10239 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
10240 && CASE_HIGH (min_label) != NULL_TREE
10241 && tree_int_cst_compare (CASE_HIGH (min_label), vr_min) >= 0)
10242 CASE_LOW (min_label) = vr_min;
10244 /* If OP's value range is [2,8] and the high label range is
10245 7 ... 10, truncate the label's range to 7 .. 8. */
10246 if (tree_int_cst_compare (CASE_LOW (max_label), vr_max) <= 0
10247 && CASE_HIGH (max_label) != NULL_TREE
10248 && tree_int_cst_compare (CASE_HIGH (max_label), vr_max) > 0)
10249 CASE_HIGH (max_label) = vr_max;
10251 else if (vr->type == VR_ANTI_RANGE)
10253 tree one_cst = build_one_cst (case_label_type);
10255 if (min_label == max_label)
10257 /* If OP's value range is ~[7,8] and the label's range is
10258 7 ... 10, truncate the label's range to 9 ... 10. */
10259 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) == 0
10260 && CASE_HIGH (min_label) != NULL_TREE
10261 && tree_int_cst_compare (CASE_HIGH (min_label), vr_max) > 0)
10262 CASE_LOW (min_label)
10263 = int_const_binop (PLUS_EXPR, vr_max, one_cst);
10265 /* If OP's value range is ~[7,8] and the label's range is
10266 5 ... 8, truncate the label's range to 5 ... 6. */
10267 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
10268 && CASE_HIGH (min_label) != NULL_TREE
10269 && tree_int_cst_compare (CASE_HIGH (min_label), vr_max) == 0)
10270 CASE_HIGH (min_label)
10271 = int_const_binop (MINUS_EXPR, vr_min, one_cst);
10273 else
10275 /* If OP's value range is ~[2,8] and the low label range is
10276 0 ... 3, truncate the label's range to 0 ... 1. */
10277 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
10278 && CASE_HIGH (min_label) != NULL_TREE
10279 && tree_int_cst_compare (CASE_HIGH (min_label), vr_min) >= 0)
10280 CASE_HIGH (min_label)
10281 = int_const_binop (MINUS_EXPR, vr_min, one_cst);
10283 /* If OP's value range is ~[2,8] and the high label range is
10284 7 ... 10, truncate the label's range to 9 ... 10. */
10285 if (tree_int_cst_compare (CASE_LOW (max_label), vr_max) <= 0
10286 && CASE_HIGH (max_label) != NULL_TREE
10287 && tree_int_cst_compare (CASE_HIGH (max_label), vr_max) > 0)
10288 CASE_LOW (max_label)
10289 = int_const_binop (PLUS_EXPR, vr_max, one_cst);
10293 /* Canonicalize singleton case ranges. */
10294 if (tree_int_cst_equal (CASE_LOW (min_label), CASE_HIGH (min_label)))
10295 CASE_HIGH (min_label) = NULL_TREE;
10296 if (tree_int_cst_equal (CASE_LOW (max_label), CASE_HIGH (max_label)))
10297 CASE_HIGH (max_label) = NULL_TREE;
10300 /* We can also eliminate case labels that lie completely outside OP's value
10301 range. */
10303 /* Bail out if this is just all edges taken. */
10304 if (i == 1
10305 && j == n - 1
10306 && take_default)
10307 return false;
10309 /* Build a new vector of taken case labels. */
10310 vec2 = make_tree_vec (j - i + 1 + l - k + 1 + (int)take_default);
10311 n2 = 0;
10313 /* Add the default edge, if necessary. */
10314 if (take_default)
10315 TREE_VEC_ELT (vec2, n2++) = gimple_switch_default_label (stmt);
10317 for (; i <= j; ++i, ++n2)
10318 TREE_VEC_ELT (vec2, n2) = gimple_switch_label (stmt, i);
10320 for (; k <= l; ++k, ++n2)
10321 TREE_VEC_ELT (vec2, n2) = gimple_switch_label (stmt, k);
10323 /* Mark needed edges. */
10324 for (i = 0; i < n2; ++i)
10326 e = find_edge (gimple_bb (stmt),
10327 label_to_block (CASE_LABEL (TREE_VEC_ELT (vec2, i))));
10328 e->aux = (void *)-1;
10331 /* Queue not needed edges for later removal. */
10332 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
10334 if (e->aux == (void *)-1)
10336 e->aux = NULL;
10337 continue;
10340 if (dump_file && (dump_flags & TDF_DETAILS))
10342 fprintf (dump_file, "removing unreachable case label\n");
10344 to_remove_edges.safe_push (e);
10345 e->flags &= ~EDGE_EXECUTABLE;
10348 /* And queue an update for the stmt. */
10349 su.stmt = stmt;
10350 su.vec = vec2;
10351 to_update_switch_stmts.safe_push (su);
10352 return false;
10355 /* Simplify an integral conversion from an SSA name in STMT. */
10357 static bool
10358 simplify_conversion_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
10360 tree innerop, middleop, finaltype;
10361 gimple *def_stmt;
10362 signop inner_sgn, middle_sgn, final_sgn;
10363 unsigned inner_prec, middle_prec, final_prec;
10364 widest_int innermin, innermed, innermax, middlemin, middlemed, middlemax;
10366 finaltype = TREE_TYPE (gimple_assign_lhs (stmt));
10367 if (!INTEGRAL_TYPE_P (finaltype))
10368 return false;
10369 middleop = gimple_assign_rhs1 (stmt);
10370 def_stmt = SSA_NAME_DEF_STMT (middleop);
10371 if (!is_gimple_assign (def_stmt)
10372 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)))
10373 return false;
10374 innerop = gimple_assign_rhs1 (def_stmt);
10375 if (TREE_CODE (innerop) != SSA_NAME
10376 || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (innerop))
10377 return false;
10379 /* Get the value-range of the inner operand. Use get_range_info in
10380 case innerop was created during substitute-and-fold. */
10381 wide_int imin, imax;
10382 if (!INTEGRAL_TYPE_P (TREE_TYPE (innerop))
10383 || get_range_info (innerop, &imin, &imax) != VR_RANGE)
10384 return false;
10385 innermin = widest_int::from (imin, TYPE_SIGN (TREE_TYPE (innerop)));
10386 innermax = widest_int::from (imax, TYPE_SIGN (TREE_TYPE (innerop)));
10388 /* Simulate the conversion chain to check if the result is equal if
10389 the middle conversion is removed. */
10390 inner_prec = TYPE_PRECISION (TREE_TYPE (innerop));
10391 middle_prec = TYPE_PRECISION (TREE_TYPE (middleop));
10392 final_prec = TYPE_PRECISION (finaltype);
10394 /* If the first conversion is not injective, the second must not
10395 be widening. */
10396 if (wi::gtu_p (innermax - innermin,
10397 wi::mask <widest_int> (middle_prec, false))
10398 && middle_prec < final_prec)
10399 return false;
10400 /* We also want a medium value so that we can track the effect that
10401 narrowing conversions with sign change have. */
10402 inner_sgn = TYPE_SIGN (TREE_TYPE (innerop));
10403 if (inner_sgn == UNSIGNED)
10404 innermed = wi::shifted_mask <widest_int> (1, inner_prec - 1, false);
10405 else
10406 innermed = 0;
10407 if (wi::cmp (innermin, innermed, inner_sgn) >= 0
10408 || wi::cmp (innermed, innermax, inner_sgn) >= 0)
10409 innermed = innermin;
10411 middle_sgn = TYPE_SIGN (TREE_TYPE (middleop));
10412 middlemin = wi::ext (innermin, middle_prec, middle_sgn);
10413 middlemed = wi::ext (innermed, middle_prec, middle_sgn);
10414 middlemax = wi::ext (innermax, middle_prec, middle_sgn);
10416 /* Require that the final conversion applied to both the original
10417 and the intermediate range produces the same result. */
10418 final_sgn = TYPE_SIGN (finaltype);
10419 if (wi::ext (middlemin, final_prec, final_sgn)
10420 != wi::ext (innermin, final_prec, final_sgn)
10421 || wi::ext (middlemed, final_prec, final_sgn)
10422 != wi::ext (innermed, final_prec, final_sgn)
10423 || wi::ext (middlemax, final_prec, final_sgn)
10424 != wi::ext (innermax, final_prec, final_sgn))
10425 return false;
10427 gimple_assign_set_rhs1 (stmt, innerop);
10428 fold_stmt (gsi, follow_single_use_edges);
10429 return true;
10432 /* Simplify a conversion from integral SSA name to float in STMT. */
10434 static bool
10435 simplify_float_conversion_using_ranges (gimple_stmt_iterator *gsi,
10436 gimple *stmt)
10438 tree rhs1 = gimple_assign_rhs1 (stmt);
10439 value_range *vr = get_value_range (rhs1);
10440 machine_mode fltmode = TYPE_MODE (TREE_TYPE (gimple_assign_lhs (stmt)));
10441 machine_mode mode;
10442 tree tem;
10443 gassign *conv;
10445 /* We can only handle constant ranges. */
10446 if (vr->type != VR_RANGE
10447 || TREE_CODE (vr->min) != INTEGER_CST
10448 || TREE_CODE (vr->max) != INTEGER_CST)
10449 return false;
10451 /* First check if we can use a signed type in place of an unsigned. */
10452 if (TYPE_UNSIGNED (TREE_TYPE (rhs1))
10453 && (can_float_p (fltmode, TYPE_MODE (TREE_TYPE (rhs1)), 0)
10454 != CODE_FOR_nothing)
10455 && range_fits_type_p (vr, TYPE_PRECISION (TREE_TYPE (rhs1)), SIGNED))
10456 mode = TYPE_MODE (TREE_TYPE (rhs1));
10457 /* If we can do the conversion in the current input mode do nothing. */
10458 else if (can_float_p (fltmode, TYPE_MODE (TREE_TYPE (rhs1)),
10459 TYPE_UNSIGNED (TREE_TYPE (rhs1))) != CODE_FOR_nothing)
10460 return false;
10461 /* Otherwise search for a mode we can use, starting from the narrowest
10462 integer mode available. */
10463 else
10465 mode = GET_CLASS_NARROWEST_MODE (MODE_INT);
10468 /* If we cannot do a signed conversion to float from mode
10469 or if the value-range does not fit in the signed type
10470 try with a wider mode. */
10471 if (can_float_p (fltmode, mode, 0) != CODE_FOR_nothing
10472 && range_fits_type_p (vr, GET_MODE_PRECISION (mode), SIGNED))
10473 break;
10475 mode = GET_MODE_WIDER_MODE (mode);
10476 /* But do not widen the input. Instead leave that to the
10477 optabs expansion code. */
10478 if (GET_MODE_PRECISION (mode) > TYPE_PRECISION (TREE_TYPE (rhs1)))
10479 return false;
10481 while (mode != VOIDmode);
10482 if (mode == VOIDmode)
10483 return false;
10486 /* It works, insert a truncation or sign-change before the
10487 float conversion. */
10488 tem = make_ssa_name (build_nonstandard_integer_type
10489 (GET_MODE_PRECISION (mode), 0));
10490 conv = gimple_build_assign (tem, NOP_EXPR, rhs1);
10491 gsi_insert_before (gsi, conv, GSI_SAME_STMT);
10492 gimple_assign_set_rhs1 (stmt, tem);
10493 fold_stmt (gsi, follow_single_use_edges);
10495 return true;
10498 /* Simplify an internal fn call using ranges if possible. */
10500 static bool
10501 simplify_internal_call_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
10503 enum tree_code subcode;
10504 bool is_ubsan = false;
10505 bool ovf = false;
10506 switch (gimple_call_internal_fn (stmt))
10508 case IFN_UBSAN_CHECK_ADD:
10509 subcode = PLUS_EXPR;
10510 is_ubsan = true;
10511 break;
10512 case IFN_UBSAN_CHECK_SUB:
10513 subcode = MINUS_EXPR;
10514 is_ubsan = true;
10515 break;
10516 case IFN_UBSAN_CHECK_MUL:
10517 subcode = MULT_EXPR;
10518 is_ubsan = true;
10519 break;
10520 case IFN_ADD_OVERFLOW:
10521 subcode = PLUS_EXPR;
10522 break;
10523 case IFN_SUB_OVERFLOW:
10524 subcode = MINUS_EXPR;
10525 break;
10526 case IFN_MUL_OVERFLOW:
10527 subcode = MULT_EXPR;
10528 break;
10529 default:
10530 return false;
10533 tree op0 = gimple_call_arg (stmt, 0);
10534 tree op1 = gimple_call_arg (stmt, 1);
10535 tree type;
10536 if (is_ubsan)
10538 type = TREE_TYPE (op0);
10539 if (VECTOR_TYPE_P (type))
10540 return false;
10542 else if (gimple_call_lhs (stmt) == NULL_TREE)
10543 return false;
10544 else
10545 type = TREE_TYPE (TREE_TYPE (gimple_call_lhs (stmt)));
10546 if (!check_for_binary_op_overflow (subcode, type, op0, op1, &ovf)
10547 || (is_ubsan && ovf))
10548 return false;
10550 gimple *g;
10551 location_t loc = gimple_location (stmt);
10552 if (is_ubsan)
10553 g = gimple_build_assign (gimple_call_lhs (stmt), subcode, op0, op1);
10554 else
10556 int prec = TYPE_PRECISION (type);
10557 tree utype = type;
10558 if (ovf
10559 || !useless_type_conversion_p (type, TREE_TYPE (op0))
10560 || !useless_type_conversion_p (type, TREE_TYPE (op1)))
10561 utype = build_nonstandard_integer_type (prec, 1);
10562 if (TREE_CODE (op0) == INTEGER_CST)
10563 op0 = fold_convert (utype, op0);
10564 else if (!useless_type_conversion_p (utype, TREE_TYPE (op0)))
10566 g = gimple_build_assign (make_ssa_name (utype), NOP_EXPR, op0);
10567 gimple_set_location (g, loc);
10568 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10569 op0 = gimple_assign_lhs (g);
10571 if (TREE_CODE (op1) == INTEGER_CST)
10572 op1 = fold_convert (utype, op1);
10573 else if (!useless_type_conversion_p (utype, TREE_TYPE (op1)))
10575 g = gimple_build_assign (make_ssa_name (utype), NOP_EXPR, op1);
10576 gimple_set_location (g, loc);
10577 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10578 op1 = gimple_assign_lhs (g);
10580 g = gimple_build_assign (make_ssa_name (utype), subcode, op0, op1);
10581 gimple_set_location (g, loc);
10582 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10583 if (utype != type)
10585 g = gimple_build_assign (make_ssa_name (type), NOP_EXPR,
10586 gimple_assign_lhs (g));
10587 gimple_set_location (g, loc);
10588 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10590 g = gimple_build_assign (gimple_call_lhs (stmt), COMPLEX_EXPR,
10591 gimple_assign_lhs (g),
10592 build_int_cst (type, ovf));
10594 gimple_set_location (g, loc);
10595 gsi_replace (gsi, g, false);
10596 return true;
10599 /* Return true if VAR is a two-valued variable. Set a and b with the
10600 two-values when it is true. Return false otherwise. */
10602 static bool
10603 two_valued_val_range_p (tree var, tree *a, tree *b)
10605 value_range *vr = get_value_range (var);
10606 if ((vr->type != VR_RANGE
10607 && vr->type != VR_ANTI_RANGE)
10608 || TREE_CODE (vr->min) != INTEGER_CST
10609 || TREE_CODE (vr->max) != INTEGER_CST)
10610 return false;
10612 if (vr->type == VR_RANGE
10613 && wi::sub (vr->max, vr->min) == 1)
10615 *a = vr->min;
10616 *b = vr->max;
10617 return true;
10620 /* ~[TYPE_MIN + 1, TYPE_MAX - 1] */
10621 if (vr->type == VR_ANTI_RANGE
10622 && wi::sub (vr->min, vrp_val_min (TREE_TYPE (var))) == 1
10623 && wi::sub (vrp_val_max (TREE_TYPE (var)), vr->max) == 1)
10625 *a = vrp_val_min (TREE_TYPE (var));
10626 *b = vrp_val_max (TREE_TYPE (var));
10627 return true;
10630 return false;
10633 /* Simplify STMT using ranges if possible. */
10635 static bool
10636 simplify_stmt_using_ranges (gimple_stmt_iterator *gsi)
10638 gimple *stmt = gsi_stmt (*gsi);
10639 if (is_gimple_assign (stmt))
10641 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
10642 tree rhs1 = gimple_assign_rhs1 (stmt);
10643 tree rhs2 = gimple_assign_rhs2 (stmt);
10644 tree lhs = gimple_assign_lhs (stmt);
10645 tree val1 = NULL_TREE, val2 = NULL_TREE;
10646 use_operand_p use_p;
10647 gimple *use_stmt;
10649 /* Convert:
10650 LHS = CST BINOP VAR
10651 Where VAR is two-valued and LHS is used in GIMPLE_COND only
10653 LHS = VAR == VAL1 ? (CST BINOP VAL1) : (CST BINOP VAL2)
10655 Also handles:
10656 LHS = VAR BINOP CST
10657 Where VAR is two-valued and LHS is used in GIMPLE_COND only
10659 LHS = VAR == VAL1 ? (VAL1 BINOP CST) : (VAL2 BINOP CST) */
10661 if (TREE_CODE_CLASS (rhs_code) == tcc_binary
10662 && INTEGRAL_TYPE_P (TREE_TYPE (lhs))
10663 && ((TREE_CODE (rhs1) == INTEGER_CST
10664 && TREE_CODE (rhs2) == SSA_NAME)
10665 || (TREE_CODE (rhs2) == INTEGER_CST
10666 && TREE_CODE (rhs1) == SSA_NAME))
10667 && single_imm_use (lhs, &use_p, &use_stmt)
10668 && gimple_code (use_stmt) == GIMPLE_COND)
10671 tree new_rhs1 = NULL_TREE;
10672 tree new_rhs2 = NULL_TREE;
10673 tree cmp_var = NULL_TREE;
10675 if (TREE_CODE (rhs2) == SSA_NAME
10676 && two_valued_val_range_p (rhs2, &val1, &val2))
10678 /* Optimize RHS1 OP [VAL1, VAL2]. */
10679 new_rhs1 = int_const_binop (rhs_code, rhs1, val1);
10680 new_rhs2 = int_const_binop (rhs_code, rhs1, val2);
10681 cmp_var = rhs2;
10683 else if (TREE_CODE (rhs1) == SSA_NAME
10684 && two_valued_val_range_p (rhs1, &val1, &val2))
10686 /* Optimize [VAL1, VAL2] OP RHS2. */
10687 new_rhs1 = int_const_binop (rhs_code, val1, rhs2);
10688 new_rhs2 = int_const_binop (rhs_code, val2, rhs2);
10689 cmp_var = rhs1;
10692 /* If we could not find two-vals or the optimzation is invalid as
10693 in divide by zero, new_rhs1 / new_rhs will be NULL_TREE. */
10694 if (new_rhs1 && new_rhs2)
10696 tree cond = build2 (EQ_EXPR, boolean_type_node, cmp_var, val1);
10697 gimple_assign_set_rhs_with_ops (gsi,
10698 COND_EXPR, cond,
10699 new_rhs1,
10700 new_rhs2);
10701 update_stmt (gsi_stmt (*gsi));
10702 fold_stmt (gsi, follow_single_use_edges);
10703 return true;
10707 switch (rhs_code)
10709 case EQ_EXPR:
10710 case NE_EXPR:
10711 /* Transform EQ_EXPR, NE_EXPR into BIT_XOR_EXPR or identity
10712 if the RHS is zero or one, and the LHS are known to be boolean
10713 values. */
10714 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10715 return simplify_truth_ops_using_ranges (gsi, stmt);
10716 break;
10718 /* Transform TRUNC_DIV_EXPR and TRUNC_MOD_EXPR into RSHIFT_EXPR
10719 and BIT_AND_EXPR respectively if the first operand is greater
10720 than zero and the second operand is an exact power of two.
10721 Also optimize TRUNC_MOD_EXPR away if the second operand is
10722 constant and the first operand already has the right value
10723 range. */
10724 case TRUNC_DIV_EXPR:
10725 case TRUNC_MOD_EXPR:
10726 if ((TREE_CODE (rhs1) == SSA_NAME
10727 || TREE_CODE (rhs1) == INTEGER_CST)
10728 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10729 return simplify_div_or_mod_using_ranges (gsi, stmt);
10730 break;
10732 /* Transform ABS (X) into X or -X as appropriate. */
10733 case ABS_EXPR:
10734 if (TREE_CODE (rhs1) == SSA_NAME
10735 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10736 return simplify_abs_using_ranges (gsi, stmt);
10737 break;
10739 case BIT_AND_EXPR:
10740 case BIT_IOR_EXPR:
10741 /* Optimize away BIT_AND_EXPR and BIT_IOR_EXPR
10742 if all the bits being cleared are already cleared or
10743 all the bits being set are already set. */
10744 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10745 return simplify_bit_ops_using_ranges (gsi, stmt);
10746 break;
10748 CASE_CONVERT:
10749 if (TREE_CODE (rhs1) == SSA_NAME
10750 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10751 return simplify_conversion_using_ranges (gsi, stmt);
10752 break;
10754 case FLOAT_EXPR:
10755 if (TREE_CODE (rhs1) == SSA_NAME
10756 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10757 return simplify_float_conversion_using_ranges (gsi, stmt);
10758 break;
10760 case MIN_EXPR:
10761 case MAX_EXPR:
10762 return simplify_min_or_max_using_ranges (gsi, stmt);
10764 default:
10765 break;
10768 else if (gimple_code (stmt) == GIMPLE_COND)
10769 return simplify_cond_using_ranges_1 (as_a <gcond *> (stmt));
10770 else if (gimple_code (stmt) == GIMPLE_SWITCH)
10771 return simplify_switch_using_ranges (as_a <gswitch *> (stmt));
10772 else if (is_gimple_call (stmt)
10773 && gimple_call_internal_p (stmt))
10774 return simplify_internal_call_using_ranges (gsi, stmt);
10776 return false;
10779 /* If the statement pointed by SI has a predicate whose value can be
10780 computed using the value range information computed by VRP, compute
10781 its value and return true. Otherwise, return false. */
10783 static bool
10784 fold_predicate_in (gimple_stmt_iterator *si)
10786 bool assignment_p = false;
10787 tree val;
10788 gimple *stmt = gsi_stmt (*si);
10790 if (is_gimple_assign (stmt)
10791 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
10793 assignment_p = true;
10794 val = vrp_evaluate_conditional (gimple_assign_rhs_code (stmt),
10795 gimple_assign_rhs1 (stmt),
10796 gimple_assign_rhs2 (stmt),
10797 stmt);
10799 else if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
10800 val = vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
10801 gimple_cond_lhs (cond_stmt),
10802 gimple_cond_rhs (cond_stmt),
10803 stmt);
10804 else
10805 return false;
10807 if (val)
10809 if (assignment_p)
10810 val = fold_convert (gimple_expr_type (stmt), val);
10812 if (dump_file)
10814 fprintf (dump_file, "Folding predicate ");
10815 print_gimple_expr (dump_file, stmt, 0, 0);
10816 fprintf (dump_file, " to ");
10817 print_generic_expr (dump_file, val, 0);
10818 fprintf (dump_file, "\n");
10821 if (is_gimple_assign (stmt))
10822 gimple_assign_set_rhs_from_tree (si, val);
10823 else
10825 gcc_assert (gimple_code (stmt) == GIMPLE_COND);
10826 gcond *cond_stmt = as_a <gcond *> (stmt);
10827 if (integer_zerop (val))
10828 gimple_cond_make_false (cond_stmt);
10829 else if (integer_onep (val))
10830 gimple_cond_make_true (cond_stmt);
10831 else
10832 gcc_unreachable ();
10835 return true;
10838 return false;
10841 /* Callback for substitute_and_fold folding the stmt at *SI. */
10843 static bool
10844 vrp_fold_stmt (gimple_stmt_iterator *si)
10846 if (fold_predicate_in (si))
10847 return true;
10849 return simplify_stmt_using_ranges (si);
10852 /* Return the LHS of any ASSERT_EXPR where OP appears as the first
10853 argument to the ASSERT_EXPR and in which the ASSERT_EXPR dominates
10854 BB. If no such ASSERT_EXPR is found, return OP. */
10856 static tree
10857 lhs_of_dominating_assert (tree op, basic_block bb, gimple *stmt)
10859 imm_use_iterator imm_iter;
10860 gimple *use_stmt;
10861 use_operand_p use_p;
10863 if (TREE_CODE (op) == SSA_NAME)
10865 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, op)
10867 use_stmt = USE_STMT (use_p);
10868 if (use_stmt != stmt
10869 && gimple_assign_single_p (use_stmt)
10870 && TREE_CODE (gimple_assign_rhs1 (use_stmt)) == ASSERT_EXPR
10871 && TREE_OPERAND (gimple_assign_rhs1 (use_stmt), 0) == op
10872 && dominated_by_p (CDI_DOMINATORS, bb, gimple_bb (use_stmt)))
10873 return gimple_assign_lhs (use_stmt);
10876 return op;
10879 /* A trivial wrapper so that we can present the generic jump threading
10880 code with a simple API for simplifying statements. STMT is the
10881 statement we want to simplify, WITHIN_STMT provides the location
10882 for any overflow warnings. */
10884 static tree
10885 simplify_stmt_for_jump_threading (gimple *stmt, gimple *within_stmt,
10886 class avail_exprs_stack *avail_exprs_stack ATTRIBUTE_UNUSED,
10887 basic_block bb)
10889 /* First see if the conditional is in the hash table. */
10890 tree cached_lhs = avail_exprs_stack->lookup_avail_expr (stmt, false, true);
10891 if (cached_lhs && is_gimple_min_invariant (cached_lhs))
10892 return cached_lhs;
10894 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
10896 tree op0 = gimple_cond_lhs (cond_stmt);
10897 op0 = lhs_of_dominating_assert (op0, bb, stmt);
10899 tree op1 = gimple_cond_rhs (cond_stmt);
10900 op1 = lhs_of_dominating_assert (op1, bb, stmt);
10902 return vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
10903 op0, op1, within_stmt);
10906 /* We simplify a switch statement by trying to determine which case label
10907 will be taken. If we are successful then we return the corresponding
10908 CASE_LABEL_EXPR. */
10909 if (gswitch *switch_stmt = dyn_cast <gswitch *> (stmt))
10911 tree op = gimple_switch_index (switch_stmt);
10912 if (TREE_CODE (op) != SSA_NAME)
10913 return NULL_TREE;
10915 op = lhs_of_dominating_assert (op, bb, stmt);
10917 value_range *vr = get_value_range (op);
10918 if ((vr->type != VR_RANGE && vr->type != VR_ANTI_RANGE)
10919 || symbolic_range_p (vr))
10920 return NULL_TREE;
10922 if (vr->type == VR_RANGE)
10924 size_t i, j;
10925 /* Get the range of labels that contain a part of the operand's
10926 value range. */
10927 find_case_label_range (switch_stmt, vr->min, vr->max, &i, &j);
10929 /* Is there only one such label? */
10930 if (i == j)
10932 tree label = gimple_switch_label (switch_stmt, i);
10934 /* The i'th label will be taken only if the value range of the
10935 operand is entirely within the bounds of this label. */
10936 if (CASE_HIGH (label) != NULL_TREE
10937 ? (tree_int_cst_compare (CASE_LOW (label), vr->min) <= 0
10938 && tree_int_cst_compare (CASE_HIGH (label), vr->max) >= 0)
10939 : (tree_int_cst_equal (CASE_LOW (label), vr->min)
10940 && tree_int_cst_equal (vr->min, vr->max)))
10941 return label;
10944 /* If there are no such labels then the default label will be
10945 taken. */
10946 if (i > j)
10947 return gimple_switch_label (switch_stmt, 0);
10950 if (vr->type == VR_ANTI_RANGE)
10952 unsigned n = gimple_switch_num_labels (switch_stmt);
10953 tree min_label = gimple_switch_label (switch_stmt, 1);
10954 tree max_label = gimple_switch_label (switch_stmt, n - 1);
10956 /* The default label will be taken only if the anti-range of the
10957 operand is entirely outside the bounds of all the (non-default)
10958 case labels. */
10959 if (tree_int_cst_compare (vr->min, CASE_LOW (min_label)) <= 0
10960 && (CASE_HIGH (max_label) != NULL_TREE
10961 ? tree_int_cst_compare (vr->max, CASE_HIGH (max_label)) >= 0
10962 : tree_int_cst_compare (vr->max, CASE_LOW (max_label)) >= 0))
10963 return gimple_switch_label (switch_stmt, 0);
10966 return NULL_TREE;
10969 if (gassign *assign_stmt = dyn_cast <gassign *> (stmt))
10971 value_range new_vr = VR_INITIALIZER;
10972 tree lhs = gimple_assign_lhs (assign_stmt);
10974 if (TREE_CODE (lhs) == SSA_NAME
10975 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
10976 || POINTER_TYPE_P (TREE_TYPE (lhs))))
10978 extract_range_from_assignment (&new_vr, assign_stmt);
10979 if (range_int_cst_singleton_p (&new_vr))
10980 return new_vr.min;
10984 return NULL_TREE;
10987 class vrp_dom_walker : public dom_walker
10989 public:
10990 vrp_dom_walker (cdi_direction direction,
10991 class const_and_copies *const_and_copies,
10992 class avail_exprs_stack *avail_exprs_stack)
10993 : dom_walker (direction, true),
10994 m_const_and_copies (const_and_copies),
10995 m_avail_exprs_stack (avail_exprs_stack),
10996 m_dummy_cond (NULL) {}
10998 virtual edge before_dom_children (basic_block);
10999 virtual void after_dom_children (basic_block);
11001 private:
11002 class const_and_copies *m_const_and_copies;
11003 class avail_exprs_stack *m_avail_exprs_stack;
11005 gcond *m_dummy_cond;
11008 /* Called before processing dominator children of BB. We want to look
11009 at ASSERT_EXPRs and record information from them in the appropriate
11010 tables.
11012 We could look at other statements here. It's not seen as likely
11013 to significantly increase the jump threads we discover. */
11015 edge
11016 vrp_dom_walker::before_dom_children (basic_block bb)
11018 gimple_stmt_iterator gsi;
11020 for (gsi = gsi_start_nondebug_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
11022 gimple *stmt = gsi_stmt (gsi);
11023 if (gimple_assign_single_p (stmt)
11024 && TREE_CODE (gimple_assign_rhs1 (stmt)) == ASSERT_EXPR)
11026 tree rhs1 = gimple_assign_rhs1 (stmt);
11027 tree cond = TREE_OPERAND (rhs1, 1);
11028 tree inverted = invert_truthvalue (cond);
11029 vec<cond_equivalence> p;
11030 p.create (3);
11031 record_conditions (&p, cond, inverted);
11032 for (unsigned int i = 0; i < p.length (); i++)
11033 m_avail_exprs_stack->record_cond (&p[i]);
11035 tree lhs = gimple_assign_lhs (stmt);
11036 m_const_and_copies->record_const_or_copy (lhs,
11037 TREE_OPERAND (rhs1, 0));
11038 p.release ();
11039 continue;
11041 break;
11043 return NULL;
11046 /* Called after processing dominator children of BB. This is where we
11047 actually call into the threader. */
11048 void
11049 vrp_dom_walker::after_dom_children (basic_block bb)
11051 if (!m_dummy_cond)
11052 m_dummy_cond = gimple_build_cond (NE_EXPR,
11053 integer_zero_node, integer_zero_node,
11054 NULL, NULL);
11056 thread_outgoing_edges (bb, m_dummy_cond, m_const_and_copies,
11057 m_avail_exprs_stack,
11058 simplify_stmt_for_jump_threading);
11060 m_avail_exprs_stack->pop_to_marker ();
11061 m_const_and_copies->pop_to_marker ();
11064 /* Blocks which have more than one predecessor and more than
11065 one successor present jump threading opportunities, i.e.,
11066 when the block is reached from a specific predecessor, we
11067 may be able to determine which of the outgoing edges will
11068 be traversed. When this optimization applies, we are able
11069 to avoid conditionals at runtime and we may expose secondary
11070 optimization opportunities.
11072 This routine is effectively a driver for the generic jump
11073 threading code. It basically just presents the generic code
11074 with edges that may be suitable for jump threading.
11076 Unlike DOM, we do not iterate VRP if jump threading was successful.
11077 While iterating may expose new opportunities for VRP, it is expected
11078 those opportunities would be very limited and the compile time cost
11079 to expose those opportunities would be significant.
11081 As jump threading opportunities are discovered, they are registered
11082 for later realization. */
11084 static void
11085 identify_jump_threads (void)
11087 int i;
11088 edge e;
11090 /* Ugh. When substituting values earlier in this pass we can
11091 wipe the dominance information. So rebuild the dominator
11092 information as we need it within the jump threading code. */
11093 calculate_dominance_info (CDI_DOMINATORS);
11095 /* We do not allow VRP information to be used for jump threading
11096 across a back edge in the CFG. Otherwise it becomes too
11097 difficult to avoid eliminating loop exit tests. Of course
11098 EDGE_DFS_BACK is not accurate at this time so we have to
11099 recompute it. */
11100 mark_dfs_back_edges ();
11102 /* Do not thread across edges we are about to remove. Just marking
11103 them as EDGE_IGNORE will do. */
11104 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
11105 e->flags |= EDGE_IGNORE;
11107 /* Allocate our unwinder stack to unwind any temporary equivalences
11108 that might be recorded. */
11109 const_and_copies *equiv_stack = new const_and_copies ();
11111 hash_table<expr_elt_hasher> *avail_exprs
11112 = new hash_table<expr_elt_hasher> (1024);
11113 avail_exprs_stack *avail_exprs_stack
11114 = new class avail_exprs_stack (avail_exprs);
11116 vrp_dom_walker walker (CDI_DOMINATORS, equiv_stack, avail_exprs_stack);
11117 walker.walk (cfun->cfg->x_entry_block_ptr);
11119 /* Clear EDGE_IGNORE. */
11120 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
11121 e->flags &= ~EDGE_IGNORE;
11123 /* We do not actually update the CFG or SSA graphs at this point as
11124 ASSERT_EXPRs are still in the IL and cfg cleanup code does not yet
11125 handle ASSERT_EXPRs gracefully. */
11126 delete equiv_stack;
11127 delete avail_exprs;
11128 delete avail_exprs_stack;
11131 /* Free VRP lattice. */
11133 static void
11134 vrp_free_lattice ()
11136 /* Free allocated memory. */
11137 free (vr_value);
11138 free (vr_phi_edge_counts);
11139 bitmap_obstack_release (&vrp_equiv_obstack);
11140 vrp_value_range_pool.release ();
11142 /* So that we can distinguish between VRP data being available
11143 and not available. */
11144 vr_value = NULL;
11145 vr_phi_edge_counts = NULL;
11148 /* Traverse all the blocks folding conditionals with known ranges. */
11150 static void
11151 vrp_finalize (bool warn_array_bounds_p)
11153 size_t i;
11155 values_propagated = true;
11157 if (dump_file)
11159 fprintf (dump_file, "\nValue ranges after VRP:\n\n");
11160 dump_all_value_ranges (dump_file);
11161 fprintf (dump_file, "\n");
11164 /* Set value range to non pointer SSA_NAMEs. */
11165 for (i = 0; i < num_vr_values; i++)
11166 if (vr_value[i])
11168 tree name = ssa_name (i);
11170 if (!name
11171 || (vr_value[i]->type == VR_VARYING)
11172 || (vr_value[i]->type == VR_UNDEFINED)
11173 || (TREE_CODE (vr_value[i]->min) != INTEGER_CST)
11174 || (TREE_CODE (vr_value[i]->max) != INTEGER_CST))
11175 continue;
11177 if (POINTER_TYPE_P (TREE_TYPE (name))
11178 && ((vr_value[i]->type == VR_RANGE
11179 && range_includes_zero_p (vr_value[i]->min,
11180 vr_value[i]->max) == 0)
11181 || (vr_value[i]->type == VR_ANTI_RANGE
11182 && range_includes_zero_p (vr_value[i]->min,
11183 vr_value[i]->max) == 1)))
11184 set_ptr_nonnull (name);
11185 else if (!POINTER_TYPE_P (TREE_TYPE (name)))
11186 set_range_info (name, vr_value[i]->type, vr_value[i]->min,
11187 vr_value[i]->max);
11190 substitute_and_fold (op_with_constant_singleton_value_range, vrp_fold_stmt);
11192 if (warn_array_bounds && warn_array_bounds_p)
11193 check_all_array_refs ();
11196 /* evrp_dom_walker visits the basic blocks in the dominance order and set
11197 the Value Ranges (VR) for SSA_NAMEs in the scope. Use this VR to
11198 discover more VRs. */
11200 class evrp_dom_walker : public dom_walker
11202 public:
11203 evrp_dom_walker ()
11204 : dom_walker (CDI_DOMINATORS), stack (10)
11206 need_eh_cleanup = BITMAP_ALLOC (NULL);
11208 ~evrp_dom_walker ()
11210 BITMAP_FREE (need_eh_cleanup);
11212 virtual edge before_dom_children (basic_block);
11213 virtual void after_dom_children (basic_block);
11214 void push_value_range (tree var, value_range *vr);
11215 value_range *pop_value_range (tree var);
11216 value_range *try_find_new_range (tree, tree op, tree_code code, tree limit);
11218 /* Cond_stack holds the old VR. */
11219 auto_vec<std::pair <tree, value_range*> > stack;
11220 bitmap need_eh_cleanup;
11221 auto_vec<gimple *> stmts_to_fixup;
11222 auto_vec<gimple *> stmts_to_remove;
11225 /* Find new range for NAME such that (OP CODE LIMIT) is true. */
11227 value_range *
11228 evrp_dom_walker::try_find_new_range (tree name,
11229 tree op, tree_code code, tree limit)
11231 value_range vr = VR_INITIALIZER;
11232 value_range *old_vr = get_value_range (name);
11234 /* Discover VR when condition is true. */
11235 extract_range_for_var_from_comparison_expr (name, code, op,
11236 limit, &vr);
11237 /* If we found any usable VR, set the VR to ssa_name and create a
11238 PUSH old value in the stack with the old VR. */
11239 if (vr.type == VR_RANGE || vr.type == VR_ANTI_RANGE)
11241 if (old_vr->type == vr.type
11242 && vrp_operand_equal_p (old_vr->min, vr.min)
11243 && vrp_operand_equal_p (old_vr->max, vr.max))
11244 return NULL;
11245 value_range *new_vr = vrp_value_range_pool.allocate ();
11246 *new_vr = vr;
11247 return new_vr;
11249 return NULL;
11252 /* See if there is any new scope is entered with new VR and set that VR to
11253 ssa_name before visiting the statements in the scope. */
11255 edge
11256 evrp_dom_walker::before_dom_children (basic_block bb)
11258 tree op0 = NULL_TREE;
11259 edge_iterator ei;
11260 edge e;
11262 if (dump_file && (dump_flags & TDF_DETAILS))
11263 fprintf (dump_file, "Visiting BB%d\n", bb->index);
11265 stack.safe_push (std::make_pair (NULL_TREE, (value_range *)NULL));
11267 edge pred_e = NULL;
11268 FOR_EACH_EDGE (e, ei, bb->preds)
11270 /* Ignore simple backedges from this to allow recording conditions
11271 in loop headers. */
11272 if (dominated_by_p (CDI_DOMINATORS, e->src, e->dest))
11273 continue;
11274 if (! pred_e)
11275 pred_e = e;
11276 else
11278 pred_e = NULL;
11279 break;
11282 if (pred_e)
11284 gimple *stmt = last_stmt (pred_e->src);
11285 if (stmt
11286 && gimple_code (stmt) == GIMPLE_COND
11287 && (op0 = gimple_cond_lhs (stmt))
11288 && TREE_CODE (op0) == SSA_NAME
11289 && (INTEGRAL_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)))
11290 || POINTER_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)))))
11292 if (dump_file && (dump_flags & TDF_DETAILS))
11294 fprintf (dump_file, "Visiting controlling predicate ");
11295 print_gimple_stmt (dump_file, stmt, 0, 0);
11297 /* Entering a new scope. Try to see if we can find a VR
11298 here. */
11299 tree op1 = gimple_cond_rhs (stmt);
11300 if (TREE_OVERFLOW_P (op1))
11301 op1 = drop_tree_overflow (op1);
11302 tree_code code = gimple_cond_code (stmt);
11304 auto_vec<assert_info, 8> asserts;
11305 register_edge_assert_for (op0, pred_e, code, op0, op1, asserts);
11306 if (TREE_CODE (op1) == SSA_NAME)
11307 register_edge_assert_for (op1, pred_e, code, op0, op1, asserts);
11309 auto_vec<std::pair<tree, value_range *>, 8> vrs;
11310 for (unsigned i = 0; i < asserts.length (); ++i)
11312 value_range *vr = try_find_new_range (asserts[i].name,
11313 asserts[i].expr,
11314 asserts[i].comp_code,
11315 asserts[i].val);
11316 if (vr)
11317 vrs.safe_push (std::make_pair (asserts[i].name, vr));
11319 /* Push updated ranges only after finding all of them to avoid
11320 ordering issues that can lead to worse ranges. */
11321 for (unsigned i = 0; i < vrs.length (); ++i)
11322 push_value_range (vrs[i].first, vrs[i].second);
11326 /* Visit PHI stmts and discover any new VRs possible. */
11327 bool has_unvisited_preds = false;
11328 FOR_EACH_EDGE (e, ei, bb->preds)
11329 if (e->flags & EDGE_EXECUTABLE
11330 && !(e->src->flags & BB_VISITED))
11332 has_unvisited_preds = true;
11333 break;
11336 for (gphi_iterator gpi = gsi_start_phis (bb);
11337 !gsi_end_p (gpi); gsi_next (&gpi))
11339 gphi *phi = gpi.phi ();
11340 tree lhs = PHI_RESULT (phi);
11341 if (virtual_operand_p (lhs))
11342 continue;
11343 value_range vr_result = VR_INITIALIZER;
11344 bool interesting = stmt_interesting_for_vrp (phi);
11345 if (interesting && dump_file && (dump_flags & TDF_DETAILS))
11347 fprintf (dump_file, "Visiting PHI node ");
11348 print_gimple_stmt (dump_file, phi, 0, 0);
11350 if (!has_unvisited_preds
11351 && interesting)
11352 extract_range_from_phi_node (phi, &vr_result);
11353 else
11355 set_value_range_to_varying (&vr_result);
11356 /* When we have an unvisited executable predecessor we can't
11357 use PHI arg ranges which may be still UNDEFINED but have
11358 to use VARYING for them. But we can still resort to
11359 SCEV for loop header PHIs. */
11360 struct loop *l;
11361 if (interesting
11362 && (l = loop_containing_stmt (phi))
11363 && l->header == gimple_bb (phi))
11364 adjust_range_with_scev (&vr_result, l, phi, lhs);
11366 update_value_range (lhs, &vr_result);
11368 /* Mark PHIs whose lhs we fully propagate for removal. */
11369 tree val = op_with_constant_singleton_value_range (lhs);
11370 if (val && may_propagate_copy (lhs, val))
11372 stmts_to_remove.safe_push (phi);
11373 continue;
11376 /* Set the SSA with the value range. */
11377 if (INTEGRAL_TYPE_P (TREE_TYPE (lhs)))
11379 if ((vr_result.type == VR_RANGE
11380 || vr_result.type == VR_ANTI_RANGE)
11381 && (TREE_CODE (vr_result.min) == INTEGER_CST)
11382 && (TREE_CODE (vr_result.max) == INTEGER_CST))
11383 set_range_info (lhs,
11384 vr_result.type, vr_result.min, vr_result.max);
11386 else if (POINTER_TYPE_P (TREE_TYPE (lhs))
11387 && ((vr_result.type == VR_RANGE
11388 && range_includes_zero_p (vr_result.min,
11389 vr_result.max) == 0)
11390 || (vr_result.type == VR_ANTI_RANGE
11391 && range_includes_zero_p (vr_result.min,
11392 vr_result.max) == 1)))
11393 set_ptr_nonnull (lhs);
11396 edge taken_edge = NULL;
11398 /* Visit all other stmts and discover any new VRs possible. */
11399 for (gimple_stmt_iterator gsi = gsi_start_bb (bb);
11400 !gsi_end_p (gsi); gsi_next (&gsi))
11402 gimple *stmt = gsi_stmt (gsi);
11403 tree output = NULL_TREE;
11404 gimple *old_stmt = stmt;
11405 bool was_noreturn = (is_gimple_call (stmt)
11406 && gimple_call_noreturn_p (stmt));
11408 if (dump_file && (dump_flags & TDF_DETAILS))
11410 fprintf (dump_file, "Visiting stmt ");
11411 print_gimple_stmt (dump_file, stmt, 0, 0);
11414 if (gcond *cond = dyn_cast <gcond *> (stmt))
11416 vrp_visit_cond_stmt (cond, &taken_edge);
11417 if (taken_edge)
11419 if (taken_edge->flags & EDGE_TRUE_VALUE)
11420 gimple_cond_make_true (cond);
11421 else if (taken_edge->flags & EDGE_FALSE_VALUE)
11422 gimple_cond_make_false (cond);
11423 else
11424 gcc_unreachable ();
11425 update_stmt (stmt);
11428 else if (stmt_interesting_for_vrp (stmt))
11430 edge taken_edge;
11431 value_range vr = VR_INITIALIZER;
11432 extract_range_from_stmt (stmt, &taken_edge, &output, &vr);
11433 if (output
11434 && (vr.type == VR_RANGE || vr.type == VR_ANTI_RANGE))
11436 update_value_range (output, &vr);
11437 vr = *get_value_range (output);
11439 /* Mark stmts whose output we fully propagate for removal. */
11440 tree val;
11441 if ((val = op_with_constant_singleton_value_range (output))
11442 && may_propagate_copy (output, val)
11443 && !stmt_could_throw_p (stmt)
11444 && !gimple_has_side_effects (stmt))
11446 stmts_to_remove.safe_push (stmt);
11447 continue;
11450 /* Set the SSA with the value range. */
11451 if (INTEGRAL_TYPE_P (TREE_TYPE (output)))
11453 if ((vr.type == VR_RANGE
11454 || vr.type == VR_ANTI_RANGE)
11455 && (TREE_CODE (vr.min) == INTEGER_CST)
11456 && (TREE_CODE (vr.max) == INTEGER_CST))
11457 set_range_info (output, vr.type, vr.min, vr.max);
11459 else if (POINTER_TYPE_P (TREE_TYPE (output))
11460 && ((vr.type == VR_RANGE
11461 && range_includes_zero_p (vr.min,
11462 vr.max) == 0)
11463 || (vr.type == VR_ANTI_RANGE
11464 && range_includes_zero_p (vr.min,
11465 vr.max) == 1)))
11466 set_ptr_nonnull (output);
11468 else
11469 set_defs_to_varying (stmt);
11471 else
11472 set_defs_to_varying (stmt);
11474 /* See if we can derive a range for any of STMT's operands. */
11475 tree op;
11476 ssa_op_iter i;
11477 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
11479 tree value;
11480 enum tree_code comp_code;
11482 /* If OP is used in such a way that we can infer a value
11483 range for it, and we don't find a previous assertion for
11484 it, create a new assertion location node for OP. */
11485 if (infer_value_range (stmt, op, &comp_code, &value))
11487 /* If we are able to infer a nonzero value range for OP,
11488 then walk backwards through the use-def chain to see if OP
11489 was set via a typecast.
11490 If so, then we can also infer a nonzero value range
11491 for the operand of the NOP_EXPR. */
11492 if (comp_code == NE_EXPR && integer_zerop (value))
11494 tree t = op;
11495 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
11496 while (is_gimple_assign (def_stmt)
11497 && CONVERT_EXPR_CODE_P
11498 (gimple_assign_rhs_code (def_stmt))
11499 && TREE_CODE
11500 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
11501 && POINTER_TYPE_P
11502 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
11504 t = gimple_assign_rhs1 (def_stmt);
11505 def_stmt = SSA_NAME_DEF_STMT (t);
11507 /* Add VR when (T COMP_CODE value) condition is
11508 true. */
11509 value_range *op_range
11510 = try_find_new_range (t, t, comp_code, value);
11511 if (op_range)
11512 push_value_range (t, op_range);
11515 /* Add VR when (OP COMP_CODE value) condition is true. */
11516 value_range *op_range = try_find_new_range (op, op,
11517 comp_code, value);
11518 if (op_range)
11519 push_value_range (op, op_range);
11523 /* Try folding stmts with the VR discovered. */
11524 bool did_replace
11525 = replace_uses_in (stmt, op_with_constant_singleton_value_range);
11526 if (fold_stmt (&gsi, follow_single_use_edges)
11527 || did_replace)
11529 stmt = gsi_stmt (gsi);
11530 update_stmt (stmt);
11531 did_replace = true;
11534 if (did_replace)
11536 /* If we cleaned up EH information from the statement,
11537 remove EH edges. */
11538 if (maybe_clean_or_replace_eh_stmt (old_stmt, stmt))
11539 bitmap_set_bit (need_eh_cleanup, bb->index);
11541 /* If we turned a not noreturn call into a noreturn one
11542 schedule it for fixup. */
11543 if (!was_noreturn
11544 && is_gimple_call (stmt)
11545 && gimple_call_noreturn_p (stmt))
11546 stmts_to_fixup.safe_push (stmt);
11548 if (gimple_assign_single_p (stmt))
11550 tree rhs = gimple_assign_rhs1 (stmt);
11551 if (TREE_CODE (rhs) == ADDR_EXPR)
11552 recompute_tree_invariant_for_addr_expr (rhs);
11557 /* Visit BB successor PHI nodes and replace PHI args. */
11558 FOR_EACH_EDGE (e, ei, bb->succs)
11560 for (gphi_iterator gpi = gsi_start_phis (e->dest);
11561 !gsi_end_p (gpi); gsi_next (&gpi))
11563 gphi *phi = gpi.phi ();
11564 use_operand_p use_p = PHI_ARG_DEF_PTR_FROM_EDGE (phi, e);
11565 tree arg = USE_FROM_PTR (use_p);
11566 if (TREE_CODE (arg) != SSA_NAME
11567 || virtual_operand_p (arg))
11568 continue;
11569 tree val = op_with_constant_singleton_value_range (arg);
11570 if (val && may_propagate_copy (arg, val))
11571 propagate_value (use_p, val);
11575 bb->flags |= BB_VISITED;
11577 return taken_edge;
11580 /* Restore/pop VRs valid only for BB when we leave BB. */
11582 void
11583 evrp_dom_walker::after_dom_children (basic_block bb ATTRIBUTE_UNUSED)
11585 gcc_checking_assert (!stack.is_empty ());
11586 while (stack.last ().first != NULL_TREE)
11587 pop_value_range (stack.last ().first);
11588 stack.pop ();
11591 /* Push the Value Range of VAR to the stack and update it with new VR. */
11593 void
11594 evrp_dom_walker::push_value_range (tree var, value_range *vr)
11596 if (SSA_NAME_VERSION (var) >= num_vr_values)
11597 return;
11598 if (dump_file && (dump_flags & TDF_DETAILS))
11600 fprintf (dump_file, "pushing new range for ");
11601 print_generic_expr (dump_file, var, 0);
11602 fprintf (dump_file, ": ");
11603 dump_value_range (dump_file, vr);
11604 fprintf (dump_file, "\n");
11606 stack.safe_push (std::make_pair (var, get_value_range (var)));
11607 vr_value[SSA_NAME_VERSION (var)] = vr;
11610 /* Pop the Value Range from the vrp_stack and update VAR with it. */
11612 value_range *
11613 evrp_dom_walker::pop_value_range (tree var)
11615 value_range *vr = stack.last ().second;
11616 gcc_checking_assert (var == stack.last ().first);
11617 if (dump_file && (dump_flags & TDF_DETAILS))
11619 fprintf (dump_file, "popping range for ");
11620 print_generic_expr (dump_file, var, 0);
11621 fprintf (dump_file, ", restoring ");
11622 dump_value_range (dump_file, vr);
11623 fprintf (dump_file, "\n");
11625 vr_value[SSA_NAME_VERSION (var)] = vr;
11626 stack.pop ();
11627 return vr;
11631 /* Main entry point for the early vrp pass which is a simplified non-iterative
11632 version of vrp where basic blocks are visited in dominance order. Value
11633 ranges discovered in early vrp will also be used by ipa-vrp. */
11635 static unsigned int
11636 execute_early_vrp ()
11638 edge e;
11639 edge_iterator ei;
11640 basic_block bb;
11642 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
11643 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
11644 scev_initialize ();
11645 calculate_dominance_info (CDI_DOMINATORS);
11646 FOR_EACH_BB_FN (bb, cfun)
11648 bb->flags &= ~BB_VISITED;
11649 FOR_EACH_EDGE (e, ei, bb->preds)
11650 e->flags |= EDGE_EXECUTABLE;
11652 vrp_initialize_lattice ();
11654 /* Walk stmts in dominance order and propagate VRP. */
11655 evrp_dom_walker walker;
11656 walker.walk (ENTRY_BLOCK_PTR_FOR_FN (cfun));
11658 if (dump_file)
11660 fprintf (dump_file, "\nValue ranges after Early VRP:\n\n");
11661 dump_all_value_ranges (dump_file);
11662 fprintf (dump_file, "\n");
11665 /* Remove stmts in reverse order to make debug stmt creation possible. */
11666 while (! walker.stmts_to_remove.is_empty ())
11668 gimple *stmt = walker.stmts_to_remove.pop ();
11669 if (dump_file && dump_flags & TDF_DETAILS)
11671 fprintf (dump_file, "Removing dead stmt ");
11672 print_gimple_stmt (dump_file, stmt, 0, 0);
11673 fprintf (dump_file, "\n");
11675 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
11676 if (gimple_code (stmt) == GIMPLE_PHI)
11677 remove_phi_node (&gsi, true);
11678 else
11680 unlink_stmt_vdef (stmt);
11681 gsi_remove (&gsi, true);
11682 release_defs (stmt);
11686 if (!bitmap_empty_p (walker.need_eh_cleanup))
11687 gimple_purge_all_dead_eh_edges (walker.need_eh_cleanup);
11689 /* Fixup stmts that became noreturn calls. This may require splitting
11690 blocks and thus isn't possible during the dominator walk. Do this
11691 in reverse order so we don't inadvertedly remove a stmt we want to
11692 fixup by visiting a dominating now noreturn call first. */
11693 while (!walker.stmts_to_fixup.is_empty ())
11695 gimple *stmt = walker.stmts_to_fixup.pop ();
11696 fixup_noreturn_call (stmt);
11699 vrp_free_lattice ();
11700 scev_finalize ();
11701 loop_optimizer_finalize ();
11702 return 0;
11706 /* Main entry point to VRP (Value Range Propagation). This pass is
11707 loosely based on J. R. C. Patterson, ``Accurate Static Branch
11708 Prediction by Value Range Propagation,'' in SIGPLAN Conference on
11709 Programming Language Design and Implementation, pp. 67-78, 1995.
11710 Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
11712 This is essentially an SSA-CCP pass modified to deal with ranges
11713 instead of constants.
11715 While propagating ranges, we may find that two or more SSA name
11716 have equivalent, though distinct ranges. For instance,
11718 1 x_9 = p_3->a;
11719 2 p_4 = ASSERT_EXPR <p_3, p_3 != 0>
11720 3 if (p_4 == q_2)
11721 4 p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
11722 5 endif
11723 6 if (q_2)
11725 In the code above, pointer p_5 has range [q_2, q_2], but from the
11726 code we can also determine that p_5 cannot be NULL and, if q_2 had
11727 a non-varying range, p_5's range should also be compatible with it.
11729 These equivalences are created by two expressions: ASSERT_EXPR and
11730 copy operations. Since p_5 is an assertion on p_4, and p_4 was the
11731 result of another assertion, then we can use the fact that p_5 and
11732 p_4 are equivalent when evaluating p_5's range.
11734 Together with value ranges, we also propagate these equivalences
11735 between names so that we can take advantage of information from
11736 multiple ranges when doing final replacement. Note that this
11737 equivalency relation is transitive but not symmetric.
11739 In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
11740 cannot assert that q_2 is equivalent to p_5 because q_2 may be used
11741 in contexts where that assertion does not hold (e.g., in line 6).
11743 TODO, the main difference between this pass and Patterson's is that
11744 we do not propagate edge probabilities. We only compute whether
11745 edges can be taken or not. That is, instead of having a spectrum
11746 of jump probabilities between 0 and 1, we only deal with 0, 1 and
11747 DON'T KNOW. In the future, it may be worthwhile to propagate
11748 probabilities to aid branch prediction. */
11750 static unsigned int
11751 execute_vrp (bool warn_array_bounds_p)
11753 int i;
11754 edge e;
11755 switch_update *su;
11757 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
11758 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
11759 scev_initialize ();
11761 /* ??? This ends up using stale EDGE_DFS_BACK for liveness computation.
11762 Inserting assertions may split edges which will invalidate
11763 EDGE_DFS_BACK. */
11764 insert_range_assertions ();
11766 to_remove_edges.create (10);
11767 to_update_switch_stmts.create (5);
11768 threadedge_initialize_values ();
11770 /* For visiting PHI nodes we need EDGE_DFS_BACK computed. */
11771 mark_dfs_back_edges ();
11773 vrp_initialize_lattice ();
11774 vrp_initialize ();
11775 ssa_propagate (vrp_visit_stmt, vrp_visit_phi_node);
11776 vrp_finalize (warn_array_bounds_p);
11778 /* We must identify jump threading opportunities before we release
11779 the datastructures built by VRP. */
11780 identify_jump_threads ();
11782 /* A comparison of an SSA_NAME against a constant where the SSA_NAME
11783 was set by a type conversion can often be rewritten to use the
11784 RHS of the type conversion.
11786 However, doing so inhibits jump threading through the comparison.
11787 So that transformation is not performed until after jump threading
11788 is complete. */
11789 basic_block bb;
11790 FOR_EACH_BB_FN (bb, cfun)
11792 gimple *last = last_stmt (bb);
11793 if (last && gimple_code (last) == GIMPLE_COND)
11794 simplify_cond_using_ranges_2 (as_a <gcond *> (last));
11797 vrp_free_lattice ();
11799 free_numbers_of_iterations_estimates (cfun);
11801 /* ASSERT_EXPRs must be removed before finalizing jump threads
11802 as finalizing jump threads calls the CFG cleanup code which
11803 does not properly handle ASSERT_EXPRs. */
11804 remove_range_assertions ();
11806 /* If we exposed any new variables, go ahead and put them into
11807 SSA form now, before we handle jump threading. This simplifies
11808 interactions between rewriting of _DECL nodes into SSA form
11809 and rewriting SSA_NAME nodes into SSA form after block
11810 duplication and CFG manipulation. */
11811 update_ssa (TODO_update_ssa);
11813 /* We identified all the jump threading opportunities earlier, but could
11814 not transform the CFG at that time. This routine transforms the
11815 CFG and arranges for the dominator tree to be rebuilt if necessary.
11817 Note the SSA graph update will occur during the normal TODO
11818 processing by the pass manager. */
11819 thread_through_all_blocks (false);
11821 /* Remove dead edges from SWITCH_EXPR optimization. This leaves the
11822 CFG in a broken state and requires a cfg_cleanup run. */
11823 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
11824 remove_edge (e);
11825 /* Update SWITCH_EXPR case label vector. */
11826 FOR_EACH_VEC_ELT (to_update_switch_stmts, i, su)
11828 size_t j;
11829 size_t n = TREE_VEC_LENGTH (su->vec);
11830 tree label;
11831 gimple_switch_set_num_labels (su->stmt, n);
11832 for (j = 0; j < n; j++)
11833 gimple_switch_set_label (su->stmt, j, TREE_VEC_ELT (su->vec, j));
11834 /* As we may have replaced the default label with a regular one
11835 make sure to make it a real default label again. This ensures
11836 optimal expansion. */
11837 label = gimple_switch_label (su->stmt, 0);
11838 CASE_LOW (label) = NULL_TREE;
11839 CASE_HIGH (label) = NULL_TREE;
11842 if (to_remove_edges.length () > 0)
11844 free_dominance_info (CDI_DOMINATORS);
11845 loops_state_set (LOOPS_NEED_FIXUP);
11848 to_remove_edges.release ();
11849 to_update_switch_stmts.release ();
11850 threadedge_finalize_values ();
11852 scev_finalize ();
11853 loop_optimizer_finalize ();
11854 return 0;
11857 namespace {
11859 const pass_data pass_data_vrp =
11861 GIMPLE_PASS, /* type */
11862 "vrp", /* name */
11863 OPTGROUP_NONE, /* optinfo_flags */
11864 TV_TREE_VRP, /* tv_id */
11865 PROP_ssa, /* properties_required */
11866 0, /* properties_provided */
11867 0, /* properties_destroyed */
11868 0, /* todo_flags_start */
11869 ( TODO_cleanup_cfg | TODO_update_ssa ), /* todo_flags_finish */
11872 class pass_vrp : public gimple_opt_pass
11874 public:
11875 pass_vrp (gcc::context *ctxt)
11876 : gimple_opt_pass (pass_data_vrp, ctxt), warn_array_bounds_p (false)
11879 /* opt_pass methods: */
11880 opt_pass * clone () { return new pass_vrp (m_ctxt); }
11881 void set_pass_param (unsigned int n, bool param)
11883 gcc_assert (n == 0);
11884 warn_array_bounds_p = param;
11886 virtual bool gate (function *) { return flag_tree_vrp != 0; }
11887 virtual unsigned int execute (function *)
11888 { return execute_vrp (warn_array_bounds_p); }
11890 private:
11891 bool warn_array_bounds_p;
11892 }; // class pass_vrp
11894 } // anon namespace
11896 gimple_opt_pass *
11897 make_pass_vrp (gcc::context *ctxt)
11899 return new pass_vrp (ctxt);
11902 namespace {
11904 const pass_data pass_data_early_vrp =
11906 GIMPLE_PASS, /* type */
11907 "evrp", /* name */
11908 OPTGROUP_NONE, /* optinfo_flags */
11909 TV_TREE_EARLY_VRP, /* tv_id */
11910 PROP_ssa, /* properties_required */
11911 0, /* properties_provided */
11912 0, /* properties_destroyed */
11913 0, /* todo_flags_start */
11914 ( TODO_cleanup_cfg | TODO_update_ssa | TODO_verify_all ),
11917 class pass_early_vrp : public gimple_opt_pass
11919 public:
11920 pass_early_vrp (gcc::context *ctxt)
11921 : gimple_opt_pass (pass_data_early_vrp, ctxt)
11924 /* opt_pass methods: */
11925 opt_pass * clone () { return new pass_early_vrp (m_ctxt); }
11926 virtual bool gate (function *)
11928 return flag_tree_vrp != 0;
11930 virtual unsigned int execute (function *)
11931 { return execute_early_vrp (); }
11933 }; // class pass_vrp
11934 } // anon namespace
11936 gimple_opt_pass *
11937 make_pass_early_vrp (gcc::context *ctxt)
11939 return new pass_early_vrp (ctxt);