* tree-ssa-reassoc.c (reassociate_bb): Clarify code slighly.
[official-gcc.git] / gcc / tree-vrp.c
blob2c86b8e5c910c5a52916acded39175a576df46c7
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"
65 #include "stringpool.h"
66 #include "attribs.h"
68 #define VR_INITIALIZER { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL }
70 /* Allocation pools for tree-vrp allocations. */
71 static object_allocator<value_range> vrp_value_range_pool ("Tree VRP value ranges");
72 static bitmap_obstack vrp_equiv_obstack;
74 /* Set of SSA names found live during the RPO traversal of the function
75 for still active basic-blocks. */
76 static sbitmap *live;
78 /* Return true if the SSA name NAME is live on the edge E. */
80 static bool
81 live_on_edge (edge e, tree name)
83 return (live[e->dest->index]
84 && bitmap_bit_p (live[e->dest->index], SSA_NAME_VERSION (name)));
87 /* Local functions. */
88 static int compare_values (tree val1, tree val2);
89 static int compare_values_warnv (tree val1, tree val2, bool *);
90 static tree vrp_evaluate_conditional_warnv_with_ops (enum tree_code,
91 tree, tree, bool, bool *,
92 bool *);
94 struct assert_info
96 /* Predicate code for the ASSERT_EXPR. Must be COMPARISON_CLASS_P. */
97 enum tree_code comp_code;
99 /* Name to register the assert for. */
100 tree name;
102 /* Value being compared against. */
103 tree val;
105 /* Expression to compare. */
106 tree expr;
109 /* Location information for ASSERT_EXPRs. Each instance of this
110 structure describes an ASSERT_EXPR for an SSA name. Since a single
111 SSA name may have more than one assertion associated with it, these
112 locations are kept in a linked list attached to the corresponding
113 SSA name. */
114 struct assert_locus
116 /* Basic block where the assertion would be inserted. */
117 basic_block bb;
119 /* Some assertions need to be inserted on an edge (e.g., assertions
120 generated by COND_EXPRs). In those cases, BB will be NULL. */
121 edge e;
123 /* Pointer to the statement that generated this assertion. */
124 gimple_stmt_iterator si;
126 /* Predicate code for the ASSERT_EXPR. Must be COMPARISON_CLASS_P. */
127 enum tree_code comp_code;
129 /* Value being compared against. */
130 tree val;
132 /* Expression to compare. */
133 tree expr;
135 /* Next node in the linked list. */
136 assert_locus *next;
139 /* If bit I is present, it means that SSA name N_i has a list of
140 assertions that should be inserted in the IL. */
141 static bitmap need_assert_for;
143 /* Array of locations lists where to insert assertions. ASSERTS_FOR[I]
144 holds a list of ASSERT_LOCUS_T nodes that describe where
145 ASSERT_EXPRs for SSA name N_I should be inserted. */
146 static assert_locus **asserts_for;
148 /* Value range array. After propagation, VR_VALUE[I] holds the range
149 of values that SSA name N_I may take. */
150 static unsigned num_vr_values;
151 static value_range **vr_value;
152 static bool values_propagated;
154 /* For a PHI node which sets SSA name N_I, VR_COUNTS[I] holds the
155 number of executable edges we saw the last time we visited the
156 node. */
157 static int *vr_phi_edge_counts;
159 struct switch_update {
160 gswitch *stmt;
161 tree vec;
164 static vec<edge> to_remove_edges;
165 static vec<switch_update> to_update_switch_stmts;
168 /* Return the maximum value for TYPE. */
170 static inline tree
171 vrp_val_max (const_tree type)
173 if (!INTEGRAL_TYPE_P (type))
174 return NULL_TREE;
176 return TYPE_MAX_VALUE (type);
179 /* Return the minimum value for TYPE. */
181 static inline tree
182 vrp_val_min (const_tree type)
184 if (!INTEGRAL_TYPE_P (type))
185 return NULL_TREE;
187 return TYPE_MIN_VALUE (type);
190 /* Return whether VAL is equal to the maximum value of its type.
191 We can't do a simple equality comparison with TYPE_MAX_VALUE because
192 C typedefs and Ada subtypes can produce types whose TYPE_MAX_VALUE
193 is not == to the integer constant with the same value in the type. */
195 static inline bool
196 vrp_val_is_max (const_tree val)
198 tree type_max = vrp_val_max (TREE_TYPE (val));
199 return (val == type_max
200 || (type_max != NULL_TREE
201 && operand_equal_p (val, type_max, 0)));
204 /* Return whether VAL is equal to the minimum value of its type. */
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 /* Set value range VR to VR_UNDEFINED. */
218 static inline void
219 set_value_range_to_undefined (value_range *vr)
221 vr->type = VR_UNDEFINED;
222 vr->min = vr->max = NULL_TREE;
223 if (vr->equiv)
224 bitmap_clear (vr->equiv);
228 /* Set value range VR to VR_VARYING. */
230 static inline void
231 set_value_range_to_varying (value_range *vr)
233 vr->type = VR_VARYING;
234 vr->min = vr->max = NULL_TREE;
235 if (vr->equiv)
236 bitmap_clear (vr->equiv);
240 /* Set value range VR to {T, MIN, MAX, EQUIV}. */
242 static void
243 set_value_range (value_range *vr, enum value_range_type t, tree min,
244 tree max, bitmap equiv)
246 /* Check the validity of the range. */
247 if (flag_checking
248 && (t == VR_RANGE || t == VR_ANTI_RANGE))
250 int cmp;
252 gcc_assert (min && max);
254 gcc_assert (!TREE_OVERFLOW_P (min) && !TREE_OVERFLOW_P (max));
256 if (INTEGRAL_TYPE_P (TREE_TYPE (min)) && t == VR_ANTI_RANGE)
257 gcc_assert (!vrp_val_is_min (min) || !vrp_val_is_max (max));
259 cmp = compare_values (min, max);
260 gcc_assert (cmp == 0 || cmp == -1 || cmp == -2);
263 if (flag_checking
264 && (t == VR_UNDEFINED || t == VR_VARYING))
266 gcc_assert (min == NULL_TREE && max == NULL_TREE);
267 gcc_assert (equiv == NULL || bitmap_empty_p (equiv));
270 vr->type = t;
271 vr->min = min;
272 vr->max = max;
274 /* Since updating the equivalence set involves deep copying the
275 bitmaps, only do it if absolutely necessary. */
276 if (vr->equiv == NULL
277 && equiv != NULL)
278 vr->equiv = BITMAP_ALLOC (&vrp_equiv_obstack);
280 if (equiv != vr->equiv)
282 if (equiv && !bitmap_empty_p (equiv))
283 bitmap_copy (vr->equiv, equiv);
284 else
285 bitmap_clear (vr->equiv);
290 /* Set value range VR to the canonical form of {T, MIN, MAX, EQUIV}.
291 This means adjusting T, MIN and MAX representing the case of a
292 wrapping range with MAX < MIN covering [MIN, type_max] U [type_min, MAX]
293 as anti-rage ~[MAX+1, MIN-1]. Likewise for wrapping anti-ranges.
294 In corner cases where MAX+1 or MIN-1 wraps this will fall back
295 to varying.
296 This routine exists to ease canonicalization in the case where we
297 extract ranges from var + CST op limit. */
299 static void
300 set_and_canonicalize_value_range (value_range *vr, enum value_range_type t,
301 tree min, tree max, bitmap equiv)
303 /* Use the canonical setters for VR_UNDEFINED and VR_VARYING. */
304 if (t == VR_UNDEFINED)
306 set_value_range_to_undefined (vr);
307 return;
309 else if (t == VR_VARYING)
311 set_value_range_to_varying (vr);
312 return;
315 /* Nothing to canonicalize for symbolic ranges. */
316 if (TREE_CODE (min) != INTEGER_CST
317 || TREE_CODE (max) != INTEGER_CST)
319 set_value_range (vr, t, min, max, equiv);
320 return;
323 /* Wrong order for min and max, to swap them and the VR type we need
324 to adjust them. */
325 if (tree_int_cst_lt (max, min))
327 tree one, tmp;
329 /* For one bit precision if max < min, then the swapped
330 range covers all values, so for VR_RANGE it is varying and
331 for VR_ANTI_RANGE empty range, so drop to varying as well. */
332 if (TYPE_PRECISION (TREE_TYPE (min)) == 1)
334 set_value_range_to_varying (vr);
335 return;
338 one = build_int_cst (TREE_TYPE (min), 1);
339 tmp = int_const_binop (PLUS_EXPR, max, one);
340 max = int_const_binop (MINUS_EXPR, min, one);
341 min = tmp;
343 /* There's one corner case, if we had [C+1, C] before we now have
344 that again. But this represents an empty value range, so drop
345 to varying in this case. */
346 if (tree_int_cst_lt (max, min))
348 set_value_range_to_varying (vr);
349 return;
352 t = t == VR_RANGE ? VR_ANTI_RANGE : VR_RANGE;
355 /* Anti-ranges that can be represented as ranges should be so. */
356 if (t == VR_ANTI_RANGE)
358 bool is_min = vrp_val_is_min (min);
359 bool is_max = vrp_val_is_max (max);
361 if (is_min && is_max)
363 /* We cannot deal with empty ranges, drop to varying.
364 ??? This could be VR_UNDEFINED instead. */
365 set_value_range_to_varying (vr);
366 return;
368 else if (TYPE_PRECISION (TREE_TYPE (min)) == 1
369 && (is_min || is_max))
371 /* Non-empty boolean ranges can always be represented
372 as a singleton range. */
373 if (is_min)
374 min = max = vrp_val_max (TREE_TYPE (min));
375 else
376 min = max = vrp_val_min (TREE_TYPE (min));
377 t = VR_RANGE;
379 else if (is_min
380 /* As a special exception preserve non-null ranges. */
381 && !(TYPE_UNSIGNED (TREE_TYPE (min))
382 && integer_zerop (max)))
384 tree one = build_int_cst (TREE_TYPE (max), 1);
385 min = int_const_binop (PLUS_EXPR, max, one);
386 max = vrp_val_max (TREE_TYPE (max));
387 t = VR_RANGE;
389 else if (is_max)
391 tree one = build_int_cst (TREE_TYPE (min), 1);
392 max = int_const_binop (MINUS_EXPR, min, one);
393 min = vrp_val_min (TREE_TYPE (min));
394 t = VR_RANGE;
398 /* Do not drop [-INF(OVF), +INF(OVF)] to varying. (OVF) has to be sticky
399 to make sure VRP iteration terminates, otherwise we can get into
400 oscillations. */
402 set_value_range (vr, t, min, max, equiv);
405 /* Copy value range FROM into value range TO. */
407 static inline void
408 copy_value_range (value_range *to, value_range *from)
410 set_value_range (to, from->type, from->min, from->max, from->equiv);
413 /* Set value range VR to a single value. This function is only called
414 with values we get from statements, and exists to clear the
415 TREE_OVERFLOW flag. */
417 static inline void
418 set_value_range_to_value (value_range *vr, tree val, bitmap equiv)
420 gcc_assert (is_gimple_min_invariant (val));
421 if (TREE_OVERFLOW_P (val))
422 val = drop_tree_overflow (val);
423 set_value_range (vr, VR_RANGE, val, val, equiv);
426 /* Set value range VR to a non-negative range of type TYPE. */
428 static inline void
429 set_value_range_to_nonnegative (value_range *vr, tree type)
431 tree zero = build_int_cst (type, 0);
432 set_value_range (vr, VR_RANGE, zero, vrp_val_max (type), vr->equiv);
435 /* Set value range VR to a non-NULL range of type TYPE. */
437 static inline void
438 set_value_range_to_nonnull (value_range *vr, tree type)
440 tree zero = build_int_cst (type, 0);
441 set_value_range (vr, VR_ANTI_RANGE, zero, zero, vr->equiv);
445 /* Set value range VR to a NULL range of type TYPE. */
447 static inline void
448 set_value_range_to_null (value_range *vr, tree type)
450 set_value_range_to_value (vr, build_int_cst (type, 0), vr->equiv);
454 /* Set value range VR to a range of a truthvalue of type TYPE. */
456 static inline void
457 set_value_range_to_truthvalue (value_range *vr, tree type)
459 if (TYPE_PRECISION (type) == 1)
460 set_value_range_to_varying (vr);
461 else
462 set_value_range (vr, VR_RANGE,
463 build_int_cst (type, 0), build_int_cst (type, 1),
464 vr->equiv);
468 /* If abs (min) < abs (max), set VR to [-max, max], if
469 abs (min) >= abs (max), set VR to [-min, min]. */
471 static void
472 abs_extent_range (value_range *vr, tree min, tree max)
474 int cmp;
476 gcc_assert (TREE_CODE (min) == INTEGER_CST);
477 gcc_assert (TREE_CODE (max) == INTEGER_CST);
478 gcc_assert (INTEGRAL_TYPE_P (TREE_TYPE (min)));
479 gcc_assert (!TYPE_UNSIGNED (TREE_TYPE (min)));
480 min = fold_unary (ABS_EXPR, TREE_TYPE (min), min);
481 max = fold_unary (ABS_EXPR, TREE_TYPE (max), max);
482 if (TREE_OVERFLOW (min) || TREE_OVERFLOW (max))
484 set_value_range_to_varying (vr);
485 return;
487 cmp = compare_values (min, max);
488 if (cmp == -1)
489 min = fold_unary (NEGATE_EXPR, TREE_TYPE (min), max);
490 else if (cmp == 0 || cmp == 1)
492 max = min;
493 min = fold_unary (NEGATE_EXPR, TREE_TYPE (min), min);
495 else
497 set_value_range_to_varying (vr);
498 return;
500 set_and_canonicalize_value_range (vr, VR_RANGE, min, max, NULL);
504 /* Return value range information for VAR.
506 If we have no values ranges recorded (ie, VRP is not running), then
507 return NULL. Otherwise create an empty range if none existed for VAR. */
509 static value_range *
510 get_value_range (const_tree var)
512 static const value_range vr_const_varying
513 = { VR_VARYING, NULL_TREE, NULL_TREE, NULL };
514 value_range *vr;
515 tree sym;
516 unsigned ver = SSA_NAME_VERSION (var);
518 /* If we have no recorded ranges, then return NULL. */
519 if (! vr_value)
520 return NULL;
522 /* If we query the range for a new SSA name return an unmodifiable VARYING.
523 We should get here at most from the substitute-and-fold stage which
524 will never try to change values. */
525 if (ver >= num_vr_values)
526 return CONST_CAST (value_range *, &vr_const_varying);
528 vr = vr_value[ver];
529 if (vr)
530 return vr;
532 /* After propagation finished do not allocate new value-ranges. */
533 if (values_propagated)
534 return CONST_CAST (value_range *, &vr_const_varying);
536 /* Create a default value range. */
537 vr_value[ver] = vr = vrp_value_range_pool.allocate ();
538 memset (vr, 0, sizeof (*vr));
540 /* Defer allocating the equivalence set. */
541 vr->equiv = NULL;
543 /* If VAR is a default definition of a parameter, the variable can
544 take any value in VAR's type. */
545 if (SSA_NAME_IS_DEFAULT_DEF (var))
547 sym = SSA_NAME_VAR (var);
548 if (TREE_CODE (sym) == PARM_DECL)
550 /* Try to use the "nonnull" attribute to create ~[0, 0]
551 anti-ranges for pointers. Note that this is only valid with
552 default definitions of PARM_DECLs. */
553 if (POINTER_TYPE_P (TREE_TYPE (sym))
554 && (nonnull_arg_p (sym)
555 || get_ptr_nonnull (var)))
556 set_value_range_to_nonnull (vr, TREE_TYPE (sym));
557 else if (INTEGRAL_TYPE_P (TREE_TYPE (sym)))
559 wide_int min, max;
560 value_range_type rtype = get_range_info (var, &min, &max);
561 if (rtype == VR_RANGE || rtype == VR_ANTI_RANGE)
562 set_value_range (vr, rtype,
563 wide_int_to_tree (TREE_TYPE (var), min),
564 wide_int_to_tree (TREE_TYPE (var), max),
565 NULL);
566 else
567 set_value_range_to_varying (vr);
569 else
570 set_value_range_to_varying (vr);
572 else if (TREE_CODE (sym) == RESULT_DECL
573 && DECL_BY_REFERENCE (sym))
574 set_value_range_to_nonnull (vr, TREE_TYPE (sym));
577 return vr;
580 /* Set value-ranges of all SSA names defined by STMT to varying. */
582 static void
583 set_defs_to_varying (gimple *stmt)
585 ssa_op_iter i;
586 tree def;
587 FOR_EACH_SSA_TREE_OPERAND (def, stmt, i, SSA_OP_DEF)
589 value_range *vr = get_value_range (def);
590 /* Avoid writing to vr_const_varying get_value_range may return. */
591 if (vr->type != VR_VARYING)
592 set_value_range_to_varying (vr);
597 /* Return true, if VAL1 and VAL2 are equal values for VRP purposes. */
599 static inline bool
600 vrp_operand_equal_p (const_tree val1, const_tree val2)
602 if (val1 == val2)
603 return true;
604 if (!val1 || !val2 || !operand_equal_p (val1, val2, 0))
605 return false;
606 return true;
609 /* Return true, if the bitmaps B1 and B2 are equal. */
611 static inline bool
612 vrp_bitmap_equal_p (const_bitmap b1, const_bitmap b2)
614 return (b1 == b2
615 || ((!b1 || bitmap_empty_p (b1))
616 && (!b2 || bitmap_empty_p (b2)))
617 || (b1 && b2
618 && bitmap_equal_p (b1, b2)));
621 /* Update the value range and equivalence set for variable VAR to
622 NEW_VR. Return true if NEW_VR is different from VAR's previous
623 value.
625 NOTE: This function assumes that NEW_VR is a temporary value range
626 object created for the sole purpose of updating VAR's range. The
627 storage used by the equivalence set from NEW_VR will be freed by
628 this function. Do not call update_value_range when NEW_VR
629 is the range object associated with another SSA name. */
631 static inline bool
632 update_value_range (const_tree var, value_range *new_vr)
634 value_range *old_vr;
635 bool is_new;
637 /* If there is a value-range on the SSA name from earlier analysis
638 factor that in. */
639 if (INTEGRAL_TYPE_P (TREE_TYPE (var)))
641 wide_int min, max;
642 value_range_type rtype = get_range_info (var, &min, &max);
643 if (rtype == VR_RANGE || rtype == VR_ANTI_RANGE)
645 tree nr_min, nr_max;
646 nr_min = wide_int_to_tree (TREE_TYPE (var), min);
647 nr_max = wide_int_to_tree (TREE_TYPE (var), max);
648 value_range nr = VR_INITIALIZER;
649 set_and_canonicalize_value_range (&nr, rtype, nr_min, nr_max, NULL);
650 vrp_intersect_ranges (new_vr, &nr);
654 /* Update the value range, if necessary. */
655 old_vr = get_value_range (var);
656 is_new = old_vr->type != new_vr->type
657 || !vrp_operand_equal_p (old_vr->min, new_vr->min)
658 || !vrp_operand_equal_p (old_vr->max, new_vr->max)
659 || !vrp_bitmap_equal_p (old_vr->equiv, new_vr->equiv);
661 if (is_new)
663 /* Do not allow transitions up the lattice. The following
664 is slightly more awkward than just new_vr->type < old_vr->type
665 because VR_RANGE and VR_ANTI_RANGE need to be considered
666 the same. We may not have is_new when transitioning to
667 UNDEFINED. If old_vr->type is VARYING, we shouldn't be
668 called. */
669 if (new_vr->type == VR_UNDEFINED)
671 BITMAP_FREE (new_vr->equiv);
672 set_value_range_to_varying (old_vr);
673 set_value_range_to_varying (new_vr);
674 return true;
676 else
677 set_value_range (old_vr, new_vr->type, new_vr->min, new_vr->max,
678 new_vr->equiv);
681 BITMAP_FREE (new_vr->equiv);
683 return is_new;
687 /* Add VAR and VAR's equivalence set to EQUIV. This is the central
688 point where equivalence processing can be turned on/off. */
690 static void
691 add_equivalence (bitmap *equiv, const_tree var)
693 unsigned ver = SSA_NAME_VERSION (var);
694 value_range *vr = get_value_range (var);
696 if (*equiv == NULL)
697 *equiv = BITMAP_ALLOC (&vrp_equiv_obstack);
698 bitmap_set_bit (*equiv, ver);
699 if (vr && vr->equiv)
700 bitmap_ior_into (*equiv, vr->equiv);
704 /* Return true if VR is ~[0, 0]. */
706 static inline bool
707 range_is_nonnull (value_range *vr)
709 return vr->type == VR_ANTI_RANGE
710 && integer_zerop (vr->min)
711 && integer_zerop (vr->max);
715 /* Return true if VR is [0, 0]. */
717 static inline bool
718 range_is_null (value_range *vr)
720 return vr->type == VR_RANGE
721 && integer_zerop (vr->min)
722 && integer_zerop (vr->max);
725 /* Return true if max and min of VR are INTEGER_CST. It's not necessary
726 a singleton. */
728 static inline bool
729 range_int_cst_p (value_range *vr)
731 return (vr->type == VR_RANGE
732 && TREE_CODE (vr->max) == INTEGER_CST
733 && TREE_CODE (vr->min) == INTEGER_CST);
736 /* Return true if VR is a INTEGER_CST singleton. */
738 static inline bool
739 range_int_cst_singleton_p (value_range *vr)
741 return (range_int_cst_p (vr)
742 && tree_int_cst_equal (vr->min, vr->max));
745 /* Return true if value range VR involves at least one symbol. */
747 static inline bool
748 symbolic_range_p (value_range *vr)
750 return (!is_gimple_min_invariant (vr->min)
751 || !is_gimple_min_invariant (vr->max));
754 /* Return the single symbol (an SSA_NAME) contained in T if any, or NULL_TREE
755 otherwise. We only handle additive operations and set NEG to true if the
756 symbol is negated and INV to the invariant part, if any. */
758 static tree
759 get_single_symbol (tree t, bool *neg, tree *inv)
761 bool neg_;
762 tree inv_;
764 *inv = NULL_TREE;
765 *neg = false;
767 if (TREE_CODE (t) == PLUS_EXPR
768 || TREE_CODE (t) == POINTER_PLUS_EXPR
769 || TREE_CODE (t) == MINUS_EXPR)
771 if (is_gimple_min_invariant (TREE_OPERAND (t, 0)))
773 neg_ = (TREE_CODE (t) == MINUS_EXPR);
774 inv_ = TREE_OPERAND (t, 0);
775 t = TREE_OPERAND (t, 1);
777 else if (is_gimple_min_invariant (TREE_OPERAND (t, 1)))
779 neg_ = false;
780 inv_ = TREE_OPERAND (t, 1);
781 t = TREE_OPERAND (t, 0);
783 else
784 return NULL_TREE;
786 else
788 neg_ = false;
789 inv_ = NULL_TREE;
792 if (TREE_CODE (t) == NEGATE_EXPR)
794 t = TREE_OPERAND (t, 0);
795 neg_ = !neg_;
798 if (TREE_CODE (t) != SSA_NAME)
799 return NULL_TREE;
801 if (inv_ && TREE_OVERFLOW_P (inv_))
802 inv_ = drop_tree_overflow (inv_);
804 *neg = neg_;
805 *inv = inv_;
806 return t;
809 /* The reverse operation: build a symbolic expression with TYPE
810 from symbol SYM, negated according to NEG, and invariant INV. */
812 static tree
813 build_symbolic_expr (tree type, tree sym, bool neg, tree inv)
815 const bool pointer_p = POINTER_TYPE_P (type);
816 tree t = sym;
818 if (neg)
819 t = build1 (NEGATE_EXPR, type, t);
821 if (integer_zerop (inv))
822 return t;
824 return build2 (pointer_p ? POINTER_PLUS_EXPR : PLUS_EXPR, type, t, inv);
827 /* Return true if value range VR involves exactly one symbol SYM. */
829 static bool
830 symbolic_range_based_on_p (value_range *vr, const_tree sym)
832 bool neg, min_has_symbol, max_has_symbol;
833 tree inv;
835 if (is_gimple_min_invariant (vr->min))
836 min_has_symbol = false;
837 else if (get_single_symbol (vr->min, &neg, &inv) == sym)
838 min_has_symbol = true;
839 else
840 return false;
842 if (is_gimple_min_invariant (vr->max))
843 max_has_symbol = false;
844 else if (get_single_symbol (vr->max, &neg, &inv) == sym)
845 max_has_symbol = true;
846 else
847 return false;
849 return (min_has_symbol || max_has_symbol);
852 /* Return true if the result of assignment STMT is know to be non-zero. */
854 static bool
855 gimple_assign_nonzero_p (gimple *stmt)
857 enum tree_code code = gimple_assign_rhs_code (stmt);
858 bool strict_overflow_p;
859 switch (get_gimple_rhs_class (code))
861 case GIMPLE_UNARY_RHS:
862 return tree_unary_nonzero_warnv_p (gimple_assign_rhs_code (stmt),
863 gimple_expr_type (stmt),
864 gimple_assign_rhs1 (stmt),
865 &strict_overflow_p);
866 case GIMPLE_BINARY_RHS:
867 return tree_binary_nonzero_warnv_p (gimple_assign_rhs_code (stmt),
868 gimple_expr_type (stmt),
869 gimple_assign_rhs1 (stmt),
870 gimple_assign_rhs2 (stmt),
871 &strict_overflow_p);
872 case GIMPLE_TERNARY_RHS:
873 return false;
874 case GIMPLE_SINGLE_RHS:
875 return tree_single_nonzero_warnv_p (gimple_assign_rhs1 (stmt),
876 &strict_overflow_p);
877 case GIMPLE_INVALID_RHS:
878 gcc_unreachable ();
879 default:
880 gcc_unreachable ();
884 /* Return true if STMT is known to compute a non-zero value. */
886 static bool
887 gimple_stmt_nonzero_p (gimple *stmt)
889 switch (gimple_code (stmt))
891 case GIMPLE_ASSIGN:
892 return gimple_assign_nonzero_p (stmt);
893 case GIMPLE_CALL:
895 tree fndecl = gimple_call_fndecl (stmt);
896 if (!fndecl) return false;
897 if (flag_delete_null_pointer_checks && !flag_check_new
898 && DECL_IS_OPERATOR_NEW (fndecl)
899 && !TREE_NOTHROW (fndecl))
900 return true;
901 /* References are always non-NULL. */
902 if (flag_delete_null_pointer_checks
903 && TREE_CODE (TREE_TYPE (fndecl)) == REFERENCE_TYPE)
904 return true;
905 if (flag_delete_null_pointer_checks &&
906 lookup_attribute ("returns_nonnull",
907 TYPE_ATTRIBUTES (gimple_call_fntype (stmt))))
908 return true;
910 gcall *call_stmt = as_a<gcall *> (stmt);
911 unsigned rf = gimple_call_return_flags (call_stmt);
912 if (rf & ERF_RETURNS_ARG)
914 unsigned argnum = rf & ERF_RETURN_ARG_MASK;
915 if (argnum < gimple_call_num_args (call_stmt))
917 tree arg = gimple_call_arg (call_stmt, argnum);
918 if (SSA_VAR_P (arg)
919 && infer_nonnull_range_by_attribute (stmt, arg))
920 return true;
923 return gimple_alloca_call_p (stmt);
925 default:
926 gcc_unreachable ();
930 /* Like tree_expr_nonzero_p, but this function uses value ranges
931 obtained so far. */
933 static bool
934 vrp_stmt_computes_nonzero (gimple *stmt)
936 if (gimple_stmt_nonzero_p (stmt))
937 return true;
939 /* If we have an expression of the form &X->a, then the expression
940 is nonnull if X is nonnull. */
941 if (is_gimple_assign (stmt)
942 && gimple_assign_rhs_code (stmt) == ADDR_EXPR)
944 tree expr = gimple_assign_rhs1 (stmt);
945 tree base = get_base_address (TREE_OPERAND (expr, 0));
947 if (base != NULL_TREE
948 && TREE_CODE (base) == MEM_REF
949 && TREE_CODE (TREE_OPERAND (base, 0)) == SSA_NAME)
951 value_range *vr = get_value_range (TREE_OPERAND (base, 0));
952 if (range_is_nonnull (vr))
953 return true;
957 return false;
960 /* Returns true if EXPR is a valid value (as expected by compare_values) --
961 a gimple invariant, or SSA_NAME +- CST. */
963 static bool
964 valid_value_p (tree expr)
966 if (TREE_CODE (expr) == SSA_NAME)
967 return true;
969 if (TREE_CODE (expr) == PLUS_EXPR
970 || TREE_CODE (expr) == MINUS_EXPR)
971 return (TREE_CODE (TREE_OPERAND (expr, 0)) == SSA_NAME
972 && TREE_CODE (TREE_OPERAND (expr, 1)) == INTEGER_CST);
974 return is_gimple_min_invariant (expr);
977 /* Return
978 1 if VAL < VAL2
979 0 if !(VAL < VAL2)
980 -2 if those are incomparable. */
981 static inline int
982 operand_less_p (tree val, tree val2)
984 /* LT is folded faster than GE and others. Inline the common case. */
985 if (TREE_CODE (val) == INTEGER_CST && TREE_CODE (val2) == INTEGER_CST)
986 return tree_int_cst_lt (val, val2);
987 else
989 tree tcmp;
991 fold_defer_overflow_warnings ();
993 tcmp = fold_binary_to_constant (LT_EXPR, boolean_type_node, val, val2);
995 fold_undefer_and_ignore_overflow_warnings ();
997 if (!tcmp
998 || TREE_CODE (tcmp) != INTEGER_CST)
999 return -2;
1001 if (!integer_zerop (tcmp))
1002 return 1;
1005 return 0;
1008 /* Compare two values VAL1 and VAL2. Return
1010 -2 if VAL1 and VAL2 cannot be compared at compile-time,
1011 -1 if VAL1 < VAL2,
1012 0 if VAL1 == VAL2,
1013 +1 if VAL1 > VAL2, and
1014 +2 if VAL1 != VAL2
1016 This is similar to tree_int_cst_compare but supports pointer values
1017 and values that cannot be compared at compile time.
1019 If STRICT_OVERFLOW_P is not NULL, then set *STRICT_OVERFLOW_P to
1020 true if the return value is only valid if we assume that signed
1021 overflow is undefined. */
1023 static int
1024 compare_values_warnv (tree val1, tree val2, bool *strict_overflow_p)
1026 if (val1 == val2)
1027 return 0;
1029 /* Below we rely on the fact that VAL1 and VAL2 are both pointers or
1030 both integers. */
1031 gcc_assert (POINTER_TYPE_P (TREE_TYPE (val1))
1032 == POINTER_TYPE_P (TREE_TYPE (val2)));
1034 /* Convert the two values into the same type. This is needed because
1035 sizetype causes sign extension even for unsigned types. */
1036 val2 = fold_convert (TREE_TYPE (val1), val2);
1037 STRIP_USELESS_TYPE_CONVERSION (val2);
1039 const bool overflow_undefined
1040 = INTEGRAL_TYPE_P (TREE_TYPE (val1))
1041 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1));
1042 tree inv1, inv2;
1043 bool neg1, neg2;
1044 tree sym1 = get_single_symbol (val1, &neg1, &inv1);
1045 tree sym2 = get_single_symbol (val2, &neg2, &inv2);
1047 /* If VAL1 and VAL2 are of the form '[-]NAME [+ CST]', return -1 or +1
1048 accordingly. If VAL1 and VAL2 don't use the same name, return -2. */
1049 if (sym1 && sym2)
1051 /* Both values must use the same name with the same sign. */
1052 if (sym1 != sym2 || neg1 != neg2)
1053 return -2;
1055 /* [-]NAME + CST == [-]NAME + CST. */
1056 if (inv1 == inv2)
1057 return 0;
1059 /* If overflow is defined we cannot simplify more. */
1060 if (!overflow_undefined)
1061 return -2;
1063 if (strict_overflow_p != NULL
1064 /* Symbolic range building sets TREE_NO_WARNING to declare
1065 that overflow doesn't happen. */
1066 && (!inv1 || !TREE_NO_WARNING (val1))
1067 && (!inv2 || !TREE_NO_WARNING (val2)))
1068 *strict_overflow_p = true;
1070 if (!inv1)
1071 inv1 = build_int_cst (TREE_TYPE (val1), 0);
1072 if (!inv2)
1073 inv2 = build_int_cst (TREE_TYPE (val2), 0);
1075 return wi::cmp (wi::to_wide (inv1), wi::to_wide (inv2),
1076 TYPE_SIGN (TREE_TYPE (val1)));
1079 const bool cst1 = is_gimple_min_invariant (val1);
1080 const bool cst2 = is_gimple_min_invariant (val2);
1082 /* If one is of the form '[-]NAME + CST' and the other is constant, then
1083 it might be possible to say something depending on the constants. */
1084 if ((sym1 && inv1 && cst2) || (sym2 && inv2 && cst1))
1086 if (!overflow_undefined)
1087 return -2;
1089 if (strict_overflow_p != NULL
1090 /* Symbolic range building sets TREE_NO_WARNING to declare
1091 that overflow doesn't happen. */
1092 && (!sym1 || !TREE_NO_WARNING (val1))
1093 && (!sym2 || !TREE_NO_WARNING (val2)))
1094 *strict_overflow_p = true;
1096 const signop sgn = TYPE_SIGN (TREE_TYPE (val1));
1097 tree cst = cst1 ? val1 : val2;
1098 tree inv = cst1 ? inv2 : inv1;
1100 /* Compute the difference between the constants. If it overflows or
1101 underflows, this means that we can trivially compare the NAME with
1102 it and, consequently, the two values with each other. */
1103 wide_int diff = wi::to_wide (cst) - wi::to_wide (inv);
1104 if (wi::cmp (0, wi::to_wide (inv), sgn)
1105 != wi::cmp (diff, wi::to_wide (cst), sgn))
1107 const int res = wi::cmp (wi::to_wide (cst), wi::to_wide (inv), sgn);
1108 return cst1 ? res : -res;
1111 return -2;
1114 /* We cannot say anything more for non-constants. */
1115 if (!cst1 || !cst2)
1116 return -2;
1118 if (!POINTER_TYPE_P (TREE_TYPE (val1)))
1120 /* We cannot compare overflowed values. */
1121 if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
1122 return -2;
1124 return tree_int_cst_compare (val1, val2);
1126 else
1128 tree t;
1130 /* First see if VAL1 and VAL2 are not the same. */
1131 if (val1 == val2 || operand_equal_p (val1, val2, 0))
1132 return 0;
1134 /* If VAL1 is a lower address than VAL2, return -1. */
1135 if (operand_less_p (val1, val2) == 1)
1136 return -1;
1138 /* If VAL1 is a higher address than VAL2, return +1. */
1139 if (operand_less_p (val2, val1) == 1)
1140 return 1;
1142 /* If VAL1 is different than VAL2, return +2.
1143 For integer constants we either have already returned -1 or 1
1144 or they are equivalent. We still might succeed in proving
1145 something about non-trivial operands. */
1146 if (TREE_CODE (val1) != INTEGER_CST
1147 || TREE_CODE (val2) != INTEGER_CST)
1149 t = fold_binary_to_constant (NE_EXPR, boolean_type_node, val1, val2);
1150 if (t && integer_onep (t))
1151 return 2;
1154 return -2;
1158 /* Compare values like compare_values_warnv. */
1160 static int
1161 compare_values (tree val1, tree val2)
1163 bool sop;
1164 return compare_values_warnv (val1, val2, &sop);
1168 /* Return 1 if VAL is inside value range MIN <= VAL <= MAX,
1169 0 if VAL is not inside [MIN, MAX],
1170 -2 if we cannot tell either way.
1172 Benchmark compile/20001226-1.c compilation time after changing this
1173 function. */
1175 static inline int
1176 value_inside_range (tree val, tree min, tree max)
1178 int cmp1, cmp2;
1180 cmp1 = operand_less_p (val, min);
1181 if (cmp1 == -2)
1182 return -2;
1183 if (cmp1 == 1)
1184 return 0;
1186 cmp2 = operand_less_p (max, val);
1187 if (cmp2 == -2)
1188 return -2;
1190 return !cmp2;
1194 /* Return true if value ranges VR0 and VR1 have a non-empty
1195 intersection.
1197 Benchmark compile/20001226-1.c compilation time after changing this
1198 function.
1201 static inline bool
1202 value_ranges_intersect_p (value_range *vr0, value_range *vr1)
1204 /* The value ranges do not intersect if the maximum of the first range is
1205 less than the minimum of the second range or vice versa.
1206 When those relations are unknown, we can't do any better. */
1207 if (operand_less_p (vr0->max, vr1->min) != 0)
1208 return false;
1209 if (operand_less_p (vr1->max, vr0->min) != 0)
1210 return false;
1211 return true;
1215 /* Return 1 if [MIN, MAX] includes the value zero, 0 if it does not
1216 include the value zero, -2 if we cannot tell. */
1218 static inline int
1219 range_includes_zero_p (tree min, tree max)
1221 tree zero = build_int_cst (TREE_TYPE (min), 0);
1222 return value_inside_range (zero, min, max);
1225 /* Return true if *VR is know to only contain nonnegative values. */
1227 static inline bool
1228 value_range_nonnegative_p (value_range *vr)
1230 /* Testing for VR_ANTI_RANGE is not useful here as any anti-range
1231 which would return a useful value should be encoded as a
1232 VR_RANGE. */
1233 if (vr->type == VR_RANGE)
1235 int result = compare_values (vr->min, integer_zero_node);
1236 return (result == 0 || result == 1);
1239 return false;
1242 /* If *VR has a value rante that is a single constant value return that,
1243 otherwise return NULL_TREE. */
1245 static tree
1246 value_range_constant_singleton (value_range *vr)
1248 if (vr->type == VR_RANGE
1249 && vrp_operand_equal_p (vr->min, vr->max)
1250 && is_gimple_min_invariant (vr->min))
1251 return vr->min;
1253 return NULL_TREE;
1256 /* If OP has a value range with a single constant value return that,
1257 otherwise return NULL_TREE. This returns OP itself if OP is a
1258 constant. */
1260 static tree
1261 op_with_constant_singleton_value_range (tree op)
1263 if (is_gimple_min_invariant (op))
1264 return op;
1266 if (TREE_CODE (op) != SSA_NAME)
1267 return NULL_TREE;
1269 return value_range_constant_singleton (get_value_range (op));
1272 /* Return true if op is in a boolean [0, 1] value-range. */
1274 static bool
1275 op_with_boolean_value_range_p (tree op)
1277 value_range *vr;
1279 if (TYPE_PRECISION (TREE_TYPE (op)) == 1)
1280 return true;
1282 if (integer_zerop (op)
1283 || integer_onep (op))
1284 return true;
1286 if (TREE_CODE (op) != SSA_NAME)
1287 return false;
1289 vr = get_value_range (op);
1290 return (vr->type == VR_RANGE
1291 && integer_zerop (vr->min)
1292 && integer_onep (vr->max));
1295 /* Extract value range information for VAR when (OP COND_CODE LIMIT) is
1296 true and store it in *VR_P. */
1298 static void
1299 extract_range_for_var_from_comparison_expr (tree var, enum tree_code cond_code,
1300 tree op, tree limit,
1301 value_range *vr_p)
1303 tree min, max, type;
1304 value_range *limit_vr;
1305 type = TREE_TYPE (var);
1306 gcc_assert (limit != var);
1308 /* For pointer arithmetic, we only keep track of pointer equality
1309 and inequality. */
1310 if (POINTER_TYPE_P (type) && cond_code != NE_EXPR && cond_code != EQ_EXPR)
1312 set_value_range_to_varying (vr_p);
1313 return;
1316 /* If LIMIT is another SSA name and LIMIT has a range of its own,
1317 try to use LIMIT's range to avoid creating symbolic ranges
1318 unnecessarily. */
1319 limit_vr = (TREE_CODE (limit) == SSA_NAME) ? get_value_range (limit) : NULL;
1321 /* LIMIT's range is only interesting if it has any useful information. */
1322 if (! limit_vr
1323 || limit_vr->type == VR_UNDEFINED
1324 || limit_vr->type == VR_VARYING
1325 || (symbolic_range_p (limit_vr)
1326 && ! (limit_vr->type == VR_RANGE
1327 && (limit_vr->min == limit_vr->max
1328 || operand_equal_p (limit_vr->min, limit_vr->max, 0)))))
1329 limit_vr = NULL;
1331 /* Initially, the new range has the same set of equivalences of
1332 VAR's range. This will be revised before returning the final
1333 value. Since assertions may be chained via mutually exclusive
1334 predicates, we will need to trim the set of equivalences before
1335 we are done. */
1336 gcc_assert (vr_p->equiv == NULL);
1337 add_equivalence (&vr_p->equiv, var);
1339 /* Extract a new range based on the asserted comparison for VAR and
1340 LIMIT's value range. Notice that if LIMIT has an anti-range, we
1341 will only use it for equality comparisons (EQ_EXPR). For any
1342 other kind of assertion, we cannot derive a range from LIMIT's
1343 anti-range that can be used to describe the new range. For
1344 instance, ASSERT_EXPR <x_2, x_2 <= b_4>. If b_4 is ~[2, 10],
1345 then b_4 takes on the ranges [-INF, 1] and [11, +INF]. There is
1346 no single range for x_2 that could describe LE_EXPR, so we might
1347 as well build the range [b_4, +INF] for it.
1348 One special case we handle is extracting a range from a
1349 range test encoded as (unsigned)var + CST <= limit. */
1350 if (TREE_CODE (op) == NOP_EXPR
1351 || TREE_CODE (op) == PLUS_EXPR)
1353 if (TREE_CODE (op) == PLUS_EXPR)
1355 min = fold_build1 (NEGATE_EXPR, TREE_TYPE (TREE_OPERAND (op, 1)),
1356 TREE_OPERAND (op, 1));
1357 max = int_const_binop (PLUS_EXPR, limit, min);
1358 op = TREE_OPERAND (op, 0);
1360 else
1362 min = build_int_cst (TREE_TYPE (var), 0);
1363 max = limit;
1366 /* Make sure to not set TREE_OVERFLOW on the final type
1367 conversion. We are willingly interpreting large positive
1368 unsigned values as negative signed values here. */
1369 min = force_fit_type (TREE_TYPE (var), wi::to_widest (min), 0, false);
1370 max = force_fit_type (TREE_TYPE (var), wi::to_widest (max), 0, false);
1372 /* We can transform a max, min range to an anti-range or
1373 vice-versa. Use set_and_canonicalize_value_range which does
1374 this for us. */
1375 if (cond_code == LE_EXPR)
1376 set_and_canonicalize_value_range (vr_p, VR_RANGE,
1377 min, max, vr_p->equiv);
1378 else if (cond_code == GT_EXPR)
1379 set_and_canonicalize_value_range (vr_p, VR_ANTI_RANGE,
1380 min, max, vr_p->equiv);
1381 else
1382 gcc_unreachable ();
1384 else if (cond_code == EQ_EXPR)
1386 enum value_range_type range_type;
1388 if (limit_vr)
1390 range_type = limit_vr->type;
1391 min = limit_vr->min;
1392 max = limit_vr->max;
1394 else
1396 range_type = VR_RANGE;
1397 min = limit;
1398 max = limit;
1401 set_value_range (vr_p, range_type, min, max, vr_p->equiv);
1403 /* When asserting the equality VAR == LIMIT and LIMIT is another
1404 SSA name, the new range will also inherit the equivalence set
1405 from LIMIT. */
1406 if (TREE_CODE (limit) == SSA_NAME)
1407 add_equivalence (&vr_p->equiv, limit);
1409 else if (cond_code == NE_EXPR)
1411 /* As described above, when LIMIT's range is an anti-range and
1412 this assertion is an inequality (NE_EXPR), then we cannot
1413 derive anything from the anti-range. For instance, if
1414 LIMIT's range was ~[0, 0], the assertion 'VAR != LIMIT' does
1415 not imply that VAR's range is [0, 0]. So, in the case of
1416 anti-ranges, we just assert the inequality using LIMIT and
1417 not its anti-range.
1419 If LIMIT_VR is a range, we can only use it to build a new
1420 anti-range if LIMIT_VR is a single-valued range. For
1421 instance, if LIMIT_VR is [0, 1], the predicate
1422 VAR != [0, 1] does not mean that VAR's range is ~[0, 1].
1423 Rather, it means that for value 0 VAR should be ~[0, 0]
1424 and for value 1, VAR should be ~[1, 1]. We cannot
1425 represent these ranges.
1427 The only situation in which we can build a valid
1428 anti-range is when LIMIT_VR is a single-valued range
1429 (i.e., LIMIT_VR->MIN == LIMIT_VR->MAX). In that case,
1430 build the anti-range ~[LIMIT_VR->MIN, LIMIT_VR->MAX]. */
1431 if (limit_vr
1432 && limit_vr->type == VR_RANGE
1433 && compare_values (limit_vr->min, limit_vr->max) == 0)
1435 min = limit_vr->min;
1436 max = limit_vr->max;
1438 else
1440 /* In any other case, we cannot use LIMIT's range to build a
1441 valid anti-range. */
1442 min = max = limit;
1445 /* If MIN and MAX cover the whole range for their type, then
1446 just use the original LIMIT. */
1447 if (INTEGRAL_TYPE_P (type)
1448 && vrp_val_is_min (min)
1449 && vrp_val_is_max (max))
1450 min = max = limit;
1452 set_and_canonicalize_value_range (vr_p, VR_ANTI_RANGE,
1453 min, max, vr_p->equiv);
1455 else if (cond_code == LE_EXPR || cond_code == LT_EXPR)
1457 min = TYPE_MIN_VALUE (type);
1459 if (limit_vr == NULL || limit_vr->type == VR_ANTI_RANGE)
1460 max = limit;
1461 else
1463 /* If LIMIT_VR is of the form [N1, N2], we need to build the
1464 range [MIN, N2] for LE_EXPR and [MIN, N2 - 1] for
1465 LT_EXPR. */
1466 max = limit_vr->max;
1469 /* If the maximum value forces us to be out of bounds, simply punt.
1470 It would be pointless to try and do anything more since this
1471 all should be optimized away above us. */
1472 if (cond_code == LT_EXPR
1473 && compare_values (max, min) == 0)
1474 set_value_range_to_varying (vr_p);
1475 else
1477 /* For LT_EXPR, we create the range [MIN, MAX - 1]. */
1478 if (cond_code == LT_EXPR)
1480 if (TYPE_PRECISION (TREE_TYPE (max)) == 1
1481 && !TYPE_UNSIGNED (TREE_TYPE (max)))
1482 max = fold_build2 (PLUS_EXPR, TREE_TYPE (max), max,
1483 build_int_cst (TREE_TYPE (max), -1));
1484 else
1485 max = fold_build2 (MINUS_EXPR, TREE_TYPE (max), max,
1486 build_int_cst (TREE_TYPE (max), 1));
1487 /* Signal to compare_values_warnv this expr doesn't overflow. */
1488 if (EXPR_P (max))
1489 TREE_NO_WARNING (max) = 1;
1492 set_value_range (vr_p, VR_RANGE, min, max, vr_p->equiv);
1495 else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
1497 max = TYPE_MAX_VALUE (type);
1499 if (limit_vr == NULL || limit_vr->type == VR_ANTI_RANGE)
1500 min = limit;
1501 else
1503 /* If LIMIT_VR is of the form [N1, N2], we need to build the
1504 range [N1, MAX] for GE_EXPR and [N1 + 1, MAX] for
1505 GT_EXPR. */
1506 min = limit_vr->min;
1509 /* If the minimum value forces us to be out of bounds, simply punt.
1510 It would be pointless to try and do anything more since this
1511 all should be optimized away above us. */
1512 if (cond_code == GT_EXPR
1513 && compare_values (min, max) == 0)
1514 set_value_range_to_varying (vr_p);
1515 else
1517 /* For GT_EXPR, we create the range [MIN + 1, MAX]. */
1518 if (cond_code == GT_EXPR)
1520 if (TYPE_PRECISION (TREE_TYPE (min)) == 1
1521 && !TYPE_UNSIGNED (TREE_TYPE (min)))
1522 min = fold_build2 (MINUS_EXPR, TREE_TYPE (min), min,
1523 build_int_cst (TREE_TYPE (min), -1));
1524 else
1525 min = fold_build2 (PLUS_EXPR, TREE_TYPE (min), min,
1526 build_int_cst (TREE_TYPE (min), 1));
1527 /* Signal to compare_values_warnv this expr doesn't overflow. */
1528 if (EXPR_P (min))
1529 TREE_NO_WARNING (min) = 1;
1532 set_value_range (vr_p, VR_RANGE, min, max, vr_p->equiv);
1535 else
1536 gcc_unreachable ();
1538 /* Finally intersect the new range with what we already know about var. */
1539 vrp_intersect_ranges (vr_p, get_value_range (var));
1542 /* Extract value range information from an ASSERT_EXPR EXPR and store
1543 it in *VR_P. */
1545 static void
1546 extract_range_from_assert (value_range *vr_p, tree expr)
1548 tree var = ASSERT_EXPR_VAR (expr);
1549 tree cond = ASSERT_EXPR_COND (expr);
1550 tree limit, op;
1551 enum tree_code cond_code;
1552 gcc_assert (COMPARISON_CLASS_P (cond));
1554 /* Find VAR in the ASSERT_EXPR conditional. */
1555 if (var == TREE_OPERAND (cond, 0)
1556 || TREE_CODE (TREE_OPERAND (cond, 0)) == PLUS_EXPR
1557 || TREE_CODE (TREE_OPERAND (cond, 0)) == NOP_EXPR)
1559 /* If the predicate is of the form VAR COMP LIMIT, then we just
1560 take LIMIT from the RHS and use the same comparison code. */
1561 cond_code = TREE_CODE (cond);
1562 limit = TREE_OPERAND (cond, 1);
1563 op = TREE_OPERAND (cond, 0);
1565 else
1567 /* If the predicate is of the form LIMIT COMP VAR, then we need
1568 to flip around the comparison code to create the proper range
1569 for VAR. */
1570 cond_code = swap_tree_comparison (TREE_CODE (cond));
1571 limit = TREE_OPERAND (cond, 0);
1572 op = TREE_OPERAND (cond, 1);
1574 extract_range_for_var_from_comparison_expr (var, cond_code, op,
1575 limit, vr_p);
1578 /* Extract range information from SSA name VAR and store it in VR. If
1579 VAR has an interesting range, use it. Otherwise, create the
1580 range [VAR, VAR] and return it. This is useful in situations where
1581 we may have conditionals testing values of VARYING names. For
1582 instance,
1584 x_3 = y_5;
1585 if (x_3 > y_5)
1588 Even if y_5 is deemed VARYING, we can determine that x_3 > y_5 is
1589 always false. */
1591 static void
1592 extract_range_from_ssa_name (value_range *vr, tree var)
1594 value_range *var_vr = get_value_range (var);
1596 if (var_vr->type != VR_VARYING)
1597 copy_value_range (vr, var_vr);
1598 else
1599 set_value_range (vr, VR_RANGE, var, var, NULL);
1601 add_equivalence (&vr->equiv, var);
1605 /* Wrapper around int_const_binop. If the operation overflows and
1606 overflow is undefined, then adjust the result to be
1607 -INF or +INF depending on CODE, VAL1 and VAL2. Sets *OVERFLOW_P
1608 to whether the operation overflowed. For division by zero
1609 the result is indeterminate but *OVERFLOW_P is set. */
1611 static wide_int
1612 vrp_int_const_binop (enum tree_code code, tree val1, tree val2,
1613 bool *overflow_p)
1615 bool overflow = false;
1616 signop sign = TYPE_SIGN (TREE_TYPE (val1));
1617 wide_int res;
1619 *overflow_p = false;
1621 switch (code)
1623 case RSHIFT_EXPR:
1624 case LSHIFT_EXPR:
1626 wide_int wval2 = wi::to_wide (val2, TYPE_PRECISION (TREE_TYPE (val1)));
1627 if (wi::neg_p (wval2))
1629 wval2 = -wval2;
1630 if (code == RSHIFT_EXPR)
1631 code = LSHIFT_EXPR;
1632 else
1633 code = RSHIFT_EXPR;
1636 if (code == RSHIFT_EXPR)
1637 /* It's unclear from the C standard whether shifts can overflow.
1638 The following code ignores overflow; perhaps a C standard
1639 interpretation ruling is needed. */
1640 res = wi::rshift (wi::to_wide (val1), wval2, sign);
1641 else
1642 res = wi::lshift (wi::to_wide (val1), wval2);
1643 break;
1646 case MULT_EXPR:
1647 res = wi::mul (wi::to_wide (val1),
1648 wi::to_wide (val2), sign, &overflow);
1649 break;
1651 case TRUNC_DIV_EXPR:
1652 case EXACT_DIV_EXPR:
1653 if (val2 == 0)
1655 *overflow_p = true;
1656 return res;
1658 else
1659 res = wi::div_trunc (wi::to_wide (val1),
1660 wi::to_wide (val2), sign, &overflow);
1661 break;
1663 case FLOOR_DIV_EXPR:
1664 if (val2 == 0)
1666 *overflow_p = true;
1667 return res;
1669 res = wi::div_floor (wi::to_wide (val1),
1670 wi::to_wide (val2), sign, &overflow);
1671 break;
1673 case CEIL_DIV_EXPR:
1674 if (val2 == 0)
1676 *overflow_p = true;
1677 return res;
1679 res = wi::div_ceil (wi::to_wide (val1),
1680 wi::to_wide (val2), sign, &overflow);
1681 break;
1683 case ROUND_DIV_EXPR:
1684 if (val2 == 0)
1686 *overflow_p = 0;
1687 return res;
1689 res = wi::div_round (wi::to_wide (val1),
1690 wi::to_wide (val2), sign, &overflow);
1691 break;
1693 default:
1694 gcc_unreachable ();
1697 if (overflow
1698 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1)))
1700 /* If the operation overflowed return -INF or +INF depending
1701 on the operation and the combination of signs of the operands. */
1702 int sgn1 = tree_int_cst_sgn (val1);
1703 int sgn2 = tree_int_cst_sgn (val2);
1705 /* Notice that we only need to handle the restricted set of
1706 operations handled by extract_range_from_binary_expr.
1707 Among them, only multiplication, addition and subtraction
1708 can yield overflow without overflown operands because we
1709 are working with integral types only... except in the
1710 case VAL1 = -INF and VAL2 = -1 which overflows to +INF
1711 for division too. */
1713 /* For multiplication, the sign of the overflow is given
1714 by the comparison of the signs of the operands. */
1715 if ((code == MULT_EXPR && sgn1 == sgn2)
1716 /* For addition, the operands must be of the same sign
1717 to yield an overflow. Its sign is therefore that
1718 of one of the operands, for example the first. */
1719 || (code == PLUS_EXPR && sgn1 >= 0)
1720 /* For subtraction, operands must be of
1721 different signs to yield an overflow. Its sign is
1722 therefore that of the first operand or the opposite of
1723 that of the second operand. A first operand of 0 counts
1724 as positive here, for the corner case 0 - (-INF), which
1725 overflows, but must yield +INF. */
1726 || (code == MINUS_EXPR && sgn1 >= 0)
1727 /* For division, the only case is -INF / -1 = +INF. */
1728 || code == TRUNC_DIV_EXPR
1729 || code == FLOOR_DIV_EXPR
1730 || code == CEIL_DIV_EXPR
1731 || code == EXACT_DIV_EXPR
1732 || code == ROUND_DIV_EXPR)
1733 return wi::max_value (TYPE_PRECISION (TREE_TYPE (val1)),
1734 TYPE_SIGN (TREE_TYPE (val1)));
1735 else
1736 return wi::min_value (TYPE_PRECISION (TREE_TYPE (val1)),
1737 TYPE_SIGN (TREE_TYPE (val1)));
1740 *overflow_p = overflow;
1742 return res;
1746 /* For range VR compute two wide_int bitmasks. In *MAY_BE_NONZERO
1747 bitmask if some bit is unset, it means for all numbers in the range
1748 the bit is 0, otherwise it might be 0 or 1. In *MUST_BE_NONZERO
1749 bitmask if some bit is set, it means for all numbers in the range
1750 the bit is 1, otherwise it might be 0 or 1. */
1752 static bool
1753 zero_nonzero_bits_from_vr (const tree expr_type,
1754 value_range *vr,
1755 wide_int *may_be_nonzero,
1756 wide_int *must_be_nonzero)
1758 *may_be_nonzero = wi::minus_one (TYPE_PRECISION (expr_type));
1759 *must_be_nonzero = wi::zero (TYPE_PRECISION (expr_type));
1760 if (!range_int_cst_p (vr))
1761 return false;
1763 if (range_int_cst_singleton_p (vr))
1765 *may_be_nonzero = wi::to_wide (vr->min);
1766 *must_be_nonzero = *may_be_nonzero;
1768 else if (tree_int_cst_sgn (vr->min) >= 0
1769 || tree_int_cst_sgn (vr->max) < 0)
1771 wide_int xor_mask = wi::to_wide (vr->min) ^ wi::to_wide (vr->max);
1772 *may_be_nonzero = wi::to_wide (vr->min) | wi::to_wide (vr->max);
1773 *must_be_nonzero = wi::to_wide (vr->min) & wi::to_wide (vr->max);
1774 if (xor_mask != 0)
1776 wide_int mask = wi::mask (wi::floor_log2 (xor_mask), false,
1777 may_be_nonzero->get_precision ());
1778 *may_be_nonzero = *may_be_nonzero | mask;
1779 *must_be_nonzero = wi::bit_and_not (*must_be_nonzero, mask);
1783 return true;
1786 /* Create two value-ranges in *VR0 and *VR1 from the anti-range *AR
1787 so that *VR0 U *VR1 == *AR. Returns true if that is possible,
1788 false otherwise. If *AR can be represented with a single range
1789 *VR1 will be VR_UNDEFINED. */
1791 static bool
1792 ranges_from_anti_range (value_range *ar,
1793 value_range *vr0, value_range *vr1)
1795 tree type = TREE_TYPE (ar->min);
1797 vr0->type = VR_UNDEFINED;
1798 vr1->type = VR_UNDEFINED;
1800 if (ar->type != VR_ANTI_RANGE
1801 || TREE_CODE (ar->min) != INTEGER_CST
1802 || TREE_CODE (ar->max) != INTEGER_CST
1803 || !vrp_val_min (type)
1804 || !vrp_val_max (type))
1805 return false;
1807 if (!vrp_val_is_min (ar->min))
1809 vr0->type = VR_RANGE;
1810 vr0->min = vrp_val_min (type);
1811 vr0->max = wide_int_to_tree (type, wi::to_wide (ar->min) - 1);
1813 if (!vrp_val_is_max (ar->max))
1815 vr1->type = VR_RANGE;
1816 vr1->min = wide_int_to_tree (type, wi::to_wide (ar->max) + 1);
1817 vr1->max = vrp_val_max (type);
1819 if (vr0->type == VR_UNDEFINED)
1821 *vr0 = *vr1;
1822 vr1->type = VR_UNDEFINED;
1825 return vr0->type != VR_UNDEFINED;
1828 /* Helper to extract a value-range *VR for a multiplicative operation
1829 *VR0 CODE *VR1. */
1831 static void
1832 extract_range_from_multiplicative_op_1 (value_range *vr,
1833 enum tree_code code,
1834 value_range *vr0, value_range *vr1)
1836 enum value_range_type rtype;
1837 wide_int val, min, max;
1838 bool sop;
1839 tree type;
1841 /* Multiplications, divisions and shifts are a bit tricky to handle,
1842 depending on the mix of signs we have in the two ranges, we
1843 need to operate on different values to get the minimum and
1844 maximum values for the new range. One approach is to figure
1845 out all the variations of range combinations and do the
1846 operations.
1848 However, this involves several calls to compare_values and it
1849 is pretty convoluted. It's simpler to do the 4 operations
1850 (MIN0 OP MIN1, MIN0 OP MAX1, MAX0 OP MIN1 and MAX0 OP MAX0 OP
1851 MAX1) and then figure the smallest and largest values to form
1852 the new range. */
1853 gcc_assert (code == MULT_EXPR
1854 || code == TRUNC_DIV_EXPR
1855 || code == FLOOR_DIV_EXPR
1856 || code == CEIL_DIV_EXPR
1857 || code == EXACT_DIV_EXPR
1858 || code == ROUND_DIV_EXPR
1859 || code == RSHIFT_EXPR
1860 || code == LSHIFT_EXPR);
1861 gcc_assert (vr0->type == VR_RANGE
1862 && vr0->type == vr1->type);
1864 rtype = vr0->type;
1865 type = TREE_TYPE (vr0->min);
1866 signop sgn = TYPE_SIGN (type);
1868 /* Compute the 4 cross operations and their minimum and maximum value. */
1869 sop = false;
1870 val = vrp_int_const_binop (code, vr0->min, vr1->min, &sop);
1871 if (! sop)
1872 min = max = val;
1874 if (vr1->max == vr1->min)
1876 else if (! sop)
1878 val = vrp_int_const_binop (code, vr0->min, vr1->max, &sop);
1879 if (! sop)
1881 if (wi::lt_p (val, min, sgn))
1882 min = val;
1883 else if (wi::gt_p (val, max, sgn))
1884 max = val;
1888 if (vr0->max == vr0->min)
1890 else if (! sop)
1892 val = vrp_int_const_binop (code, vr0->max, vr1->min, &sop);
1893 if (! sop)
1895 if (wi::lt_p (val, min, sgn))
1896 min = val;
1897 else if (wi::gt_p (val, max, sgn))
1898 max = val;
1902 if (vr0->min == vr0->max || vr1->min == vr1->max)
1904 else if (! sop)
1906 val = vrp_int_const_binop (code, vr0->max, vr1->max, &sop);
1907 if (! sop)
1909 if (wi::lt_p (val, min, sgn))
1910 min = val;
1911 else if (wi::gt_p (val, max, sgn))
1912 max = val;
1916 /* If either operation overflowed, drop to VARYING. */
1917 if (sop)
1919 set_value_range_to_varying (vr);
1920 return;
1923 /* If the new range has its limits swapped around (MIN > MAX),
1924 then the operation caused one of them to wrap around, mark
1925 the new range VARYING. */
1926 if (wi::gt_p (min, max, sgn))
1928 set_value_range_to_varying (vr);
1929 return;
1932 /* We punt for [-INF, +INF].
1933 We learn nothing when we have INF on both sides.
1934 Note that we do accept [-INF, -INF] and [+INF, +INF]. */
1935 if (wi::eq_p (min, wi::min_value (TYPE_PRECISION (type), sgn))
1936 && wi::eq_p (max, wi::max_value (TYPE_PRECISION (type), sgn)))
1938 set_value_range_to_varying (vr);
1939 return;
1942 set_value_range (vr, rtype,
1943 wide_int_to_tree (type, min),
1944 wide_int_to_tree (type, max), NULL);
1947 /* Extract range information from a binary operation CODE based on
1948 the ranges of each of its operands *VR0 and *VR1 with resulting
1949 type EXPR_TYPE. The resulting range is stored in *VR. */
1951 static void
1952 extract_range_from_binary_expr_1 (value_range *vr,
1953 enum tree_code code, tree expr_type,
1954 value_range *vr0_, value_range *vr1_)
1956 value_range vr0 = *vr0_, vr1 = *vr1_;
1957 value_range vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
1958 enum value_range_type type;
1959 tree min = NULL_TREE, max = NULL_TREE;
1960 int cmp;
1962 if (!INTEGRAL_TYPE_P (expr_type)
1963 && !POINTER_TYPE_P (expr_type))
1965 set_value_range_to_varying (vr);
1966 return;
1969 /* Not all binary expressions can be applied to ranges in a
1970 meaningful way. Handle only arithmetic operations. */
1971 if (code != PLUS_EXPR
1972 && code != MINUS_EXPR
1973 && code != POINTER_PLUS_EXPR
1974 && code != MULT_EXPR
1975 && code != TRUNC_DIV_EXPR
1976 && code != FLOOR_DIV_EXPR
1977 && code != CEIL_DIV_EXPR
1978 && code != EXACT_DIV_EXPR
1979 && code != ROUND_DIV_EXPR
1980 && code != TRUNC_MOD_EXPR
1981 && code != RSHIFT_EXPR
1982 && code != LSHIFT_EXPR
1983 && code != MIN_EXPR
1984 && code != MAX_EXPR
1985 && code != BIT_AND_EXPR
1986 && code != BIT_IOR_EXPR
1987 && code != BIT_XOR_EXPR)
1989 set_value_range_to_varying (vr);
1990 return;
1993 /* If both ranges are UNDEFINED, so is the result. */
1994 if (vr0.type == VR_UNDEFINED && vr1.type == VR_UNDEFINED)
1996 set_value_range_to_undefined (vr);
1997 return;
1999 /* If one of the ranges is UNDEFINED drop it to VARYING for the following
2000 code. At some point we may want to special-case operations that
2001 have UNDEFINED result for all or some value-ranges of the not UNDEFINED
2002 operand. */
2003 else if (vr0.type == VR_UNDEFINED)
2004 set_value_range_to_varying (&vr0);
2005 else if (vr1.type == VR_UNDEFINED)
2006 set_value_range_to_varying (&vr1);
2008 /* We get imprecise results from ranges_from_anti_range when
2009 code is EXACT_DIV_EXPR. We could mask out bits in the resulting
2010 range, but then we also need to hack up vrp_meet. It's just
2011 easier to special case when vr0 is ~[0,0] for EXACT_DIV_EXPR. */
2012 if (code == EXACT_DIV_EXPR
2013 && vr0.type == VR_ANTI_RANGE
2014 && vr0.min == vr0.max
2015 && integer_zerop (vr0.min))
2017 set_value_range_to_nonnull (vr, expr_type);
2018 return;
2021 /* Now canonicalize anti-ranges to ranges when they are not symbolic
2022 and express ~[] op X as ([]' op X) U ([]'' op X). */
2023 if (vr0.type == VR_ANTI_RANGE
2024 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
2026 extract_range_from_binary_expr_1 (vr, code, expr_type, &vrtem0, vr1_);
2027 if (vrtem1.type != VR_UNDEFINED)
2029 value_range vrres = VR_INITIALIZER;
2030 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
2031 &vrtem1, vr1_);
2032 vrp_meet (vr, &vrres);
2034 return;
2036 /* Likewise for X op ~[]. */
2037 if (vr1.type == VR_ANTI_RANGE
2038 && ranges_from_anti_range (&vr1, &vrtem0, &vrtem1))
2040 extract_range_from_binary_expr_1 (vr, code, expr_type, vr0_, &vrtem0);
2041 if (vrtem1.type != VR_UNDEFINED)
2043 value_range vrres = VR_INITIALIZER;
2044 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
2045 vr0_, &vrtem1);
2046 vrp_meet (vr, &vrres);
2048 return;
2051 /* The type of the resulting value range defaults to VR0.TYPE. */
2052 type = vr0.type;
2054 /* Refuse to operate on VARYING ranges, ranges of different kinds
2055 and symbolic ranges. As an exception, we allow BIT_{AND,IOR}
2056 because we may be able to derive a useful range even if one of
2057 the operands is VR_VARYING or symbolic range. Similarly for
2058 divisions, MIN/MAX and PLUS/MINUS.
2060 TODO, we may be able to derive anti-ranges in some cases. */
2061 if (code != BIT_AND_EXPR
2062 && code != BIT_IOR_EXPR
2063 && code != TRUNC_DIV_EXPR
2064 && code != FLOOR_DIV_EXPR
2065 && code != CEIL_DIV_EXPR
2066 && code != EXACT_DIV_EXPR
2067 && code != ROUND_DIV_EXPR
2068 && code != TRUNC_MOD_EXPR
2069 && code != MIN_EXPR
2070 && code != MAX_EXPR
2071 && code != PLUS_EXPR
2072 && code != MINUS_EXPR
2073 && code != RSHIFT_EXPR
2074 && (vr0.type == VR_VARYING
2075 || vr1.type == VR_VARYING
2076 || vr0.type != vr1.type
2077 || symbolic_range_p (&vr0)
2078 || symbolic_range_p (&vr1)))
2080 set_value_range_to_varying (vr);
2081 return;
2084 /* Now evaluate the expression to determine the new range. */
2085 if (POINTER_TYPE_P (expr_type))
2087 if (code == MIN_EXPR || code == MAX_EXPR)
2089 /* For MIN/MAX expressions with pointers, we only care about
2090 nullness, if both are non null, then the result is nonnull.
2091 If both are null, then the result is null. Otherwise they
2092 are varying. */
2093 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
2094 set_value_range_to_nonnull (vr, expr_type);
2095 else if (range_is_null (&vr0) && range_is_null (&vr1))
2096 set_value_range_to_null (vr, expr_type);
2097 else
2098 set_value_range_to_varying (vr);
2100 else if (code == POINTER_PLUS_EXPR)
2102 /* For pointer types, we are really only interested in asserting
2103 whether the expression evaluates to non-NULL. */
2104 if (range_is_nonnull (&vr0) || range_is_nonnull (&vr1))
2105 set_value_range_to_nonnull (vr, expr_type);
2106 else if (range_is_null (&vr0) && range_is_null (&vr1))
2107 set_value_range_to_null (vr, expr_type);
2108 else
2109 set_value_range_to_varying (vr);
2111 else if (code == BIT_AND_EXPR)
2113 /* For pointer types, we are really only interested in asserting
2114 whether the expression evaluates to non-NULL. */
2115 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
2116 set_value_range_to_nonnull (vr, expr_type);
2117 else if (range_is_null (&vr0) || range_is_null (&vr1))
2118 set_value_range_to_null (vr, expr_type);
2119 else
2120 set_value_range_to_varying (vr);
2122 else
2123 set_value_range_to_varying (vr);
2125 return;
2128 /* For integer ranges, apply the operation to each end of the
2129 range and see what we end up with. */
2130 if (code == PLUS_EXPR || code == MINUS_EXPR)
2132 const bool minus_p = (code == MINUS_EXPR);
2133 tree min_op0 = vr0.min;
2134 tree min_op1 = minus_p ? vr1.max : vr1.min;
2135 tree max_op0 = vr0.max;
2136 tree max_op1 = minus_p ? vr1.min : vr1.max;
2137 tree sym_min_op0 = NULL_TREE;
2138 tree sym_min_op1 = NULL_TREE;
2139 tree sym_max_op0 = NULL_TREE;
2140 tree sym_max_op1 = NULL_TREE;
2141 bool neg_min_op0, neg_min_op1, neg_max_op0, neg_max_op1;
2143 /* If we have a PLUS or MINUS with two VR_RANGEs, either constant or
2144 single-symbolic ranges, try to compute the precise resulting range,
2145 but only if we know that this resulting range will also be constant
2146 or single-symbolic. */
2147 if (vr0.type == VR_RANGE && vr1.type == VR_RANGE
2148 && (TREE_CODE (min_op0) == INTEGER_CST
2149 || (sym_min_op0
2150 = get_single_symbol (min_op0, &neg_min_op0, &min_op0)))
2151 && (TREE_CODE (min_op1) == INTEGER_CST
2152 || (sym_min_op1
2153 = get_single_symbol (min_op1, &neg_min_op1, &min_op1)))
2154 && (!(sym_min_op0 && sym_min_op1)
2155 || (sym_min_op0 == sym_min_op1
2156 && neg_min_op0 == (minus_p ? neg_min_op1 : !neg_min_op1)))
2157 && (TREE_CODE (max_op0) == INTEGER_CST
2158 || (sym_max_op0
2159 = get_single_symbol (max_op0, &neg_max_op0, &max_op0)))
2160 && (TREE_CODE (max_op1) == INTEGER_CST
2161 || (sym_max_op1
2162 = get_single_symbol (max_op1, &neg_max_op1, &max_op1)))
2163 && (!(sym_max_op0 && sym_max_op1)
2164 || (sym_max_op0 == sym_max_op1
2165 && neg_max_op0 == (minus_p ? neg_max_op1 : !neg_max_op1))))
2167 const signop sgn = TYPE_SIGN (expr_type);
2168 const unsigned int prec = TYPE_PRECISION (expr_type);
2169 wide_int type_min, type_max, wmin, wmax;
2170 int min_ovf = 0;
2171 int max_ovf = 0;
2173 /* Get the lower and upper bounds of the type. */
2174 if (TYPE_OVERFLOW_WRAPS (expr_type))
2176 type_min = wi::min_value (prec, sgn);
2177 type_max = wi::max_value (prec, sgn);
2179 else
2181 type_min = wi::to_wide (vrp_val_min (expr_type));
2182 type_max = wi::to_wide (vrp_val_max (expr_type));
2185 /* Combine the lower bounds, if any. */
2186 if (min_op0 && min_op1)
2188 if (minus_p)
2190 wmin = wi::to_wide (min_op0) - wi::to_wide (min_op1);
2192 /* Check for overflow. */
2193 if (wi::cmp (0, wi::to_wide (min_op1), sgn)
2194 != wi::cmp (wmin, wi::to_wide (min_op0), sgn))
2195 min_ovf = wi::cmp (wi::to_wide (min_op0),
2196 wi::to_wide (min_op1), sgn);
2198 else
2200 wmin = wi::to_wide (min_op0) + wi::to_wide (min_op1);
2202 /* Check for overflow. */
2203 if (wi::cmp (wi::to_wide (min_op1), 0, sgn)
2204 != wi::cmp (wmin, wi::to_wide (min_op0), sgn))
2205 min_ovf = wi::cmp (wi::to_wide (min_op0), wmin, sgn);
2208 else if (min_op0)
2209 wmin = wi::to_wide (min_op0);
2210 else if (min_op1)
2212 if (minus_p)
2214 wmin = -wi::to_wide (min_op1);
2216 /* Check for overflow. */
2217 if (sgn == SIGNED
2218 && wi::neg_p (wi::to_wide (min_op1))
2219 && wi::neg_p (wmin))
2220 min_ovf = 1;
2221 else if (sgn == UNSIGNED && wi::to_wide (min_op1) != 0)
2222 min_ovf = -1;
2224 else
2225 wmin = wi::to_wide (min_op1);
2227 else
2228 wmin = wi::shwi (0, prec);
2230 /* Combine the upper bounds, if any. */
2231 if (max_op0 && max_op1)
2233 if (minus_p)
2235 wmax = wi::to_wide (max_op0) - wi::to_wide (max_op1);
2237 /* Check for overflow. */
2238 if (wi::cmp (0, wi::to_wide (max_op1), sgn)
2239 != wi::cmp (wmax, wi::to_wide (max_op0), sgn))
2240 max_ovf = wi::cmp (wi::to_wide (max_op0),
2241 wi::to_wide (max_op1), sgn);
2243 else
2245 wmax = wi::to_wide (max_op0) + wi::to_wide (max_op1);
2247 if (wi::cmp (wi::to_wide (max_op1), 0, sgn)
2248 != wi::cmp (wmax, wi::to_wide (max_op0), sgn))
2249 max_ovf = wi::cmp (wi::to_wide (max_op0), wmax, sgn);
2252 else if (max_op0)
2253 wmax = wi::to_wide (max_op0);
2254 else if (max_op1)
2256 if (minus_p)
2258 wmax = -wi::to_wide (max_op1);
2260 /* Check for overflow. */
2261 if (sgn == SIGNED
2262 && wi::neg_p (wi::to_wide (max_op1))
2263 && wi::neg_p (wmax))
2264 max_ovf = 1;
2265 else if (sgn == UNSIGNED && wi::to_wide (max_op1) != 0)
2266 max_ovf = -1;
2268 else
2269 wmax = wi::to_wide (max_op1);
2271 else
2272 wmax = wi::shwi (0, prec);
2274 /* Check for type overflow. */
2275 if (min_ovf == 0)
2277 if (wi::cmp (wmin, type_min, sgn) == -1)
2278 min_ovf = -1;
2279 else if (wi::cmp (wmin, type_max, sgn) == 1)
2280 min_ovf = 1;
2282 if (max_ovf == 0)
2284 if (wi::cmp (wmax, type_min, sgn) == -1)
2285 max_ovf = -1;
2286 else if (wi::cmp (wmax, type_max, sgn) == 1)
2287 max_ovf = 1;
2290 /* If we have overflow for the constant part and the resulting
2291 range will be symbolic, drop to VR_VARYING. */
2292 if ((min_ovf && sym_min_op0 != sym_min_op1)
2293 || (max_ovf && sym_max_op0 != sym_max_op1))
2295 set_value_range_to_varying (vr);
2296 return;
2299 if (TYPE_OVERFLOW_WRAPS (expr_type))
2301 /* If overflow wraps, truncate the values and adjust the
2302 range kind and bounds appropriately. */
2303 wide_int tmin = wide_int::from (wmin, prec, sgn);
2304 wide_int tmax = wide_int::from (wmax, prec, sgn);
2305 if (min_ovf == max_ovf)
2307 /* No overflow or both overflow or underflow. The
2308 range kind stays VR_RANGE. */
2309 min = wide_int_to_tree (expr_type, tmin);
2310 max = wide_int_to_tree (expr_type, tmax);
2312 else if ((min_ovf == -1 && max_ovf == 0)
2313 || (max_ovf == 1 && min_ovf == 0))
2315 /* Min underflow or max overflow. The range kind
2316 changes to VR_ANTI_RANGE. */
2317 bool covers = false;
2318 wide_int tem = tmin;
2319 type = VR_ANTI_RANGE;
2320 tmin = tmax + 1;
2321 if (wi::cmp (tmin, tmax, sgn) < 0)
2322 covers = true;
2323 tmax = tem - 1;
2324 if (wi::cmp (tmax, tem, sgn) > 0)
2325 covers = true;
2326 /* If the anti-range would cover nothing, drop to varying.
2327 Likewise if the anti-range bounds are outside of the
2328 types values. */
2329 if (covers || wi::cmp (tmin, tmax, sgn) > 0)
2331 set_value_range_to_varying (vr);
2332 return;
2334 min = wide_int_to_tree (expr_type, tmin);
2335 max = wide_int_to_tree (expr_type, tmax);
2337 else
2339 /* Other underflow and/or overflow, drop to VR_VARYING. */
2340 set_value_range_to_varying (vr);
2341 return;
2344 else
2346 /* If overflow does not wrap, saturate to the types min/max
2347 value. */
2348 if (min_ovf == -1)
2349 min = wide_int_to_tree (expr_type, type_min);
2350 else if (min_ovf == 1)
2351 min = wide_int_to_tree (expr_type, type_max);
2352 else
2353 min = wide_int_to_tree (expr_type, wmin);
2355 if (max_ovf == -1)
2356 max = wide_int_to_tree (expr_type, type_min);
2357 else if (max_ovf == 1)
2358 max = wide_int_to_tree (expr_type, type_max);
2359 else
2360 max = wide_int_to_tree (expr_type, wmax);
2363 /* If the result lower bound is constant, we're done;
2364 otherwise, build the symbolic lower bound. */
2365 if (sym_min_op0 == sym_min_op1)
2367 else if (sym_min_op0)
2368 min = build_symbolic_expr (expr_type, sym_min_op0,
2369 neg_min_op0, min);
2370 else if (sym_min_op1)
2372 /* We may not negate if that might introduce
2373 undefined overflow. */
2374 if (! minus_p
2375 || neg_min_op1
2376 || TYPE_OVERFLOW_WRAPS (expr_type))
2377 min = build_symbolic_expr (expr_type, sym_min_op1,
2378 neg_min_op1 ^ minus_p, min);
2379 else
2380 min = NULL_TREE;
2383 /* Likewise for the upper bound. */
2384 if (sym_max_op0 == sym_max_op1)
2386 else if (sym_max_op0)
2387 max = build_symbolic_expr (expr_type, sym_max_op0,
2388 neg_max_op0, max);
2389 else if (sym_max_op1)
2391 /* We may not negate if that might introduce
2392 undefined overflow. */
2393 if (! minus_p
2394 || neg_max_op1
2395 || TYPE_OVERFLOW_WRAPS (expr_type))
2396 max = build_symbolic_expr (expr_type, sym_max_op1,
2397 neg_max_op1 ^ minus_p, max);
2398 else
2399 max = NULL_TREE;
2402 else
2404 /* For other cases, for example if we have a PLUS_EXPR with two
2405 VR_ANTI_RANGEs, drop to VR_VARYING. It would take more effort
2406 to compute a precise range for such a case.
2407 ??? General even mixed range kind operations can be expressed
2408 by for example transforming ~[3, 5] + [1, 2] to range-only
2409 operations and a union primitive:
2410 [-INF, 2] + [1, 2] U [5, +INF] + [1, 2]
2411 [-INF+1, 4] U [6, +INF(OVF)]
2412 though usually the union is not exactly representable with
2413 a single range or anti-range as the above is
2414 [-INF+1, +INF(OVF)] intersected with ~[5, 5]
2415 but one could use a scheme similar to equivalences for this. */
2416 set_value_range_to_varying (vr);
2417 return;
2420 else if (code == MIN_EXPR
2421 || code == MAX_EXPR)
2423 if (vr0.type == VR_RANGE
2424 && !symbolic_range_p (&vr0))
2426 type = VR_RANGE;
2427 if (vr1.type == VR_RANGE
2428 && !symbolic_range_p (&vr1))
2430 /* For operations that make the resulting range directly
2431 proportional to the original ranges, apply the operation to
2432 the same end of each range. */
2433 min = int_const_binop (code, vr0.min, vr1.min);
2434 max = int_const_binop (code, vr0.max, vr1.max);
2436 else if (code == MIN_EXPR)
2438 min = vrp_val_min (expr_type);
2439 max = vr0.max;
2441 else if (code == MAX_EXPR)
2443 min = vr0.min;
2444 max = vrp_val_max (expr_type);
2447 else if (vr1.type == VR_RANGE
2448 && !symbolic_range_p (&vr1))
2450 type = VR_RANGE;
2451 if (code == MIN_EXPR)
2453 min = vrp_val_min (expr_type);
2454 max = vr1.max;
2456 else if (code == MAX_EXPR)
2458 min = vr1.min;
2459 max = vrp_val_max (expr_type);
2462 else
2464 set_value_range_to_varying (vr);
2465 return;
2468 else if (code == MULT_EXPR)
2470 /* Fancy code so that with unsigned, [-3,-1]*[-3,-1] does not
2471 drop to varying. This test requires 2*prec bits if both
2472 operands are signed and 2*prec + 2 bits if either is not. */
2474 signop sign = TYPE_SIGN (expr_type);
2475 unsigned int prec = TYPE_PRECISION (expr_type);
2477 if (!range_int_cst_p (&vr0)
2478 || !range_int_cst_p (&vr1))
2480 set_value_range_to_varying (vr);
2481 return;
2484 if (TYPE_OVERFLOW_WRAPS (expr_type))
2486 typedef FIXED_WIDE_INT (WIDE_INT_MAX_PRECISION * 2) vrp_int;
2487 typedef generic_wide_int
2488 <wi::extended_tree <WIDE_INT_MAX_PRECISION * 2> > vrp_int_cst;
2489 vrp_int sizem1 = wi::mask <vrp_int> (prec, false);
2490 vrp_int size = sizem1 + 1;
2492 /* Extend the values using the sign of the result to PREC2.
2493 From here on out, everthing is just signed math no matter
2494 what the input types were. */
2495 vrp_int min0 = vrp_int_cst (vr0.min);
2496 vrp_int max0 = vrp_int_cst (vr0.max);
2497 vrp_int min1 = vrp_int_cst (vr1.min);
2498 vrp_int max1 = vrp_int_cst (vr1.max);
2499 /* Canonicalize the intervals. */
2500 if (sign == UNSIGNED)
2502 if (wi::ltu_p (size, min0 + max0))
2504 min0 -= size;
2505 max0 -= size;
2508 if (wi::ltu_p (size, min1 + max1))
2510 min1 -= size;
2511 max1 -= size;
2515 vrp_int prod0 = min0 * min1;
2516 vrp_int prod1 = min0 * max1;
2517 vrp_int prod2 = max0 * min1;
2518 vrp_int prod3 = max0 * max1;
2520 /* Sort the 4 products so that min is in prod0 and max is in
2521 prod3. */
2522 /* min0min1 > max0max1 */
2523 if (prod0 > prod3)
2524 std::swap (prod0, prod3);
2526 /* min0max1 > max0min1 */
2527 if (prod1 > prod2)
2528 std::swap (prod1, prod2);
2530 if (prod0 > prod1)
2531 std::swap (prod0, prod1);
2533 if (prod2 > prod3)
2534 std::swap (prod2, prod3);
2536 /* diff = max - min. */
2537 prod2 = prod3 - prod0;
2538 if (wi::geu_p (prod2, sizem1))
2540 /* the range covers all values. */
2541 set_value_range_to_varying (vr);
2542 return;
2545 /* The following should handle the wrapping and selecting
2546 VR_ANTI_RANGE for us. */
2547 min = wide_int_to_tree (expr_type, prod0);
2548 max = wide_int_to_tree (expr_type, prod3);
2549 set_and_canonicalize_value_range (vr, VR_RANGE, min, max, NULL);
2550 return;
2553 /* If we have an unsigned MULT_EXPR with two VR_ANTI_RANGEs,
2554 drop to VR_VARYING. It would take more effort to compute a
2555 precise range for such a case. For example, if we have
2556 op0 == 65536 and op1 == 65536 with their ranges both being
2557 ~[0,0] on a 32-bit machine, we would have op0 * op1 == 0, so
2558 we cannot claim that the product is in ~[0,0]. Note that we
2559 are guaranteed to have vr0.type == vr1.type at this
2560 point. */
2561 if (vr0.type == VR_ANTI_RANGE
2562 && !TYPE_OVERFLOW_UNDEFINED (expr_type))
2564 set_value_range_to_varying (vr);
2565 return;
2568 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2569 return;
2571 else if (code == RSHIFT_EXPR
2572 || code == LSHIFT_EXPR)
2574 /* If we have a RSHIFT_EXPR with any shift values outside [0..prec-1],
2575 then drop to VR_VARYING. Outside of this range we get undefined
2576 behavior from the shift operation. We cannot even trust
2577 SHIFT_COUNT_TRUNCATED at this stage, because that applies to rtl
2578 shifts, and the operation at the tree level may be widened. */
2579 if (range_int_cst_p (&vr1)
2580 && compare_tree_int (vr1.min, 0) >= 0
2581 && compare_tree_int (vr1.max, TYPE_PRECISION (expr_type)) == -1)
2583 if (code == RSHIFT_EXPR)
2585 /* Even if vr0 is VARYING or otherwise not usable, we can derive
2586 useful ranges just from the shift count. E.g.
2587 x >> 63 for signed 64-bit x is always [-1, 0]. */
2588 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
2590 vr0.type = type = VR_RANGE;
2591 vr0.min = vrp_val_min (expr_type);
2592 vr0.max = vrp_val_max (expr_type);
2594 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2595 return;
2597 /* We can map lshifts by constants to MULT_EXPR handling. */
2598 else if (code == LSHIFT_EXPR
2599 && range_int_cst_singleton_p (&vr1))
2601 bool saved_flag_wrapv;
2602 value_range vr1p = VR_INITIALIZER;
2603 vr1p.type = VR_RANGE;
2604 vr1p.min = (wide_int_to_tree
2605 (expr_type,
2606 wi::set_bit_in_zero (tree_to_shwi (vr1.min),
2607 TYPE_PRECISION (expr_type))));
2608 vr1p.max = vr1p.min;
2609 /* We have to use a wrapping multiply though as signed overflow
2610 on lshifts is implementation defined in C89. */
2611 saved_flag_wrapv = flag_wrapv;
2612 flag_wrapv = 1;
2613 extract_range_from_binary_expr_1 (vr, MULT_EXPR, expr_type,
2614 &vr0, &vr1p);
2615 flag_wrapv = saved_flag_wrapv;
2616 return;
2618 else if (code == LSHIFT_EXPR
2619 && range_int_cst_p (&vr0))
2621 int prec = TYPE_PRECISION (expr_type);
2622 int overflow_pos = prec;
2623 int bound_shift;
2624 wide_int low_bound, high_bound;
2625 bool uns = TYPE_UNSIGNED (expr_type);
2626 bool in_bounds = false;
2628 if (!uns)
2629 overflow_pos -= 1;
2631 bound_shift = overflow_pos - tree_to_shwi (vr1.max);
2632 /* If bound_shift == HOST_BITS_PER_WIDE_INT, the llshift can
2633 overflow. However, for that to happen, vr1.max needs to be
2634 zero, which means vr1 is a singleton range of zero, which
2635 means it should be handled by the previous LSHIFT_EXPR
2636 if-clause. */
2637 wide_int bound = wi::set_bit_in_zero (bound_shift, prec);
2638 wide_int complement = ~(bound - 1);
2640 if (uns)
2642 low_bound = bound;
2643 high_bound = complement;
2644 if (wi::ltu_p (wi::to_wide (vr0.max), low_bound))
2646 /* [5, 6] << [1, 2] == [10, 24]. */
2647 /* We're shifting out only zeroes, the value increases
2648 monotonically. */
2649 in_bounds = true;
2651 else if (wi::ltu_p (high_bound, wi::to_wide (vr0.min)))
2653 /* [0xffffff00, 0xffffffff] << [1, 2]
2654 == [0xfffffc00, 0xfffffffe]. */
2655 /* We're shifting out only ones, the value decreases
2656 monotonically. */
2657 in_bounds = true;
2660 else
2662 /* [-1, 1] << [1, 2] == [-4, 4]. */
2663 low_bound = complement;
2664 high_bound = bound;
2665 if (wi::lts_p (wi::to_wide (vr0.max), high_bound)
2666 && wi::lts_p (low_bound, wi::to_wide (vr0.min)))
2668 /* For non-negative numbers, we're shifting out only
2669 zeroes, the value increases monotonically.
2670 For negative numbers, we're shifting out only ones, the
2671 value decreases monotomically. */
2672 in_bounds = true;
2676 if (in_bounds)
2678 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2679 return;
2683 set_value_range_to_varying (vr);
2684 return;
2686 else if (code == TRUNC_DIV_EXPR
2687 || code == FLOOR_DIV_EXPR
2688 || code == CEIL_DIV_EXPR
2689 || code == EXACT_DIV_EXPR
2690 || code == ROUND_DIV_EXPR)
2692 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
2694 /* For division, if op1 has VR_RANGE but op0 does not, something
2695 can be deduced just from that range. Say [min, max] / [4, max]
2696 gives [min / 4, max / 4] range. */
2697 if (vr1.type == VR_RANGE
2698 && !symbolic_range_p (&vr1)
2699 && range_includes_zero_p (vr1.min, vr1.max) == 0)
2701 vr0.type = type = VR_RANGE;
2702 vr0.min = vrp_val_min (expr_type);
2703 vr0.max = vrp_val_max (expr_type);
2705 else
2707 set_value_range_to_varying (vr);
2708 return;
2712 /* For divisions, if flag_non_call_exceptions is true, we must
2713 not eliminate a division by zero. */
2714 if (cfun->can_throw_non_call_exceptions
2715 && (vr1.type != VR_RANGE
2716 || range_includes_zero_p (vr1.min, vr1.max) != 0))
2718 set_value_range_to_varying (vr);
2719 return;
2722 /* For divisions, if op0 is VR_RANGE, we can deduce a range
2723 even if op1 is VR_VARYING, VR_ANTI_RANGE, symbolic or can
2724 include 0. */
2725 if (vr0.type == VR_RANGE
2726 && (vr1.type != VR_RANGE
2727 || range_includes_zero_p (vr1.min, vr1.max) != 0))
2729 tree zero = build_int_cst (TREE_TYPE (vr0.min), 0);
2730 int cmp;
2732 min = NULL_TREE;
2733 max = NULL_TREE;
2734 if (TYPE_UNSIGNED (expr_type)
2735 || value_range_nonnegative_p (&vr1))
2737 /* For unsigned division or when divisor is known
2738 to be non-negative, the range has to cover
2739 all numbers from 0 to max for positive max
2740 and all numbers from min to 0 for negative min. */
2741 cmp = compare_values (vr0.max, zero);
2742 if (cmp == -1)
2744 /* When vr0.max < 0, vr1.min != 0 and value
2745 ranges for dividend and divisor are available. */
2746 if (vr1.type == VR_RANGE
2747 && !symbolic_range_p (&vr0)
2748 && !symbolic_range_p (&vr1)
2749 && compare_values (vr1.min, zero) != 0)
2750 max = int_const_binop (code, vr0.max, vr1.min);
2751 else
2752 max = zero;
2754 else if (cmp == 0 || cmp == 1)
2755 max = vr0.max;
2756 else
2757 type = VR_VARYING;
2758 cmp = compare_values (vr0.min, zero);
2759 if (cmp == 1)
2761 /* For unsigned division when value ranges for dividend
2762 and divisor are available. */
2763 if (vr1.type == VR_RANGE
2764 && !symbolic_range_p (&vr0)
2765 && !symbolic_range_p (&vr1)
2766 && compare_values (vr1.max, zero) != 0)
2767 min = int_const_binop (code, vr0.min, vr1.max);
2768 else
2769 min = zero;
2771 else if (cmp == 0 || cmp == -1)
2772 min = vr0.min;
2773 else
2774 type = VR_VARYING;
2776 else
2778 /* Otherwise the range is -max .. max or min .. -min
2779 depending on which bound is bigger in absolute value,
2780 as the division can change the sign. */
2781 abs_extent_range (vr, vr0.min, vr0.max);
2782 return;
2784 if (type == VR_VARYING)
2786 set_value_range_to_varying (vr);
2787 return;
2790 else if (!symbolic_range_p (&vr0) && !symbolic_range_p (&vr1))
2792 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2793 return;
2796 else if (code == TRUNC_MOD_EXPR)
2798 if (range_is_null (&vr1))
2800 set_value_range_to_undefined (vr);
2801 return;
2803 /* ABS (A % B) < ABS (B) and either
2804 0 <= A % B <= A or A <= A % B <= 0. */
2805 type = VR_RANGE;
2806 signop sgn = TYPE_SIGN (expr_type);
2807 unsigned int prec = TYPE_PRECISION (expr_type);
2808 wide_int wmin, wmax, tmp;
2809 if (vr1.type == VR_RANGE && !symbolic_range_p (&vr1))
2811 wmax = wi::to_wide (vr1.max) - 1;
2812 if (sgn == SIGNED)
2814 tmp = -1 - wi::to_wide (vr1.min);
2815 wmax = wi::smax (wmax, tmp);
2818 else
2820 wmax = wi::max_value (prec, sgn);
2821 /* X % INT_MIN may be INT_MAX. */
2822 if (sgn == UNSIGNED)
2823 wmax = wmax - 1;
2826 if (sgn == UNSIGNED)
2827 wmin = wi::zero (prec);
2828 else
2830 wmin = -wmax;
2831 if (vr0.type == VR_RANGE && TREE_CODE (vr0.min) == INTEGER_CST)
2833 tmp = wi::to_wide (vr0.min);
2834 if (wi::gts_p (tmp, 0))
2835 tmp = wi::zero (prec);
2836 wmin = wi::smax (wmin, tmp);
2840 if (vr0.type == VR_RANGE && TREE_CODE (vr0.max) == INTEGER_CST)
2842 tmp = wi::to_wide (vr0.max);
2843 if (sgn == SIGNED && wi::neg_p (tmp))
2844 tmp = wi::zero (prec);
2845 wmax = wi::min (wmax, tmp, sgn);
2848 min = wide_int_to_tree (expr_type, wmin);
2849 max = wide_int_to_tree (expr_type, wmax);
2851 else if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR || code == BIT_XOR_EXPR)
2853 bool int_cst_range0, int_cst_range1;
2854 wide_int may_be_nonzero0, may_be_nonzero1;
2855 wide_int must_be_nonzero0, must_be_nonzero1;
2857 int_cst_range0 = zero_nonzero_bits_from_vr (expr_type, &vr0,
2858 &may_be_nonzero0,
2859 &must_be_nonzero0);
2860 int_cst_range1 = zero_nonzero_bits_from_vr (expr_type, &vr1,
2861 &may_be_nonzero1,
2862 &must_be_nonzero1);
2864 if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR)
2866 value_range *vr0p = NULL, *vr1p = NULL;
2867 if (range_int_cst_singleton_p (&vr1))
2869 vr0p = &vr0;
2870 vr1p = &vr1;
2872 else if (range_int_cst_singleton_p (&vr0))
2874 vr0p = &vr1;
2875 vr1p = &vr0;
2877 /* For op & or | attempt to optimize:
2878 [x, y] op z into [x op z, y op z]
2879 if z is a constant which (for op | its bitwise not) has n
2880 consecutive least significant bits cleared followed by m 1
2881 consecutive bits set immediately above it and either
2882 m + n == precision, or (x >> (m + n)) == (y >> (m + n)).
2883 The least significant n bits of all the values in the range are
2884 cleared or set, the m bits above it are preserved and any bits
2885 above these are required to be the same for all values in the
2886 range. */
2887 if (vr0p && range_int_cst_p (vr0p))
2889 wide_int w = wi::to_wide (vr1p->min);
2890 int m = 0, n = 0;
2891 if (code == BIT_IOR_EXPR)
2892 w = ~w;
2893 if (wi::eq_p (w, 0))
2894 n = TYPE_PRECISION (expr_type);
2895 else
2897 n = wi::ctz (w);
2898 w = ~(w | wi::mask (n, false, w.get_precision ()));
2899 if (wi::eq_p (w, 0))
2900 m = TYPE_PRECISION (expr_type) - n;
2901 else
2902 m = wi::ctz (w) - n;
2904 wide_int mask = wi::mask (m + n, true, w.get_precision ());
2905 if ((mask & wi::to_wide (vr0p->min))
2906 == (mask & wi::to_wide (vr0p->max)))
2908 min = int_const_binop (code, vr0p->min, vr1p->min);
2909 max = int_const_binop (code, vr0p->max, vr1p->min);
2914 type = VR_RANGE;
2915 if (min && max)
2916 /* Optimized above already. */;
2917 else if (code == BIT_AND_EXPR)
2919 min = wide_int_to_tree (expr_type,
2920 must_be_nonzero0 & must_be_nonzero1);
2921 wide_int wmax = may_be_nonzero0 & may_be_nonzero1;
2922 /* If both input ranges contain only negative values we can
2923 truncate the result range maximum to the minimum of the
2924 input range maxima. */
2925 if (int_cst_range0 && int_cst_range1
2926 && tree_int_cst_sgn (vr0.max) < 0
2927 && tree_int_cst_sgn (vr1.max) < 0)
2929 wmax = wi::min (wmax, wi::to_wide (vr0.max),
2930 TYPE_SIGN (expr_type));
2931 wmax = wi::min (wmax, wi::to_wide (vr1.max),
2932 TYPE_SIGN (expr_type));
2934 /* If either input range contains only non-negative values
2935 we can truncate the result range maximum to the respective
2936 maximum of the input range. */
2937 if (int_cst_range0 && tree_int_cst_sgn (vr0.min) >= 0)
2938 wmax = wi::min (wmax, wi::to_wide (vr0.max),
2939 TYPE_SIGN (expr_type));
2940 if (int_cst_range1 && tree_int_cst_sgn (vr1.min) >= 0)
2941 wmax = wi::min (wmax, wi::to_wide (vr1.max),
2942 TYPE_SIGN (expr_type));
2943 max = wide_int_to_tree (expr_type, wmax);
2944 cmp = compare_values (min, max);
2945 /* PR68217: In case of signed & sign-bit-CST should
2946 result in [-INF, 0] instead of [-INF, INF]. */
2947 if (cmp == -2 || cmp == 1)
2949 wide_int sign_bit
2950 = wi::set_bit_in_zero (TYPE_PRECISION (expr_type) - 1,
2951 TYPE_PRECISION (expr_type));
2952 if (!TYPE_UNSIGNED (expr_type)
2953 && ((int_cst_range0
2954 && value_range_constant_singleton (&vr0)
2955 && !wi::cmps (wi::to_wide (vr0.min), sign_bit))
2956 || (int_cst_range1
2957 && value_range_constant_singleton (&vr1)
2958 && !wi::cmps (wi::to_wide (vr1.min), sign_bit))))
2960 min = TYPE_MIN_VALUE (expr_type);
2961 max = build_int_cst (expr_type, 0);
2965 else if (code == BIT_IOR_EXPR)
2967 max = wide_int_to_tree (expr_type,
2968 may_be_nonzero0 | may_be_nonzero1);
2969 wide_int wmin = must_be_nonzero0 | must_be_nonzero1;
2970 /* If the input ranges contain only positive values we can
2971 truncate the minimum of the result range to the maximum
2972 of the input range minima. */
2973 if (int_cst_range0 && int_cst_range1
2974 && tree_int_cst_sgn (vr0.min) >= 0
2975 && tree_int_cst_sgn (vr1.min) >= 0)
2977 wmin = wi::max (wmin, wi::to_wide (vr0.min),
2978 TYPE_SIGN (expr_type));
2979 wmin = wi::max (wmin, wi::to_wide (vr1.min),
2980 TYPE_SIGN (expr_type));
2982 /* If either input range contains only negative values
2983 we can truncate the minimum of the result range to the
2984 respective minimum range. */
2985 if (int_cst_range0 && tree_int_cst_sgn (vr0.max) < 0)
2986 wmin = wi::max (wmin, wi::to_wide (vr0.min),
2987 TYPE_SIGN (expr_type));
2988 if (int_cst_range1 && tree_int_cst_sgn (vr1.max) < 0)
2989 wmin = wi::max (wmin, wi::to_wide (vr1.min),
2990 TYPE_SIGN (expr_type));
2991 min = wide_int_to_tree (expr_type, wmin);
2993 else if (code == BIT_XOR_EXPR)
2995 wide_int result_zero_bits = ((must_be_nonzero0 & must_be_nonzero1)
2996 | ~(may_be_nonzero0 | may_be_nonzero1));
2997 wide_int result_one_bits
2998 = (wi::bit_and_not (must_be_nonzero0, may_be_nonzero1)
2999 | wi::bit_and_not (must_be_nonzero1, may_be_nonzero0));
3000 max = wide_int_to_tree (expr_type, ~result_zero_bits);
3001 min = wide_int_to_tree (expr_type, result_one_bits);
3002 /* If the range has all positive or all negative values the
3003 result is better than VARYING. */
3004 if (tree_int_cst_sgn (min) < 0
3005 || tree_int_cst_sgn (max) >= 0)
3007 else
3008 max = min = NULL_TREE;
3011 else
3012 gcc_unreachable ();
3014 /* If either MIN or MAX overflowed, then set the resulting range to
3015 VARYING. */
3016 if (min == NULL_TREE
3017 || TREE_OVERFLOW_P (min)
3018 || max == NULL_TREE
3019 || TREE_OVERFLOW_P (max))
3021 set_value_range_to_varying (vr);
3022 return;
3025 /* We punt for [-INF, +INF].
3026 We learn nothing when we have INF on both sides.
3027 Note that we do accept [-INF, -INF] and [+INF, +INF]. */
3028 if (vrp_val_is_min (min) && vrp_val_is_max (max))
3030 set_value_range_to_varying (vr);
3031 return;
3034 cmp = compare_values (min, max);
3035 if (cmp == -2 || cmp == 1)
3037 /* If the new range has its limits swapped around (MIN > MAX),
3038 then the operation caused one of them to wrap around, mark
3039 the new range VARYING. */
3040 set_value_range_to_varying (vr);
3042 else
3043 set_value_range (vr, type, min, max, NULL);
3046 /* Extract range information from a binary expression OP0 CODE OP1 based on
3047 the ranges of each of its operands with resulting type EXPR_TYPE.
3048 The resulting range is stored in *VR. */
3050 static void
3051 extract_range_from_binary_expr (value_range *vr,
3052 enum tree_code code,
3053 tree expr_type, tree op0, tree op1)
3055 value_range vr0 = VR_INITIALIZER;
3056 value_range vr1 = VR_INITIALIZER;
3058 /* Get value ranges for each operand. For constant operands, create
3059 a new value range with the operand to simplify processing. */
3060 if (TREE_CODE (op0) == SSA_NAME)
3061 vr0 = *(get_value_range (op0));
3062 else if (is_gimple_min_invariant (op0))
3063 set_value_range_to_value (&vr0, op0, NULL);
3064 else
3065 set_value_range_to_varying (&vr0);
3067 if (TREE_CODE (op1) == SSA_NAME)
3068 vr1 = *(get_value_range (op1));
3069 else if (is_gimple_min_invariant (op1))
3070 set_value_range_to_value (&vr1, op1, NULL);
3071 else
3072 set_value_range_to_varying (&vr1);
3074 extract_range_from_binary_expr_1 (vr, code, expr_type, &vr0, &vr1);
3076 /* Try harder for PLUS and MINUS if the range of one operand is symbolic
3077 and based on the other operand, for example if it was deduced from a
3078 symbolic comparison. When a bound of the range of the first operand
3079 is invariant, we set the corresponding bound of the new range to INF
3080 in order to avoid recursing on the range of the second operand. */
3081 if (vr->type == VR_VARYING
3082 && (code == PLUS_EXPR || code == MINUS_EXPR)
3083 && TREE_CODE (op1) == SSA_NAME
3084 && vr0.type == VR_RANGE
3085 && symbolic_range_based_on_p (&vr0, op1))
3087 const bool minus_p = (code == MINUS_EXPR);
3088 value_range n_vr1 = VR_INITIALIZER;
3090 /* Try with VR0 and [-INF, OP1]. */
3091 if (is_gimple_min_invariant (minus_p ? vr0.max : vr0.min))
3092 set_value_range (&n_vr1, VR_RANGE, vrp_val_min (expr_type), op1, NULL);
3094 /* Try with VR0 and [OP1, +INF]. */
3095 else if (is_gimple_min_invariant (minus_p ? vr0.min : vr0.max))
3096 set_value_range (&n_vr1, VR_RANGE, op1, vrp_val_max (expr_type), NULL);
3098 /* Try with VR0 and [OP1, OP1]. */
3099 else
3100 set_value_range (&n_vr1, VR_RANGE, op1, op1, NULL);
3102 extract_range_from_binary_expr_1 (vr, code, expr_type, &vr0, &n_vr1);
3105 if (vr->type == VR_VARYING
3106 && (code == PLUS_EXPR || code == MINUS_EXPR)
3107 && TREE_CODE (op0) == SSA_NAME
3108 && vr1.type == VR_RANGE
3109 && symbolic_range_based_on_p (&vr1, op0))
3111 const bool minus_p = (code == MINUS_EXPR);
3112 value_range n_vr0 = VR_INITIALIZER;
3114 /* Try with [-INF, OP0] and VR1. */
3115 if (is_gimple_min_invariant (minus_p ? vr1.max : vr1.min))
3116 set_value_range (&n_vr0, VR_RANGE, vrp_val_min (expr_type), op0, NULL);
3118 /* Try with [OP0, +INF] and VR1. */
3119 else if (is_gimple_min_invariant (minus_p ? vr1.min : vr1.max))
3120 set_value_range (&n_vr0, VR_RANGE, op0, vrp_val_max (expr_type), NULL);
3122 /* Try with [OP0, OP0] and VR1. */
3123 else
3124 set_value_range (&n_vr0, VR_RANGE, op0, op0, NULL);
3126 extract_range_from_binary_expr_1 (vr, code, expr_type, &n_vr0, &vr1);
3129 /* If we didn't derive a range for MINUS_EXPR, and
3130 op1's range is ~[op0,op0] or vice-versa, then we
3131 can derive a non-null range. This happens often for
3132 pointer subtraction. */
3133 if (vr->type == VR_VARYING
3134 && code == MINUS_EXPR
3135 && TREE_CODE (op0) == SSA_NAME
3136 && ((vr0.type == VR_ANTI_RANGE
3137 && vr0.min == op1
3138 && vr0.min == vr0.max)
3139 || (vr1.type == VR_ANTI_RANGE
3140 && vr1.min == op0
3141 && vr1.min == vr1.max)))
3142 set_value_range_to_nonnull (vr, TREE_TYPE (op0));
3145 /* Extract range information from a unary operation CODE based on
3146 the range of its operand *VR0 with type OP0_TYPE with resulting type TYPE.
3147 The resulting range is stored in *VR. */
3149 void
3150 extract_range_from_unary_expr (value_range *vr,
3151 enum tree_code code, tree type,
3152 value_range *vr0_, tree op0_type)
3154 value_range vr0 = *vr0_, vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
3156 /* VRP only operates on integral and pointer types. */
3157 if (!(INTEGRAL_TYPE_P (op0_type)
3158 || POINTER_TYPE_P (op0_type))
3159 || !(INTEGRAL_TYPE_P (type)
3160 || POINTER_TYPE_P (type)))
3162 set_value_range_to_varying (vr);
3163 return;
3166 /* If VR0 is UNDEFINED, so is the result. */
3167 if (vr0.type == VR_UNDEFINED)
3169 set_value_range_to_undefined (vr);
3170 return;
3173 /* Handle operations that we express in terms of others. */
3174 if (code == PAREN_EXPR || code == OBJ_TYPE_REF)
3176 /* PAREN_EXPR and OBJ_TYPE_REF are simple copies. */
3177 copy_value_range (vr, &vr0);
3178 return;
3180 else if (code == NEGATE_EXPR)
3182 /* -X is simply 0 - X, so re-use existing code that also handles
3183 anti-ranges fine. */
3184 value_range zero = VR_INITIALIZER;
3185 set_value_range_to_value (&zero, build_int_cst (type, 0), NULL);
3186 extract_range_from_binary_expr_1 (vr, MINUS_EXPR, type, &zero, &vr0);
3187 return;
3189 else if (code == BIT_NOT_EXPR)
3191 /* ~X is simply -1 - X, so re-use existing code that also handles
3192 anti-ranges fine. */
3193 value_range minusone = VR_INITIALIZER;
3194 set_value_range_to_value (&minusone, build_int_cst (type, -1), NULL);
3195 extract_range_from_binary_expr_1 (vr, MINUS_EXPR,
3196 type, &minusone, &vr0);
3197 return;
3200 /* Now canonicalize anti-ranges to ranges when they are not symbolic
3201 and express op ~[] as (op []') U (op []''). */
3202 if (vr0.type == VR_ANTI_RANGE
3203 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
3205 extract_range_from_unary_expr (vr, code, type, &vrtem0, op0_type);
3206 if (vrtem1.type != VR_UNDEFINED)
3208 value_range vrres = VR_INITIALIZER;
3209 extract_range_from_unary_expr (&vrres, code, type,
3210 &vrtem1, op0_type);
3211 vrp_meet (vr, &vrres);
3213 return;
3216 if (CONVERT_EXPR_CODE_P (code))
3218 tree inner_type = op0_type;
3219 tree outer_type = type;
3221 /* If the expression evaluates to a pointer, we are only interested in
3222 determining if it evaluates to NULL [0, 0] or non-NULL (~[0, 0]). */
3223 if (POINTER_TYPE_P (type))
3225 if (range_is_nonnull (&vr0))
3226 set_value_range_to_nonnull (vr, type);
3227 else if (range_is_null (&vr0))
3228 set_value_range_to_null (vr, type);
3229 else
3230 set_value_range_to_varying (vr);
3231 return;
3234 /* If VR0 is varying and we increase the type precision, assume
3235 a full range for the following transformation. */
3236 if (vr0.type == VR_VARYING
3237 && INTEGRAL_TYPE_P (inner_type)
3238 && TYPE_PRECISION (inner_type) < TYPE_PRECISION (outer_type))
3240 vr0.type = VR_RANGE;
3241 vr0.min = TYPE_MIN_VALUE (inner_type);
3242 vr0.max = TYPE_MAX_VALUE (inner_type);
3245 /* If VR0 is a constant range or anti-range and the conversion is
3246 not truncating we can convert the min and max values and
3247 canonicalize the resulting range. Otherwise we can do the
3248 conversion if the size of the range is less than what the
3249 precision of the target type can represent and the range is
3250 not an anti-range. */
3251 if ((vr0.type == VR_RANGE
3252 || vr0.type == VR_ANTI_RANGE)
3253 && TREE_CODE (vr0.min) == INTEGER_CST
3254 && TREE_CODE (vr0.max) == INTEGER_CST
3255 && (TYPE_PRECISION (outer_type) >= TYPE_PRECISION (inner_type)
3256 || (vr0.type == VR_RANGE
3257 && integer_zerop (int_const_binop (RSHIFT_EXPR,
3258 int_const_binop (MINUS_EXPR, vr0.max, vr0.min),
3259 size_int (TYPE_PRECISION (outer_type)))))))
3261 tree new_min, new_max;
3262 new_min = force_fit_type (outer_type, wi::to_widest (vr0.min),
3263 0, false);
3264 new_max = force_fit_type (outer_type, wi::to_widest (vr0.max),
3265 0, false);
3266 set_and_canonicalize_value_range (vr, vr0.type,
3267 new_min, new_max, NULL);
3268 return;
3271 set_value_range_to_varying (vr);
3272 return;
3274 else if (code == ABS_EXPR)
3276 tree min, max;
3277 int cmp;
3279 /* Pass through vr0 in the easy cases. */
3280 if (TYPE_UNSIGNED (type)
3281 || value_range_nonnegative_p (&vr0))
3283 copy_value_range (vr, &vr0);
3284 return;
3287 /* For the remaining varying or symbolic ranges we can't do anything
3288 useful. */
3289 if (vr0.type == VR_VARYING
3290 || symbolic_range_p (&vr0))
3292 set_value_range_to_varying (vr);
3293 return;
3296 /* -TYPE_MIN_VALUE = TYPE_MIN_VALUE with flag_wrapv so we can't get a
3297 useful range. */
3298 if (!TYPE_OVERFLOW_UNDEFINED (type)
3299 && ((vr0.type == VR_RANGE
3300 && vrp_val_is_min (vr0.min))
3301 || (vr0.type == VR_ANTI_RANGE
3302 && !vrp_val_is_min (vr0.min))))
3304 set_value_range_to_varying (vr);
3305 return;
3308 /* ABS_EXPR may flip the range around, if the original range
3309 included negative values. */
3310 if (!vrp_val_is_min (vr0.min))
3311 min = fold_unary_to_constant (code, type, vr0.min);
3312 else
3313 min = TYPE_MAX_VALUE (type);
3315 if (!vrp_val_is_min (vr0.max))
3316 max = fold_unary_to_constant (code, type, vr0.max);
3317 else
3318 max = TYPE_MAX_VALUE (type);
3320 cmp = compare_values (min, max);
3322 /* If a VR_ANTI_RANGEs contains zero, then we have
3323 ~[-INF, min(MIN, MAX)]. */
3324 if (vr0.type == VR_ANTI_RANGE)
3326 if (range_includes_zero_p (vr0.min, vr0.max) == 1)
3328 /* Take the lower of the two values. */
3329 if (cmp != 1)
3330 max = min;
3332 /* Create ~[-INF, min (abs(MIN), abs(MAX))]
3333 or ~[-INF + 1, min (abs(MIN), abs(MAX))] when
3334 flag_wrapv is set and the original anti-range doesn't include
3335 TYPE_MIN_VALUE, remember -TYPE_MIN_VALUE = TYPE_MIN_VALUE. */
3336 if (TYPE_OVERFLOW_WRAPS (type))
3338 tree type_min_value = TYPE_MIN_VALUE (type);
3340 min = (vr0.min != type_min_value
3341 ? int_const_binop (PLUS_EXPR, type_min_value,
3342 build_int_cst (TREE_TYPE (type_min_value), 1))
3343 : type_min_value);
3345 else
3346 min = TYPE_MIN_VALUE (type);
3348 else
3350 /* All else has failed, so create the range [0, INF], even for
3351 flag_wrapv since TYPE_MIN_VALUE is in the original
3352 anti-range. */
3353 vr0.type = VR_RANGE;
3354 min = build_int_cst (type, 0);
3355 max = TYPE_MAX_VALUE (type);
3359 /* If the range contains zero then we know that the minimum value in the
3360 range will be zero. */
3361 else if (range_includes_zero_p (vr0.min, vr0.max) == 1)
3363 if (cmp == 1)
3364 max = min;
3365 min = build_int_cst (type, 0);
3367 else
3369 /* If the range was reversed, swap MIN and MAX. */
3370 if (cmp == 1)
3371 std::swap (min, max);
3374 cmp = compare_values (min, max);
3375 if (cmp == -2 || cmp == 1)
3377 /* If the new range has its limits swapped around (MIN > MAX),
3378 then the operation caused one of them to wrap around, mark
3379 the new range VARYING. */
3380 set_value_range_to_varying (vr);
3382 else
3383 set_value_range (vr, vr0.type, min, max, NULL);
3384 return;
3387 /* For unhandled operations fall back to varying. */
3388 set_value_range_to_varying (vr);
3389 return;
3393 /* Extract range information from a unary expression CODE OP0 based on
3394 the range of its operand with resulting type TYPE.
3395 The resulting range is stored in *VR. */
3397 static void
3398 extract_range_from_unary_expr (value_range *vr, enum tree_code code,
3399 tree type, tree op0)
3401 value_range vr0 = VR_INITIALIZER;
3403 /* Get value ranges for the operand. For constant operands, create
3404 a new value range with the operand to simplify processing. */
3405 if (TREE_CODE (op0) == SSA_NAME)
3406 vr0 = *(get_value_range (op0));
3407 else if (is_gimple_min_invariant (op0))
3408 set_value_range_to_value (&vr0, op0, NULL);
3409 else
3410 set_value_range_to_varying (&vr0);
3412 extract_range_from_unary_expr (vr, code, type, &vr0, TREE_TYPE (op0));
3416 /* Extract range information from a conditional expression STMT based on
3417 the ranges of each of its operands and the expression code. */
3419 static void
3420 extract_range_from_cond_expr (value_range *vr, gassign *stmt)
3422 tree op0, op1;
3423 value_range vr0 = VR_INITIALIZER;
3424 value_range vr1 = VR_INITIALIZER;
3426 /* Get value ranges for each operand. For constant operands, create
3427 a new value range with the operand to simplify processing. */
3428 op0 = gimple_assign_rhs2 (stmt);
3429 if (TREE_CODE (op0) == SSA_NAME)
3430 vr0 = *(get_value_range (op0));
3431 else if (is_gimple_min_invariant (op0))
3432 set_value_range_to_value (&vr0, op0, NULL);
3433 else
3434 set_value_range_to_varying (&vr0);
3436 op1 = gimple_assign_rhs3 (stmt);
3437 if (TREE_CODE (op1) == SSA_NAME)
3438 vr1 = *(get_value_range (op1));
3439 else if (is_gimple_min_invariant (op1))
3440 set_value_range_to_value (&vr1, op1, NULL);
3441 else
3442 set_value_range_to_varying (&vr1);
3444 /* The resulting value range is the union of the operand ranges */
3445 copy_value_range (vr, &vr0);
3446 vrp_meet (vr, &vr1);
3450 /* Extract range information from a comparison expression EXPR based
3451 on the range of its operand and the expression code. */
3453 static void
3454 extract_range_from_comparison (value_range *vr, enum tree_code code,
3455 tree type, tree op0, tree op1)
3457 bool sop;
3458 tree val;
3460 val = vrp_evaluate_conditional_warnv_with_ops (code, op0, op1, false, &sop,
3461 NULL);
3462 if (val)
3464 /* Since this expression was found on the RHS of an assignment,
3465 its type may be different from _Bool. Convert VAL to EXPR's
3466 type. */
3467 val = fold_convert (type, val);
3468 if (is_gimple_min_invariant (val))
3469 set_value_range_to_value (vr, val, vr->equiv);
3470 else
3471 set_value_range (vr, VR_RANGE, val, val, vr->equiv);
3473 else
3474 /* The result of a comparison is always true or false. */
3475 set_value_range_to_truthvalue (vr, type);
3478 /* Helper function for simplify_internal_call_using_ranges and
3479 extract_range_basic. Return true if OP0 SUBCODE OP1 for
3480 SUBCODE {PLUS,MINUS,MULT}_EXPR is known to never overflow or
3481 always overflow. Set *OVF to true if it is known to always
3482 overflow. */
3484 static bool
3485 check_for_binary_op_overflow (enum tree_code subcode, tree type,
3486 tree op0, tree op1, bool *ovf)
3488 value_range vr0 = VR_INITIALIZER;
3489 value_range vr1 = VR_INITIALIZER;
3490 if (TREE_CODE (op0) == SSA_NAME)
3491 vr0 = *get_value_range (op0);
3492 else if (TREE_CODE (op0) == INTEGER_CST)
3493 set_value_range_to_value (&vr0, op0, NULL);
3494 else
3495 set_value_range_to_varying (&vr0);
3497 if (TREE_CODE (op1) == SSA_NAME)
3498 vr1 = *get_value_range (op1);
3499 else if (TREE_CODE (op1) == INTEGER_CST)
3500 set_value_range_to_value (&vr1, op1, NULL);
3501 else
3502 set_value_range_to_varying (&vr1);
3504 if (!range_int_cst_p (&vr0)
3505 || TREE_OVERFLOW (vr0.min)
3506 || TREE_OVERFLOW (vr0.max))
3508 vr0.min = vrp_val_min (TREE_TYPE (op0));
3509 vr0.max = vrp_val_max (TREE_TYPE (op0));
3511 if (!range_int_cst_p (&vr1)
3512 || TREE_OVERFLOW (vr1.min)
3513 || TREE_OVERFLOW (vr1.max))
3515 vr1.min = vrp_val_min (TREE_TYPE (op1));
3516 vr1.max = vrp_val_max (TREE_TYPE (op1));
3518 *ovf = arith_overflowed_p (subcode, type, vr0.min,
3519 subcode == MINUS_EXPR ? vr1.max : vr1.min);
3520 if (arith_overflowed_p (subcode, type, vr0.max,
3521 subcode == MINUS_EXPR ? vr1.min : vr1.max) != *ovf)
3522 return false;
3523 if (subcode == MULT_EXPR)
3525 if (arith_overflowed_p (subcode, type, vr0.min, vr1.max) != *ovf
3526 || arith_overflowed_p (subcode, type, vr0.max, vr1.min) != *ovf)
3527 return false;
3529 if (*ovf)
3531 /* So far we found that there is an overflow on the boundaries.
3532 That doesn't prove that there is an overflow even for all values
3533 in between the boundaries. For that compute widest_int range
3534 of the result and see if it doesn't overlap the range of
3535 type. */
3536 widest_int wmin, wmax;
3537 widest_int w[4];
3538 int i;
3539 w[0] = wi::to_widest (vr0.min);
3540 w[1] = wi::to_widest (vr0.max);
3541 w[2] = wi::to_widest (vr1.min);
3542 w[3] = wi::to_widest (vr1.max);
3543 for (i = 0; i < 4; i++)
3545 widest_int wt;
3546 switch (subcode)
3548 case PLUS_EXPR:
3549 wt = wi::add (w[i & 1], w[2 + (i & 2) / 2]);
3550 break;
3551 case MINUS_EXPR:
3552 wt = wi::sub (w[i & 1], w[2 + (i & 2) / 2]);
3553 break;
3554 case MULT_EXPR:
3555 wt = wi::mul (w[i & 1], w[2 + (i & 2) / 2]);
3556 break;
3557 default:
3558 gcc_unreachable ();
3560 if (i == 0)
3562 wmin = wt;
3563 wmax = wt;
3565 else
3567 wmin = wi::smin (wmin, wt);
3568 wmax = wi::smax (wmax, wt);
3571 /* The result of op0 CODE op1 is known to be in range
3572 [wmin, wmax]. */
3573 widest_int wtmin = wi::to_widest (vrp_val_min (type));
3574 widest_int wtmax = wi::to_widest (vrp_val_max (type));
3575 /* If all values in [wmin, wmax] are smaller than
3576 [wtmin, wtmax] or all are larger than [wtmin, wtmax],
3577 the arithmetic operation will always overflow. */
3578 if (wmax < wtmin || wmin > wtmax)
3579 return true;
3580 return false;
3582 return true;
3585 /* Try to derive a nonnegative or nonzero range out of STMT relying
3586 primarily on generic routines in fold in conjunction with range data.
3587 Store the result in *VR */
3589 static void
3590 extract_range_basic (value_range *vr, gimple *stmt)
3592 bool sop;
3593 tree type = gimple_expr_type (stmt);
3595 if (is_gimple_call (stmt))
3597 tree arg;
3598 int mini, maxi, zerov = 0, prec;
3599 enum tree_code subcode = ERROR_MARK;
3600 combined_fn cfn = gimple_call_combined_fn (stmt);
3601 scalar_int_mode mode;
3603 switch (cfn)
3605 case CFN_BUILT_IN_CONSTANT_P:
3606 /* If the call is __builtin_constant_p and the argument is a
3607 function parameter resolve it to false. This avoids bogus
3608 array bound warnings.
3609 ??? We could do this as early as inlining is finished. */
3610 arg = gimple_call_arg (stmt, 0);
3611 if (TREE_CODE (arg) == SSA_NAME
3612 && SSA_NAME_IS_DEFAULT_DEF (arg)
3613 && TREE_CODE (SSA_NAME_VAR (arg)) == PARM_DECL
3614 && cfun->after_inlining)
3616 set_value_range_to_null (vr, type);
3617 return;
3619 break;
3620 /* Both __builtin_ffs* and __builtin_popcount return
3621 [0, prec]. */
3622 CASE_CFN_FFS:
3623 CASE_CFN_POPCOUNT:
3624 arg = gimple_call_arg (stmt, 0);
3625 prec = TYPE_PRECISION (TREE_TYPE (arg));
3626 mini = 0;
3627 maxi = prec;
3628 if (TREE_CODE (arg) == SSA_NAME)
3630 value_range *vr0 = get_value_range (arg);
3631 /* If arg is non-zero, then ffs or popcount
3632 are non-zero. */
3633 if ((vr0->type == VR_RANGE
3634 && range_includes_zero_p (vr0->min, vr0->max) == 0)
3635 || (vr0->type == VR_ANTI_RANGE
3636 && range_includes_zero_p (vr0->min, vr0->max) == 1))
3637 mini = 1;
3638 /* If some high bits are known to be zero,
3639 we can decrease the maximum. */
3640 if (vr0->type == VR_RANGE
3641 && TREE_CODE (vr0->max) == INTEGER_CST
3642 && !operand_less_p (vr0->min,
3643 build_zero_cst (TREE_TYPE (vr0->min))))
3644 maxi = tree_floor_log2 (vr0->max) + 1;
3646 goto bitop_builtin;
3647 /* __builtin_parity* returns [0, 1]. */
3648 CASE_CFN_PARITY:
3649 mini = 0;
3650 maxi = 1;
3651 goto bitop_builtin;
3652 /* __builtin_c[lt]z* return [0, prec-1], except for
3653 when the argument is 0, but that is undefined behavior.
3654 On many targets where the CLZ RTL or optab value is defined
3655 for 0 the value is prec, so include that in the range
3656 by default. */
3657 CASE_CFN_CLZ:
3658 arg = gimple_call_arg (stmt, 0);
3659 prec = TYPE_PRECISION (TREE_TYPE (arg));
3660 mini = 0;
3661 maxi = prec;
3662 mode = SCALAR_INT_TYPE_MODE (TREE_TYPE (arg));
3663 if (optab_handler (clz_optab, mode) != CODE_FOR_nothing
3664 && CLZ_DEFINED_VALUE_AT_ZERO (mode, zerov)
3665 /* Handle only the single common value. */
3666 && zerov != prec)
3667 /* Magic value to give up, unless vr0 proves
3668 arg is non-zero. */
3669 mini = -2;
3670 if (TREE_CODE (arg) == SSA_NAME)
3672 value_range *vr0 = get_value_range (arg);
3673 /* From clz of VR_RANGE minimum we can compute
3674 result maximum. */
3675 if (vr0->type == VR_RANGE
3676 && TREE_CODE (vr0->min) == INTEGER_CST)
3678 maxi = prec - 1 - tree_floor_log2 (vr0->min);
3679 if (maxi != prec)
3680 mini = 0;
3682 else if (vr0->type == VR_ANTI_RANGE
3683 && integer_zerop (vr0->min))
3685 maxi = prec - 1;
3686 mini = 0;
3688 if (mini == -2)
3689 break;
3690 /* From clz of VR_RANGE maximum we can compute
3691 result minimum. */
3692 if (vr0->type == VR_RANGE
3693 && TREE_CODE (vr0->max) == INTEGER_CST)
3695 mini = prec - 1 - tree_floor_log2 (vr0->max);
3696 if (mini == prec)
3697 break;
3700 if (mini == -2)
3701 break;
3702 goto bitop_builtin;
3703 /* __builtin_ctz* return [0, prec-1], except for
3704 when the argument is 0, but that is undefined behavior.
3705 If there is a ctz optab for this mode and
3706 CTZ_DEFINED_VALUE_AT_ZERO, include that in the range,
3707 otherwise just assume 0 won't be seen. */
3708 CASE_CFN_CTZ:
3709 arg = gimple_call_arg (stmt, 0);
3710 prec = TYPE_PRECISION (TREE_TYPE (arg));
3711 mini = 0;
3712 maxi = prec - 1;
3713 mode = SCALAR_INT_TYPE_MODE (TREE_TYPE (arg));
3714 if (optab_handler (ctz_optab, mode) != CODE_FOR_nothing
3715 && CTZ_DEFINED_VALUE_AT_ZERO (mode, zerov))
3717 /* Handle only the two common values. */
3718 if (zerov == -1)
3719 mini = -1;
3720 else if (zerov == prec)
3721 maxi = prec;
3722 else
3723 /* Magic value to give up, unless vr0 proves
3724 arg is non-zero. */
3725 mini = -2;
3727 if (TREE_CODE (arg) == SSA_NAME)
3729 value_range *vr0 = get_value_range (arg);
3730 /* If arg is non-zero, then use [0, prec - 1]. */
3731 if ((vr0->type == VR_RANGE
3732 && integer_nonzerop (vr0->min))
3733 || (vr0->type == VR_ANTI_RANGE
3734 && integer_zerop (vr0->min)))
3736 mini = 0;
3737 maxi = prec - 1;
3739 /* If some high bits are known to be zero,
3740 we can decrease the result maximum. */
3741 if (vr0->type == VR_RANGE
3742 && TREE_CODE (vr0->max) == INTEGER_CST)
3744 maxi = tree_floor_log2 (vr0->max);
3745 /* For vr0 [0, 0] give up. */
3746 if (maxi == -1)
3747 break;
3750 if (mini == -2)
3751 break;
3752 goto bitop_builtin;
3753 /* __builtin_clrsb* returns [0, prec-1]. */
3754 CASE_CFN_CLRSB:
3755 arg = gimple_call_arg (stmt, 0);
3756 prec = TYPE_PRECISION (TREE_TYPE (arg));
3757 mini = 0;
3758 maxi = prec - 1;
3759 goto bitop_builtin;
3760 bitop_builtin:
3761 set_value_range (vr, VR_RANGE, build_int_cst (type, mini),
3762 build_int_cst (type, maxi), NULL);
3763 return;
3764 case CFN_UBSAN_CHECK_ADD:
3765 subcode = PLUS_EXPR;
3766 break;
3767 case CFN_UBSAN_CHECK_SUB:
3768 subcode = MINUS_EXPR;
3769 break;
3770 case CFN_UBSAN_CHECK_MUL:
3771 subcode = MULT_EXPR;
3772 break;
3773 case CFN_GOACC_DIM_SIZE:
3774 case CFN_GOACC_DIM_POS:
3775 /* Optimizing these two internal functions helps the loop
3776 optimizer eliminate outer comparisons. Size is [1,N]
3777 and pos is [0,N-1]. */
3779 bool is_pos = cfn == CFN_GOACC_DIM_POS;
3780 int axis = oacc_get_ifn_dim_arg (stmt);
3781 int size = oacc_get_fn_dim_size (current_function_decl, axis);
3783 if (!size)
3784 /* If it's dynamic, the backend might know a hardware
3785 limitation. */
3786 size = targetm.goacc.dim_limit (axis);
3788 tree type = TREE_TYPE (gimple_call_lhs (stmt));
3789 set_value_range (vr, VR_RANGE,
3790 build_int_cst (type, is_pos ? 0 : 1),
3791 size ? build_int_cst (type, size - is_pos)
3792 : vrp_val_max (type), NULL);
3794 return;
3795 case CFN_BUILT_IN_STRLEN:
3796 if (tree lhs = gimple_call_lhs (stmt))
3797 if (ptrdiff_type_node
3798 && (TYPE_PRECISION (ptrdiff_type_node)
3799 == TYPE_PRECISION (TREE_TYPE (lhs))))
3801 tree type = TREE_TYPE (lhs);
3802 tree max = vrp_val_max (ptrdiff_type_node);
3803 wide_int wmax = wi::to_wide (max, TYPE_PRECISION (TREE_TYPE (max)));
3804 tree range_min = build_zero_cst (type);
3805 tree range_max = wide_int_to_tree (type, wmax - 1);
3806 set_value_range (vr, VR_RANGE, range_min, range_max, NULL);
3807 return;
3809 break;
3810 default:
3811 break;
3813 if (subcode != ERROR_MARK)
3815 bool saved_flag_wrapv = flag_wrapv;
3816 /* Pretend the arithmetics is wrapping. If there is
3817 any overflow, we'll complain, but will actually do
3818 wrapping operation. */
3819 flag_wrapv = 1;
3820 extract_range_from_binary_expr (vr, subcode, type,
3821 gimple_call_arg (stmt, 0),
3822 gimple_call_arg (stmt, 1));
3823 flag_wrapv = saved_flag_wrapv;
3825 /* If for both arguments vrp_valueize returned non-NULL,
3826 this should have been already folded and if not, it
3827 wasn't folded because of overflow. Avoid removing the
3828 UBSAN_CHECK_* calls in that case. */
3829 if (vr->type == VR_RANGE
3830 && (vr->min == vr->max
3831 || operand_equal_p (vr->min, vr->max, 0)))
3832 set_value_range_to_varying (vr);
3833 return;
3836 /* Handle extraction of the two results (result of arithmetics and
3837 a flag whether arithmetics overflowed) from {ADD,SUB,MUL}_OVERFLOW
3838 internal function. Similarly from ATOMIC_COMPARE_EXCHANGE. */
3839 else if (is_gimple_assign (stmt)
3840 && (gimple_assign_rhs_code (stmt) == REALPART_EXPR
3841 || gimple_assign_rhs_code (stmt) == IMAGPART_EXPR)
3842 && INTEGRAL_TYPE_P (type))
3844 enum tree_code code = gimple_assign_rhs_code (stmt);
3845 tree op = gimple_assign_rhs1 (stmt);
3846 if (TREE_CODE (op) == code && TREE_CODE (TREE_OPERAND (op, 0)) == SSA_NAME)
3848 gimple *g = SSA_NAME_DEF_STMT (TREE_OPERAND (op, 0));
3849 if (is_gimple_call (g) && gimple_call_internal_p (g))
3851 enum tree_code subcode = ERROR_MARK;
3852 switch (gimple_call_internal_fn (g))
3854 case IFN_ADD_OVERFLOW:
3855 subcode = PLUS_EXPR;
3856 break;
3857 case IFN_SUB_OVERFLOW:
3858 subcode = MINUS_EXPR;
3859 break;
3860 case IFN_MUL_OVERFLOW:
3861 subcode = MULT_EXPR;
3862 break;
3863 case IFN_ATOMIC_COMPARE_EXCHANGE:
3864 if (code == IMAGPART_EXPR)
3866 /* This is the boolean return value whether compare and
3867 exchange changed anything or not. */
3868 set_value_range (vr, VR_RANGE, build_int_cst (type, 0),
3869 build_int_cst (type, 1), NULL);
3870 return;
3872 break;
3873 default:
3874 break;
3876 if (subcode != ERROR_MARK)
3878 tree op0 = gimple_call_arg (g, 0);
3879 tree op1 = gimple_call_arg (g, 1);
3880 if (code == IMAGPART_EXPR)
3882 bool ovf = false;
3883 if (check_for_binary_op_overflow (subcode, type,
3884 op0, op1, &ovf))
3885 set_value_range_to_value (vr,
3886 build_int_cst (type, ovf),
3887 NULL);
3888 else if (TYPE_PRECISION (type) == 1
3889 && !TYPE_UNSIGNED (type))
3890 set_value_range_to_varying (vr);
3891 else
3892 set_value_range (vr, VR_RANGE, build_int_cst (type, 0),
3893 build_int_cst (type, 1), NULL);
3895 else if (types_compatible_p (type, TREE_TYPE (op0))
3896 && types_compatible_p (type, TREE_TYPE (op1)))
3898 bool saved_flag_wrapv = flag_wrapv;
3899 /* Pretend the arithmetics is wrapping. If there is
3900 any overflow, IMAGPART_EXPR will be set. */
3901 flag_wrapv = 1;
3902 extract_range_from_binary_expr (vr, subcode, type,
3903 op0, op1);
3904 flag_wrapv = saved_flag_wrapv;
3906 else
3908 value_range vr0 = VR_INITIALIZER;
3909 value_range vr1 = VR_INITIALIZER;
3910 bool saved_flag_wrapv = flag_wrapv;
3911 /* Pretend the arithmetics is wrapping. If there is
3912 any overflow, IMAGPART_EXPR will be set. */
3913 flag_wrapv = 1;
3914 extract_range_from_unary_expr (&vr0, NOP_EXPR,
3915 type, op0);
3916 extract_range_from_unary_expr (&vr1, NOP_EXPR,
3917 type, op1);
3918 extract_range_from_binary_expr_1 (vr, subcode, type,
3919 &vr0, &vr1);
3920 flag_wrapv = saved_flag_wrapv;
3922 return;
3927 if (INTEGRAL_TYPE_P (type)
3928 && gimple_stmt_nonnegative_warnv_p (stmt, &sop))
3929 set_value_range_to_nonnegative (vr, type);
3930 else if (vrp_stmt_computes_nonzero (stmt))
3931 set_value_range_to_nonnull (vr, type);
3932 else
3933 set_value_range_to_varying (vr);
3937 /* Try to compute a useful range out of assignment STMT and store it
3938 in *VR. */
3940 static void
3941 extract_range_from_assignment (value_range *vr, gassign *stmt)
3943 enum tree_code code = gimple_assign_rhs_code (stmt);
3945 if (code == ASSERT_EXPR)
3946 extract_range_from_assert (vr, gimple_assign_rhs1 (stmt));
3947 else if (code == SSA_NAME)
3948 extract_range_from_ssa_name (vr, gimple_assign_rhs1 (stmt));
3949 else if (TREE_CODE_CLASS (code) == tcc_binary)
3950 extract_range_from_binary_expr (vr, gimple_assign_rhs_code (stmt),
3951 gimple_expr_type (stmt),
3952 gimple_assign_rhs1 (stmt),
3953 gimple_assign_rhs2 (stmt));
3954 else if (TREE_CODE_CLASS (code) == tcc_unary)
3955 extract_range_from_unary_expr (vr, gimple_assign_rhs_code (stmt),
3956 gimple_expr_type (stmt),
3957 gimple_assign_rhs1 (stmt));
3958 else if (code == COND_EXPR)
3959 extract_range_from_cond_expr (vr, stmt);
3960 else if (TREE_CODE_CLASS (code) == tcc_comparison)
3961 extract_range_from_comparison (vr, gimple_assign_rhs_code (stmt),
3962 gimple_expr_type (stmt),
3963 gimple_assign_rhs1 (stmt),
3964 gimple_assign_rhs2 (stmt));
3965 else if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS
3966 && is_gimple_min_invariant (gimple_assign_rhs1 (stmt)))
3967 set_value_range_to_value (vr, gimple_assign_rhs1 (stmt), NULL);
3968 else
3969 set_value_range_to_varying (vr);
3971 if (vr->type == VR_VARYING)
3972 extract_range_basic (vr, stmt);
3975 /* Given a range VR, a LOOP and a variable VAR, determine whether it
3976 would be profitable to adjust VR using scalar evolution information
3977 for VAR. If so, update VR with the new limits. */
3979 static void
3980 adjust_range_with_scev (value_range *vr, struct loop *loop,
3981 gimple *stmt, tree var)
3983 tree init, step, chrec, tmin, tmax, min, max, type, tem;
3984 enum ev_direction dir;
3986 /* TODO. Don't adjust anti-ranges. An anti-range may provide
3987 better opportunities than a regular range, but I'm not sure. */
3988 if (vr->type == VR_ANTI_RANGE)
3989 return;
3991 chrec = instantiate_parameters (loop, analyze_scalar_evolution (loop, var));
3993 /* Like in PR19590, scev can return a constant function. */
3994 if (is_gimple_min_invariant (chrec))
3996 set_value_range_to_value (vr, chrec, vr->equiv);
3997 return;
4000 if (TREE_CODE (chrec) != POLYNOMIAL_CHREC)
4001 return;
4003 init = initial_condition_in_loop_num (chrec, loop->num);
4004 tem = op_with_constant_singleton_value_range (init);
4005 if (tem)
4006 init = tem;
4007 step = evolution_part_in_loop_num (chrec, loop->num);
4008 tem = op_with_constant_singleton_value_range (step);
4009 if (tem)
4010 step = tem;
4012 /* If STEP is symbolic, we can't know whether INIT will be the
4013 minimum or maximum value in the range. Also, unless INIT is
4014 a simple expression, compare_values and possibly other functions
4015 in tree-vrp won't be able to handle it. */
4016 if (step == NULL_TREE
4017 || !is_gimple_min_invariant (step)
4018 || !valid_value_p (init))
4019 return;
4021 dir = scev_direction (chrec);
4022 if (/* Do not adjust ranges if we do not know whether the iv increases
4023 or decreases, ... */
4024 dir == EV_DIR_UNKNOWN
4025 /* ... or if it may wrap. */
4026 || scev_probably_wraps_p (NULL_TREE, init, step, stmt,
4027 get_chrec_loop (chrec), true))
4028 return;
4030 type = TREE_TYPE (var);
4031 if (POINTER_TYPE_P (type) || !TYPE_MIN_VALUE (type))
4032 tmin = lower_bound_in_type (type, type);
4033 else
4034 tmin = TYPE_MIN_VALUE (type);
4035 if (POINTER_TYPE_P (type) || !TYPE_MAX_VALUE (type))
4036 tmax = upper_bound_in_type (type, type);
4037 else
4038 tmax = TYPE_MAX_VALUE (type);
4040 /* Try to use estimated number of iterations for the loop to constrain the
4041 final value in the evolution. */
4042 if (TREE_CODE (step) == INTEGER_CST
4043 && is_gimple_val (init)
4044 && (TREE_CODE (init) != SSA_NAME
4045 || get_value_range (init)->type == VR_RANGE))
4047 widest_int nit;
4049 /* We are only entering here for loop header PHI nodes, so using
4050 the number of latch executions is the correct thing to use. */
4051 if (max_loop_iterations (loop, &nit))
4053 value_range maxvr = VR_INITIALIZER;
4054 signop sgn = TYPE_SIGN (TREE_TYPE (step));
4055 bool overflow;
4057 widest_int wtmp = wi::mul (wi::to_widest (step), nit, sgn,
4058 &overflow);
4059 /* If the multiplication overflowed we can't do a meaningful
4060 adjustment. Likewise if the result doesn't fit in the type
4061 of the induction variable. For a signed type we have to
4062 check whether the result has the expected signedness which
4063 is that of the step as number of iterations is unsigned. */
4064 if (!overflow
4065 && wi::fits_to_tree_p (wtmp, TREE_TYPE (init))
4066 && (sgn == UNSIGNED
4067 || wi::gts_p (wtmp, 0) == wi::gts_p (wi::to_wide (step), 0)))
4069 tem = wide_int_to_tree (TREE_TYPE (init), wtmp);
4070 extract_range_from_binary_expr (&maxvr, PLUS_EXPR,
4071 TREE_TYPE (init), init, tem);
4072 /* Likewise if the addition did. */
4073 if (maxvr.type == VR_RANGE)
4075 value_range initvr = VR_INITIALIZER;
4077 if (TREE_CODE (init) == SSA_NAME)
4078 initvr = *(get_value_range (init));
4079 else if (is_gimple_min_invariant (init))
4080 set_value_range_to_value (&initvr, init, NULL);
4081 else
4082 return;
4084 /* Check if init + nit * step overflows. Though we checked
4085 scev {init, step}_loop doesn't wrap, it is not enough
4086 because the loop may exit immediately. Overflow could
4087 happen in the plus expression in this case. */
4088 if ((dir == EV_DIR_DECREASES
4089 && compare_values (maxvr.min, initvr.min) != -1)
4090 || (dir == EV_DIR_GROWS
4091 && compare_values (maxvr.max, initvr.max) != 1))
4092 return;
4094 tmin = maxvr.min;
4095 tmax = maxvr.max;
4101 if (vr->type == VR_VARYING || vr->type == VR_UNDEFINED)
4103 min = tmin;
4104 max = tmax;
4106 /* For VARYING or UNDEFINED ranges, just about anything we get
4107 from scalar evolutions should be better. */
4109 if (dir == EV_DIR_DECREASES)
4110 max = init;
4111 else
4112 min = init;
4114 else if (vr->type == VR_RANGE)
4116 min = vr->min;
4117 max = vr->max;
4119 if (dir == EV_DIR_DECREASES)
4121 /* INIT is the maximum value. If INIT is lower than VR->MAX
4122 but no smaller than VR->MIN, set VR->MAX to INIT. */
4123 if (compare_values (init, max) == -1)
4124 max = init;
4126 /* According to the loop information, the variable does not
4127 overflow. */
4128 if (compare_values (min, tmin) == -1)
4129 min = tmin;
4132 else
4134 /* If INIT is bigger than VR->MIN, set VR->MIN to INIT. */
4135 if (compare_values (init, min) == 1)
4136 min = init;
4138 if (compare_values (tmax, max) == -1)
4139 max = tmax;
4142 else
4143 return;
4145 /* If we just created an invalid range with the minimum
4146 greater than the maximum, we fail conservatively.
4147 This should happen only in unreachable
4148 parts of code, or for invalid programs. */
4149 if (compare_values (min, max) == 1)
4150 return;
4152 /* Even for valid range info, sometimes overflow flag will leak in.
4153 As GIMPLE IL should have no constants with TREE_OVERFLOW set, we
4154 drop them. */
4155 if (TREE_OVERFLOW_P (min))
4156 min = drop_tree_overflow (min);
4157 if (TREE_OVERFLOW_P (max))
4158 max = drop_tree_overflow (max);
4160 set_value_range (vr, VR_RANGE, min, max, vr->equiv);
4164 /* Given two numeric value ranges VR0, VR1 and a comparison code COMP:
4166 - Return BOOLEAN_TRUE_NODE if VR0 COMP VR1 always returns true for
4167 all the values in the ranges.
4169 - Return BOOLEAN_FALSE_NODE if the comparison always returns false.
4171 - Return NULL_TREE if it is not always possible to determine the
4172 value of the comparison.
4174 Also set *STRICT_OVERFLOW_P to indicate whether comparision evaluation
4175 assumed signed overflow is undefined. */
4178 static tree
4179 compare_ranges (enum tree_code comp, value_range *vr0, value_range *vr1,
4180 bool *strict_overflow_p)
4182 /* VARYING or UNDEFINED ranges cannot be compared. */
4183 if (vr0->type == VR_VARYING
4184 || vr0->type == VR_UNDEFINED
4185 || vr1->type == VR_VARYING
4186 || vr1->type == VR_UNDEFINED)
4187 return NULL_TREE;
4189 /* Anti-ranges need to be handled separately. */
4190 if (vr0->type == VR_ANTI_RANGE || vr1->type == VR_ANTI_RANGE)
4192 /* If both are anti-ranges, then we cannot compute any
4193 comparison. */
4194 if (vr0->type == VR_ANTI_RANGE && vr1->type == VR_ANTI_RANGE)
4195 return NULL_TREE;
4197 /* These comparisons are never statically computable. */
4198 if (comp == GT_EXPR
4199 || comp == GE_EXPR
4200 || comp == LT_EXPR
4201 || comp == LE_EXPR)
4202 return NULL_TREE;
4204 /* Equality can be computed only between a range and an
4205 anti-range. ~[VAL1, VAL2] == [VAL1, VAL2] is always false. */
4206 if (vr0->type == VR_RANGE)
4208 /* To simplify processing, make VR0 the anti-range. */
4209 value_range *tmp = vr0;
4210 vr0 = vr1;
4211 vr1 = tmp;
4214 gcc_assert (comp == NE_EXPR || comp == EQ_EXPR);
4216 if (compare_values_warnv (vr0->min, vr1->min, strict_overflow_p) == 0
4217 && compare_values_warnv (vr0->max, vr1->max, strict_overflow_p) == 0)
4218 return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
4220 return NULL_TREE;
4223 /* Simplify processing. If COMP is GT_EXPR or GE_EXPR, switch the
4224 operands around and change the comparison code. */
4225 if (comp == GT_EXPR || comp == GE_EXPR)
4227 comp = (comp == GT_EXPR) ? LT_EXPR : LE_EXPR;
4228 std::swap (vr0, vr1);
4231 if (comp == EQ_EXPR)
4233 /* Equality may only be computed if both ranges represent
4234 exactly one value. */
4235 if (compare_values_warnv (vr0->min, vr0->max, strict_overflow_p) == 0
4236 && compare_values_warnv (vr1->min, vr1->max, strict_overflow_p) == 0)
4238 int cmp_min = compare_values_warnv (vr0->min, vr1->min,
4239 strict_overflow_p);
4240 int cmp_max = compare_values_warnv (vr0->max, vr1->max,
4241 strict_overflow_p);
4242 if (cmp_min == 0 && cmp_max == 0)
4243 return boolean_true_node;
4244 else if (cmp_min != -2 && cmp_max != -2)
4245 return boolean_false_node;
4247 /* If [V0_MIN, V1_MAX] < [V1_MIN, V1_MAX] then V0 != V1. */
4248 else if (compare_values_warnv (vr0->min, vr1->max,
4249 strict_overflow_p) == 1
4250 || compare_values_warnv (vr1->min, vr0->max,
4251 strict_overflow_p) == 1)
4252 return boolean_false_node;
4254 return NULL_TREE;
4256 else if (comp == NE_EXPR)
4258 int cmp1, cmp2;
4260 /* If VR0 is completely to the left or completely to the right
4261 of VR1, they are always different. Notice that we need to
4262 make sure that both comparisons yield similar results to
4263 avoid comparing values that cannot be compared at
4264 compile-time. */
4265 cmp1 = compare_values_warnv (vr0->max, vr1->min, strict_overflow_p);
4266 cmp2 = compare_values_warnv (vr0->min, vr1->max, strict_overflow_p);
4267 if ((cmp1 == -1 && cmp2 == -1) || (cmp1 == 1 && cmp2 == 1))
4268 return boolean_true_node;
4270 /* If VR0 and VR1 represent a single value and are identical,
4271 return false. */
4272 else if (compare_values_warnv (vr0->min, vr0->max,
4273 strict_overflow_p) == 0
4274 && compare_values_warnv (vr1->min, vr1->max,
4275 strict_overflow_p) == 0
4276 && compare_values_warnv (vr0->min, vr1->min,
4277 strict_overflow_p) == 0
4278 && compare_values_warnv (vr0->max, vr1->max,
4279 strict_overflow_p) == 0)
4280 return boolean_false_node;
4282 /* Otherwise, they may or may not be different. */
4283 else
4284 return NULL_TREE;
4286 else if (comp == LT_EXPR || comp == LE_EXPR)
4288 int tst;
4290 /* If VR0 is to the left of VR1, return true. */
4291 tst = compare_values_warnv (vr0->max, vr1->min, strict_overflow_p);
4292 if ((comp == LT_EXPR && tst == -1)
4293 || (comp == LE_EXPR && (tst == -1 || tst == 0)))
4294 return boolean_true_node;
4296 /* If VR0 is to the right of VR1, return false. */
4297 tst = compare_values_warnv (vr0->min, vr1->max, strict_overflow_p);
4298 if ((comp == LT_EXPR && (tst == 0 || tst == 1))
4299 || (comp == LE_EXPR && tst == 1))
4300 return boolean_false_node;
4302 /* Otherwise, we don't know. */
4303 return NULL_TREE;
4306 gcc_unreachable ();
4310 /* Given a value range VR, a value VAL and a comparison code COMP, return
4311 BOOLEAN_TRUE_NODE if VR COMP VAL always returns true for all the
4312 values in VR. Return BOOLEAN_FALSE_NODE if the comparison
4313 always returns false. Return NULL_TREE if it is not always
4314 possible to determine the value of the comparison. Also set
4315 *STRICT_OVERFLOW_P to indicate whether comparision evaluation
4316 assumed signed overflow is undefined. */
4318 static tree
4319 compare_range_with_value (enum tree_code comp, value_range *vr, tree val,
4320 bool *strict_overflow_p)
4322 if (vr->type == VR_VARYING || vr->type == VR_UNDEFINED)
4323 return NULL_TREE;
4325 /* Anti-ranges need to be handled separately. */
4326 if (vr->type == VR_ANTI_RANGE)
4328 /* For anti-ranges, the only predicates that we can compute at
4329 compile time are equality and inequality. */
4330 if (comp == GT_EXPR
4331 || comp == GE_EXPR
4332 || comp == LT_EXPR
4333 || comp == LE_EXPR)
4334 return NULL_TREE;
4336 /* ~[VAL_1, VAL_2] OP VAL is known if VAL_1 <= VAL <= VAL_2. */
4337 if (value_inside_range (val, vr->min, vr->max) == 1)
4338 return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
4340 return NULL_TREE;
4343 if (comp == EQ_EXPR)
4345 /* EQ_EXPR may only be computed if VR represents exactly
4346 one value. */
4347 if (compare_values_warnv (vr->min, vr->max, strict_overflow_p) == 0)
4349 int cmp = compare_values_warnv (vr->min, val, strict_overflow_p);
4350 if (cmp == 0)
4351 return boolean_true_node;
4352 else if (cmp == -1 || cmp == 1 || cmp == 2)
4353 return boolean_false_node;
4355 else if (compare_values_warnv (val, vr->min, strict_overflow_p) == -1
4356 || compare_values_warnv (vr->max, val, strict_overflow_p) == -1)
4357 return boolean_false_node;
4359 return NULL_TREE;
4361 else if (comp == NE_EXPR)
4363 /* If VAL is not inside VR, then they are always different. */
4364 if (compare_values_warnv (vr->max, val, strict_overflow_p) == -1
4365 || compare_values_warnv (vr->min, val, strict_overflow_p) == 1)
4366 return boolean_true_node;
4368 /* If VR represents exactly one value equal to VAL, then return
4369 false. */
4370 if (compare_values_warnv (vr->min, vr->max, strict_overflow_p) == 0
4371 && compare_values_warnv (vr->min, val, strict_overflow_p) == 0)
4372 return boolean_false_node;
4374 /* Otherwise, they may or may not be different. */
4375 return NULL_TREE;
4377 else if (comp == LT_EXPR || comp == LE_EXPR)
4379 int tst;
4381 /* If VR is to the left of VAL, return true. */
4382 tst = compare_values_warnv (vr->max, val, strict_overflow_p);
4383 if ((comp == LT_EXPR && tst == -1)
4384 || (comp == LE_EXPR && (tst == -1 || tst == 0)))
4385 return boolean_true_node;
4387 /* If VR is to the right of VAL, return false. */
4388 tst = compare_values_warnv (vr->min, val, strict_overflow_p);
4389 if ((comp == LT_EXPR && (tst == 0 || tst == 1))
4390 || (comp == LE_EXPR && tst == 1))
4391 return boolean_false_node;
4393 /* Otherwise, we don't know. */
4394 return NULL_TREE;
4396 else if (comp == GT_EXPR || comp == GE_EXPR)
4398 int tst;
4400 /* If VR is to the right of VAL, return true. */
4401 tst = compare_values_warnv (vr->min, val, strict_overflow_p);
4402 if ((comp == GT_EXPR && tst == 1)
4403 || (comp == GE_EXPR && (tst == 0 || tst == 1)))
4404 return boolean_true_node;
4406 /* If VR is to the left of VAL, return false. */
4407 tst = compare_values_warnv (vr->max, val, strict_overflow_p);
4408 if ((comp == GT_EXPR && (tst == -1 || tst == 0))
4409 || (comp == GE_EXPR && tst == -1))
4410 return boolean_false_node;
4412 /* Otherwise, we don't know. */
4413 return NULL_TREE;
4416 gcc_unreachable ();
4420 /* Debugging dumps. */
4422 void dump_value_range (FILE *, const value_range *);
4423 void debug_value_range (value_range *);
4424 void dump_all_value_ranges (FILE *);
4425 void debug_all_value_ranges (void);
4426 void dump_vr_equiv (FILE *, bitmap);
4427 void debug_vr_equiv (bitmap);
4430 /* Dump value range VR to FILE. */
4432 void
4433 dump_value_range (FILE *file, const value_range *vr)
4435 if (vr == NULL)
4436 fprintf (file, "[]");
4437 else if (vr->type == VR_UNDEFINED)
4438 fprintf (file, "UNDEFINED");
4439 else if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
4441 tree type = TREE_TYPE (vr->min);
4443 fprintf (file, "%s[", (vr->type == VR_ANTI_RANGE) ? "~" : "");
4445 if (INTEGRAL_TYPE_P (type)
4446 && !TYPE_UNSIGNED (type)
4447 && vrp_val_is_min (vr->min))
4448 fprintf (file, "-INF");
4449 else
4450 print_generic_expr (file, vr->min);
4452 fprintf (file, ", ");
4454 if (INTEGRAL_TYPE_P (type)
4455 && vrp_val_is_max (vr->max))
4456 fprintf (file, "+INF");
4457 else
4458 print_generic_expr (file, vr->max);
4460 fprintf (file, "]");
4462 if (vr->equiv)
4464 bitmap_iterator bi;
4465 unsigned i, c = 0;
4467 fprintf (file, " EQUIVALENCES: { ");
4469 EXECUTE_IF_SET_IN_BITMAP (vr->equiv, 0, i, bi)
4471 print_generic_expr (file, ssa_name (i));
4472 fprintf (file, " ");
4473 c++;
4476 fprintf (file, "} (%u elements)", c);
4479 else if (vr->type == VR_VARYING)
4480 fprintf (file, "VARYING");
4481 else
4482 fprintf (file, "INVALID RANGE");
4486 /* Dump value range VR to stderr. */
4488 DEBUG_FUNCTION void
4489 debug_value_range (value_range *vr)
4491 dump_value_range (stderr, vr);
4492 fprintf (stderr, "\n");
4496 /* Dump value ranges of all SSA_NAMEs to FILE. */
4498 void
4499 dump_all_value_ranges (FILE *file)
4501 size_t i;
4503 for (i = 0; i < num_vr_values; i++)
4505 if (vr_value[i])
4507 print_generic_expr (file, ssa_name (i));
4508 fprintf (file, ": ");
4509 dump_value_range (file, vr_value[i]);
4510 fprintf (file, "\n");
4514 fprintf (file, "\n");
4518 /* Dump all value ranges to stderr. */
4520 DEBUG_FUNCTION void
4521 debug_all_value_ranges (void)
4523 dump_all_value_ranges (stderr);
4527 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
4528 create a new SSA name N and return the assertion assignment
4529 'N = ASSERT_EXPR <V, V OP W>'. */
4531 static gimple *
4532 build_assert_expr_for (tree cond, tree v)
4534 tree a;
4535 gassign *assertion;
4537 gcc_assert (TREE_CODE (v) == SSA_NAME
4538 && COMPARISON_CLASS_P (cond));
4540 a = build2 (ASSERT_EXPR, TREE_TYPE (v), v, cond);
4541 assertion = gimple_build_assign (NULL_TREE, a);
4543 /* The new ASSERT_EXPR, creates a new SSA name that replaces the
4544 operand of the ASSERT_EXPR. Create it so the new name and the old one
4545 are registered in the replacement table so that we can fix the SSA web
4546 after adding all the ASSERT_EXPRs. */
4547 tree new_def = create_new_def_for (v, assertion, NULL);
4548 /* Make sure we preserve abnormalness throughout an ASSERT_EXPR chain
4549 given we have to be able to fully propagate those out to re-create
4550 valid SSA when removing the asserts. */
4551 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (v))
4552 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_def) = 1;
4554 return assertion;
4558 /* Return false if EXPR is a predicate expression involving floating
4559 point values. */
4561 static inline bool
4562 fp_predicate (gimple *stmt)
4564 GIMPLE_CHECK (stmt, GIMPLE_COND);
4566 return FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)));
4569 /* If the range of values taken by OP can be inferred after STMT executes,
4570 return the comparison code (COMP_CODE_P) and value (VAL_P) that
4571 describes the inferred range. Return true if a range could be
4572 inferred. */
4574 static bool
4575 infer_value_range (gimple *stmt, tree op, tree_code *comp_code_p, tree *val_p)
4577 *val_p = NULL_TREE;
4578 *comp_code_p = ERROR_MARK;
4580 /* Do not attempt to infer anything in names that flow through
4581 abnormal edges. */
4582 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
4583 return false;
4585 /* If STMT is the last statement of a basic block with no normal
4586 successors, there is no point inferring anything about any of its
4587 operands. We would not be able to find a proper insertion point
4588 for the assertion, anyway. */
4589 if (stmt_ends_bb_p (stmt))
4591 edge_iterator ei;
4592 edge e;
4594 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
4595 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
4596 break;
4597 if (e == NULL)
4598 return false;
4601 if (infer_nonnull_range (stmt, op))
4603 *val_p = build_int_cst (TREE_TYPE (op), 0);
4604 *comp_code_p = NE_EXPR;
4605 return true;
4608 return false;
4612 void dump_asserts_for (FILE *, tree);
4613 void debug_asserts_for (tree);
4614 void dump_all_asserts (FILE *);
4615 void debug_all_asserts (void);
4617 /* Dump all the registered assertions for NAME to FILE. */
4619 void
4620 dump_asserts_for (FILE *file, tree name)
4622 assert_locus *loc;
4624 fprintf (file, "Assertions to be inserted for ");
4625 print_generic_expr (file, name);
4626 fprintf (file, "\n");
4628 loc = asserts_for[SSA_NAME_VERSION (name)];
4629 while (loc)
4631 fprintf (file, "\t");
4632 print_gimple_stmt (file, gsi_stmt (loc->si), 0);
4633 fprintf (file, "\n\tBB #%d", loc->bb->index);
4634 if (loc->e)
4636 fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
4637 loc->e->dest->index);
4638 dump_edge_info (file, loc->e, dump_flags, 0);
4640 fprintf (file, "\n\tPREDICATE: ");
4641 print_generic_expr (file, loc->expr);
4642 fprintf (file, " %s ", get_tree_code_name (loc->comp_code));
4643 print_generic_expr (file, loc->val);
4644 fprintf (file, "\n\n");
4645 loc = loc->next;
4648 fprintf (file, "\n");
4652 /* Dump all the registered assertions for NAME to stderr. */
4654 DEBUG_FUNCTION void
4655 debug_asserts_for (tree name)
4657 dump_asserts_for (stderr, name);
4661 /* Dump all the registered assertions for all the names to FILE. */
4663 void
4664 dump_all_asserts (FILE *file)
4666 unsigned i;
4667 bitmap_iterator bi;
4669 fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
4670 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
4671 dump_asserts_for (file, ssa_name (i));
4672 fprintf (file, "\n");
4676 /* Dump all the registered assertions for all the names to stderr. */
4678 DEBUG_FUNCTION void
4679 debug_all_asserts (void)
4681 dump_all_asserts (stderr);
4684 /* Push the assert info for NAME, EXPR, COMP_CODE and VAL to ASSERTS. */
4686 static void
4687 add_assert_info (vec<assert_info> &asserts,
4688 tree name, tree expr, enum tree_code comp_code, tree val)
4690 assert_info info;
4691 info.comp_code = comp_code;
4692 info.name = name;
4693 info.val = val;
4694 info.expr = expr;
4695 asserts.safe_push (info);
4698 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
4699 'EXPR COMP_CODE VAL' at a location that dominates block BB or
4700 E->DEST, then register this location as a possible insertion point
4701 for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
4703 BB, E and SI provide the exact insertion point for the new
4704 ASSERT_EXPR. If BB is NULL, then the ASSERT_EXPR is to be inserted
4705 on edge E. Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
4706 BB. If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
4707 must not be NULL. */
4709 static void
4710 register_new_assert_for (tree name, tree expr,
4711 enum tree_code comp_code,
4712 tree val,
4713 basic_block bb,
4714 edge e,
4715 gimple_stmt_iterator si)
4717 assert_locus *n, *loc, *last_loc;
4718 basic_block dest_bb;
4720 gcc_checking_assert (bb == NULL || e == NULL);
4722 if (e == NULL)
4723 gcc_checking_assert (gimple_code (gsi_stmt (si)) != GIMPLE_COND
4724 && gimple_code (gsi_stmt (si)) != GIMPLE_SWITCH);
4726 /* Never build an assert comparing against an integer constant with
4727 TREE_OVERFLOW set. This confuses our undefined overflow warning
4728 machinery. */
4729 if (TREE_OVERFLOW_P (val))
4730 val = drop_tree_overflow (val);
4732 /* The new assertion A will be inserted at BB or E. We need to
4733 determine if the new location is dominated by a previously
4734 registered location for A. If we are doing an edge insertion,
4735 assume that A will be inserted at E->DEST. Note that this is not
4736 necessarily true.
4738 If E is a critical edge, it will be split. But even if E is
4739 split, the new block will dominate the same set of blocks that
4740 E->DEST dominates.
4742 The reverse, however, is not true, blocks dominated by E->DEST
4743 will not be dominated by the new block created to split E. So,
4744 if the insertion location is on a critical edge, we will not use
4745 the new location to move another assertion previously registered
4746 at a block dominated by E->DEST. */
4747 dest_bb = (bb) ? bb : e->dest;
4749 /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
4750 VAL at a block dominating DEST_BB, then we don't need to insert a new
4751 one. Similarly, if the same assertion already exists at a block
4752 dominated by DEST_BB and the new location is not on a critical
4753 edge, then update the existing location for the assertion (i.e.,
4754 move the assertion up in the dominance tree).
4756 Note, this is implemented as a simple linked list because there
4757 should not be more than a handful of assertions registered per
4758 name. If this becomes a performance problem, a table hashed by
4759 COMP_CODE and VAL could be implemented. */
4760 loc = asserts_for[SSA_NAME_VERSION (name)];
4761 last_loc = loc;
4762 while (loc)
4764 if (loc->comp_code == comp_code
4765 && (loc->val == val
4766 || operand_equal_p (loc->val, val, 0))
4767 && (loc->expr == expr
4768 || operand_equal_p (loc->expr, expr, 0)))
4770 /* If E is not a critical edge and DEST_BB
4771 dominates the existing location for the assertion, move
4772 the assertion up in the dominance tree by updating its
4773 location information. */
4774 if ((e == NULL || !EDGE_CRITICAL_P (e))
4775 && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
4777 loc->bb = dest_bb;
4778 loc->e = e;
4779 loc->si = si;
4780 return;
4784 /* Update the last node of the list and move to the next one. */
4785 last_loc = loc;
4786 loc = loc->next;
4789 /* If we didn't find an assertion already registered for
4790 NAME COMP_CODE VAL, add a new one at the end of the list of
4791 assertions associated with NAME. */
4792 n = XNEW (struct assert_locus);
4793 n->bb = dest_bb;
4794 n->e = e;
4795 n->si = si;
4796 n->comp_code = comp_code;
4797 n->val = val;
4798 n->expr = expr;
4799 n->next = NULL;
4801 if (last_loc)
4802 last_loc->next = n;
4803 else
4804 asserts_for[SSA_NAME_VERSION (name)] = n;
4806 bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
4809 /* (COND_OP0 COND_CODE COND_OP1) is a predicate which uses NAME.
4810 Extract a suitable test code and value and store them into *CODE_P and
4811 *VAL_P so the predicate is normalized to NAME *CODE_P *VAL_P.
4813 If no extraction was possible, return FALSE, otherwise return TRUE.
4815 If INVERT is true, then we invert the result stored into *CODE_P. */
4817 static bool
4818 extract_code_and_val_from_cond_with_ops (tree name, enum tree_code cond_code,
4819 tree cond_op0, tree cond_op1,
4820 bool invert, enum tree_code *code_p,
4821 tree *val_p)
4823 enum tree_code comp_code;
4824 tree val;
4826 /* Otherwise, we have a comparison of the form NAME COMP VAL
4827 or VAL COMP NAME. */
4828 if (name == cond_op1)
4830 /* If the predicate is of the form VAL COMP NAME, flip
4831 COMP around because we need to register NAME as the
4832 first operand in the predicate. */
4833 comp_code = swap_tree_comparison (cond_code);
4834 val = cond_op0;
4836 else if (name == cond_op0)
4838 /* The comparison is of the form NAME COMP VAL, so the
4839 comparison code remains unchanged. */
4840 comp_code = cond_code;
4841 val = cond_op1;
4843 else
4844 gcc_unreachable ();
4846 /* Invert the comparison code as necessary. */
4847 if (invert)
4848 comp_code = invert_tree_comparison (comp_code, 0);
4850 /* VRP only handles integral and pointer types. */
4851 if (! INTEGRAL_TYPE_P (TREE_TYPE (val))
4852 && ! POINTER_TYPE_P (TREE_TYPE (val)))
4853 return false;
4855 /* Do not register always-false predicates.
4856 FIXME: this works around a limitation in fold() when dealing with
4857 enumerations. Given 'enum { N1, N2 } x;', fold will not
4858 fold 'if (x > N2)' to 'if (0)'. */
4859 if ((comp_code == GT_EXPR || comp_code == LT_EXPR)
4860 && INTEGRAL_TYPE_P (TREE_TYPE (val)))
4862 tree min = TYPE_MIN_VALUE (TREE_TYPE (val));
4863 tree max = TYPE_MAX_VALUE (TREE_TYPE (val));
4865 if (comp_code == GT_EXPR
4866 && (!max
4867 || compare_values (val, max) == 0))
4868 return false;
4870 if (comp_code == LT_EXPR
4871 && (!min
4872 || compare_values (val, min) == 0))
4873 return false;
4875 *code_p = comp_code;
4876 *val_p = val;
4877 return true;
4880 /* Find out smallest RES where RES > VAL && (RES & MASK) == RES, if any
4881 (otherwise return VAL). VAL and MASK must be zero-extended for
4882 precision PREC. If SGNBIT is non-zero, first xor VAL with SGNBIT
4883 (to transform signed values into unsigned) and at the end xor
4884 SGNBIT back. */
4886 static wide_int
4887 masked_increment (const wide_int &val_in, const wide_int &mask,
4888 const wide_int &sgnbit, unsigned int prec)
4890 wide_int bit = wi::one (prec), res;
4891 unsigned int i;
4893 wide_int val = val_in ^ sgnbit;
4894 for (i = 0; i < prec; i++, bit += bit)
4896 res = mask;
4897 if ((res & bit) == 0)
4898 continue;
4899 res = bit - 1;
4900 res = wi::bit_and_not (val + bit, res);
4901 res &= mask;
4902 if (wi::gtu_p (res, val))
4903 return res ^ sgnbit;
4905 return val ^ sgnbit;
4908 /* Helper for overflow_comparison_p
4910 OP0 CODE OP1 is a comparison. Examine the comparison and potentially
4911 OP1's defining statement to see if it ultimately has the form
4912 OP0 CODE (OP0 PLUS INTEGER_CST)
4914 If so, return TRUE indicating this is an overflow test and store into
4915 *NEW_CST an updated constant that can be used in a narrowed range test.
4917 REVERSED indicates if the comparison was originally:
4919 OP1 CODE' OP0.
4921 This affects how we build the updated constant. */
4923 static bool
4924 overflow_comparison_p_1 (enum tree_code code, tree op0, tree op1,
4925 bool follow_assert_exprs, bool reversed, tree *new_cst)
4927 /* See if this is a relational operation between two SSA_NAMES with
4928 unsigned, overflow wrapping values. If so, check it more deeply. */
4929 if ((code == LT_EXPR || code == LE_EXPR
4930 || code == GE_EXPR || code == GT_EXPR)
4931 && TREE_CODE (op0) == SSA_NAME
4932 && TREE_CODE (op1) == SSA_NAME
4933 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
4934 && TYPE_UNSIGNED (TREE_TYPE (op0))
4935 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0)))
4937 gimple *op1_def = SSA_NAME_DEF_STMT (op1);
4939 /* If requested, follow any ASSERT_EXPRs backwards for OP1. */
4940 if (follow_assert_exprs)
4942 while (gimple_assign_single_p (op1_def)
4943 && TREE_CODE (gimple_assign_rhs1 (op1_def)) == ASSERT_EXPR)
4945 op1 = TREE_OPERAND (gimple_assign_rhs1 (op1_def), 0);
4946 if (TREE_CODE (op1) != SSA_NAME)
4947 break;
4948 op1_def = SSA_NAME_DEF_STMT (op1);
4952 /* Now look at the defining statement of OP1 to see if it adds
4953 or subtracts a nonzero constant from another operand. */
4954 if (op1_def
4955 && is_gimple_assign (op1_def)
4956 && gimple_assign_rhs_code (op1_def) == PLUS_EXPR
4957 && TREE_CODE (gimple_assign_rhs2 (op1_def)) == INTEGER_CST
4958 && !integer_zerop (gimple_assign_rhs2 (op1_def)))
4960 tree target = gimple_assign_rhs1 (op1_def);
4962 /* If requested, follow ASSERT_EXPRs backwards for op0 looking
4963 for one where TARGET appears on the RHS. */
4964 if (follow_assert_exprs)
4966 /* Now see if that "other operand" is op0, following the chain
4967 of ASSERT_EXPRs if necessary. */
4968 gimple *op0_def = SSA_NAME_DEF_STMT (op0);
4969 while (op0 != target
4970 && gimple_assign_single_p (op0_def)
4971 && TREE_CODE (gimple_assign_rhs1 (op0_def)) == ASSERT_EXPR)
4973 op0 = TREE_OPERAND (gimple_assign_rhs1 (op0_def), 0);
4974 if (TREE_CODE (op0) != SSA_NAME)
4975 break;
4976 op0_def = SSA_NAME_DEF_STMT (op0);
4980 /* If we did not find our target SSA_NAME, then this is not
4981 an overflow test. */
4982 if (op0 != target)
4983 return false;
4985 tree type = TREE_TYPE (op0);
4986 wide_int max = wi::max_value (TYPE_PRECISION (type), UNSIGNED);
4987 tree inc = gimple_assign_rhs2 (op1_def);
4988 if (reversed)
4989 *new_cst = wide_int_to_tree (type, max + wi::to_wide (inc));
4990 else
4991 *new_cst = wide_int_to_tree (type, max - wi::to_wide (inc));
4992 return true;
4995 return false;
4998 /* OP0 CODE OP1 is a comparison. Examine the comparison and potentially
4999 OP1's defining statement to see if it ultimately has the form
5000 OP0 CODE (OP0 PLUS INTEGER_CST)
5002 If so, return TRUE indicating this is an overflow test and store into
5003 *NEW_CST an updated constant that can be used in a narrowed range test.
5005 These statements are left as-is in the IL to facilitate discovery of
5006 {ADD,SUB}_OVERFLOW sequences later in the optimizer pipeline. But
5007 the alternate range representation is often useful within VRP. */
5009 static bool
5010 overflow_comparison_p (tree_code code, tree name, tree val,
5011 bool use_equiv_p, tree *new_cst)
5013 if (overflow_comparison_p_1 (code, name, val, use_equiv_p, false, new_cst))
5014 return true;
5015 return overflow_comparison_p_1 (swap_tree_comparison (code), val, name,
5016 use_equiv_p, true, new_cst);
5020 /* Try to register an edge assertion for SSA name NAME on edge E for
5021 the condition COND contributing to the conditional jump pointed to by BSI.
5022 Invert the condition COND if INVERT is true. */
5024 static void
5025 register_edge_assert_for_2 (tree name, edge e,
5026 enum tree_code cond_code,
5027 tree cond_op0, tree cond_op1, bool invert,
5028 vec<assert_info> &asserts)
5030 tree val;
5031 enum tree_code comp_code;
5033 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
5034 cond_op0,
5035 cond_op1,
5036 invert, &comp_code, &val))
5037 return;
5039 /* Queue the assert. */
5040 tree x;
5041 if (overflow_comparison_p (comp_code, name, val, false, &x))
5043 enum tree_code new_code = ((comp_code == GT_EXPR || comp_code == GE_EXPR)
5044 ? GT_EXPR : LE_EXPR);
5045 add_assert_info (asserts, name, name, new_code, x);
5047 add_assert_info (asserts, name, name, comp_code, val);
5049 /* In the case of NAME <= CST and NAME being defined as
5050 NAME = (unsigned) NAME2 + CST2 we can assert NAME2 >= -CST2
5051 and NAME2 <= CST - CST2. We can do the same for NAME > CST.
5052 This catches range and anti-range tests. */
5053 if ((comp_code == LE_EXPR
5054 || comp_code == GT_EXPR)
5055 && TREE_CODE (val) == INTEGER_CST
5056 && TYPE_UNSIGNED (TREE_TYPE (val)))
5058 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5059 tree cst2 = NULL_TREE, name2 = NULL_TREE, name3 = NULL_TREE;
5061 /* Extract CST2 from the (optional) addition. */
5062 if (is_gimple_assign (def_stmt)
5063 && gimple_assign_rhs_code (def_stmt) == PLUS_EXPR)
5065 name2 = gimple_assign_rhs1 (def_stmt);
5066 cst2 = gimple_assign_rhs2 (def_stmt);
5067 if (TREE_CODE (name2) == SSA_NAME
5068 && TREE_CODE (cst2) == INTEGER_CST)
5069 def_stmt = SSA_NAME_DEF_STMT (name2);
5072 /* Extract NAME2 from the (optional) sign-changing cast. */
5073 if (gimple_assign_cast_p (def_stmt))
5075 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt))
5076 && ! TYPE_UNSIGNED (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
5077 && (TYPE_PRECISION (gimple_expr_type (def_stmt))
5078 == TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))))
5079 name3 = gimple_assign_rhs1 (def_stmt);
5082 /* If name3 is used later, create an ASSERT_EXPR for it. */
5083 if (name3 != NULL_TREE
5084 && TREE_CODE (name3) == SSA_NAME
5085 && (cst2 == NULL_TREE
5086 || TREE_CODE (cst2) == INTEGER_CST)
5087 && INTEGRAL_TYPE_P (TREE_TYPE (name3)))
5089 tree tmp;
5091 /* Build an expression for the range test. */
5092 tmp = build1 (NOP_EXPR, TREE_TYPE (name), name3);
5093 if (cst2 != NULL_TREE)
5094 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
5096 if (dump_file)
5098 fprintf (dump_file, "Adding assert for ");
5099 print_generic_expr (dump_file, name3);
5100 fprintf (dump_file, " from ");
5101 print_generic_expr (dump_file, tmp);
5102 fprintf (dump_file, "\n");
5105 add_assert_info (asserts, name3, tmp, comp_code, val);
5108 /* If name2 is used later, create an ASSERT_EXPR for it. */
5109 if (name2 != NULL_TREE
5110 && TREE_CODE (name2) == SSA_NAME
5111 && TREE_CODE (cst2) == INTEGER_CST
5112 && INTEGRAL_TYPE_P (TREE_TYPE (name2)))
5114 tree tmp;
5116 /* Build an expression for the range test. */
5117 tmp = name2;
5118 if (TREE_TYPE (name) != TREE_TYPE (name2))
5119 tmp = build1 (NOP_EXPR, TREE_TYPE (name), tmp);
5120 if (cst2 != NULL_TREE)
5121 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
5123 if (dump_file)
5125 fprintf (dump_file, "Adding assert for ");
5126 print_generic_expr (dump_file, name2);
5127 fprintf (dump_file, " from ");
5128 print_generic_expr (dump_file, tmp);
5129 fprintf (dump_file, "\n");
5132 add_assert_info (asserts, name2, tmp, comp_code, val);
5136 /* In the case of post-in/decrement tests like if (i++) ... and uses
5137 of the in/decremented value on the edge the extra name we want to
5138 assert for is not on the def chain of the name compared. Instead
5139 it is in the set of use stmts.
5140 Similar cases happen for conversions that were simplified through
5141 fold_{sign_changed,widened}_comparison. */
5142 if ((comp_code == NE_EXPR
5143 || comp_code == EQ_EXPR)
5144 && TREE_CODE (val) == INTEGER_CST)
5146 imm_use_iterator ui;
5147 gimple *use_stmt;
5148 FOR_EACH_IMM_USE_STMT (use_stmt, ui, name)
5150 if (!is_gimple_assign (use_stmt))
5151 continue;
5153 /* Cut off to use-stmts that are dominating the predecessor. */
5154 if (!dominated_by_p (CDI_DOMINATORS, e->src, gimple_bb (use_stmt)))
5155 continue;
5157 tree name2 = gimple_assign_lhs (use_stmt);
5158 if (TREE_CODE (name2) != SSA_NAME)
5159 continue;
5161 enum tree_code code = gimple_assign_rhs_code (use_stmt);
5162 tree cst;
5163 if (code == PLUS_EXPR
5164 || code == MINUS_EXPR)
5166 cst = gimple_assign_rhs2 (use_stmt);
5167 if (TREE_CODE (cst) != INTEGER_CST)
5168 continue;
5169 cst = int_const_binop (code, val, cst);
5171 else if (CONVERT_EXPR_CODE_P (code))
5173 /* For truncating conversions we cannot record
5174 an inequality. */
5175 if (comp_code == NE_EXPR
5176 && (TYPE_PRECISION (TREE_TYPE (name2))
5177 < TYPE_PRECISION (TREE_TYPE (name))))
5178 continue;
5179 cst = fold_convert (TREE_TYPE (name2), val);
5181 else
5182 continue;
5184 if (TREE_OVERFLOW_P (cst))
5185 cst = drop_tree_overflow (cst);
5186 add_assert_info (asserts, name2, name2, comp_code, cst);
5190 if (TREE_CODE_CLASS (comp_code) == tcc_comparison
5191 && TREE_CODE (val) == INTEGER_CST)
5193 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5194 tree name2 = NULL_TREE, names[2], cst2 = NULL_TREE;
5195 tree val2 = NULL_TREE;
5196 unsigned int prec = TYPE_PRECISION (TREE_TYPE (val));
5197 wide_int mask = wi::zero (prec);
5198 unsigned int nprec = prec;
5199 enum tree_code rhs_code = ERROR_MARK;
5201 if (is_gimple_assign (def_stmt))
5202 rhs_code = gimple_assign_rhs_code (def_stmt);
5204 /* In the case of NAME != CST1 where NAME = A +- CST2 we can
5205 assert that A != CST1 -+ CST2. */
5206 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
5207 && (rhs_code == PLUS_EXPR || rhs_code == MINUS_EXPR))
5209 tree op0 = gimple_assign_rhs1 (def_stmt);
5210 tree op1 = gimple_assign_rhs2 (def_stmt);
5211 if (TREE_CODE (op0) == SSA_NAME
5212 && TREE_CODE (op1) == INTEGER_CST)
5214 enum tree_code reverse_op = (rhs_code == PLUS_EXPR
5215 ? MINUS_EXPR : PLUS_EXPR);
5216 op1 = int_const_binop (reverse_op, val, op1);
5217 if (TREE_OVERFLOW (op1))
5218 op1 = drop_tree_overflow (op1);
5219 add_assert_info (asserts, op0, op0, comp_code, op1);
5223 /* Add asserts for NAME cmp CST and NAME being defined
5224 as NAME = (int) NAME2. */
5225 if (!TYPE_UNSIGNED (TREE_TYPE (val))
5226 && (comp_code == LE_EXPR || comp_code == LT_EXPR
5227 || comp_code == GT_EXPR || comp_code == GE_EXPR)
5228 && gimple_assign_cast_p (def_stmt))
5230 name2 = gimple_assign_rhs1 (def_stmt);
5231 if (CONVERT_EXPR_CODE_P (rhs_code)
5232 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
5233 && TYPE_UNSIGNED (TREE_TYPE (name2))
5234 && prec == TYPE_PRECISION (TREE_TYPE (name2))
5235 && (comp_code == LE_EXPR || comp_code == GT_EXPR
5236 || !tree_int_cst_equal (val,
5237 TYPE_MIN_VALUE (TREE_TYPE (val)))))
5239 tree tmp, cst;
5240 enum tree_code new_comp_code = comp_code;
5242 cst = fold_convert (TREE_TYPE (name2),
5243 TYPE_MIN_VALUE (TREE_TYPE (val)));
5244 /* Build an expression for the range test. */
5245 tmp = build2 (PLUS_EXPR, TREE_TYPE (name2), name2, cst);
5246 cst = fold_build2 (PLUS_EXPR, TREE_TYPE (name2), cst,
5247 fold_convert (TREE_TYPE (name2), val));
5248 if (comp_code == LT_EXPR || comp_code == GE_EXPR)
5250 new_comp_code = comp_code == LT_EXPR ? LE_EXPR : GT_EXPR;
5251 cst = fold_build2 (MINUS_EXPR, TREE_TYPE (name2), cst,
5252 build_int_cst (TREE_TYPE (name2), 1));
5255 if (dump_file)
5257 fprintf (dump_file, "Adding assert for ");
5258 print_generic_expr (dump_file, name2);
5259 fprintf (dump_file, " from ");
5260 print_generic_expr (dump_file, tmp);
5261 fprintf (dump_file, "\n");
5264 add_assert_info (asserts, name2, tmp, new_comp_code, cst);
5268 /* Add asserts for NAME cmp CST and NAME being defined as
5269 NAME = NAME2 >> CST2.
5271 Extract CST2 from the right shift. */
5272 if (rhs_code == RSHIFT_EXPR)
5274 name2 = gimple_assign_rhs1 (def_stmt);
5275 cst2 = gimple_assign_rhs2 (def_stmt);
5276 if (TREE_CODE (name2) == SSA_NAME
5277 && tree_fits_uhwi_p (cst2)
5278 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
5279 && IN_RANGE (tree_to_uhwi (cst2), 1, prec - 1)
5280 && type_has_mode_precision_p (TREE_TYPE (val)))
5282 mask = wi::mask (tree_to_uhwi (cst2), false, prec);
5283 val2 = fold_binary (LSHIFT_EXPR, TREE_TYPE (val), val, cst2);
5286 if (val2 != NULL_TREE
5287 && TREE_CODE (val2) == INTEGER_CST
5288 && simple_cst_equal (fold_build2 (RSHIFT_EXPR,
5289 TREE_TYPE (val),
5290 val2, cst2), val))
5292 enum tree_code new_comp_code = comp_code;
5293 tree tmp, new_val;
5295 tmp = name2;
5296 if (comp_code == EQ_EXPR || comp_code == NE_EXPR)
5298 if (!TYPE_UNSIGNED (TREE_TYPE (val)))
5300 tree type = build_nonstandard_integer_type (prec, 1);
5301 tmp = build1 (NOP_EXPR, type, name2);
5302 val2 = fold_convert (type, val2);
5304 tmp = fold_build2 (MINUS_EXPR, TREE_TYPE (tmp), tmp, val2);
5305 new_val = wide_int_to_tree (TREE_TYPE (tmp), mask);
5306 new_comp_code = comp_code == EQ_EXPR ? LE_EXPR : GT_EXPR;
5308 else if (comp_code == LT_EXPR || comp_code == GE_EXPR)
5310 wide_int minval
5311 = wi::min_value (prec, TYPE_SIGN (TREE_TYPE (val)));
5312 new_val = val2;
5313 if (minval == wi::to_wide (new_val))
5314 new_val = NULL_TREE;
5316 else
5318 wide_int maxval
5319 = wi::max_value (prec, TYPE_SIGN (TREE_TYPE (val)));
5320 mask |= wi::to_wide (val2);
5321 if (wi::eq_p (mask, maxval))
5322 new_val = NULL_TREE;
5323 else
5324 new_val = wide_int_to_tree (TREE_TYPE (val2), mask);
5327 if (new_val)
5329 if (dump_file)
5331 fprintf (dump_file, "Adding assert for ");
5332 print_generic_expr (dump_file, name2);
5333 fprintf (dump_file, " from ");
5334 print_generic_expr (dump_file, tmp);
5335 fprintf (dump_file, "\n");
5338 add_assert_info (asserts, name2, tmp, new_comp_code, new_val);
5342 /* Add asserts for NAME cmp CST and NAME being defined as
5343 NAME = NAME2 & CST2.
5345 Extract CST2 from the and.
5347 Also handle
5348 NAME = (unsigned) NAME2;
5349 casts where NAME's type is unsigned and has smaller precision
5350 than NAME2's type as if it was NAME = NAME2 & MASK. */
5351 names[0] = NULL_TREE;
5352 names[1] = NULL_TREE;
5353 cst2 = NULL_TREE;
5354 if (rhs_code == BIT_AND_EXPR
5355 || (CONVERT_EXPR_CODE_P (rhs_code)
5356 && INTEGRAL_TYPE_P (TREE_TYPE (val))
5357 && TYPE_UNSIGNED (TREE_TYPE (val))
5358 && TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
5359 > prec))
5361 name2 = gimple_assign_rhs1 (def_stmt);
5362 if (rhs_code == BIT_AND_EXPR)
5363 cst2 = gimple_assign_rhs2 (def_stmt);
5364 else
5366 cst2 = TYPE_MAX_VALUE (TREE_TYPE (val));
5367 nprec = TYPE_PRECISION (TREE_TYPE (name2));
5369 if (TREE_CODE (name2) == SSA_NAME
5370 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
5371 && TREE_CODE (cst2) == INTEGER_CST
5372 && !integer_zerop (cst2)
5373 && (nprec > 1
5374 || TYPE_UNSIGNED (TREE_TYPE (val))))
5376 gimple *def_stmt2 = SSA_NAME_DEF_STMT (name2);
5377 if (gimple_assign_cast_p (def_stmt2))
5379 names[1] = gimple_assign_rhs1 (def_stmt2);
5380 if (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt2))
5381 || !INTEGRAL_TYPE_P (TREE_TYPE (names[1]))
5382 || (TYPE_PRECISION (TREE_TYPE (name2))
5383 != TYPE_PRECISION (TREE_TYPE (names[1]))))
5384 names[1] = NULL_TREE;
5386 names[0] = name2;
5389 if (names[0] || names[1])
5391 wide_int minv, maxv, valv, cst2v;
5392 wide_int tem, sgnbit;
5393 bool valid_p = false, valn, cst2n;
5394 enum tree_code ccode = comp_code;
5396 valv = wide_int::from (wi::to_wide (val), nprec, UNSIGNED);
5397 cst2v = wide_int::from (wi::to_wide (cst2), nprec, UNSIGNED);
5398 valn = wi::neg_p (valv, TYPE_SIGN (TREE_TYPE (val)));
5399 cst2n = wi::neg_p (cst2v, TYPE_SIGN (TREE_TYPE (val)));
5400 /* If CST2 doesn't have most significant bit set,
5401 but VAL is negative, we have comparison like
5402 if ((x & 0x123) > -4) (always true). Just give up. */
5403 if (!cst2n && valn)
5404 ccode = ERROR_MARK;
5405 if (cst2n)
5406 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
5407 else
5408 sgnbit = wi::zero (nprec);
5409 minv = valv & cst2v;
5410 switch (ccode)
5412 case EQ_EXPR:
5413 /* Minimum unsigned value for equality is VAL & CST2
5414 (should be equal to VAL, otherwise we probably should
5415 have folded the comparison into false) and
5416 maximum unsigned value is VAL | ~CST2. */
5417 maxv = valv | ~cst2v;
5418 valid_p = true;
5419 break;
5421 case NE_EXPR:
5422 tem = valv | ~cst2v;
5423 /* If VAL is 0, handle (X & CST2) != 0 as (X & CST2) > 0U. */
5424 if (valv == 0)
5426 cst2n = false;
5427 sgnbit = wi::zero (nprec);
5428 goto gt_expr;
5430 /* If (VAL | ~CST2) is all ones, handle it as
5431 (X & CST2) < VAL. */
5432 if (tem == -1)
5434 cst2n = false;
5435 valn = false;
5436 sgnbit = wi::zero (nprec);
5437 goto lt_expr;
5439 if (!cst2n && wi::neg_p (cst2v))
5440 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
5441 if (sgnbit != 0)
5443 if (valv == sgnbit)
5445 cst2n = true;
5446 valn = true;
5447 goto gt_expr;
5449 if (tem == wi::mask (nprec - 1, false, nprec))
5451 cst2n = true;
5452 goto lt_expr;
5454 if (!cst2n)
5455 sgnbit = wi::zero (nprec);
5457 break;
5459 case GE_EXPR:
5460 /* Minimum unsigned value for >= if (VAL & CST2) == VAL
5461 is VAL and maximum unsigned value is ~0. For signed
5462 comparison, if CST2 doesn't have most significant bit
5463 set, handle it similarly. If CST2 has MSB set,
5464 the minimum is the same, and maximum is ~0U/2. */
5465 if (minv != valv)
5467 /* If (VAL & CST2) != VAL, X & CST2 can't be equal to
5468 VAL. */
5469 minv = masked_increment (valv, cst2v, sgnbit, nprec);
5470 if (minv == valv)
5471 break;
5473 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
5474 valid_p = true;
5475 break;
5477 case GT_EXPR:
5478 gt_expr:
5479 /* Find out smallest MINV where MINV > VAL
5480 && (MINV & CST2) == MINV, if any. If VAL is signed and
5481 CST2 has MSB set, compute it biased by 1 << (nprec - 1). */
5482 minv = masked_increment (valv, cst2v, sgnbit, nprec);
5483 if (minv == valv)
5484 break;
5485 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
5486 valid_p = true;
5487 break;
5489 case LE_EXPR:
5490 /* Minimum unsigned value for <= is 0 and maximum
5491 unsigned value is VAL | ~CST2 if (VAL & CST2) == VAL.
5492 Otherwise, find smallest VAL2 where VAL2 > VAL
5493 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
5494 as maximum.
5495 For signed comparison, if CST2 doesn't have most
5496 significant bit set, handle it similarly. If CST2 has
5497 MSB set, the maximum is the same and minimum is INT_MIN. */
5498 if (minv == valv)
5499 maxv = valv;
5500 else
5502 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
5503 if (maxv == valv)
5504 break;
5505 maxv -= 1;
5507 maxv |= ~cst2v;
5508 minv = sgnbit;
5509 valid_p = true;
5510 break;
5512 case LT_EXPR:
5513 lt_expr:
5514 /* Minimum unsigned value for < is 0 and maximum
5515 unsigned value is (VAL-1) | ~CST2 if (VAL & CST2) == VAL.
5516 Otherwise, find smallest VAL2 where VAL2 > VAL
5517 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
5518 as maximum.
5519 For signed comparison, if CST2 doesn't have most
5520 significant bit set, handle it similarly. If CST2 has
5521 MSB set, the maximum is the same and minimum is INT_MIN. */
5522 if (minv == valv)
5524 if (valv == sgnbit)
5525 break;
5526 maxv = valv;
5528 else
5530 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
5531 if (maxv == valv)
5532 break;
5534 maxv -= 1;
5535 maxv |= ~cst2v;
5536 minv = sgnbit;
5537 valid_p = true;
5538 break;
5540 default:
5541 break;
5543 if (valid_p
5544 && (maxv - minv) != -1)
5546 tree tmp, new_val, type;
5547 int i;
5549 for (i = 0; i < 2; i++)
5550 if (names[i])
5552 wide_int maxv2 = maxv;
5553 tmp = names[i];
5554 type = TREE_TYPE (names[i]);
5555 if (!TYPE_UNSIGNED (type))
5557 type = build_nonstandard_integer_type (nprec, 1);
5558 tmp = build1 (NOP_EXPR, type, names[i]);
5560 if (minv != 0)
5562 tmp = build2 (PLUS_EXPR, type, tmp,
5563 wide_int_to_tree (type, -minv));
5564 maxv2 = maxv - minv;
5566 new_val = wide_int_to_tree (type, maxv2);
5568 if (dump_file)
5570 fprintf (dump_file, "Adding assert for ");
5571 print_generic_expr (dump_file, names[i]);
5572 fprintf (dump_file, " from ");
5573 print_generic_expr (dump_file, tmp);
5574 fprintf (dump_file, "\n");
5577 add_assert_info (asserts, names[i], tmp, LE_EXPR, new_val);
5584 /* OP is an operand of a truth value expression which is known to have
5585 a particular value. Register any asserts for OP and for any
5586 operands in OP's defining statement.
5588 If CODE is EQ_EXPR, then we want to register OP is zero (false),
5589 if CODE is NE_EXPR, then we want to register OP is nonzero (true). */
5591 static void
5592 register_edge_assert_for_1 (tree op, enum tree_code code,
5593 edge e, vec<assert_info> &asserts)
5595 gimple *op_def;
5596 tree val;
5597 enum tree_code rhs_code;
5599 /* We only care about SSA_NAMEs. */
5600 if (TREE_CODE (op) != SSA_NAME)
5601 return;
5603 /* We know that OP will have a zero or nonzero value. */
5604 val = build_int_cst (TREE_TYPE (op), 0);
5605 add_assert_info (asserts, op, op, code, val);
5607 /* Now look at how OP is set. If it's set from a comparison,
5608 a truth operation or some bit operations, then we may be able
5609 to register information about the operands of that assignment. */
5610 op_def = SSA_NAME_DEF_STMT (op);
5611 if (gimple_code (op_def) != GIMPLE_ASSIGN)
5612 return;
5614 rhs_code = gimple_assign_rhs_code (op_def);
5616 if (TREE_CODE_CLASS (rhs_code) == tcc_comparison)
5618 bool invert = (code == EQ_EXPR ? true : false);
5619 tree op0 = gimple_assign_rhs1 (op_def);
5620 tree op1 = gimple_assign_rhs2 (op_def);
5622 if (TREE_CODE (op0) == SSA_NAME)
5623 register_edge_assert_for_2 (op0, e, rhs_code, op0, op1, invert, asserts);
5624 if (TREE_CODE (op1) == SSA_NAME)
5625 register_edge_assert_for_2 (op1, e, rhs_code, op0, op1, invert, asserts);
5627 else if ((code == NE_EXPR
5628 && gimple_assign_rhs_code (op_def) == BIT_AND_EXPR)
5629 || (code == EQ_EXPR
5630 && gimple_assign_rhs_code (op_def) == BIT_IOR_EXPR))
5632 /* Recurse on each operand. */
5633 tree op0 = gimple_assign_rhs1 (op_def);
5634 tree op1 = gimple_assign_rhs2 (op_def);
5635 if (TREE_CODE (op0) == SSA_NAME
5636 && has_single_use (op0))
5637 register_edge_assert_for_1 (op0, code, e, asserts);
5638 if (TREE_CODE (op1) == SSA_NAME
5639 && has_single_use (op1))
5640 register_edge_assert_for_1 (op1, code, e, asserts);
5642 else if (gimple_assign_rhs_code (op_def) == BIT_NOT_EXPR
5643 && TYPE_PRECISION (TREE_TYPE (gimple_assign_lhs (op_def))) == 1)
5645 /* Recurse, flipping CODE. */
5646 code = invert_tree_comparison (code, false);
5647 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
5649 else if (gimple_assign_rhs_code (op_def) == SSA_NAME)
5651 /* Recurse through the copy. */
5652 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
5654 else if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (op_def)))
5656 /* Recurse through the type conversion, unless it is a narrowing
5657 conversion or conversion from non-integral type. */
5658 tree rhs = gimple_assign_rhs1 (op_def);
5659 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs))
5660 && (TYPE_PRECISION (TREE_TYPE (rhs))
5661 <= TYPE_PRECISION (TREE_TYPE (op))))
5662 register_edge_assert_for_1 (rhs, code, e, asserts);
5666 /* Check if comparison
5667 NAME COND_OP INTEGER_CST
5668 has a form of
5669 (X & 11...100..0) COND_OP XX...X00...0
5670 Such comparison can yield assertions like
5671 X >= XX...X00...0
5672 X <= XX...X11...1
5673 in case of COND_OP being NE_EXPR or
5674 X < XX...X00...0
5675 X > XX...X11...1
5676 in case of EQ_EXPR. */
5678 static bool
5679 is_masked_range_test (tree name, tree valt, enum tree_code cond_code,
5680 tree *new_name, tree *low, enum tree_code *low_code,
5681 tree *high, enum tree_code *high_code)
5683 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5685 if (!is_gimple_assign (def_stmt)
5686 || gimple_assign_rhs_code (def_stmt) != BIT_AND_EXPR)
5687 return false;
5689 tree t = gimple_assign_rhs1 (def_stmt);
5690 tree maskt = gimple_assign_rhs2 (def_stmt);
5691 if (TREE_CODE (t) != SSA_NAME || TREE_CODE (maskt) != INTEGER_CST)
5692 return false;
5694 wi::tree_to_wide_ref mask = wi::to_wide (maskt);
5695 wide_int inv_mask = ~mask;
5696 /* Assume VALT is INTEGER_CST. */
5697 wi::tree_to_wide_ref val = wi::to_wide (valt);
5699 if ((inv_mask & (inv_mask + 1)) != 0
5700 || (val & mask) != val)
5701 return false;
5703 bool is_range = cond_code == EQ_EXPR;
5705 tree type = TREE_TYPE (t);
5706 wide_int min = wi::min_value (type),
5707 max = wi::max_value (type);
5709 if (is_range)
5711 *low_code = val == min ? ERROR_MARK : GE_EXPR;
5712 *high_code = val == max ? ERROR_MARK : LE_EXPR;
5714 else
5716 /* We can still generate assertion if one of alternatives
5717 is known to always be false. */
5718 if (val == min)
5720 *low_code = (enum tree_code) 0;
5721 *high_code = GT_EXPR;
5723 else if ((val | inv_mask) == max)
5725 *low_code = LT_EXPR;
5726 *high_code = (enum tree_code) 0;
5728 else
5729 return false;
5732 *new_name = t;
5733 *low = wide_int_to_tree (type, val);
5734 *high = wide_int_to_tree (type, val | inv_mask);
5736 if (wi::neg_p (val, TYPE_SIGN (type)))
5737 std::swap (*low, *high);
5739 return true;
5742 /* Try to register an edge assertion for SSA name NAME on edge E for
5743 the condition COND contributing to the conditional jump pointed to by
5744 SI. */
5746 static void
5747 register_edge_assert_for (tree name, edge e,
5748 enum tree_code cond_code, tree cond_op0,
5749 tree cond_op1, vec<assert_info> &asserts)
5751 tree val;
5752 enum tree_code comp_code;
5753 bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
5755 /* Do not attempt to infer anything in names that flow through
5756 abnormal edges. */
5757 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
5758 return;
5760 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
5761 cond_op0, cond_op1,
5762 is_else_edge,
5763 &comp_code, &val))
5764 return;
5766 /* Register ASSERT_EXPRs for name. */
5767 register_edge_assert_for_2 (name, e, cond_code, cond_op0,
5768 cond_op1, is_else_edge, asserts);
5771 /* If COND is effectively an equality test of an SSA_NAME against
5772 the value zero or one, then we may be able to assert values
5773 for SSA_NAMEs which flow into COND. */
5775 /* In the case of NAME == 1 or NAME != 0, for BIT_AND_EXPR defining
5776 statement of NAME we can assert both operands of the BIT_AND_EXPR
5777 have nonzero value. */
5778 if (((comp_code == EQ_EXPR && integer_onep (val))
5779 || (comp_code == NE_EXPR && integer_zerop (val))))
5781 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5783 if (is_gimple_assign (def_stmt)
5784 && gimple_assign_rhs_code (def_stmt) == BIT_AND_EXPR)
5786 tree op0 = gimple_assign_rhs1 (def_stmt);
5787 tree op1 = gimple_assign_rhs2 (def_stmt);
5788 register_edge_assert_for_1 (op0, NE_EXPR, e, asserts);
5789 register_edge_assert_for_1 (op1, NE_EXPR, e, asserts);
5793 /* In the case of NAME == 0 or NAME != 1, for BIT_IOR_EXPR defining
5794 statement of NAME we can assert both operands of the BIT_IOR_EXPR
5795 have zero value. */
5796 if (((comp_code == EQ_EXPR && integer_zerop (val))
5797 || (comp_code == NE_EXPR && integer_onep (val))))
5799 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5801 /* For BIT_IOR_EXPR only if NAME == 0 both operands have
5802 necessarily zero value, or if type-precision is one. */
5803 if (is_gimple_assign (def_stmt)
5804 && (gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR
5805 && (TYPE_PRECISION (TREE_TYPE (name)) == 1
5806 || comp_code == EQ_EXPR)))
5808 tree op0 = gimple_assign_rhs1 (def_stmt);
5809 tree op1 = gimple_assign_rhs2 (def_stmt);
5810 register_edge_assert_for_1 (op0, EQ_EXPR, e, asserts);
5811 register_edge_assert_for_1 (op1, EQ_EXPR, e, asserts);
5815 /* Sometimes we can infer ranges from (NAME & MASK) == VALUE. */
5816 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
5817 && TREE_CODE (val) == INTEGER_CST)
5819 enum tree_code low_code, high_code;
5820 tree low, high;
5821 if (is_masked_range_test (name, val, comp_code, &name, &low,
5822 &low_code, &high, &high_code))
5824 if (low_code != ERROR_MARK)
5825 register_edge_assert_for_2 (name, e, low_code, name,
5826 low, /*invert*/false, asserts);
5827 if (high_code != ERROR_MARK)
5828 register_edge_assert_for_2 (name, e, high_code, name,
5829 high, /*invert*/false, asserts);
5834 /* Finish found ASSERTS for E and register them at GSI. */
5836 static void
5837 finish_register_edge_assert_for (edge e, gimple_stmt_iterator gsi,
5838 vec<assert_info> &asserts)
5840 for (unsigned i = 0; i < asserts.length (); ++i)
5841 /* Only register an ASSERT_EXPR if NAME was found in the sub-graph
5842 reachable from E. */
5843 if (live_on_edge (e, asserts[i].name))
5844 register_new_assert_for (asserts[i].name, asserts[i].expr,
5845 asserts[i].comp_code, asserts[i].val,
5846 NULL, e, gsi);
5851 /* Determine whether the outgoing edges of BB should receive an
5852 ASSERT_EXPR for each of the operands of BB's LAST statement.
5853 The last statement of BB must be a COND_EXPR.
5855 If any of the sub-graphs rooted at BB have an interesting use of
5856 the predicate operands, an assert location node is added to the
5857 list of assertions for the corresponding operands. */
5859 static void
5860 find_conditional_asserts (basic_block bb, gcond *last)
5862 gimple_stmt_iterator bsi;
5863 tree op;
5864 edge_iterator ei;
5865 edge e;
5866 ssa_op_iter iter;
5868 bsi = gsi_for_stmt (last);
5870 /* Look for uses of the operands in each of the sub-graphs
5871 rooted at BB. We need to check each of the outgoing edges
5872 separately, so that we know what kind of ASSERT_EXPR to
5873 insert. */
5874 FOR_EACH_EDGE (e, ei, bb->succs)
5876 if (e->dest == bb)
5877 continue;
5879 /* Register the necessary assertions for each operand in the
5880 conditional predicate. */
5881 auto_vec<assert_info, 8> asserts;
5882 FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
5883 register_edge_assert_for (op, e,
5884 gimple_cond_code (last),
5885 gimple_cond_lhs (last),
5886 gimple_cond_rhs (last), asserts);
5887 finish_register_edge_assert_for (e, bsi, asserts);
5891 struct case_info
5893 tree expr;
5894 basic_block bb;
5897 /* Compare two case labels sorting first by the destination bb index
5898 and then by the case value. */
5900 static int
5901 compare_case_labels (const void *p1, const void *p2)
5903 const struct case_info *ci1 = (const struct case_info *) p1;
5904 const struct case_info *ci2 = (const struct case_info *) p2;
5905 int idx1 = ci1->bb->index;
5906 int idx2 = ci2->bb->index;
5908 if (idx1 < idx2)
5909 return -1;
5910 else if (idx1 == idx2)
5912 /* Make sure the default label is first in a group. */
5913 if (!CASE_LOW (ci1->expr))
5914 return -1;
5915 else if (!CASE_LOW (ci2->expr))
5916 return 1;
5917 else
5918 return tree_int_cst_compare (CASE_LOW (ci1->expr),
5919 CASE_LOW (ci2->expr));
5921 else
5922 return 1;
5925 /* Determine whether the outgoing edges of BB should receive an
5926 ASSERT_EXPR for each of the operands of BB's LAST statement.
5927 The last statement of BB must be a SWITCH_EXPR.
5929 If any of the sub-graphs rooted at BB have an interesting use of
5930 the predicate operands, an assert location node is added to the
5931 list of assertions for the corresponding operands. */
5933 static void
5934 find_switch_asserts (basic_block bb, gswitch *last)
5936 gimple_stmt_iterator bsi;
5937 tree op;
5938 edge e;
5939 struct case_info *ci;
5940 size_t n = gimple_switch_num_labels (last);
5941 #if GCC_VERSION >= 4000
5942 unsigned int idx;
5943 #else
5944 /* Work around GCC 3.4 bug (PR 37086). */
5945 volatile unsigned int idx;
5946 #endif
5948 bsi = gsi_for_stmt (last);
5949 op = gimple_switch_index (last);
5950 if (TREE_CODE (op) != SSA_NAME)
5951 return;
5953 /* Build a vector of case labels sorted by destination label. */
5954 ci = XNEWVEC (struct case_info, n);
5955 for (idx = 0; idx < n; ++idx)
5957 ci[idx].expr = gimple_switch_label (last, idx);
5958 ci[idx].bb = label_to_block (CASE_LABEL (ci[idx].expr));
5960 edge default_edge = find_edge (bb, ci[0].bb);
5961 qsort (ci, n, sizeof (struct case_info), compare_case_labels);
5963 for (idx = 0; idx < n; ++idx)
5965 tree min, max;
5966 tree cl = ci[idx].expr;
5967 basic_block cbb = ci[idx].bb;
5969 min = CASE_LOW (cl);
5970 max = CASE_HIGH (cl);
5972 /* If there are multiple case labels with the same destination
5973 we need to combine them to a single value range for the edge. */
5974 if (idx + 1 < n && cbb == ci[idx + 1].bb)
5976 /* Skip labels until the last of the group. */
5977 do {
5978 ++idx;
5979 } while (idx < n && cbb == ci[idx].bb);
5980 --idx;
5982 /* Pick up the maximum of the case label range. */
5983 if (CASE_HIGH (ci[idx].expr))
5984 max = CASE_HIGH (ci[idx].expr);
5985 else
5986 max = CASE_LOW (ci[idx].expr);
5989 /* Can't extract a useful assertion out of a range that includes the
5990 default label. */
5991 if (min == NULL_TREE)
5992 continue;
5994 /* Find the edge to register the assert expr on. */
5995 e = find_edge (bb, cbb);
5997 /* Register the necessary assertions for the operand in the
5998 SWITCH_EXPR. */
5999 auto_vec<assert_info, 8> asserts;
6000 register_edge_assert_for (op, e,
6001 max ? GE_EXPR : EQ_EXPR,
6002 op, fold_convert (TREE_TYPE (op), min),
6003 asserts);
6004 if (max)
6005 register_edge_assert_for (op, e, LE_EXPR, op,
6006 fold_convert (TREE_TYPE (op), max),
6007 asserts);
6008 finish_register_edge_assert_for (e, bsi, asserts);
6011 XDELETEVEC (ci);
6013 if (!live_on_edge (default_edge, op))
6014 return;
6016 /* Now register along the default label assertions that correspond to the
6017 anti-range of each label. */
6018 int insertion_limit = PARAM_VALUE (PARAM_MAX_VRP_SWITCH_ASSERTIONS);
6019 if (insertion_limit == 0)
6020 return;
6022 /* We can't do this if the default case shares a label with another case. */
6023 tree default_cl = gimple_switch_default_label (last);
6024 for (idx = 1; idx < n; idx++)
6026 tree min, max;
6027 tree cl = gimple_switch_label (last, idx);
6028 if (CASE_LABEL (cl) == CASE_LABEL (default_cl))
6029 continue;
6031 min = CASE_LOW (cl);
6032 max = CASE_HIGH (cl);
6034 /* Combine contiguous case ranges to reduce the number of assertions
6035 to insert. */
6036 for (idx = idx + 1; idx < n; idx++)
6038 tree next_min, next_max;
6039 tree next_cl = gimple_switch_label (last, idx);
6040 if (CASE_LABEL (next_cl) == CASE_LABEL (default_cl))
6041 break;
6043 next_min = CASE_LOW (next_cl);
6044 next_max = CASE_HIGH (next_cl);
6046 wide_int difference = (wi::to_wide (next_min)
6047 - wi::to_wide (max ? max : min));
6048 if (wi::eq_p (difference, 1))
6049 max = next_max ? next_max : next_min;
6050 else
6051 break;
6053 idx--;
6055 if (max == NULL_TREE)
6057 /* Register the assertion OP != MIN. */
6058 auto_vec<assert_info, 8> asserts;
6059 min = fold_convert (TREE_TYPE (op), min);
6060 register_edge_assert_for (op, default_edge, NE_EXPR, op, min,
6061 asserts);
6062 finish_register_edge_assert_for (default_edge, bsi, asserts);
6064 else
6066 /* Register the assertion (unsigned)OP - MIN > (MAX - MIN),
6067 which will give OP the anti-range ~[MIN,MAX]. */
6068 tree uop = fold_convert (unsigned_type_for (TREE_TYPE (op)), op);
6069 min = fold_convert (TREE_TYPE (uop), min);
6070 max = fold_convert (TREE_TYPE (uop), max);
6072 tree lhs = fold_build2 (MINUS_EXPR, TREE_TYPE (uop), uop, min);
6073 tree rhs = int_const_binop (MINUS_EXPR, max, min);
6074 register_new_assert_for (op, lhs, GT_EXPR, rhs,
6075 NULL, default_edge, bsi);
6078 if (--insertion_limit == 0)
6079 break;
6084 /* Traverse all the statements in block BB looking for statements that
6085 may generate useful assertions for the SSA names in their operand.
6086 If a statement produces a useful assertion A for name N_i, then the
6087 list of assertions already generated for N_i is scanned to
6088 determine if A is actually needed.
6090 If N_i already had the assertion A at a location dominating the
6091 current location, then nothing needs to be done. Otherwise, the
6092 new location for A is recorded instead.
6094 1- For every statement S in BB, all the variables used by S are
6095 added to bitmap FOUND_IN_SUBGRAPH.
6097 2- If statement S uses an operand N in a way that exposes a known
6098 value range for N, then if N was not already generated by an
6099 ASSERT_EXPR, create a new assert location for N. For instance,
6100 if N is a pointer and the statement dereferences it, we can
6101 assume that N is not NULL.
6103 3- COND_EXPRs are a special case of #2. We can derive range
6104 information from the predicate but need to insert different
6105 ASSERT_EXPRs for each of the sub-graphs rooted at the
6106 conditional block. If the last statement of BB is a conditional
6107 expression of the form 'X op Y', then
6109 a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
6111 b) If the conditional is the only entry point to the sub-graph
6112 corresponding to the THEN_CLAUSE, recurse into it. On
6113 return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
6114 an ASSERT_EXPR is added for the corresponding variable.
6116 c) Repeat step (b) on the ELSE_CLAUSE.
6118 d) Mark X and Y in FOUND_IN_SUBGRAPH.
6120 For instance,
6122 if (a == 9)
6123 b = a;
6124 else
6125 b = c + 1;
6127 In this case, an assertion on the THEN clause is useful to
6128 determine that 'a' is always 9 on that edge. However, an assertion
6129 on the ELSE clause would be unnecessary.
6131 4- If BB does not end in a conditional expression, then we recurse
6132 into BB's dominator children.
6134 At the end of the recursive traversal, every SSA name will have a
6135 list of locations where ASSERT_EXPRs should be added. When a new
6136 location for name N is found, it is registered by calling
6137 register_new_assert_for. That function keeps track of all the
6138 registered assertions to prevent adding unnecessary assertions.
6139 For instance, if a pointer P_4 is dereferenced more than once in a
6140 dominator tree, only the location dominating all the dereference of
6141 P_4 will receive an ASSERT_EXPR. */
6143 static void
6144 find_assert_locations_1 (basic_block bb, sbitmap live)
6146 gimple *last;
6148 last = last_stmt (bb);
6150 /* If BB's last statement is a conditional statement involving integer
6151 operands, determine if we need to add ASSERT_EXPRs. */
6152 if (last
6153 && gimple_code (last) == GIMPLE_COND
6154 && !fp_predicate (last)
6155 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
6156 find_conditional_asserts (bb, as_a <gcond *> (last));
6158 /* If BB's last statement is a switch statement involving integer
6159 operands, determine if we need to add ASSERT_EXPRs. */
6160 if (last
6161 && gimple_code (last) == GIMPLE_SWITCH
6162 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
6163 find_switch_asserts (bb, as_a <gswitch *> (last));
6165 /* Traverse all the statements in BB marking used names and looking
6166 for statements that may infer assertions for their used operands. */
6167 for (gimple_stmt_iterator si = gsi_last_bb (bb); !gsi_end_p (si);
6168 gsi_prev (&si))
6170 gimple *stmt;
6171 tree op;
6172 ssa_op_iter i;
6174 stmt = gsi_stmt (si);
6176 if (is_gimple_debug (stmt))
6177 continue;
6179 /* See if we can derive an assertion for any of STMT's operands. */
6180 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
6182 tree value;
6183 enum tree_code comp_code;
6185 /* If op is not live beyond this stmt, do not bother to insert
6186 asserts for it. */
6187 if (!bitmap_bit_p (live, SSA_NAME_VERSION (op)))
6188 continue;
6190 /* If OP is used in such a way that we can infer a value
6191 range for it, and we don't find a previous assertion for
6192 it, create a new assertion location node for OP. */
6193 if (infer_value_range (stmt, op, &comp_code, &value))
6195 /* If we are able to infer a nonzero value range for OP,
6196 then walk backwards through the use-def chain to see if OP
6197 was set via a typecast.
6199 If so, then we can also infer a nonzero value range
6200 for the operand of the NOP_EXPR. */
6201 if (comp_code == NE_EXPR && integer_zerop (value))
6203 tree t = op;
6204 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
6206 while (is_gimple_assign (def_stmt)
6207 && CONVERT_EXPR_CODE_P
6208 (gimple_assign_rhs_code (def_stmt))
6209 && TREE_CODE
6210 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
6211 && POINTER_TYPE_P
6212 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
6214 t = gimple_assign_rhs1 (def_stmt);
6215 def_stmt = SSA_NAME_DEF_STMT (t);
6217 /* Note we want to register the assert for the
6218 operand of the NOP_EXPR after SI, not after the
6219 conversion. */
6220 if (bitmap_bit_p (live, SSA_NAME_VERSION (t)))
6221 register_new_assert_for (t, t, comp_code, value,
6222 bb, NULL, si);
6226 register_new_assert_for (op, op, comp_code, value, bb, NULL, si);
6230 /* Update live. */
6231 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
6232 bitmap_set_bit (live, SSA_NAME_VERSION (op));
6233 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_DEF)
6234 bitmap_clear_bit (live, SSA_NAME_VERSION (op));
6237 /* Traverse all PHI nodes in BB, updating live. */
6238 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
6239 gsi_next (&si))
6241 use_operand_p arg_p;
6242 ssa_op_iter i;
6243 gphi *phi = si.phi ();
6244 tree res = gimple_phi_result (phi);
6246 if (virtual_operand_p (res))
6247 continue;
6249 FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
6251 tree arg = USE_FROM_PTR (arg_p);
6252 if (TREE_CODE (arg) == SSA_NAME)
6253 bitmap_set_bit (live, SSA_NAME_VERSION (arg));
6256 bitmap_clear_bit (live, SSA_NAME_VERSION (res));
6260 /* Do an RPO walk over the function computing SSA name liveness
6261 on-the-fly and deciding on assert expressions to insert. */
6263 static void
6264 find_assert_locations (void)
6266 int *rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
6267 int *bb_rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
6268 int *last_rpo = XCNEWVEC (int, last_basic_block_for_fn (cfun));
6269 int rpo_cnt, i;
6271 live = XCNEWVEC (sbitmap, last_basic_block_for_fn (cfun));
6272 rpo_cnt = pre_and_rev_post_order_compute (NULL, rpo, false);
6273 for (i = 0; i < rpo_cnt; ++i)
6274 bb_rpo[rpo[i]] = i;
6276 /* Pre-seed loop latch liveness from loop header PHI nodes. Due to
6277 the order we compute liveness and insert asserts we otherwise
6278 fail to insert asserts into the loop latch. */
6279 loop_p loop;
6280 FOR_EACH_LOOP (loop, 0)
6282 i = loop->latch->index;
6283 unsigned int j = single_succ_edge (loop->latch)->dest_idx;
6284 for (gphi_iterator gsi = gsi_start_phis (loop->header);
6285 !gsi_end_p (gsi); gsi_next (&gsi))
6287 gphi *phi = gsi.phi ();
6288 if (virtual_operand_p (gimple_phi_result (phi)))
6289 continue;
6290 tree arg = gimple_phi_arg_def (phi, j);
6291 if (TREE_CODE (arg) == SSA_NAME)
6293 if (live[i] == NULL)
6295 live[i] = sbitmap_alloc (num_ssa_names);
6296 bitmap_clear (live[i]);
6298 bitmap_set_bit (live[i], SSA_NAME_VERSION (arg));
6303 for (i = rpo_cnt - 1; i >= 0; --i)
6305 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, rpo[i]);
6306 edge e;
6307 edge_iterator ei;
6309 if (!live[rpo[i]])
6311 live[rpo[i]] = sbitmap_alloc (num_ssa_names);
6312 bitmap_clear (live[rpo[i]]);
6315 /* Process BB and update the live information with uses in
6316 this block. */
6317 find_assert_locations_1 (bb, live[rpo[i]]);
6319 /* Merge liveness into the predecessor blocks and free it. */
6320 if (!bitmap_empty_p (live[rpo[i]]))
6322 int pred_rpo = i;
6323 FOR_EACH_EDGE (e, ei, bb->preds)
6325 int pred = e->src->index;
6326 if ((e->flags & EDGE_DFS_BACK) || pred == ENTRY_BLOCK)
6327 continue;
6329 if (!live[pred])
6331 live[pred] = sbitmap_alloc (num_ssa_names);
6332 bitmap_clear (live[pred]);
6334 bitmap_ior (live[pred], live[pred], live[rpo[i]]);
6336 if (bb_rpo[pred] < pred_rpo)
6337 pred_rpo = bb_rpo[pred];
6340 /* Record the RPO number of the last visited block that needs
6341 live information from this block. */
6342 last_rpo[rpo[i]] = pred_rpo;
6344 else
6346 sbitmap_free (live[rpo[i]]);
6347 live[rpo[i]] = NULL;
6350 /* We can free all successors live bitmaps if all their
6351 predecessors have been visited already. */
6352 FOR_EACH_EDGE (e, ei, bb->succs)
6353 if (last_rpo[e->dest->index] == i
6354 && live[e->dest->index])
6356 sbitmap_free (live[e->dest->index]);
6357 live[e->dest->index] = NULL;
6361 XDELETEVEC (rpo);
6362 XDELETEVEC (bb_rpo);
6363 XDELETEVEC (last_rpo);
6364 for (i = 0; i < last_basic_block_for_fn (cfun); ++i)
6365 if (live[i])
6366 sbitmap_free (live[i]);
6367 XDELETEVEC (live);
6370 /* Create an ASSERT_EXPR for NAME and insert it in the location
6371 indicated by LOC. Return true if we made any edge insertions. */
6373 static bool
6374 process_assert_insertions_for (tree name, assert_locus *loc)
6376 /* Build the comparison expression NAME_i COMP_CODE VAL. */
6377 gimple *stmt;
6378 tree cond;
6379 gimple *assert_stmt;
6380 edge_iterator ei;
6381 edge e;
6383 /* If we have X <=> X do not insert an assert expr for that. */
6384 if (loc->expr == loc->val)
6385 return false;
6387 cond = build2 (loc->comp_code, boolean_type_node, loc->expr, loc->val);
6388 assert_stmt = build_assert_expr_for (cond, name);
6389 if (loc->e)
6391 /* We have been asked to insert the assertion on an edge. This
6392 is used only by COND_EXPR and SWITCH_EXPR assertions. */
6393 gcc_checking_assert (gimple_code (gsi_stmt (loc->si)) == GIMPLE_COND
6394 || (gimple_code (gsi_stmt (loc->si))
6395 == GIMPLE_SWITCH));
6397 gsi_insert_on_edge (loc->e, assert_stmt);
6398 return true;
6401 /* If the stmt iterator points at the end then this is an insertion
6402 at the beginning of a block. */
6403 if (gsi_end_p (loc->si))
6405 gimple_stmt_iterator si = gsi_after_labels (loc->bb);
6406 gsi_insert_before (&si, assert_stmt, GSI_SAME_STMT);
6407 return false;
6410 /* Otherwise, we can insert right after LOC->SI iff the
6411 statement must not be the last statement in the block. */
6412 stmt = gsi_stmt (loc->si);
6413 if (!stmt_ends_bb_p (stmt))
6415 gsi_insert_after (&loc->si, assert_stmt, GSI_SAME_STMT);
6416 return false;
6419 /* If STMT must be the last statement in BB, we can only insert new
6420 assertions on the non-abnormal edge out of BB. Note that since
6421 STMT is not control flow, there may only be one non-abnormal/eh edge
6422 out of BB. */
6423 FOR_EACH_EDGE (e, ei, loc->bb->succs)
6424 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
6426 gsi_insert_on_edge (e, assert_stmt);
6427 return true;
6430 gcc_unreachable ();
6433 /* Qsort helper for sorting assert locations. If stable is true, don't
6434 use iterative_hash_expr because it can be unstable for -fcompare-debug,
6435 on the other side some pointers might be NULL. */
6437 template <bool stable>
6438 static int
6439 compare_assert_loc (const void *pa, const void *pb)
6441 assert_locus * const a = *(assert_locus * const *)pa;
6442 assert_locus * const b = *(assert_locus * const *)pb;
6444 /* If stable, some asserts might be optimized away already, sort
6445 them last. */
6446 if (stable)
6448 if (a == NULL)
6449 return b != NULL;
6450 else if (b == NULL)
6451 return -1;
6454 if (a->e == NULL && b->e != NULL)
6455 return 1;
6456 else if (a->e != NULL && b->e == NULL)
6457 return -1;
6459 /* After the above checks, we know that (a->e == NULL) == (b->e == NULL),
6460 no need to test both a->e and b->e. */
6462 /* Sort after destination index. */
6463 if (a->e == NULL)
6465 else if (a->e->dest->index > b->e->dest->index)
6466 return 1;
6467 else if (a->e->dest->index < b->e->dest->index)
6468 return -1;
6470 /* Sort after comp_code. */
6471 if (a->comp_code > b->comp_code)
6472 return 1;
6473 else if (a->comp_code < b->comp_code)
6474 return -1;
6476 hashval_t ha, hb;
6478 /* E.g. if a->val is ADDR_EXPR of a VAR_DECL, iterative_hash_expr
6479 uses DECL_UID of the VAR_DECL, so sorting might differ between
6480 -g and -g0. When doing the removal of redundant assert exprs
6481 and commonization to successors, this does not matter, but for
6482 the final sort needs to be stable. */
6483 if (stable)
6485 ha = 0;
6486 hb = 0;
6488 else
6490 ha = iterative_hash_expr (a->expr, iterative_hash_expr (a->val, 0));
6491 hb = iterative_hash_expr (b->expr, iterative_hash_expr (b->val, 0));
6494 /* Break the tie using hashing and source/bb index. */
6495 if (ha == hb)
6496 return (a->e != NULL
6497 ? a->e->src->index - b->e->src->index
6498 : a->bb->index - b->bb->index);
6499 return ha > hb ? 1 : -1;
6502 /* Process all the insertions registered for every name N_i registered
6503 in NEED_ASSERT_FOR. The list of assertions to be inserted are
6504 found in ASSERTS_FOR[i]. */
6506 static void
6507 process_assert_insertions (void)
6509 unsigned i;
6510 bitmap_iterator bi;
6511 bool update_edges_p = false;
6512 int num_asserts = 0;
6514 if (dump_file && (dump_flags & TDF_DETAILS))
6515 dump_all_asserts (dump_file);
6517 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
6519 assert_locus *loc = asserts_for[i];
6520 gcc_assert (loc);
6522 auto_vec<assert_locus *, 16> asserts;
6523 for (; loc; loc = loc->next)
6524 asserts.safe_push (loc);
6525 asserts.qsort (compare_assert_loc<false>);
6527 /* Push down common asserts to successors and remove redundant ones. */
6528 unsigned ecnt = 0;
6529 assert_locus *common = NULL;
6530 unsigned commonj = 0;
6531 for (unsigned j = 0; j < asserts.length (); ++j)
6533 loc = asserts[j];
6534 if (! loc->e)
6535 common = NULL;
6536 else if (! common
6537 || loc->e->dest != common->e->dest
6538 || loc->comp_code != common->comp_code
6539 || ! operand_equal_p (loc->val, common->val, 0)
6540 || ! operand_equal_p (loc->expr, common->expr, 0))
6542 commonj = j;
6543 common = loc;
6544 ecnt = 1;
6546 else if (loc->e == asserts[j-1]->e)
6548 /* Remove duplicate asserts. */
6549 if (commonj == j - 1)
6551 commonj = j;
6552 common = loc;
6554 free (asserts[j-1]);
6555 asserts[j-1] = NULL;
6557 else
6559 ecnt++;
6560 if (EDGE_COUNT (common->e->dest->preds) == ecnt)
6562 /* We have the same assertion on all incoming edges of a BB.
6563 Insert it at the beginning of that block. */
6564 loc->bb = loc->e->dest;
6565 loc->e = NULL;
6566 loc->si = gsi_none ();
6567 common = NULL;
6568 /* Clear asserts commoned. */
6569 for (; commonj != j; ++commonj)
6570 if (asserts[commonj])
6572 free (asserts[commonj]);
6573 asserts[commonj] = NULL;
6579 /* The asserts vector sorting above might be unstable for
6580 -fcompare-debug, sort again to ensure a stable sort. */
6581 asserts.qsort (compare_assert_loc<true>);
6582 for (unsigned j = 0; j < asserts.length (); ++j)
6584 loc = asserts[j];
6585 if (! loc)
6586 break;
6587 update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
6588 num_asserts++;
6589 free (loc);
6593 if (update_edges_p)
6594 gsi_commit_edge_inserts ();
6596 statistics_counter_event (cfun, "Number of ASSERT_EXPR expressions inserted",
6597 num_asserts);
6601 /* Traverse the flowgraph looking for conditional jumps to insert range
6602 expressions. These range expressions are meant to provide information
6603 to optimizations that need to reason in terms of value ranges. They
6604 will not be expanded into RTL. For instance, given:
6606 x = ...
6607 y = ...
6608 if (x < y)
6609 y = x - 2;
6610 else
6611 x = y + 3;
6613 this pass will transform the code into:
6615 x = ...
6616 y = ...
6617 if (x < y)
6619 x = ASSERT_EXPR <x, x < y>
6620 y = x - 2
6622 else
6624 y = ASSERT_EXPR <y, x >= y>
6625 x = y + 3
6628 The idea is that once copy and constant propagation have run, other
6629 optimizations will be able to determine what ranges of values can 'x'
6630 take in different paths of the code, simply by checking the reaching
6631 definition of 'x'. */
6633 static void
6634 insert_range_assertions (void)
6636 need_assert_for = BITMAP_ALLOC (NULL);
6637 asserts_for = XCNEWVEC (assert_locus *, num_ssa_names);
6639 calculate_dominance_info (CDI_DOMINATORS);
6641 find_assert_locations ();
6642 if (!bitmap_empty_p (need_assert_for))
6644 process_assert_insertions ();
6645 update_ssa (TODO_update_ssa_no_phi);
6648 if (dump_file && (dump_flags & TDF_DETAILS))
6650 fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
6651 dump_function_to_file (current_function_decl, dump_file, dump_flags);
6654 free (asserts_for);
6655 BITMAP_FREE (need_assert_for);
6658 /* Checks one ARRAY_REF in REF, located at LOCUS. Ignores flexible arrays
6659 and "struct" hacks. If VRP can determine that the
6660 array subscript is a constant, check if it is outside valid
6661 range. If the array subscript is a RANGE, warn if it is
6662 non-overlapping with valid range.
6663 IGNORE_OFF_BY_ONE is true if the ARRAY_REF is inside a ADDR_EXPR. */
6665 static void
6666 check_array_ref (location_t location, tree ref, bool ignore_off_by_one)
6668 value_range *vr = NULL;
6669 tree low_sub, up_sub;
6670 tree low_bound, up_bound, up_bound_p1;
6672 if (TREE_NO_WARNING (ref))
6673 return;
6675 low_sub = up_sub = TREE_OPERAND (ref, 1);
6676 up_bound = array_ref_up_bound (ref);
6678 /* Can not check flexible arrays. */
6679 if (!up_bound
6680 || TREE_CODE (up_bound) != INTEGER_CST)
6681 return;
6683 /* Accesses to trailing arrays via pointers may access storage
6684 beyond the types array bounds. */
6685 if (warn_array_bounds < 2
6686 && array_at_struct_end_p (ref))
6687 return;
6689 low_bound = array_ref_low_bound (ref);
6690 up_bound_p1 = int_const_binop (PLUS_EXPR, up_bound,
6691 build_int_cst (TREE_TYPE (up_bound), 1));
6693 /* Empty array. */
6694 if (tree_int_cst_equal (low_bound, up_bound_p1))
6696 warning_at (location, OPT_Warray_bounds,
6697 "array subscript is above array bounds");
6698 TREE_NO_WARNING (ref) = 1;
6701 if (TREE_CODE (low_sub) == SSA_NAME)
6703 vr = get_value_range (low_sub);
6704 if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
6706 low_sub = vr->type == VR_RANGE ? vr->max : vr->min;
6707 up_sub = vr->type == VR_RANGE ? vr->min : vr->max;
6711 if (vr && vr->type == VR_ANTI_RANGE)
6713 if (TREE_CODE (up_sub) == INTEGER_CST
6714 && (ignore_off_by_one
6715 ? tree_int_cst_lt (up_bound, up_sub)
6716 : tree_int_cst_le (up_bound, up_sub))
6717 && TREE_CODE (low_sub) == INTEGER_CST
6718 && tree_int_cst_le (low_sub, low_bound))
6720 warning_at (location, OPT_Warray_bounds,
6721 "array subscript is outside array bounds");
6722 TREE_NO_WARNING (ref) = 1;
6725 else if (TREE_CODE (up_sub) == INTEGER_CST
6726 && (ignore_off_by_one
6727 ? !tree_int_cst_le (up_sub, up_bound_p1)
6728 : !tree_int_cst_le (up_sub, up_bound)))
6730 if (dump_file && (dump_flags & TDF_DETAILS))
6732 fprintf (dump_file, "Array bound warning for ");
6733 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
6734 fprintf (dump_file, "\n");
6736 warning_at (location, OPT_Warray_bounds,
6737 "array subscript is above array bounds");
6738 TREE_NO_WARNING (ref) = 1;
6740 else if (TREE_CODE (low_sub) == INTEGER_CST
6741 && tree_int_cst_lt (low_sub, low_bound))
6743 if (dump_file && (dump_flags & TDF_DETAILS))
6745 fprintf (dump_file, "Array bound warning for ");
6746 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
6747 fprintf (dump_file, "\n");
6749 warning_at (location, OPT_Warray_bounds,
6750 "array subscript is below array bounds");
6751 TREE_NO_WARNING (ref) = 1;
6755 /* Searches if the expr T, located at LOCATION computes
6756 address of an ARRAY_REF, and call check_array_ref on it. */
6758 static void
6759 search_for_addr_array (tree t, location_t location)
6761 /* Check each ARRAY_REFs in the reference chain. */
6764 if (TREE_CODE (t) == ARRAY_REF)
6765 check_array_ref (location, t, true /*ignore_off_by_one*/);
6767 t = TREE_OPERAND (t, 0);
6769 while (handled_component_p (t));
6771 if (TREE_CODE (t) == MEM_REF
6772 && TREE_CODE (TREE_OPERAND (t, 0)) == ADDR_EXPR
6773 && !TREE_NO_WARNING (t))
6775 tree tem = TREE_OPERAND (TREE_OPERAND (t, 0), 0);
6776 tree low_bound, up_bound, el_sz;
6777 offset_int idx;
6778 if (TREE_CODE (TREE_TYPE (tem)) != ARRAY_TYPE
6779 || TREE_CODE (TREE_TYPE (TREE_TYPE (tem))) == ARRAY_TYPE
6780 || !TYPE_DOMAIN (TREE_TYPE (tem)))
6781 return;
6783 low_bound = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
6784 up_bound = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
6785 el_sz = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (tem)));
6786 if (!low_bound
6787 || TREE_CODE (low_bound) != INTEGER_CST
6788 || !up_bound
6789 || TREE_CODE (up_bound) != INTEGER_CST
6790 || !el_sz
6791 || TREE_CODE (el_sz) != INTEGER_CST)
6792 return;
6794 idx = mem_ref_offset (t);
6795 idx = wi::sdiv_trunc (idx, wi::to_offset (el_sz));
6796 if (idx < 0)
6798 if (dump_file && (dump_flags & TDF_DETAILS))
6800 fprintf (dump_file, "Array bound warning for ");
6801 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
6802 fprintf (dump_file, "\n");
6804 warning_at (location, OPT_Warray_bounds,
6805 "array subscript is below array bounds");
6806 TREE_NO_WARNING (t) = 1;
6808 else if (idx > (wi::to_offset (up_bound)
6809 - wi::to_offset (low_bound) + 1))
6811 if (dump_file && (dump_flags & TDF_DETAILS))
6813 fprintf (dump_file, "Array bound warning for ");
6814 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
6815 fprintf (dump_file, "\n");
6817 warning_at (location, OPT_Warray_bounds,
6818 "array subscript is above array bounds");
6819 TREE_NO_WARNING (t) = 1;
6824 /* walk_tree() callback that checks if *TP is
6825 an ARRAY_REF inside an ADDR_EXPR (in which an array
6826 subscript one outside the valid range is allowed). Call
6827 check_array_ref for each ARRAY_REF found. The location is
6828 passed in DATA. */
6830 static tree
6831 check_array_bounds (tree *tp, int *walk_subtree, void *data)
6833 tree t = *tp;
6834 struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
6835 location_t location;
6837 if (EXPR_HAS_LOCATION (t))
6838 location = EXPR_LOCATION (t);
6839 else
6841 location_t *locp = (location_t *) wi->info;
6842 location = *locp;
6845 *walk_subtree = TRUE;
6847 if (TREE_CODE (t) == ARRAY_REF)
6848 check_array_ref (location, t, false /*ignore_off_by_one*/);
6850 else if (TREE_CODE (t) == ADDR_EXPR)
6852 search_for_addr_array (t, location);
6853 *walk_subtree = FALSE;
6856 return NULL_TREE;
6859 /* Walk over all statements of all reachable BBs and call check_array_bounds
6860 on them. */
6862 static void
6863 check_all_array_refs (void)
6865 basic_block bb;
6866 gimple_stmt_iterator si;
6868 FOR_EACH_BB_FN (bb, cfun)
6870 edge_iterator ei;
6871 edge e;
6872 bool executable = false;
6874 /* Skip blocks that were found to be unreachable. */
6875 FOR_EACH_EDGE (e, ei, bb->preds)
6876 executable |= !!(e->flags & EDGE_EXECUTABLE);
6877 if (!executable)
6878 continue;
6880 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
6882 gimple *stmt = gsi_stmt (si);
6883 struct walk_stmt_info wi;
6884 if (!gimple_has_location (stmt)
6885 || is_gimple_debug (stmt))
6886 continue;
6888 memset (&wi, 0, sizeof (wi));
6890 location_t loc = gimple_location (stmt);
6891 wi.info = &loc;
6893 walk_gimple_op (gsi_stmt (si),
6894 check_array_bounds,
6895 &wi);
6900 /* Return true if all imm uses of VAR are either in STMT, or
6901 feed (optionally through a chain of single imm uses) GIMPLE_COND
6902 in basic block COND_BB. */
6904 static bool
6905 all_imm_uses_in_stmt_or_feed_cond (tree var, gimple *stmt, basic_block cond_bb)
6907 use_operand_p use_p, use2_p;
6908 imm_use_iterator iter;
6910 FOR_EACH_IMM_USE_FAST (use_p, iter, var)
6911 if (USE_STMT (use_p) != stmt)
6913 gimple *use_stmt = USE_STMT (use_p), *use_stmt2;
6914 if (is_gimple_debug (use_stmt))
6915 continue;
6916 while (is_gimple_assign (use_stmt)
6917 && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
6918 && single_imm_use (gimple_assign_lhs (use_stmt),
6919 &use2_p, &use_stmt2))
6920 use_stmt = use_stmt2;
6921 if (gimple_code (use_stmt) != GIMPLE_COND
6922 || gimple_bb (use_stmt) != cond_bb)
6923 return false;
6925 return true;
6928 /* Handle
6929 _4 = x_3 & 31;
6930 if (_4 != 0)
6931 goto <bb 6>;
6932 else
6933 goto <bb 7>;
6934 <bb 6>:
6935 __builtin_unreachable ();
6936 <bb 7>:
6937 x_5 = ASSERT_EXPR <x_3, ...>;
6938 If x_3 has no other immediate uses (checked by caller),
6939 var is the x_3 var from ASSERT_EXPR, we can clear low 5 bits
6940 from the non-zero bitmask. */
6942 static void
6943 maybe_set_nonzero_bits (basic_block bb, tree var)
6945 edge e = single_pred_edge (bb);
6946 basic_block cond_bb = e->src;
6947 gimple *stmt = last_stmt (cond_bb);
6948 tree cst;
6950 if (stmt == NULL
6951 || gimple_code (stmt) != GIMPLE_COND
6952 || gimple_cond_code (stmt) != ((e->flags & EDGE_TRUE_VALUE)
6953 ? EQ_EXPR : NE_EXPR)
6954 || TREE_CODE (gimple_cond_lhs (stmt)) != SSA_NAME
6955 || !integer_zerop (gimple_cond_rhs (stmt)))
6956 return;
6958 stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt));
6959 if (!is_gimple_assign (stmt)
6960 || gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
6961 || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
6962 return;
6963 if (gimple_assign_rhs1 (stmt) != var)
6965 gimple *stmt2;
6967 if (TREE_CODE (gimple_assign_rhs1 (stmt)) != SSA_NAME)
6968 return;
6969 stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
6970 if (!gimple_assign_cast_p (stmt2)
6971 || gimple_assign_rhs1 (stmt2) != var
6972 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt2))
6973 || (TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (stmt)))
6974 != TYPE_PRECISION (TREE_TYPE (var))))
6975 return;
6977 cst = gimple_assign_rhs2 (stmt);
6978 set_nonzero_bits (var, wi::bit_and_not (get_nonzero_bits (var),
6979 wi::to_wide (cst)));
6982 /* Convert range assertion expressions into the implied copies and
6983 copy propagate away the copies. Doing the trivial copy propagation
6984 here avoids the need to run the full copy propagation pass after
6985 VRP.
6987 FIXME, this will eventually lead to copy propagation removing the
6988 names that had useful range information attached to them. For
6989 instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
6990 then N_i will have the range [3, +INF].
6992 However, by converting the assertion into the implied copy
6993 operation N_i = N_j, we will then copy-propagate N_j into the uses
6994 of N_i and lose the range information. We may want to hold on to
6995 ASSERT_EXPRs a little while longer as the ranges could be used in
6996 things like jump threading.
6998 The problem with keeping ASSERT_EXPRs around is that passes after
6999 VRP need to handle them appropriately.
7001 Another approach would be to make the range information a first
7002 class property of the SSA_NAME so that it can be queried from
7003 any pass. This is made somewhat more complex by the need for
7004 multiple ranges to be associated with one SSA_NAME. */
7006 static void
7007 remove_range_assertions (void)
7009 basic_block bb;
7010 gimple_stmt_iterator si;
7011 /* 1 if looking at ASSERT_EXPRs immediately at the beginning of
7012 a basic block preceeded by GIMPLE_COND branching to it and
7013 __builtin_trap, -1 if not yet checked, 0 otherwise. */
7014 int is_unreachable;
7016 /* Note that the BSI iterator bump happens at the bottom of the
7017 loop and no bump is necessary if we're removing the statement
7018 referenced by the current BSI. */
7019 FOR_EACH_BB_FN (bb, cfun)
7020 for (si = gsi_after_labels (bb), is_unreachable = -1; !gsi_end_p (si);)
7022 gimple *stmt = gsi_stmt (si);
7024 if (is_gimple_assign (stmt)
7025 && gimple_assign_rhs_code (stmt) == ASSERT_EXPR)
7027 tree lhs = gimple_assign_lhs (stmt);
7028 tree rhs = gimple_assign_rhs1 (stmt);
7029 tree var;
7031 var = ASSERT_EXPR_VAR (rhs);
7033 if (TREE_CODE (var) == SSA_NAME
7034 && !POINTER_TYPE_P (TREE_TYPE (lhs))
7035 && SSA_NAME_RANGE_INFO (lhs))
7037 if (is_unreachable == -1)
7039 is_unreachable = 0;
7040 if (single_pred_p (bb)
7041 && assert_unreachable_fallthru_edge_p
7042 (single_pred_edge (bb)))
7043 is_unreachable = 1;
7045 /* Handle
7046 if (x_7 >= 10 && x_7 < 20)
7047 __builtin_unreachable ();
7048 x_8 = ASSERT_EXPR <x_7, ...>;
7049 if the only uses of x_7 are in the ASSERT_EXPR and
7050 in the condition. In that case, we can copy the
7051 range info from x_8 computed in this pass also
7052 for x_7. */
7053 if (is_unreachable
7054 && all_imm_uses_in_stmt_or_feed_cond (var, stmt,
7055 single_pred (bb)))
7057 set_range_info (var, SSA_NAME_RANGE_TYPE (lhs),
7058 SSA_NAME_RANGE_INFO (lhs)->get_min (),
7059 SSA_NAME_RANGE_INFO (lhs)->get_max ());
7060 maybe_set_nonzero_bits (bb, var);
7064 /* Propagate the RHS into every use of the LHS. For SSA names
7065 also propagate abnormals as it merely restores the original
7066 IL in this case (an replace_uses_by would assert). */
7067 if (TREE_CODE (var) == SSA_NAME)
7069 imm_use_iterator iter;
7070 use_operand_p use_p;
7071 gimple *use_stmt;
7072 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
7073 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
7074 SET_USE (use_p, var);
7076 else
7077 replace_uses_by (lhs, var);
7079 /* And finally, remove the copy, it is not needed. */
7080 gsi_remove (&si, true);
7081 release_defs (stmt);
7083 else
7085 if (!is_gimple_debug (gsi_stmt (si)))
7086 is_unreachable = 0;
7087 gsi_next (&si);
7093 /* Return true if STMT is interesting for VRP. */
7095 static bool
7096 stmt_interesting_for_vrp (gimple *stmt)
7098 if (gimple_code (stmt) == GIMPLE_PHI)
7100 tree res = gimple_phi_result (stmt);
7101 return (!virtual_operand_p (res)
7102 && (INTEGRAL_TYPE_P (TREE_TYPE (res))
7103 || POINTER_TYPE_P (TREE_TYPE (res))));
7105 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
7107 tree lhs = gimple_get_lhs (stmt);
7109 /* In general, assignments with virtual operands are not useful
7110 for deriving ranges, with the obvious exception of calls to
7111 builtin functions. */
7112 if (lhs && TREE_CODE (lhs) == SSA_NAME
7113 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
7114 || POINTER_TYPE_P (TREE_TYPE (lhs)))
7115 && (is_gimple_call (stmt)
7116 || !gimple_vuse (stmt)))
7117 return true;
7118 else if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
7119 switch (gimple_call_internal_fn (stmt))
7121 case IFN_ADD_OVERFLOW:
7122 case IFN_SUB_OVERFLOW:
7123 case IFN_MUL_OVERFLOW:
7124 case IFN_ATOMIC_COMPARE_EXCHANGE:
7125 /* These internal calls return _Complex integer type,
7126 but are interesting to VRP nevertheless. */
7127 if (lhs && TREE_CODE (lhs) == SSA_NAME)
7128 return true;
7129 break;
7130 default:
7131 break;
7134 else if (gimple_code (stmt) == GIMPLE_COND
7135 || gimple_code (stmt) == GIMPLE_SWITCH)
7136 return true;
7138 return false;
7141 /* Initialize VRP lattice. */
7143 static void
7144 vrp_initialize_lattice ()
7146 values_propagated = false;
7147 num_vr_values = num_ssa_names;
7148 vr_value = XCNEWVEC (value_range *, num_vr_values);
7149 vr_phi_edge_counts = XCNEWVEC (int, num_ssa_names);
7150 bitmap_obstack_initialize (&vrp_equiv_obstack);
7153 /* Initialization required by ssa_propagate engine. */
7155 static void
7156 vrp_initialize ()
7158 basic_block bb;
7160 FOR_EACH_BB_FN (bb, cfun)
7162 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
7163 gsi_next (&si))
7165 gphi *phi = si.phi ();
7166 if (!stmt_interesting_for_vrp (phi))
7168 tree lhs = PHI_RESULT (phi);
7169 set_value_range_to_varying (get_value_range (lhs));
7170 prop_set_simulate_again (phi, false);
7172 else
7173 prop_set_simulate_again (phi, true);
7176 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
7177 gsi_next (&si))
7179 gimple *stmt = gsi_stmt (si);
7181 /* If the statement is a control insn, then we do not
7182 want to avoid simulating the statement once. Failure
7183 to do so means that those edges will never get added. */
7184 if (stmt_ends_bb_p (stmt))
7185 prop_set_simulate_again (stmt, true);
7186 else if (!stmt_interesting_for_vrp (stmt))
7188 set_defs_to_varying (stmt);
7189 prop_set_simulate_again (stmt, false);
7191 else
7192 prop_set_simulate_again (stmt, true);
7197 /* Return the singleton value-range for NAME or NAME. */
7199 static inline tree
7200 vrp_valueize (tree name)
7202 if (TREE_CODE (name) == SSA_NAME)
7204 value_range *vr = get_value_range (name);
7205 if (vr->type == VR_RANGE
7206 && (TREE_CODE (vr->min) == SSA_NAME
7207 || is_gimple_min_invariant (vr->min))
7208 && vrp_operand_equal_p (vr->min, vr->max))
7209 return vr->min;
7211 return name;
7214 /* Return the singleton value-range for NAME if that is a constant
7215 but signal to not follow SSA edges. */
7217 static inline tree
7218 vrp_valueize_1 (tree name)
7220 if (TREE_CODE (name) == SSA_NAME)
7222 /* If the definition may be simulated again we cannot follow
7223 this SSA edge as the SSA propagator does not necessarily
7224 re-visit the use. */
7225 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
7226 if (!gimple_nop_p (def_stmt)
7227 && prop_simulate_again_p (def_stmt))
7228 return NULL_TREE;
7229 value_range *vr = get_value_range (name);
7230 if (range_int_cst_singleton_p (vr))
7231 return vr->min;
7233 return name;
7236 /* Visit assignment STMT. If it produces an interesting range, record
7237 the range in VR and set LHS to OUTPUT_P. */
7239 static void
7240 vrp_visit_assignment_or_call (gimple *stmt, tree *output_p, value_range *vr)
7242 tree lhs;
7243 enum gimple_code code = gimple_code (stmt);
7244 lhs = gimple_get_lhs (stmt);
7245 *output_p = NULL_TREE;
7247 /* We only keep track of ranges in integral and pointer types. */
7248 if (TREE_CODE (lhs) == SSA_NAME
7249 && ((INTEGRAL_TYPE_P (TREE_TYPE (lhs))
7250 /* It is valid to have NULL MIN/MAX values on a type. See
7251 build_range_type. */
7252 && TYPE_MIN_VALUE (TREE_TYPE (lhs))
7253 && TYPE_MAX_VALUE (TREE_TYPE (lhs)))
7254 || POINTER_TYPE_P (TREE_TYPE (lhs))))
7256 *output_p = lhs;
7258 /* Try folding the statement to a constant first. */
7259 tree tem = gimple_fold_stmt_to_constant_1 (stmt, vrp_valueize,
7260 vrp_valueize_1);
7261 if (tem)
7263 if (TREE_CODE (tem) == SSA_NAME
7264 && (SSA_NAME_IS_DEFAULT_DEF (tem)
7265 || ! prop_simulate_again_p (SSA_NAME_DEF_STMT (tem))))
7267 extract_range_from_ssa_name (vr, tem);
7268 return;
7270 else if (is_gimple_min_invariant (tem))
7272 set_value_range_to_value (vr, tem, NULL);
7273 return;
7276 /* Then dispatch to value-range extracting functions. */
7277 if (code == GIMPLE_CALL)
7278 extract_range_basic (vr, stmt);
7279 else
7280 extract_range_from_assignment (vr, as_a <gassign *> (stmt));
7284 /* Helper that gets the value range of the SSA_NAME with version I
7285 or a symbolic range containing the SSA_NAME only if the value range
7286 is varying or undefined. */
7288 static inline value_range
7289 get_vr_for_comparison (int i)
7291 value_range vr = *get_value_range (ssa_name (i));
7293 /* If name N_i does not have a valid range, use N_i as its own
7294 range. This allows us to compare against names that may
7295 have N_i in their ranges. */
7296 if (vr.type == VR_VARYING || vr.type == VR_UNDEFINED)
7298 vr.type = VR_RANGE;
7299 vr.min = ssa_name (i);
7300 vr.max = ssa_name (i);
7303 return vr;
7306 /* Compare all the value ranges for names equivalent to VAR with VAL
7307 using comparison code COMP. Return the same value returned by
7308 compare_range_with_value, including the setting of
7309 *STRICT_OVERFLOW_P. */
7311 static tree
7312 compare_name_with_value (enum tree_code comp, tree var, tree val,
7313 bool *strict_overflow_p, bool use_equiv_p)
7315 bitmap_iterator bi;
7316 unsigned i;
7317 bitmap e;
7318 tree retval, t;
7319 int used_strict_overflow;
7320 bool sop;
7321 value_range equiv_vr;
7323 /* Get the set of equivalences for VAR. */
7324 e = get_value_range (var)->equiv;
7326 /* Start at -1. Set it to 0 if we do a comparison without relying
7327 on overflow, or 1 if all comparisons rely on overflow. */
7328 used_strict_overflow = -1;
7330 /* Compare vars' value range with val. */
7331 equiv_vr = get_vr_for_comparison (SSA_NAME_VERSION (var));
7332 sop = false;
7333 retval = compare_range_with_value (comp, &equiv_vr, val, &sop);
7334 if (retval)
7335 used_strict_overflow = sop ? 1 : 0;
7337 /* If the equiv set is empty we have done all work we need to do. */
7338 if (e == NULL)
7340 if (retval
7341 && used_strict_overflow > 0)
7342 *strict_overflow_p = true;
7343 return retval;
7346 EXECUTE_IF_SET_IN_BITMAP (e, 0, i, bi)
7348 tree name = ssa_name (i);
7349 if (! name)
7350 continue;
7352 if (! use_equiv_p
7353 && ! SSA_NAME_IS_DEFAULT_DEF (name)
7354 && prop_simulate_again_p (SSA_NAME_DEF_STMT (name)))
7355 continue;
7357 equiv_vr = get_vr_for_comparison (i);
7358 sop = false;
7359 t = compare_range_with_value (comp, &equiv_vr, val, &sop);
7360 if (t)
7362 /* If we get different answers from different members
7363 of the equivalence set this check must be in a dead
7364 code region. Folding it to a trap representation
7365 would be correct here. For now just return don't-know. */
7366 if (retval != NULL
7367 && t != retval)
7369 retval = NULL_TREE;
7370 break;
7372 retval = t;
7374 if (!sop)
7375 used_strict_overflow = 0;
7376 else if (used_strict_overflow < 0)
7377 used_strict_overflow = 1;
7381 if (retval
7382 && used_strict_overflow > 0)
7383 *strict_overflow_p = true;
7385 return retval;
7389 /* Given a comparison code COMP and names N1 and N2, compare all the
7390 ranges equivalent to N1 against all the ranges equivalent to N2
7391 to determine the value of N1 COMP N2. Return the same value
7392 returned by compare_ranges. Set *STRICT_OVERFLOW_P to indicate
7393 whether we relied on undefined signed overflow in the comparison. */
7396 static tree
7397 compare_names (enum tree_code comp, tree n1, tree n2,
7398 bool *strict_overflow_p)
7400 tree t, retval;
7401 bitmap e1, e2;
7402 bitmap_iterator bi1, bi2;
7403 unsigned i1, i2;
7404 int used_strict_overflow;
7405 static bitmap_obstack *s_obstack = NULL;
7406 static bitmap s_e1 = NULL, s_e2 = NULL;
7408 /* Compare the ranges of every name equivalent to N1 against the
7409 ranges of every name equivalent to N2. */
7410 e1 = get_value_range (n1)->equiv;
7411 e2 = get_value_range (n2)->equiv;
7413 /* Use the fake bitmaps if e1 or e2 are not available. */
7414 if (s_obstack == NULL)
7416 s_obstack = XNEW (bitmap_obstack);
7417 bitmap_obstack_initialize (s_obstack);
7418 s_e1 = BITMAP_ALLOC (s_obstack);
7419 s_e2 = BITMAP_ALLOC (s_obstack);
7421 if (e1 == NULL)
7422 e1 = s_e1;
7423 if (e2 == NULL)
7424 e2 = s_e2;
7426 /* Add N1 and N2 to their own set of equivalences to avoid
7427 duplicating the body of the loop just to check N1 and N2
7428 ranges. */
7429 bitmap_set_bit (e1, SSA_NAME_VERSION (n1));
7430 bitmap_set_bit (e2, SSA_NAME_VERSION (n2));
7432 /* If the equivalence sets have a common intersection, then the two
7433 names can be compared without checking their ranges. */
7434 if (bitmap_intersect_p (e1, e2))
7436 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7437 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7439 return (comp == EQ_EXPR || comp == GE_EXPR || comp == LE_EXPR)
7440 ? boolean_true_node
7441 : boolean_false_node;
7444 /* Start at -1. Set it to 0 if we do a comparison without relying
7445 on overflow, or 1 if all comparisons rely on overflow. */
7446 used_strict_overflow = -1;
7448 /* Otherwise, compare all the equivalent ranges. First, add N1 and
7449 N2 to their own set of equivalences to avoid duplicating the body
7450 of the loop just to check N1 and N2 ranges. */
7451 EXECUTE_IF_SET_IN_BITMAP (e1, 0, i1, bi1)
7453 if (! ssa_name (i1))
7454 continue;
7456 value_range vr1 = get_vr_for_comparison (i1);
7458 t = retval = NULL_TREE;
7459 EXECUTE_IF_SET_IN_BITMAP (e2, 0, i2, bi2)
7461 if (! ssa_name (i2))
7462 continue;
7464 bool sop = false;
7466 value_range vr2 = get_vr_for_comparison (i2);
7468 t = compare_ranges (comp, &vr1, &vr2, &sop);
7469 if (t)
7471 /* If we get different answers from different members
7472 of the equivalence set this check must be in a dead
7473 code region. Folding it to a trap representation
7474 would be correct here. For now just return don't-know. */
7475 if (retval != NULL
7476 && t != retval)
7478 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7479 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7480 return NULL_TREE;
7482 retval = t;
7484 if (!sop)
7485 used_strict_overflow = 0;
7486 else if (used_strict_overflow < 0)
7487 used_strict_overflow = 1;
7491 if (retval)
7493 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7494 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7495 if (used_strict_overflow > 0)
7496 *strict_overflow_p = true;
7497 return retval;
7501 /* None of the equivalent ranges are useful in computing this
7502 comparison. */
7503 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7504 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7505 return NULL_TREE;
7508 /* Helper function for vrp_evaluate_conditional_warnv & other
7509 optimizers. */
7511 static tree
7512 vrp_evaluate_conditional_warnv_with_ops_using_ranges (enum tree_code code,
7513 tree op0, tree op1,
7514 bool * strict_overflow_p)
7516 value_range *vr0, *vr1;
7518 vr0 = (TREE_CODE (op0) == SSA_NAME) ? get_value_range (op0) : NULL;
7519 vr1 = (TREE_CODE (op1) == SSA_NAME) ? get_value_range (op1) : NULL;
7521 tree res = NULL_TREE;
7522 if (vr0 && vr1)
7523 res = compare_ranges (code, vr0, vr1, strict_overflow_p);
7524 if (!res && vr0)
7525 res = compare_range_with_value (code, vr0, op1, strict_overflow_p);
7526 if (!res && vr1)
7527 res = (compare_range_with_value
7528 (swap_tree_comparison (code), vr1, op0, strict_overflow_p));
7529 return res;
7532 /* Helper function for vrp_evaluate_conditional_warnv. */
7534 static tree
7535 vrp_evaluate_conditional_warnv_with_ops (enum tree_code code, tree op0,
7536 tree op1, bool use_equiv_p,
7537 bool *strict_overflow_p, bool *only_ranges)
7539 tree ret;
7540 if (only_ranges)
7541 *only_ranges = true;
7543 /* We only deal with integral and pointer types. */
7544 if (!INTEGRAL_TYPE_P (TREE_TYPE (op0))
7545 && !POINTER_TYPE_P (TREE_TYPE (op0)))
7546 return NULL_TREE;
7548 /* If OP0 CODE OP1 is an overflow comparison, if it can be expressed
7549 as a simple equality test, then prefer that over its current form
7550 for evaluation.
7552 An overflow test which collapses to an equality test can always be
7553 expressed as a comparison of one argument against zero. Overflow
7554 occurs when the chosen argument is zero and does not occur if the
7555 chosen argument is not zero. */
7556 tree x;
7557 if (overflow_comparison_p (code, op0, op1, use_equiv_p, &x))
7559 wide_int max = wi::max_value (TYPE_PRECISION (TREE_TYPE (op0)), UNSIGNED);
7560 /* B = A - 1; if (A < B) -> B = A - 1; if (A == 0)
7561 B = A - 1; if (A > B) -> B = A - 1; if (A != 0)
7562 B = A + 1; if (B < A) -> B = A + 1; if (B == 0)
7563 B = A + 1; if (B > A) -> B = A + 1; if (B != 0) */
7564 if (integer_zerop (x))
7566 op1 = x;
7567 code = (code == LT_EXPR || code == LE_EXPR) ? EQ_EXPR : NE_EXPR;
7569 /* B = A + 1; if (A > B) -> B = A + 1; if (B == 0)
7570 B = A + 1; if (A < B) -> B = A + 1; if (B != 0)
7571 B = A - 1; if (B > A) -> B = A - 1; if (A == 0)
7572 B = A - 1; if (B < A) -> B = A - 1; if (A != 0) */
7573 else if (wi::to_wide (x) == max - 1)
7575 op0 = op1;
7576 op1 = wide_int_to_tree (TREE_TYPE (op0), 0);
7577 code = (code == GT_EXPR || code == GE_EXPR) ? EQ_EXPR : NE_EXPR;
7581 if ((ret = vrp_evaluate_conditional_warnv_with_ops_using_ranges
7582 (code, op0, op1, strict_overflow_p)))
7583 return ret;
7584 if (only_ranges)
7585 *only_ranges = false;
7586 /* Do not use compare_names during propagation, it's quadratic. */
7587 if (TREE_CODE (op0) == SSA_NAME && TREE_CODE (op1) == SSA_NAME
7588 && use_equiv_p)
7589 return compare_names (code, op0, op1, strict_overflow_p);
7590 else if (TREE_CODE (op0) == SSA_NAME)
7591 return compare_name_with_value (code, op0, op1,
7592 strict_overflow_p, use_equiv_p);
7593 else if (TREE_CODE (op1) == SSA_NAME)
7594 return compare_name_with_value (swap_tree_comparison (code), op1, op0,
7595 strict_overflow_p, use_equiv_p);
7596 return NULL_TREE;
7599 /* Given (CODE OP0 OP1) within STMT, try to simplify it based on value range
7600 information. Return NULL if the conditional can not be evaluated.
7601 The ranges of all the names equivalent with the operands in COND
7602 will be used when trying to compute the value. If the result is
7603 based on undefined signed overflow, issue a warning if
7604 appropriate. */
7606 static tree
7607 vrp_evaluate_conditional (tree_code code, tree op0, tree op1, gimple *stmt)
7609 bool sop;
7610 tree ret;
7611 bool only_ranges;
7613 /* Some passes and foldings leak constants with overflow flag set
7614 into the IL. Avoid doing wrong things with these and bail out. */
7615 if ((TREE_CODE (op0) == INTEGER_CST
7616 && TREE_OVERFLOW (op0))
7617 || (TREE_CODE (op1) == INTEGER_CST
7618 && TREE_OVERFLOW (op1)))
7619 return NULL_TREE;
7621 sop = false;
7622 ret = vrp_evaluate_conditional_warnv_with_ops (code, op0, op1, true, &sop,
7623 &only_ranges);
7625 if (ret && sop)
7627 enum warn_strict_overflow_code wc;
7628 const char* warnmsg;
7630 if (is_gimple_min_invariant (ret))
7632 wc = WARN_STRICT_OVERFLOW_CONDITIONAL;
7633 warnmsg = G_("assuming signed overflow does not occur when "
7634 "simplifying conditional to constant");
7636 else
7638 wc = WARN_STRICT_OVERFLOW_COMPARISON;
7639 warnmsg = G_("assuming signed overflow does not occur when "
7640 "simplifying conditional");
7643 if (issue_strict_overflow_warning (wc))
7645 location_t location;
7647 if (!gimple_has_location (stmt))
7648 location = input_location;
7649 else
7650 location = gimple_location (stmt);
7651 warning_at (location, OPT_Wstrict_overflow, "%s", warnmsg);
7655 if (warn_type_limits
7656 && ret && only_ranges
7657 && TREE_CODE_CLASS (code) == tcc_comparison
7658 && TREE_CODE (op0) == SSA_NAME)
7660 /* If the comparison is being folded and the operand on the LHS
7661 is being compared against a constant value that is outside of
7662 the natural range of OP0's type, then the predicate will
7663 always fold regardless of the value of OP0. If -Wtype-limits
7664 was specified, emit a warning. */
7665 tree type = TREE_TYPE (op0);
7666 value_range *vr0 = get_value_range (op0);
7668 if (vr0->type == VR_RANGE
7669 && INTEGRAL_TYPE_P (type)
7670 && vrp_val_is_min (vr0->min)
7671 && vrp_val_is_max (vr0->max)
7672 && is_gimple_min_invariant (op1))
7674 location_t location;
7676 if (!gimple_has_location (stmt))
7677 location = input_location;
7678 else
7679 location = gimple_location (stmt);
7681 warning_at (location, OPT_Wtype_limits,
7682 integer_zerop (ret)
7683 ? G_("comparison always false "
7684 "due to limited range of data type")
7685 : G_("comparison always true "
7686 "due to limited range of data type"));
7690 return ret;
7694 /* Visit conditional statement STMT. If we can determine which edge
7695 will be taken out of STMT's basic block, record it in
7696 *TAKEN_EDGE_P. Otherwise, set *TAKEN_EDGE_P to NULL. */
7698 static void
7699 vrp_visit_cond_stmt (gcond *stmt, edge *taken_edge_p)
7701 tree val;
7703 *taken_edge_p = NULL;
7705 if (dump_file && (dump_flags & TDF_DETAILS))
7707 tree use;
7708 ssa_op_iter i;
7710 fprintf (dump_file, "\nVisiting conditional with predicate: ");
7711 print_gimple_stmt (dump_file, stmt, 0);
7712 fprintf (dump_file, "\nWith known ranges\n");
7714 FOR_EACH_SSA_TREE_OPERAND (use, stmt, i, SSA_OP_USE)
7716 fprintf (dump_file, "\t");
7717 print_generic_expr (dump_file, use);
7718 fprintf (dump_file, ": ");
7719 dump_value_range (dump_file, vr_value[SSA_NAME_VERSION (use)]);
7722 fprintf (dump_file, "\n");
7725 /* Compute the value of the predicate COND by checking the known
7726 ranges of each of its operands.
7728 Note that we cannot evaluate all the equivalent ranges here
7729 because those ranges may not yet be final and with the current
7730 propagation strategy, we cannot determine when the value ranges
7731 of the names in the equivalence set have changed.
7733 For instance, given the following code fragment
7735 i_5 = PHI <8, i_13>
7737 i_14 = ASSERT_EXPR <i_5, i_5 != 0>
7738 if (i_14 == 1)
7741 Assume that on the first visit to i_14, i_5 has the temporary
7742 range [8, 8] because the second argument to the PHI function is
7743 not yet executable. We derive the range ~[0, 0] for i_14 and the
7744 equivalence set { i_5 }. So, when we visit 'if (i_14 == 1)' for
7745 the first time, since i_14 is equivalent to the range [8, 8], we
7746 determine that the predicate is always false.
7748 On the next round of propagation, i_13 is determined to be
7749 VARYING, which causes i_5 to drop down to VARYING. So, another
7750 visit to i_14 is scheduled. In this second visit, we compute the
7751 exact same range and equivalence set for i_14, namely ~[0, 0] and
7752 { i_5 }. But we did not have the previous range for i_5
7753 registered, so vrp_visit_assignment thinks that the range for
7754 i_14 has not changed. Therefore, the predicate 'if (i_14 == 1)'
7755 is not visited again, which stops propagation from visiting
7756 statements in the THEN clause of that if().
7758 To properly fix this we would need to keep the previous range
7759 value for the names in the equivalence set. This way we would've
7760 discovered that from one visit to the other i_5 changed from
7761 range [8, 8] to VR_VARYING.
7763 However, fixing this apparent limitation may not be worth the
7764 additional checking. Testing on several code bases (GCC, DLV,
7765 MICO, TRAMP3D and SPEC2000) showed that doing this results in
7766 4 more predicates folded in SPEC. */
7768 bool sop;
7769 val = vrp_evaluate_conditional_warnv_with_ops (gimple_cond_code (stmt),
7770 gimple_cond_lhs (stmt),
7771 gimple_cond_rhs (stmt),
7772 false, &sop, NULL);
7773 if (val)
7774 *taken_edge_p = find_taken_edge (gimple_bb (stmt), val);
7776 if (dump_file && (dump_flags & TDF_DETAILS))
7778 fprintf (dump_file, "\nPredicate evaluates to: ");
7779 if (val == NULL_TREE)
7780 fprintf (dump_file, "DON'T KNOW\n");
7781 else
7782 print_generic_stmt (dump_file, val);
7786 /* Searches the case label vector VEC for the index *IDX of the CASE_LABEL
7787 that includes the value VAL. The search is restricted to the range
7788 [START_IDX, n - 1] where n is the size of VEC.
7790 If there is a CASE_LABEL for VAL, its index is placed in IDX and true is
7791 returned.
7793 If there is no CASE_LABEL for VAL and there is one that is larger than VAL,
7794 it is placed in IDX and false is returned.
7796 If VAL is larger than any CASE_LABEL, n is placed on IDX and false is
7797 returned. */
7799 static bool
7800 find_case_label_index (gswitch *stmt, size_t start_idx, tree val, size_t *idx)
7802 size_t n = gimple_switch_num_labels (stmt);
7803 size_t low, high;
7805 /* Find case label for minimum of the value range or the next one.
7806 At each iteration we are searching in [low, high - 1]. */
7808 for (low = start_idx, high = n; high != low; )
7810 tree t;
7811 int cmp;
7812 /* Note that i != high, so we never ask for n. */
7813 size_t i = (high + low) / 2;
7814 t = gimple_switch_label (stmt, i);
7816 /* Cache the result of comparing CASE_LOW and val. */
7817 cmp = tree_int_cst_compare (CASE_LOW (t), val);
7819 if (cmp == 0)
7821 /* Ranges cannot be empty. */
7822 *idx = i;
7823 return true;
7825 else if (cmp > 0)
7826 high = i;
7827 else
7829 low = i + 1;
7830 if (CASE_HIGH (t) != NULL
7831 && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
7833 *idx = i;
7834 return true;
7839 *idx = high;
7840 return false;
7843 /* Searches the case label vector VEC for the range of CASE_LABELs that is used
7844 for values between MIN and MAX. The first index is placed in MIN_IDX. The
7845 last index is placed in MAX_IDX. If the range of CASE_LABELs is empty
7846 then MAX_IDX < MIN_IDX.
7847 Returns true if the default label is not needed. */
7849 static bool
7850 find_case_label_range (gswitch *stmt, tree min, tree max, size_t *min_idx,
7851 size_t *max_idx)
7853 size_t i, j;
7854 bool min_take_default = !find_case_label_index (stmt, 1, min, &i);
7855 bool max_take_default = !find_case_label_index (stmt, i, max, &j);
7857 if (i == j
7858 && min_take_default
7859 && max_take_default)
7861 /* Only the default case label reached.
7862 Return an empty range. */
7863 *min_idx = 1;
7864 *max_idx = 0;
7865 return false;
7867 else
7869 bool take_default = min_take_default || max_take_default;
7870 tree low, high;
7871 size_t k;
7873 if (max_take_default)
7874 j--;
7876 /* If the case label range is continuous, we do not need
7877 the default case label. Verify that. */
7878 high = CASE_LOW (gimple_switch_label (stmt, i));
7879 if (CASE_HIGH (gimple_switch_label (stmt, i)))
7880 high = CASE_HIGH (gimple_switch_label (stmt, i));
7881 for (k = i + 1; k <= j; ++k)
7883 low = CASE_LOW (gimple_switch_label (stmt, k));
7884 if (!integer_onep (int_const_binop (MINUS_EXPR, low, high)))
7886 take_default = true;
7887 break;
7889 high = low;
7890 if (CASE_HIGH (gimple_switch_label (stmt, k)))
7891 high = CASE_HIGH (gimple_switch_label (stmt, k));
7894 *min_idx = i;
7895 *max_idx = j;
7896 return !take_default;
7900 /* Searches the case label vector VEC for the ranges of CASE_LABELs that are
7901 used in range VR. The indices are placed in MIN_IDX1, MAX_IDX, MIN_IDX2 and
7902 MAX_IDX2. If the ranges of CASE_LABELs are empty then MAX_IDX1 < MIN_IDX1.
7903 Returns true if the default label is not needed. */
7905 static bool
7906 find_case_label_ranges (gswitch *stmt, value_range *vr, size_t *min_idx1,
7907 size_t *max_idx1, size_t *min_idx2,
7908 size_t *max_idx2)
7910 size_t i, j, k, l;
7911 unsigned int n = gimple_switch_num_labels (stmt);
7912 bool take_default;
7913 tree case_low, case_high;
7914 tree min = vr->min, max = vr->max;
7916 gcc_checking_assert (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE);
7918 take_default = !find_case_label_range (stmt, min, max, &i, &j);
7920 /* Set second range to emtpy. */
7921 *min_idx2 = 1;
7922 *max_idx2 = 0;
7924 if (vr->type == VR_RANGE)
7926 *min_idx1 = i;
7927 *max_idx1 = j;
7928 return !take_default;
7931 /* Set first range to all case labels. */
7932 *min_idx1 = 1;
7933 *max_idx1 = n - 1;
7935 if (i > j)
7936 return false;
7938 /* Make sure all the values of case labels [i , j] are contained in
7939 range [MIN, MAX]. */
7940 case_low = CASE_LOW (gimple_switch_label (stmt, i));
7941 case_high = CASE_HIGH (gimple_switch_label (stmt, j));
7942 if (tree_int_cst_compare (case_low, min) < 0)
7943 i += 1;
7944 if (case_high != NULL_TREE
7945 && tree_int_cst_compare (max, case_high) < 0)
7946 j -= 1;
7948 if (i > j)
7949 return false;
7951 /* If the range spans case labels [i, j], the corresponding anti-range spans
7952 the labels [1, i - 1] and [j + 1, n - 1]. */
7953 k = j + 1;
7954 l = n - 1;
7955 if (k > l)
7957 k = 1;
7958 l = 0;
7961 j = i - 1;
7962 i = 1;
7963 if (i > j)
7965 i = k;
7966 j = l;
7967 k = 1;
7968 l = 0;
7971 *min_idx1 = i;
7972 *max_idx1 = j;
7973 *min_idx2 = k;
7974 *max_idx2 = l;
7975 return false;
7978 /* Visit switch statement STMT. If we can determine which edge
7979 will be taken out of STMT's basic block, record it in
7980 *TAKEN_EDGE_P. Otherwise, *TAKEN_EDGE_P set to NULL. */
7982 static void
7983 vrp_visit_switch_stmt (gswitch *stmt, edge *taken_edge_p)
7985 tree op, val;
7986 value_range *vr;
7987 size_t i = 0, j = 0, k, l;
7988 bool take_default;
7990 *taken_edge_p = NULL;
7991 op = gimple_switch_index (stmt);
7992 if (TREE_CODE (op) != SSA_NAME)
7993 return;
7995 vr = get_value_range (op);
7996 if (dump_file && (dump_flags & TDF_DETAILS))
7998 fprintf (dump_file, "\nVisiting switch expression with operand ");
7999 print_generic_expr (dump_file, op);
8000 fprintf (dump_file, " with known range ");
8001 dump_value_range (dump_file, vr);
8002 fprintf (dump_file, "\n");
8005 if ((vr->type != VR_RANGE
8006 && vr->type != VR_ANTI_RANGE)
8007 || symbolic_range_p (vr))
8008 return;
8010 /* Find the single edge that is taken from the switch expression. */
8011 take_default = !find_case_label_ranges (stmt, vr, &i, &j, &k, &l);
8013 /* Check if the range spans no CASE_LABEL. If so, we only reach the default
8014 label */
8015 if (j < i)
8017 gcc_assert (take_default);
8018 val = gimple_switch_default_label (stmt);
8020 else
8022 /* Check if labels with index i to j and maybe the default label
8023 are all reaching the same label. */
8025 val = gimple_switch_label (stmt, i);
8026 if (take_default
8027 && CASE_LABEL (gimple_switch_default_label (stmt))
8028 != CASE_LABEL (val))
8030 if (dump_file && (dump_flags & TDF_DETAILS))
8031 fprintf (dump_file, " not a single destination for this "
8032 "range\n");
8033 return;
8035 for (++i; i <= j; ++i)
8037 if (CASE_LABEL (gimple_switch_label (stmt, i)) != CASE_LABEL (val))
8039 if (dump_file && (dump_flags & TDF_DETAILS))
8040 fprintf (dump_file, " not a single destination for this "
8041 "range\n");
8042 return;
8045 for (; k <= l; ++k)
8047 if (CASE_LABEL (gimple_switch_label (stmt, k)) != CASE_LABEL (val))
8049 if (dump_file && (dump_flags & TDF_DETAILS))
8050 fprintf (dump_file, " not a single destination for this "
8051 "range\n");
8052 return;
8057 *taken_edge_p = find_edge (gimple_bb (stmt),
8058 label_to_block (CASE_LABEL (val)));
8060 if (dump_file && (dump_flags & TDF_DETAILS))
8062 fprintf (dump_file, " will take edge to ");
8063 print_generic_stmt (dump_file, CASE_LABEL (val));
8068 /* Evaluate statement STMT. If the statement produces a useful range,
8069 set VR and corepsponding OUTPUT_P.
8071 If STMT is a conditional branch and we can determine its truth
8072 value, the taken edge is recorded in *TAKEN_EDGE_P. */
8074 static void
8075 extract_range_from_stmt (gimple *stmt, edge *taken_edge_p,
8076 tree *output_p, value_range *vr)
8079 if (dump_file && (dump_flags & TDF_DETAILS))
8081 fprintf (dump_file, "\nVisiting statement:\n");
8082 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
8085 if (!stmt_interesting_for_vrp (stmt))
8086 gcc_assert (stmt_ends_bb_p (stmt));
8087 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
8088 vrp_visit_assignment_or_call (stmt, output_p, vr);
8089 else if (gimple_code (stmt) == GIMPLE_COND)
8090 vrp_visit_cond_stmt (as_a <gcond *> (stmt), taken_edge_p);
8091 else if (gimple_code (stmt) == GIMPLE_SWITCH)
8092 vrp_visit_switch_stmt (as_a <gswitch *> (stmt), taken_edge_p);
8095 /* Evaluate statement STMT. If the statement produces a useful range,
8096 return SSA_PROP_INTERESTING and record the SSA name with the
8097 interesting range into *OUTPUT_P.
8099 If STMT is a conditional branch and we can determine its truth
8100 value, the taken edge is recorded in *TAKEN_EDGE_P.
8102 If STMT produces a varying value, return SSA_PROP_VARYING. */
8104 static enum ssa_prop_result
8105 vrp_visit_stmt (gimple *stmt, edge *taken_edge_p, tree *output_p)
8107 value_range vr = VR_INITIALIZER;
8108 tree lhs = gimple_get_lhs (stmt);
8109 extract_range_from_stmt (stmt, taken_edge_p, output_p, &vr);
8111 if (*output_p)
8113 if (update_value_range (*output_p, &vr))
8115 if (dump_file && (dump_flags & TDF_DETAILS))
8117 fprintf (dump_file, "Found new range for ");
8118 print_generic_expr (dump_file, *output_p);
8119 fprintf (dump_file, ": ");
8120 dump_value_range (dump_file, &vr);
8121 fprintf (dump_file, "\n");
8124 if (vr.type == VR_VARYING)
8125 return SSA_PROP_VARYING;
8127 return SSA_PROP_INTERESTING;
8129 return SSA_PROP_NOT_INTERESTING;
8132 if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
8133 switch (gimple_call_internal_fn (stmt))
8135 case IFN_ADD_OVERFLOW:
8136 case IFN_SUB_OVERFLOW:
8137 case IFN_MUL_OVERFLOW:
8138 case IFN_ATOMIC_COMPARE_EXCHANGE:
8139 /* These internal calls return _Complex integer type,
8140 which VRP does not track, but the immediate uses
8141 thereof might be interesting. */
8142 if (lhs && TREE_CODE (lhs) == SSA_NAME)
8144 imm_use_iterator iter;
8145 use_operand_p use_p;
8146 enum ssa_prop_result res = SSA_PROP_VARYING;
8148 set_value_range_to_varying (get_value_range (lhs));
8150 FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
8152 gimple *use_stmt = USE_STMT (use_p);
8153 if (!is_gimple_assign (use_stmt))
8154 continue;
8155 enum tree_code rhs_code = gimple_assign_rhs_code (use_stmt);
8156 if (rhs_code != REALPART_EXPR && rhs_code != IMAGPART_EXPR)
8157 continue;
8158 tree rhs1 = gimple_assign_rhs1 (use_stmt);
8159 tree use_lhs = gimple_assign_lhs (use_stmt);
8160 if (TREE_CODE (rhs1) != rhs_code
8161 || TREE_OPERAND (rhs1, 0) != lhs
8162 || TREE_CODE (use_lhs) != SSA_NAME
8163 || !stmt_interesting_for_vrp (use_stmt)
8164 || (!INTEGRAL_TYPE_P (TREE_TYPE (use_lhs))
8165 || !TYPE_MIN_VALUE (TREE_TYPE (use_lhs))
8166 || !TYPE_MAX_VALUE (TREE_TYPE (use_lhs))))
8167 continue;
8169 /* If there is a change in the value range for any of the
8170 REALPART_EXPR/IMAGPART_EXPR immediate uses, return
8171 SSA_PROP_INTERESTING. If there are any REALPART_EXPR
8172 or IMAGPART_EXPR immediate uses, but none of them have
8173 a change in their value ranges, return
8174 SSA_PROP_NOT_INTERESTING. If there are no
8175 {REAL,IMAG}PART_EXPR uses at all,
8176 return SSA_PROP_VARYING. */
8177 value_range new_vr = VR_INITIALIZER;
8178 extract_range_basic (&new_vr, use_stmt);
8179 value_range *old_vr = get_value_range (use_lhs);
8180 if (old_vr->type != new_vr.type
8181 || !vrp_operand_equal_p (old_vr->min, new_vr.min)
8182 || !vrp_operand_equal_p (old_vr->max, new_vr.max)
8183 || !vrp_bitmap_equal_p (old_vr->equiv, new_vr.equiv))
8184 res = SSA_PROP_INTERESTING;
8185 else
8186 res = SSA_PROP_NOT_INTERESTING;
8187 BITMAP_FREE (new_vr.equiv);
8188 if (res == SSA_PROP_INTERESTING)
8190 *output_p = lhs;
8191 return res;
8195 return res;
8197 break;
8198 default:
8199 break;
8202 /* All other statements produce nothing of interest for VRP, so mark
8203 their outputs varying and prevent further simulation. */
8204 set_defs_to_varying (stmt);
8206 return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
8209 /* Union the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
8210 { VR1TYPE, VR0MIN, VR0MAX } and store the result
8211 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
8212 possible such range. The resulting range is not canonicalized. */
8214 static void
8215 union_ranges (enum value_range_type *vr0type,
8216 tree *vr0min, tree *vr0max,
8217 enum value_range_type vr1type,
8218 tree vr1min, tree vr1max)
8220 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
8221 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
8223 /* [] is vr0, () is vr1 in the following classification comments. */
8224 if (mineq && maxeq)
8226 /* [( )] */
8227 if (*vr0type == vr1type)
8228 /* Nothing to do for equal ranges. */
8230 else if ((*vr0type == VR_RANGE
8231 && vr1type == VR_ANTI_RANGE)
8232 || (*vr0type == VR_ANTI_RANGE
8233 && vr1type == VR_RANGE))
8235 /* For anti-range with range union the result is varying. */
8236 goto give_up;
8238 else
8239 gcc_unreachable ();
8241 else if (operand_less_p (*vr0max, vr1min) == 1
8242 || operand_less_p (vr1max, *vr0min) == 1)
8244 /* [ ] ( ) or ( ) [ ]
8245 If the ranges have an empty intersection, result of the union
8246 operation is the anti-range or if both are anti-ranges
8247 it covers all. */
8248 if (*vr0type == VR_ANTI_RANGE
8249 && vr1type == VR_ANTI_RANGE)
8250 goto give_up;
8251 else if (*vr0type == VR_ANTI_RANGE
8252 && vr1type == VR_RANGE)
8254 else if (*vr0type == VR_RANGE
8255 && vr1type == VR_ANTI_RANGE)
8257 *vr0type = vr1type;
8258 *vr0min = vr1min;
8259 *vr0max = vr1max;
8261 else if (*vr0type == VR_RANGE
8262 && vr1type == VR_RANGE)
8264 /* The result is the convex hull of both ranges. */
8265 if (operand_less_p (*vr0max, vr1min) == 1)
8267 /* If the result can be an anti-range, create one. */
8268 if (TREE_CODE (*vr0max) == INTEGER_CST
8269 && TREE_CODE (vr1min) == INTEGER_CST
8270 && vrp_val_is_min (*vr0min)
8271 && vrp_val_is_max (vr1max))
8273 tree min = int_const_binop (PLUS_EXPR,
8274 *vr0max,
8275 build_int_cst (TREE_TYPE (*vr0max), 1));
8276 tree max = int_const_binop (MINUS_EXPR,
8277 vr1min,
8278 build_int_cst (TREE_TYPE (vr1min), 1));
8279 if (!operand_less_p (max, min))
8281 *vr0type = VR_ANTI_RANGE;
8282 *vr0min = min;
8283 *vr0max = max;
8285 else
8286 *vr0max = vr1max;
8288 else
8289 *vr0max = vr1max;
8291 else
8293 /* If the result can be an anti-range, create one. */
8294 if (TREE_CODE (vr1max) == INTEGER_CST
8295 && TREE_CODE (*vr0min) == INTEGER_CST
8296 && vrp_val_is_min (vr1min)
8297 && vrp_val_is_max (*vr0max))
8299 tree min = int_const_binop (PLUS_EXPR,
8300 vr1max,
8301 build_int_cst (TREE_TYPE (vr1max), 1));
8302 tree max = int_const_binop (MINUS_EXPR,
8303 *vr0min,
8304 build_int_cst (TREE_TYPE (*vr0min), 1));
8305 if (!operand_less_p (max, min))
8307 *vr0type = VR_ANTI_RANGE;
8308 *vr0min = min;
8309 *vr0max = max;
8311 else
8312 *vr0min = vr1min;
8314 else
8315 *vr0min = vr1min;
8318 else
8319 gcc_unreachable ();
8321 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
8322 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
8324 /* [ ( ) ] or [( ) ] or [ ( )] */
8325 if (*vr0type == VR_RANGE
8326 && vr1type == VR_RANGE)
8328 else if (*vr0type == VR_ANTI_RANGE
8329 && vr1type == VR_ANTI_RANGE)
8331 *vr0type = vr1type;
8332 *vr0min = vr1min;
8333 *vr0max = vr1max;
8335 else if (*vr0type == VR_ANTI_RANGE
8336 && vr1type == VR_RANGE)
8338 /* Arbitrarily choose the right or left gap. */
8339 if (!mineq && TREE_CODE (vr1min) == INTEGER_CST)
8340 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8341 build_int_cst (TREE_TYPE (vr1min), 1));
8342 else if (!maxeq && TREE_CODE (vr1max) == INTEGER_CST)
8343 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
8344 build_int_cst (TREE_TYPE (vr1max), 1));
8345 else
8346 goto give_up;
8348 else if (*vr0type == VR_RANGE
8349 && vr1type == VR_ANTI_RANGE)
8350 /* The result covers everything. */
8351 goto give_up;
8352 else
8353 gcc_unreachable ();
8355 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
8356 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
8358 /* ( [ ] ) or ([ ] ) or ( [ ]) */
8359 if (*vr0type == VR_RANGE
8360 && vr1type == VR_RANGE)
8362 *vr0type = vr1type;
8363 *vr0min = vr1min;
8364 *vr0max = vr1max;
8366 else if (*vr0type == VR_ANTI_RANGE
8367 && vr1type == VR_ANTI_RANGE)
8369 else if (*vr0type == VR_RANGE
8370 && vr1type == VR_ANTI_RANGE)
8372 *vr0type = VR_ANTI_RANGE;
8373 if (!mineq && TREE_CODE (*vr0min) == INTEGER_CST)
8375 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
8376 build_int_cst (TREE_TYPE (*vr0min), 1));
8377 *vr0min = vr1min;
8379 else if (!maxeq && TREE_CODE (*vr0max) == INTEGER_CST)
8381 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8382 build_int_cst (TREE_TYPE (*vr0max), 1));
8383 *vr0max = vr1max;
8385 else
8386 goto give_up;
8388 else if (*vr0type == VR_ANTI_RANGE
8389 && vr1type == VR_RANGE)
8390 /* The result covers everything. */
8391 goto give_up;
8392 else
8393 gcc_unreachable ();
8395 else if ((operand_less_p (vr1min, *vr0max) == 1
8396 || operand_equal_p (vr1min, *vr0max, 0))
8397 && operand_less_p (*vr0min, vr1min) == 1
8398 && operand_less_p (*vr0max, vr1max) == 1)
8400 /* [ ( ] ) or [ ]( ) */
8401 if (*vr0type == VR_RANGE
8402 && vr1type == VR_RANGE)
8403 *vr0max = vr1max;
8404 else if (*vr0type == VR_ANTI_RANGE
8405 && vr1type == VR_ANTI_RANGE)
8406 *vr0min = vr1min;
8407 else if (*vr0type == VR_ANTI_RANGE
8408 && vr1type == VR_RANGE)
8410 if (TREE_CODE (vr1min) == INTEGER_CST)
8411 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8412 build_int_cst (TREE_TYPE (vr1min), 1));
8413 else
8414 goto give_up;
8416 else if (*vr0type == VR_RANGE
8417 && vr1type == VR_ANTI_RANGE)
8419 if (TREE_CODE (*vr0max) == INTEGER_CST)
8421 *vr0type = vr1type;
8422 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8423 build_int_cst (TREE_TYPE (*vr0max), 1));
8424 *vr0max = vr1max;
8426 else
8427 goto give_up;
8429 else
8430 gcc_unreachable ();
8432 else if ((operand_less_p (*vr0min, vr1max) == 1
8433 || operand_equal_p (*vr0min, vr1max, 0))
8434 && operand_less_p (vr1min, *vr0min) == 1
8435 && operand_less_p (vr1max, *vr0max) == 1)
8437 /* ( [ ) ] or ( )[ ] */
8438 if (*vr0type == VR_RANGE
8439 && vr1type == VR_RANGE)
8440 *vr0min = vr1min;
8441 else if (*vr0type == VR_ANTI_RANGE
8442 && vr1type == VR_ANTI_RANGE)
8443 *vr0max = vr1max;
8444 else if (*vr0type == VR_ANTI_RANGE
8445 && vr1type == VR_RANGE)
8447 if (TREE_CODE (vr1max) == INTEGER_CST)
8448 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
8449 build_int_cst (TREE_TYPE (vr1max), 1));
8450 else
8451 goto give_up;
8453 else if (*vr0type == VR_RANGE
8454 && vr1type == VR_ANTI_RANGE)
8456 if (TREE_CODE (*vr0min) == INTEGER_CST)
8458 *vr0type = vr1type;
8459 *vr0min = vr1min;
8460 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
8461 build_int_cst (TREE_TYPE (*vr0min), 1));
8463 else
8464 goto give_up;
8466 else
8467 gcc_unreachable ();
8469 else
8470 goto give_up;
8472 return;
8474 give_up:
8475 *vr0type = VR_VARYING;
8476 *vr0min = NULL_TREE;
8477 *vr0max = NULL_TREE;
8480 /* Intersect the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
8481 { VR1TYPE, VR0MIN, VR0MAX } and store the result
8482 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
8483 possible such range. The resulting range is not canonicalized. */
8485 static void
8486 intersect_ranges (enum value_range_type *vr0type,
8487 tree *vr0min, tree *vr0max,
8488 enum value_range_type vr1type,
8489 tree vr1min, tree vr1max)
8491 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
8492 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
8494 /* [] is vr0, () is vr1 in the following classification comments. */
8495 if (mineq && maxeq)
8497 /* [( )] */
8498 if (*vr0type == vr1type)
8499 /* Nothing to do for equal ranges. */
8501 else if ((*vr0type == VR_RANGE
8502 && vr1type == VR_ANTI_RANGE)
8503 || (*vr0type == VR_ANTI_RANGE
8504 && vr1type == VR_RANGE))
8506 /* For anti-range with range intersection the result is empty. */
8507 *vr0type = VR_UNDEFINED;
8508 *vr0min = NULL_TREE;
8509 *vr0max = NULL_TREE;
8511 else
8512 gcc_unreachable ();
8514 else if (operand_less_p (*vr0max, vr1min) == 1
8515 || operand_less_p (vr1max, *vr0min) == 1)
8517 /* [ ] ( ) or ( ) [ ]
8518 If the ranges have an empty intersection, the result of the
8519 intersect operation is the range for intersecting an
8520 anti-range with a range or empty when intersecting two ranges. */
8521 if (*vr0type == VR_RANGE
8522 && vr1type == VR_ANTI_RANGE)
8524 else if (*vr0type == VR_ANTI_RANGE
8525 && vr1type == VR_RANGE)
8527 *vr0type = vr1type;
8528 *vr0min = vr1min;
8529 *vr0max = vr1max;
8531 else if (*vr0type == VR_RANGE
8532 && vr1type == VR_RANGE)
8534 *vr0type = VR_UNDEFINED;
8535 *vr0min = NULL_TREE;
8536 *vr0max = NULL_TREE;
8538 else if (*vr0type == VR_ANTI_RANGE
8539 && vr1type == VR_ANTI_RANGE)
8541 /* If the anti-ranges are adjacent to each other merge them. */
8542 if (TREE_CODE (*vr0max) == INTEGER_CST
8543 && TREE_CODE (vr1min) == INTEGER_CST
8544 && operand_less_p (*vr0max, vr1min) == 1
8545 && integer_onep (int_const_binop (MINUS_EXPR,
8546 vr1min, *vr0max)))
8547 *vr0max = vr1max;
8548 else if (TREE_CODE (vr1max) == INTEGER_CST
8549 && TREE_CODE (*vr0min) == INTEGER_CST
8550 && operand_less_p (vr1max, *vr0min) == 1
8551 && integer_onep (int_const_binop (MINUS_EXPR,
8552 *vr0min, vr1max)))
8553 *vr0min = vr1min;
8554 /* Else arbitrarily take VR0. */
8557 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
8558 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
8560 /* [ ( ) ] or [( ) ] or [ ( )] */
8561 if (*vr0type == VR_RANGE
8562 && vr1type == VR_RANGE)
8564 /* If both are ranges the result is the inner one. */
8565 *vr0type = vr1type;
8566 *vr0min = vr1min;
8567 *vr0max = vr1max;
8569 else if (*vr0type == VR_RANGE
8570 && vr1type == VR_ANTI_RANGE)
8572 /* Choose the right gap if the left one is empty. */
8573 if (mineq)
8575 if (TREE_CODE (vr1max) != INTEGER_CST)
8576 *vr0min = vr1max;
8577 else if (TYPE_PRECISION (TREE_TYPE (vr1max)) == 1
8578 && !TYPE_UNSIGNED (TREE_TYPE (vr1max)))
8579 *vr0min
8580 = int_const_binop (MINUS_EXPR, vr1max,
8581 build_int_cst (TREE_TYPE (vr1max), -1));
8582 else
8583 *vr0min
8584 = int_const_binop (PLUS_EXPR, vr1max,
8585 build_int_cst (TREE_TYPE (vr1max), 1));
8587 /* Choose the left gap if the right one is empty. */
8588 else if (maxeq)
8590 if (TREE_CODE (vr1min) != INTEGER_CST)
8591 *vr0max = vr1min;
8592 else if (TYPE_PRECISION (TREE_TYPE (vr1min)) == 1
8593 && !TYPE_UNSIGNED (TREE_TYPE (vr1min)))
8594 *vr0max
8595 = int_const_binop (PLUS_EXPR, vr1min,
8596 build_int_cst (TREE_TYPE (vr1min), -1));
8597 else
8598 *vr0max
8599 = int_const_binop (MINUS_EXPR, vr1min,
8600 build_int_cst (TREE_TYPE (vr1min), 1));
8602 /* Choose the anti-range if the range is effectively varying. */
8603 else if (vrp_val_is_min (*vr0min)
8604 && vrp_val_is_max (*vr0max))
8606 *vr0type = vr1type;
8607 *vr0min = vr1min;
8608 *vr0max = vr1max;
8610 /* Else choose the range. */
8612 else if (*vr0type == VR_ANTI_RANGE
8613 && vr1type == VR_ANTI_RANGE)
8614 /* If both are anti-ranges the result is the outer one. */
8616 else if (*vr0type == VR_ANTI_RANGE
8617 && vr1type == VR_RANGE)
8619 /* The intersection is empty. */
8620 *vr0type = VR_UNDEFINED;
8621 *vr0min = NULL_TREE;
8622 *vr0max = NULL_TREE;
8624 else
8625 gcc_unreachable ();
8627 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
8628 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
8630 /* ( [ ] ) or ([ ] ) or ( [ ]) */
8631 if (*vr0type == VR_RANGE
8632 && vr1type == VR_RANGE)
8633 /* Choose the inner range. */
8635 else if (*vr0type == VR_ANTI_RANGE
8636 && vr1type == VR_RANGE)
8638 /* Choose the right gap if the left is empty. */
8639 if (mineq)
8641 *vr0type = VR_RANGE;
8642 if (TREE_CODE (*vr0max) != INTEGER_CST)
8643 *vr0min = *vr0max;
8644 else if (TYPE_PRECISION (TREE_TYPE (*vr0max)) == 1
8645 && !TYPE_UNSIGNED (TREE_TYPE (*vr0max)))
8646 *vr0min
8647 = int_const_binop (MINUS_EXPR, *vr0max,
8648 build_int_cst (TREE_TYPE (*vr0max), -1));
8649 else
8650 *vr0min
8651 = int_const_binop (PLUS_EXPR, *vr0max,
8652 build_int_cst (TREE_TYPE (*vr0max), 1));
8653 *vr0max = vr1max;
8655 /* Choose the left gap if the right is empty. */
8656 else if (maxeq)
8658 *vr0type = VR_RANGE;
8659 if (TREE_CODE (*vr0min) != INTEGER_CST)
8660 *vr0max = *vr0min;
8661 else if (TYPE_PRECISION (TREE_TYPE (*vr0min)) == 1
8662 && !TYPE_UNSIGNED (TREE_TYPE (*vr0min)))
8663 *vr0max
8664 = int_const_binop (PLUS_EXPR, *vr0min,
8665 build_int_cst (TREE_TYPE (*vr0min), -1));
8666 else
8667 *vr0max
8668 = int_const_binop (MINUS_EXPR, *vr0min,
8669 build_int_cst (TREE_TYPE (*vr0min), 1));
8670 *vr0min = vr1min;
8672 /* Choose the anti-range if the range is effectively varying. */
8673 else if (vrp_val_is_min (vr1min)
8674 && vrp_val_is_max (vr1max))
8676 /* Choose the anti-range if it is ~[0,0], that range is special
8677 enough to special case when vr1's range is relatively wide. */
8678 else if (*vr0min == *vr0max
8679 && integer_zerop (*vr0min)
8680 && (TYPE_PRECISION (TREE_TYPE (*vr0min))
8681 == TYPE_PRECISION (ptr_type_node))
8682 && TREE_CODE (vr1max) == INTEGER_CST
8683 && TREE_CODE (vr1min) == INTEGER_CST
8684 && (wi::clz (wi::to_wide (vr1max) - wi::to_wide (vr1min))
8685 < TYPE_PRECISION (TREE_TYPE (*vr0min)) / 2))
8687 /* Else choose the range. */
8688 else
8690 *vr0type = vr1type;
8691 *vr0min = vr1min;
8692 *vr0max = vr1max;
8695 else if (*vr0type == VR_ANTI_RANGE
8696 && vr1type == VR_ANTI_RANGE)
8698 /* If both are anti-ranges the result is the outer one. */
8699 *vr0type = vr1type;
8700 *vr0min = vr1min;
8701 *vr0max = vr1max;
8703 else if (vr1type == VR_ANTI_RANGE
8704 && *vr0type == VR_RANGE)
8706 /* The intersection is empty. */
8707 *vr0type = VR_UNDEFINED;
8708 *vr0min = NULL_TREE;
8709 *vr0max = NULL_TREE;
8711 else
8712 gcc_unreachable ();
8714 else if ((operand_less_p (vr1min, *vr0max) == 1
8715 || operand_equal_p (vr1min, *vr0max, 0))
8716 && operand_less_p (*vr0min, vr1min) == 1)
8718 /* [ ( ] ) or [ ]( ) */
8719 if (*vr0type == VR_ANTI_RANGE
8720 && vr1type == VR_ANTI_RANGE)
8721 *vr0max = vr1max;
8722 else if (*vr0type == VR_RANGE
8723 && vr1type == VR_RANGE)
8724 *vr0min = vr1min;
8725 else if (*vr0type == VR_RANGE
8726 && vr1type == VR_ANTI_RANGE)
8728 if (TREE_CODE (vr1min) == INTEGER_CST)
8729 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8730 build_int_cst (TREE_TYPE (vr1min), 1));
8731 else
8732 *vr0max = vr1min;
8734 else if (*vr0type == VR_ANTI_RANGE
8735 && vr1type == VR_RANGE)
8737 *vr0type = VR_RANGE;
8738 if (TREE_CODE (*vr0max) == INTEGER_CST)
8739 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8740 build_int_cst (TREE_TYPE (*vr0max), 1));
8741 else
8742 *vr0min = *vr0max;
8743 *vr0max = vr1max;
8745 else
8746 gcc_unreachable ();
8748 else if ((operand_less_p (*vr0min, vr1max) == 1
8749 || operand_equal_p (*vr0min, vr1max, 0))
8750 && operand_less_p (vr1min, *vr0min) == 1)
8752 /* ( [ ) ] or ( )[ ] */
8753 if (*vr0type == VR_ANTI_RANGE
8754 && vr1type == VR_ANTI_RANGE)
8755 *vr0min = vr1min;
8756 else if (*vr0type == VR_RANGE
8757 && vr1type == VR_RANGE)
8758 *vr0max = vr1max;
8759 else if (*vr0type == VR_RANGE
8760 && vr1type == VR_ANTI_RANGE)
8762 if (TREE_CODE (vr1max) == INTEGER_CST)
8763 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
8764 build_int_cst (TREE_TYPE (vr1max), 1));
8765 else
8766 *vr0min = vr1max;
8768 else if (*vr0type == VR_ANTI_RANGE
8769 && vr1type == VR_RANGE)
8771 *vr0type = VR_RANGE;
8772 if (TREE_CODE (*vr0min) == INTEGER_CST)
8773 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
8774 build_int_cst (TREE_TYPE (*vr0min), 1));
8775 else
8776 *vr0max = *vr0min;
8777 *vr0min = vr1min;
8779 else
8780 gcc_unreachable ();
8783 /* As a fallback simply use { *VRTYPE, *VR0MIN, *VR0MAX } as
8784 result for the intersection. That's always a conservative
8785 correct estimate unless VR1 is a constant singleton range
8786 in which case we choose that. */
8787 if (vr1type == VR_RANGE
8788 && is_gimple_min_invariant (vr1min)
8789 && vrp_operand_equal_p (vr1min, vr1max))
8791 *vr0type = vr1type;
8792 *vr0min = vr1min;
8793 *vr0max = vr1max;
8796 return;
8800 /* Intersect the two value-ranges *VR0 and *VR1 and store the result
8801 in *VR0. This may not be the smallest possible such range. */
8803 static void
8804 vrp_intersect_ranges_1 (value_range *vr0, value_range *vr1)
8806 value_range saved;
8808 /* If either range is VR_VARYING the other one wins. */
8809 if (vr1->type == VR_VARYING)
8810 return;
8811 if (vr0->type == VR_VARYING)
8813 copy_value_range (vr0, vr1);
8814 return;
8817 /* When either range is VR_UNDEFINED the resulting range is
8818 VR_UNDEFINED, too. */
8819 if (vr0->type == VR_UNDEFINED)
8820 return;
8821 if (vr1->type == VR_UNDEFINED)
8823 set_value_range_to_undefined (vr0);
8824 return;
8827 /* Save the original vr0 so we can return it as conservative intersection
8828 result when our worker turns things to varying. */
8829 saved = *vr0;
8830 intersect_ranges (&vr0->type, &vr0->min, &vr0->max,
8831 vr1->type, vr1->min, vr1->max);
8832 /* Make sure to canonicalize the result though as the inversion of a
8833 VR_RANGE can still be a VR_RANGE. */
8834 set_and_canonicalize_value_range (vr0, vr0->type,
8835 vr0->min, vr0->max, vr0->equiv);
8836 /* If that failed, use the saved original VR0. */
8837 if (vr0->type == VR_VARYING)
8839 *vr0 = saved;
8840 return;
8842 /* If the result is VR_UNDEFINED there is no need to mess with
8843 the equivalencies. */
8844 if (vr0->type == VR_UNDEFINED)
8845 return;
8847 /* The resulting set of equivalences for range intersection is the union of
8848 the two sets. */
8849 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
8850 bitmap_ior_into (vr0->equiv, vr1->equiv);
8851 else if (vr1->equiv && !vr0->equiv)
8853 vr0->equiv = BITMAP_ALLOC (&vrp_equiv_obstack);
8854 bitmap_copy (vr0->equiv, vr1->equiv);
8858 void
8859 vrp_intersect_ranges (value_range *vr0, value_range *vr1)
8861 if (dump_file && (dump_flags & TDF_DETAILS))
8863 fprintf (dump_file, "Intersecting\n ");
8864 dump_value_range (dump_file, vr0);
8865 fprintf (dump_file, "\nand\n ");
8866 dump_value_range (dump_file, vr1);
8867 fprintf (dump_file, "\n");
8869 vrp_intersect_ranges_1 (vr0, vr1);
8870 if (dump_file && (dump_flags & TDF_DETAILS))
8872 fprintf (dump_file, "to\n ");
8873 dump_value_range (dump_file, vr0);
8874 fprintf (dump_file, "\n");
8878 /* Meet operation for value ranges. Given two value ranges VR0 and
8879 VR1, store in VR0 a range that contains both VR0 and VR1. This
8880 may not be the smallest possible such range. */
8882 static void
8883 vrp_meet_1 (value_range *vr0, const value_range *vr1)
8885 value_range saved;
8887 if (vr0->type == VR_UNDEFINED)
8889 set_value_range (vr0, vr1->type, vr1->min, vr1->max, vr1->equiv);
8890 return;
8893 if (vr1->type == VR_UNDEFINED)
8895 /* VR0 already has the resulting range. */
8896 return;
8899 if (vr0->type == VR_VARYING)
8901 /* Nothing to do. VR0 already has the resulting range. */
8902 return;
8905 if (vr1->type == VR_VARYING)
8907 set_value_range_to_varying (vr0);
8908 return;
8911 saved = *vr0;
8912 union_ranges (&vr0->type, &vr0->min, &vr0->max,
8913 vr1->type, vr1->min, vr1->max);
8914 if (vr0->type == VR_VARYING)
8916 /* Failed to find an efficient meet. Before giving up and setting
8917 the result to VARYING, see if we can at least derive a useful
8918 anti-range. FIXME, all this nonsense about distinguishing
8919 anti-ranges from ranges is necessary because of the odd
8920 semantics of range_includes_zero_p and friends. */
8921 if (((saved.type == VR_RANGE
8922 && range_includes_zero_p (saved.min, saved.max) == 0)
8923 || (saved.type == VR_ANTI_RANGE
8924 && range_includes_zero_p (saved.min, saved.max) == 1))
8925 && ((vr1->type == VR_RANGE
8926 && range_includes_zero_p (vr1->min, vr1->max) == 0)
8927 || (vr1->type == VR_ANTI_RANGE
8928 && range_includes_zero_p (vr1->min, vr1->max) == 1)))
8930 set_value_range_to_nonnull (vr0, TREE_TYPE (saved.min));
8932 /* Since this meet operation did not result from the meeting of
8933 two equivalent names, VR0 cannot have any equivalences. */
8934 if (vr0->equiv)
8935 bitmap_clear (vr0->equiv);
8936 return;
8939 set_value_range_to_varying (vr0);
8940 return;
8942 set_and_canonicalize_value_range (vr0, vr0->type, vr0->min, vr0->max,
8943 vr0->equiv);
8944 if (vr0->type == VR_VARYING)
8945 return;
8947 /* The resulting set of equivalences is always the intersection of
8948 the two sets. */
8949 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
8950 bitmap_and_into (vr0->equiv, vr1->equiv);
8951 else if (vr0->equiv && !vr1->equiv)
8952 bitmap_clear (vr0->equiv);
8955 void
8956 vrp_meet (value_range *vr0, const value_range *vr1)
8958 if (dump_file && (dump_flags & TDF_DETAILS))
8960 fprintf (dump_file, "Meeting\n ");
8961 dump_value_range (dump_file, vr0);
8962 fprintf (dump_file, "\nand\n ");
8963 dump_value_range (dump_file, vr1);
8964 fprintf (dump_file, "\n");
8966 vrp_meet_1 (vr0, vr1);
8967 if (dump_file && (dump_flags & TDF_DETAILS))
8969 fprintf (dump_file, "to\n ");
8970 dump_value_range (dump_file, vr0);
8971 fprintf (dump_file, "\n");
8976 /* Visit all arguments for PHI node PHI that flow through executable
8977 edges. If a valid value range can be derived from all the incoming
8978 value ranges, set a new range in VR_RESULT. */
8980 static void
8981 extract_range_from_phi_node (gphi *phi, value_range *vr_result)
8983 size_t i;
8984 tree lhs = PHI_RESULT (phi);
8985 value_range *lhs_vr = get_value_range (lhs);
8986 bool first = true;
8987 int edges, old_edges;
8988 struct loop *l;
8990 if (dump_file && (dump_flags & TDF_DETAILS))
8992 fprintf (dump_file, "\nVisiting PHI node: ");
8993 print_gimple_stmt (dump_file, phi, 0, dump_flags);
8996 bool may_simulate_backedge_again = false;
8997 edges = 0;
8998 for (i = 0; i < gimple_phi_num_args (phi); i++)
9000 edge e = gimple_phi_arg_edge (phi, i);
9002 if (dump_file && (dump_flags & TDF_DETAILS))
9004 fprintf (dump_file,
9005 " Argument #%d (%d -> %d %sexecutable)\n",
9006 (int) i, e->src->index, e->dest->index,
9007 (e->flags & EDGE_EXECUTABLE) ? "" : "not ");
9010 if (e->flags & EDGE_EXECUTABLE)
9012 tree arg = PHI_ARG_DEF (phi, i);
9013 value_range vr_arg;
9015 ++edges;
9017 if (TREE_CODE (arg) == SSA_NAME)
9019 /* See if we are eventually going to change one of the args. */
9020 gimple *def_stmt = SSA_NAME_DEF_STMT (arg);
9021 if (! gimple_nop_p (def_stmt)
9022 && prop_simulate_again_p (def_stmt)
9023 && e->flags & EDGE_DFS_BACK)
9024 may_simulate_backedge_again = true;
9026 vr_arg = *(get_value_range (arg));
9027 /* Do not allow equivalences or symbolic ranges to leak in from
9028 backedges. That creates invalid equivalencies.
9029 See PR53465 and PR54767. */
9030 if (e->flags & EDGE_DFS_BACK)
9032 if (vr_arg.type == VR_RANGE
9033 || vr_arg.type == VR_ANTI_RANGE)
9035 vr_arg.equiv = NULL;
9036 if (symbolic_range_p (&vr_arg))
9038 vr_arg.type = VR_VARYING;
9039 vr_arg.min = NULL_TREE;
9040 vr_arg.max = NULL_TREE;
9044 else
9046 /* If the non-backedge arguments range is VR_VARYING then
9047 we can still try recording a simple equivalence. */
9048 if (vr_arg.type == VR_VARYING)
9050 vr_arg.type = VR_RANGE;
9051 vr_arg.min = arg;
9052 vr_arg.max = arg;
9053 vr_arg.equiv = NULL;
9057 else
9059 if (TREE_OVERFLOW_P (arg))
9060 arg = drop_tree_overflow (arg);
9062 vr_arg.type = VR_RANGE;
9063 vr_arg.min = arg;
9064 vr_arg.max = arg;
9065 vr_arg.equiv = NULL;
9068 if (dump_file && (dump_flags & TDF_DETAILS))
9070 fprintf (dump_file, "\t");
9071 print_generic_expr (dump_file, arg, dump_flags);
9072 fprintf (dump_file, ": ");
9073 dump_value_range (dump_file, &vr_arg);
9074 fprintf (dump_file, "\n");
9077 if (first)
9078 copy_value_range (vr_result, &vr_arg);
9079 else
9080 vrp_meet (vr_result, &vr_arg);
9081 first = false;
9083 if (vr_result->type == VR_VARYING)
9084 break;
9088 if (vr_result->type == VR_VARYING)
9089 goto varying;
9090 else if (vr_result->type == VR_UNDEFINED)
9091 goto update_range;
9093 old_edges = vr_phi_edge_counts[SSA_NAME_VERSION (lhs)];
9094 vr_phi_edge_counts[SSA_NAME_VERSION (lhs)] = edges;
9096 /* To prevent infinite iterations in the algorithm, derive ranges
9097 when the new value is slightly bigger or smaller than the
9098 previous one. We don't do this if we have seen a new executable
9099 edge; this helps us avoid an infinity for conditionals
9100 which are not in a loop. If the old value-range was VR_UNDEFINED
9101 use the updated range and iterate one more time. If we will not
9102 simulate this PHI again via the backedge allow us to iterate. */
9103 if (edges > 0
9104 && gimple_phi_num_args (phi) > 1
9105 && edges == old_edges
9106 && lhs_vr->type != VR_UNDEFINED
9107 && may_simulate_backedge_again)
9109 /* Compare old and new ranges, fall back to varying if the
9110 values are not comparable. */
9111 int cmp_min = compare_values (lhs_vr->min, vr_result->min);
9112 if (cmp_min == -2)
9113 goto varying;
9114 int cmp_max = compare_values (lhs_vr->max, vr_result->max);
9115 if (cmp_max == -2)
9116 goto varying;
9118 /* For non VR_RANGE or for pointers fall back to varying if
9119 the range changed. */
9120 if ((lhs_vr->type != VR_RANGE || vr_result->type != VR_RANGE
9121 || POINTER_TYPE_P (TREE_TYPE (lhs)))
9122 && (cmp_min != 0 || cmp_max != 0))
9123 goto varying;
9125 /* If the new minimum is larger than the previous one
9126 retain the old value. If the new minimum value is smaller
9127 than the previous one and not -INF go all the way to -INF + 1.
9128 In the first case, to avoid infinite bouncing between different
9129 minimums, and in the other case to avoid iterating millions of
9130 times to reach -INF. Going to -INF + 1 also lets the following
9131 iteration compute whether there will be any overflow, at the
9132 expense of one additional iteration. */
9133 if (cmp_min < 0)
9134 vr_result->min = lhs_vr->min;
9135 else if (cmp_min > 0
9136 && !vrp_val_is_min (vr_result->min))
9137 vr_result->min
9138 = int_const_binop (PLUS_EXPR,
9139 vrp_val_min (TREE_TYPE (vr_result->min)),
9140 build_int_cst (TREE_TYPE (vr_result->min), 1));
9142 /* Similarly for the maximum value. */
9143 if (cmp_max > 0)
9144 vr_result->max = lhs_vr->max;
9145 else if (cmp_max < 0
9146 && !vrp_val_is_max (vr_result->max))
9147 vr_result->max
9148 = int_const_binop (MINUS_EXPR,
9149 vrp_val_max (TREE_TYPE (vr_result->min)),
9150 build_int_cst (TREE_TYPE (vr_result->min), 1));
9152 /* If we dropped either bound to +-INF then if this is a loop
9153 PHI node SCEV may known more about its value-range. */
9154 if (cmp_min > 0 || cmp_min < 0
9155 || cmp_max < 0 || cmp_max > 0)
9156 goto scev_check;
9158 goto infinite_check;
9161 goto update_range;
9163 varying:
9164 set_value_range_to_varying (vr_result);
9166 scev_check:
9167 /* If this is a loop PHI node SCEV may known more about its value-range.
9168 scev_check can be reached from two paths, one is a fall through from above
9169 "varying" label, the other is direct goto from code block which tries to
9170 avoid infinite simulation. */
9171 if ((l = loop_containing_stmt (phi))
9172 && l->header == gimple_bb (phi))
9173 adjust_range_with_scev (vr_result, l, phi, lhs);
9175 infinite_check:
9176 /* If we will end up with a (-INF, +INF) range, set it to
9177 VARYING. Same if the previous max value was invalid for
9178 the type and we end up with vr_result.min > vr_result.max. */
9179 if ((vr_result->type == VR_RANGE || vr_result->type == VR_ANTI_RANGE)
9180 && !((vrp_val_is_max (vr_result->max) && vrp_val_is_min (vr_result->min))
9181 || compare_values (vr_result->min, vr_result->max) > 0))
9183 else
9184 set_value_range_to_varying (vr_result);
9186 /* If the new range is different than the previous value, keep
9187 iterating. */
9188 update_range:
9189 return;
9192 /* Visit all arguments for PHI node PHI that flow through executable
9193 edges. If a valid value range can be derived from all the incoming
9194 value ranges, set a new range for the LHS of PHI. */
9196 static enum ssa_prop_result
9197 vrp_visit_phi_node (gphi *phi)
9199 tree lhs = PHI_RESULT (phi);
9200 value_range vr_result = VR_INITIALIZER;
9201 extract_range_from_phi_node (phi, &vr_result);
9202 if (update_value_range (lhs, &vr_result))
9204 if (dump_file && (dump_flags & TDF_DETAILS))
9206 fprintf (dump_file, "Found new range for ");
9207 print_generic_expr (dump_file, lhs);
9208 fprintf (dump_file, ": ");
9209 dump_value_range (dump_file, &vr_result);
9210 fprintf (dump_file, "\n");
9213 if (vr_result.type == VR_VARYING)
9214 return SSA_PROP_VARYING;
9216 return SSA_PROP_INTERESTING;
9219 /* Nothing changed, don't add outgoing edges. */
9220 return SSA_PROP_NOT_INTERESTING;
9223 /* Simplify boolean operations if the source is known
9224 to be already a boolean. */
9225 static bool
9226 simplify_truth_ops_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9228 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
9229 tree lhs, op0, op1;
9230 bool need_conversion;
9232 /* We handle only !=/== case here. */
9233 gcc_assert (rhs_code == EQ_EXPR || rhs_code == NE_EXPR);
9235 op0 = gimple_assign_rhs1 (stmt);
9236 if (!op_with_boolean_value_range_p (op0))
9237 return false;
9239 op1 = gimple_assign_rhs2 (stmt);
9240 if (!op_with_boolean_value_range_p (op1))
9241 return false;
9243 /* Reduce number of cases to handle to NE_EXPR. As there is no
9244 BIT_XNOR_EXPR we cannot replace A == B with a single statement. */
9245 if (rhs_code == EQ_EXPR)
9247 if (TREE_CODE (op1) == INTEGER_CST)
9248 op1 = int_const_binop (BIT_XOR_EXPR, op1,
9249 build_int_cst (TREE_TYPE (op1), 1));
9250 else
9251 return false;
9254 lhs = gimple_assign_lhs (stmt);
9255 need_conversion
9256 = !useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (op0));
9258 /* Make sure to not sign-extend a 1-bit 1 when converting the result. */
9259 if (need_conversion
9260 && !TYPE_UNSIGNED (TREE_TYPE (op0))
9261 && TYPE_PRECISION (TREE_TYPE (op0)) == 1
9262 && TYPE_PRECISION (TREE_TYPE (lhs)) > 1)
9263 return false;
9265 /* For A != 0 we can substitute A itself. */
9266 if (integer_zerop (op1))
9267 gimple_assign_set_rhs_with_ops (gsi,
9268 need_conversion
9269 ? NOP_EXPR : TREE_CODE (op0), op0);
9270 /* For A != B we substitute A ^ B. Either with conversion. */
9271 else if (need_conversion)
9273 tree tem = make_ssa_name (TREE_TYPE (op0));
9274 gassign *newop
9275 = gimple_build_assign (tem, BIT_XOR_EXPR, op0, op1);
9276 gsi_insert_before (gsi, newop, GSI_SAME_STMT);
9277 if (INTEGRAL_TYPE_P (TREE_TYPE (tem))
9278 && TYPE_PRECISION (TREE_TYPE (tem)) > 1)
9279 set_range_info (tem, VR_RANGE,
9280 wi::zero (TYPE_PRECISION (TREE_TYPE (tem))),
9281 wi::one (TYPE_PRECISION (TREE_TYPE (tem))));
9282 gimple_assign_set_rhs_with_ops (gsi, NOP_EXPR, tem);
9284 /* Or without. */
9285 else
9286 gimple_assign_set_rhs_with_ops (gsi, BIT_XOR_EXPR, op0, op1);
9287 update_stmt (gsi_stmt (*gsi));
9288 fold_stmt (gsi, follow_single_use_edges);
9290 return true;
9293 /* Simplify a division or modulo operator to a right shift or bitwise and
9294 if the first operand is unsigned or is greater than zero and the second
9295 operand is an exact power of two. For TRUNC_MOD_EXPR op0 % op1 with
9296 constant op1 (op1min = op1) or with op1 in [op1min, op1max] range,
9297 optimize it into just op0 if op0's range is known to be a subset of
9298 [-op1min + 1, op1min - 1] for signed and [0, op1min - 1] for unsigned
9299 modulo. */
9301 static bool
9302 simplify_div_or_mod_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9304 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
9305 tree val = NULL;
9306 tree op0 = gimple_assign_rhs1 (stmt);
9307 tree op1 = gimple_assign_rhs2 (stmt);
9308 tree op0min = NULL_TREE, op0max = NULL_TREE;
9309 tree op1min = op1;
9310 value_range *vr = NULL;
9312 if (TREE_CODE (op0) == INTEGER_CST)
9314 op0min = op0;
9315 op0max = op0;
9317 else
9319 vr = get_value_range (op0);
9320 if (range_int_cst_p (vr))
9322 op0min = vr->min;
9323 op0max = vr->max;
9327 if (rhs_code == TRUNC_MOD_EXPR
9328 && TREE_CODE (op1) == SSA_NAME)
9330 value_range *vr1 = get_value_range (op1);
9331 if (range_int_cst_p (vr1))
9332 op1min = vr1->min;
9334 if (rhs_code == TRUNC_MOD_EXPR
9335 && TREE_CODE (op1min) == INTEGER_CST
9336 && tree_int_cst_sgn (op1min) == 1
9337 && op0max
9338 && tree_int_cst_lt (op0max, op1min))
9340 if (TYPE_UNSIGNED (TREE_TYPE (op0))
9341 || tree_int_cst_sgn (op0min) >= 0
9342 || tree_int_cst_lt (fold_unary (NEGATE_EXPR, TREE_TYPE (op1min), op1min),
9343 op0min))
9345 /* If op0 already has the range op0 % op1 has,
9346 then TRUNC_MOD_EXPR won't change anything. */
9347 gimple_assign_set_rhs_from_tree (gsi, op0);
9348 return true;
9352 if (TREE_CODE (op0) != SSA_NAME)
9353 return false;
9355 if (!integer_pow2p (op1))
9357 /* X % -Y can be only optimized into X % Y either if
9358 X is not INT_MIN, or Y is not -1. Fold it now, as after
9359 remove_range_assertions the range info might be not available
9360 anymore. */
9361 if (rhs_code == TRUNC_MOD_EXPR
9362 && fold_stmt (gsi, follow_single_use_edges))
9363 return true;
9364 return false;
9367 if (TYPE_UNSIGNED (TREE_TYPE (op0)))
9368 val = integer_one_node;
9369 else
9371 bool sop = false;
9373 val = compare_range_with_value (GE_EXPR, vr, integer_zero_node, &sop);
9375 if (val
9376 && sop
9377 && integer_onep (val)
9378 && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
9380 location_t location;
9382 if (!gimple_has_location (stmt))
9383 location = input_location;
9384 else
9385 location = gimple_location (stmt);
9386 warning_at (location, OPT_Wstrict_overflow,
9387 "assuming signed overflow does not occur when "
9388 "simplifying %</%> or %<%%%> to %<>>%> or %<&%>");
9392 if (val && integer_onep (val))
9394 tree t;
9396 if (rhs_code == TRUNC_DIV_EXPR)
9398 t = build_int_cst (integer_type_node, tree_log2 (op1));
9399 gimple_assign_set_rhs_code (stmt, RSHIFT_EXPR);
9400 gimple_assign_set_rhs1 (stmt, op0);
9401 gimple_assign_set_rhs2 (stmt, t);
9403 else
9405 t = build_int_cst (TREE_TYPE (op1), 1);
9406 t = int_const_binop (MINUS_EXPR, op1, t);
9407 t = fold_convert (TREE_TYPE (op0), t);
9409 gimple_assign_set_rhs_code (stmt, BIT_AND_EXPR);
9410 gimple_assign_set_rhs1 (stmt, op0);
9411 gimple_assign_set_rhs2 (stmt, t);
9414 update_stmt (stmt);
9415 fold_stmt (gsi, follow_single_use_edges);
9416 return true;
9419 return false;
9422 /* Simplify a min or max if the ranges of the two operands are
9423 disjoint. Return true if we do simplify. */
9425 static bool
9426 simplify_min_or_max_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9428 tree op0 = gimple_assign_rhs1 (stmt);
9429 tree op1 = gimple_assign_rhs2 (stmt);
9430 bool sop = false;
9431 tree val;
9433 val = (vrp_evaluate_conditional_warnv_with_ops_using_ranges
9434 (LE_EXPR, op0, op1, &sop));
9435 if (!val)
9437 sop = false;
9438 val = (vrp_evaluate_conditional_warnv_with_ops_using_ranges
9439 (LT_EXPR, op0, op1, &sop));
9442 if (val)
9444 if (sop && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
9446 location_t location;
9448 if (!gimple_has_location (stmt))
9449 location = input_location;
9450 else
9451 location = gimple_location (stmt);
9452 warning_at (location, OPT_Wstrict_overflow,
9453 "assuming signed overflow does not occur when "
9454 "simplifying %<min/max (X,Y)%> to %<X%> or %<Y%>");
9457 /* VAL == TRUE -> OP0 < or <= op1
9458 VAL == FALSE -> OP0 > or >= op1. */
9459 tree res = ((gimple_assign_rhs_code (stmt) == MAX_EXPR)
9460 == integer_zerop (val)) ? op0 : op1;
9461 gimple_assign_set_rhs_from_tree (gsi, res);
9462 return true;
9465 return false;
9468 /* If the operand to an ABS_EXPR is >= 0, then eliminate the
9469 ABS_EXPR. If the operand is <= 0, then simplify the
9470 ABS_EXPR into a NEGATE_EXPR. */
9472 static bool
9473 simplify_abs_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9475 tree op = gimple_assign_rhs1 (stmt);
9476 value_range *vr = get_value_range (op);
9478 if (vr)
9480 tree val = NULL;
9481 bool sop = false;
9483 val = compare_range_with_value (LE_EXPR, vr, integer_zero_node, &sop);
9484 if (!val)
9486 /* The range is neither <= 0 nor > 0. Now see if it is
9487 either < 0 or >= 0. */
9488 sop = false;
9489 val = compare_range_with_value (LT_EXPR, vr, integer_zero_node,
9490 &sop);
9493 if (val)
9495 if (sop && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
9497 location_t location;
9499 if (!gimple_has_location (stmt))
9500 location = input_location;
9501 else
9502 location = gimple_location (stmt);
9503 warning_at (location, OPT_Wstrict_overflow,
9504 "assuming signed overflow does not occur when "
9505 "simplifying %<abs (X)%> to %<X%> or %<-X%>");
9508 gimple_assign_set_rhs1 (stmt, op);
9509 if (integer_zerop (val))
9510 gimple_assign_set_rhs_code (stmt, SSA_NAME);
9511 else
9512 gimple_assign_set_rhs_code (stmt, NEGATE_EXPR);
9513 update_stmt (stmt);
9514 fold_stmt (gsi, follow_single_use_edges);
9515 return true;
9519 return false;
9522 /* Optimize away redundant BIT_AND_EXPR and BIT_IOR_EXPR.
9523 If all the bits that are being cleared by & are already
9524 known to be zero from VR, or all the bits that are being
9525 set by | are already known to be one from VR, the bit
9526 operation is redundant. */
9528 static bool
9529 simplify_bit_ops_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9531 tree op0 = gimple_assign_rhs1 (stmt);
9532 tree op1 = gimple_assign_rhs2 (stmt);
9533 tree op = NULL_TREE;
9534 value_range vr0 = VR_INITIALIZER;
9535 value_range vr1 = VR_INITIALIZER;
9536 wide_int may_be_nonzero0, may_be_nonzero1;
9537 wide_int must_be_nonzero0, must_be_nonzero1;
9538 wide_int mask;
9540 if (TREE_CODE (op0) == SSA_NAME)
9541 vr0 = *(get_value_range (op0));
9542 else if (is_gimple_min_invariant (op0))
9543 set_value_range_to_value (&vr0, op0, NULL);
9544 else
9545 return false;
9547 if (TREE_CODE (op1) == SSA_NAME)
9548 vr1 = *(get_value_range (op1));
9549 else if (is_gimple_min_invariant (op1))
9550 set_value_range_to_value (&vr1, op1, NULL);
9551 else
9552 return false;
9554 if (!zero_nonzero_bits_from_vr (TREE_TYPE (op0), &vr0, &may_be_nonzero0,
9555 &must_be_nonzero0))
9556 return false;
9557 if (!zero_nonzero_bits_from_vr (TREE_TYPE (op1), &vr1, &may_be_nonzero1,
9558 &must_be_nonzero1))
9559 return false;
9561 switch (gimple_assign_rhs_code (stmt))
9563 case BIT_AND_EXPR:
9564 mask = wi::bit_and_not (may_be_nonzero0, must_be_nonzero1);
9565 if (mask == 0)
9567 op = op0;
9568 break;
9570 mask = wi::bit_and_not (may_be_nonzero1, must_be_nonzero0);
9571 if (mask == 0)
9573 op = op1;
9574 break;
9576 break;
9577 case BIT_IOR_EXPR:
9578 mask = wi::bit_and_not (may_be_nonzero0, must_be_nonzero1);
9579 if (mask == 0)
9581 op = op1;
9582 break;
9584 mask = wi::bit_and_not (may_be_nonzero1, must_be_nonzero0);
9585 if (mask == 0)
9587 op = op0;
9588 break;
9590 break;
9591 default:
9592 gcc_unreachable ();
9595 if (op == NULL_TREE)
9596 return false;
9598 gimple_assign_set_rhs_with_ops (gsi, TREE_CODE (op), op);
9599 update_stmt (gsi_stmt (*gsi));
9600 return true;
9603 /* We are comparing trees OP0 and OP1 using COND_CODE. OP0 has
9604 a known value range VR.
9606 If there is one and only one value which will satisfy the
9607 conditional, then return that value. Else return NULL.
9609 If signed overflow must be undefined for the value to satisfy
9610 the conditional, then set *STRICT_OVERFLOW_P to true. */
9612 static tree
9613 test_for_singularity (enum tree_code cond_code, tree op0,
9614 tree op1, value_range *vr)
9616 tree min = NULL;
9617 tree max = NULL;
9619 /* Extract minimum/maximum values which satisfy the conditional as it was
9620 written. */
9621 if (cond_code == LE_EXPR || cond_code == LT_EXPR)
9623 min = TYPE_MIN_VALUE (TREE_TYPE (op0));
9625 max = op1;
9626 if (cond_code == LT_EXPR)
9628 tree one = build_int_cst (TREE_TYPE (op0), 1);
9629 max = fold_build2 (MINUS_EXPR, TREE_TYPE (op0), max, one);
9630 /* Signal to compare_values_warnv this expr doesn't overflow. */
9631 if (EXPR_P (max))
9632 TREE_NO_WARNING (max) = 1;
9635 else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
9637 max = TYPE_MAX_VALUE (TREE_TYPE (op0));
9639 min = op1;
9640 if (cond_code == GT_EXPR)
9642 tree one = build_int_cst (TREE_TYPE (op0), 1);
9643 min = fold_build2 (PLUS_EXPR, TREE_TYPE (op0), min, one);
9644 /* Signal to compare_values_warnv this expr doesn't overflow. */
9645 if (EXPR_P (min))
9646 TREE_NO_WARNING (min) = 1;
9650 /* Now refine the minimum and maximum values using any
9651 value range information we have for op0. */
9652 if (min && max)
9654 if (compare_values (vr->min, min) == 1)
9655 min = vr->min;
9656 if (compare_values (vr->max, max) == -1)
9657 max = vr->max;
9659 /* If the new min/max values have converged to a single value,
9660 then there is only one value which can satisfy the condition,
9661 return that value. */
9662 if (operand_equal_p (min, max, 0) && is_gimple_min_invariant (min))
9663 return min;
9665 return NULL;
9668 /* Return whether the value range *VR fits in an integer type specified
9669 by PRECISION and UNSIGNED_P. */
9671 static bool
9672 range_fits_type_p (value_range *vr, unsigned dest_precision, signop dest_sgn)
9674 tree src_type;
9675 unsigned src_precision;
9676 widest_int tem;
9677 signop src_sgn;
9679 /* We can only handle integral and pointer types. */
9680 src_type = TREE_TYPE (vr->min);
9681 if (!INTEGRAL_TYPE_P (src_type)
9682 && !POINTER_TYPE_P (src_type))
9683 return false;
9685 /* An extension is fine unless VR is SIGNED and dest_sgn is UNSIGNED,
9686 and so is an identity transform. */
9687 src_precision = TYPE_PRECISION (TREE_TYPE (vr->min));
9688 src_sgn = TYPE_SIGN (src_type);
9689 if ((src_precision < dest_precision
9690 && !(dest_sgn == UNSIGNED && src_sgn == SIGNED))
9691 || (src_precision == dest_precision && src_sgn == dest_sgn))
9692 return true;
9694 /* Now we can only handle ranges with constant bounds. */
9695 if (vr->type != VR_RANGE
9696 || TREE_CODE (vr->min) != INTEGER_CST
9697 || TREE_CODE (vr->max) != INTEGER_CST)
9698 return false;
9700 /* For sign changes, the MSB of the wide_int has to be clear.
9701 An unsigned value with its MSB set cannot be represented by
9702 a signed wide_int, while a negative value cannot be represented
9703 by an unsigned wide_int. */
9704 if (src_sgn != dest_sgn
9705 && (wi::lts_p (wi::to_wide (vr->min), 0)
9706 || wi::lts_p (wi::to_wide (vr->max), 0)))
9707 return false;
9709 /* Then we can perform the conversion on both ends and compare
9710 the result for equality. */
9711 tem = wi::ext (wi::to_widest (vr->min), dest_precision, dest_sgn);
9712 if (tem != wi::to_widest (vr->min))
9713 return false;
9714 tem = wi::ext (wi::to_widest (vr->max), dest_precision, dest_sgn);
9715 if (tem != wi::to_widest (vr->max))
9716 return false;
9718 return true;
9721 /* Simplify a conditional using a relational operator to an equality
9722 test if the range information indicates only one value can satisfy
9723 the original conditional. */
9725 static bool
9726 simplify_cond_using_ranges_1 (gcond *stmt)
9728 tree op0 = gimple_cond_lhs (stmt);
9729 tree op1 = gimple_cond_rhs (stmt);
9730 enum tree_code cond_code = gimple_cond_code (stmt);
9732 if (cond_code != NE_EXPR
9733 && cond_code != EQ_EXPR
9734 && TREE_CODE (op0) == SSA_NAME
9735 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
9736 && is_gimple_min_invariant (op1))
9738 value_range *vr = get_value_range (op0);
9740 /* If we have range information for OP0, then we might be
9741 able to simplify this conditional. */
9742 if (vr->type == VR_RANGE)
9744 tree new_tree = test_for_singularity (cond_code, op0, op1, vr);
9745 if (new_tree)
9747 if (dump_file)
9749 fprintf (dump_file, "Simplified relational ");
9750 print_gimple_stmt (dump_file, stmt, 0);
9751 fprintf (dump_file, " into ");
9754 gimple_cond_set_code (stmt, EQ_EXPR);
9755 gimple_cond_set_lhs (stmt, op0);
9756 gimple_cond_set_rhs (stmt, new_tree);
9758 update_stmt (stmt);
9760 if (dump_file)
9762 print_gimple_stmt (dump_file, stmt, 0);
9763 fprintf (dump_file, "\n");
9766 return true;
9769 /* Try again after inverting the condition. We only deal
9770 with integral types here, so no need to worry about
9771 issues with inverting FP comparisons. */
9772 new_tree = test_for_singularity
9773 (invert_tree_comparison (cond_code, false),
9774 op0, op1, vr);
9775 if (new_tree)
9777 if (dump_file)
9779 fprintf (dump_file, "Simplified relational ");
9780 print_gimple_stmt (dump_file, stmt, 0);
9781 fprintf (dump_file, " into ");
9784 gimple_cond_set_code (stmt, NE_EXPR);
9785 gimple_cond_set_lhs (stmt, op0);
9786 gimple_cond_set_rhs (stmt, new_tree);
9788 update_stmt (stmt);
9790 if (dump_file)
9792 print_gimple_stmt (dump_file, stmt, 0);
9793 fprintf (dump_file, "\n");
9796 return true;
9800 return false;
9803 /* STMT is a conditional at the end of a basic block.
9805 If the conditional is of the form SSA_NAME op constant and the SSA_NAME
9806 was set via a type conversion, try to replace the SSA_NAME with the RHS
9807 of the type conversion. Doing so makes the conversion dead which helps
9808 subsequent passes. */
9810 static void
9811 simplify_cond_using_ranges_2 (gcond *stmt)
9813 tree op0 = gimple_cond_lhs (stmt);
9814 tree op1 = gimple_cond_rhs (stmt);
9816 /* If we have a comparison of an SSA_NAME (OP0) against a constant,
9817 see if OP0 was set by a type conversion where the source of
9818 the conversion is another SSA_NAME with a range that fits
9819 into the range of OP0's type.
9821 If so, the conversion is redundant as the earlier SSA_NAME can be
9822 used for the comparison directly if we just massage the constant in the
9823 comparison. */
9824 if (TREE_CODE (op0) == SSA_NAME
9825 && TREE_CODE (op1) == INTEGER_CST)
9827 gimple *def_stmt = SSA_NAME_DEF_STMT (op0);
9828 tree innerop;
9830 if (!is_gimple_assign (def_stmt)
9831 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)))
9832 return;
9834 innerop = gimple_assign_rhs1 (def_stmt);
9836 if (TREE_CODE (innerop) == SSA_NAME
9837 && !POINTER_TYPE_P (TREE_TYPE (innerop))
9838 && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (innerop)
9839 && desired_pro_or_demotion_p (TREE_TYPE (innerop), TREE_TYPE (op0)))
9841 value_range *vr = get_value_range (innerop);
9843 if (range_int_cst_p (vr)
9844 && range_fits_type_p (vr,
9845 TYPE_PRECISION (TREE_TYPE (op0)),
9846 TYPE_SIGN (TREE_TYPE (op0)))
9847 && int_fits_type_p (op1, TREE_TYPE (innerop)))
9849 tree newconst = fold_convert (TREE_TYPE (innerop), op1);
9850 gimple_cond_set_lhs (stmt, innerop);
9851 gimple_cond_set_rhs (stmt, newconst);
9852 update_stmt (stmt);
9853 if (dump_file && (dump_flags & TDF_DETAILS))
9855 fprintf (dump_file, "Folded into: ");
9856 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
9857 fprintf (dump_file, "\n");
9864 /* Simplify a switch statement using the value range of the switch
9865 argument. */
9867 static bool
9868 simplify_switch_using_ranges (gswitch *stmt)
9870 tree op = gimple_switch_index (stmt);
9871 value_range *vr = NULL;
9872 bool take_default;
9873 edge e;
9874 edge_iterator ei;
9875 size_t i = 0, j = 0, n, n2;
9876 tree vec2;
9877 switch_update su;
9878 size_t k = 1, l = 0;
9880 if (TREE_CODE (op) == SSA_NAME)
9882 vr = get_value_range (op);
9884 /* We can only handle integer ranges. */
9885 if ((vr->type != VR_RANGE
9886 && vr->type != VR_ANTI_RANGE)
9887 || symbolic_range_p (vr))
9888 return false;
9890 /* Find case label for min/max of the value range. */
9891 take_default = !find_case_label_ranges (stmt, vr, &i, &j, &k, &l);
9893 else if (TREE_CODE (op) == INTEGER_CST)
9895 take_default = !find_case_label_index (stmt, 1, op, &i);
9896 if (take_default)
9898 i = 1;
9899 j = 0;
9901 else
9903 j = i;
9906 else
9907 return false;
9909 n = gimple_switch_num_labels (stmt);
9911 /* We can truncate the case label ranges that partially overlap with OP's
9912 value range. */
9913 size_t min_idx = 1, max_idx = 0;
9914 if (vr != NULL)
9915 find_case_label_range (stmt, vr->min, vr->max, &min_idx, &max_idx);
9916 if (min_idx <= max_idx)
9918 tree min_label = gimple_switch_label (stmt, min_idx);
9919 tree max_label = gimple_switch_label (stmt, max_idx);
9921 /* Avoid changing the type of the case labels when truncating. */
9922 tree case_label_type = TREE_TYPE (CASE_LOW (min_label));
9923 tree vr_min = fold_convert (case_label_type, vr->min);
9924 tree vr_max = fold_convert (case_label_type, vr->max);
9926 if (vr->type == VR_RANGE)
9928 /* If OP's value range is [2,8] and the low label range is
9929 0 ... 3, truncate the label's range to 2 .. 3. */
9930 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
9931 && CASE_HIGH (min_label) != NULL_TREE
9932 && tree_int_cst_compare (CASE_HIGH (min_label), vr_min) >= 0)
9933 CASE_LOW (min_label) = vr_min;
9935 /* If OP's value range is [2,8] and the high label range is
9936 7 ... 10, truncate the label's range to 7 .. 8. */
9937 if (tree_int_cst_compare (CASE_LOW (max_label), vr_max) <= 0
9938 && CASE_HIGH (max_label) != NULL_TREE
9939 && tree_int_cst_compare (CASE_HIGH (max_label), vr_max) > 0)
9940 CASE_HIGH (max_label) = vr_max;
9942 else if (vr->type == VR_ANTI_RANGE)
9944 tree one_cst = build_one_cst (case_label_type);
9946 if (min_label == max_label)
9948 /* If OP's value range is ~[7,8] and the label's range is
9949 7 ... 10, truncate the label's range to 9 ... 10. */
9950 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) == 0
9951 && CASE_HIGH (min_label) != NULL_TREE
9952 && tree_int_cst_compare (CASE_HIGH (min_label), vr_max) > 0)
9953 CASE_LOW (min_label)
9954 = int_const_binop (PLUS_EXPR, vr_max, one_cst);
9956 /* If OP's value range is ~[7,8] and the label's range is
9957 5 ... 8, truncate the label's range to 5 ... 6. */
9958 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
9959 && CASE_HIGH (min_label) != NULL_TREE
9960 && tree_int_cst_compare (CASE_HIGH (min_label), vr_max) == 0)
9961 CASE_HIGH (min_label)
9962 = int_const_binop (MINUS_EXPR, vr_min, one_cst);
9964 else
9966 /* If OP's value range is ~[2,8] and the low label range is
9967 0 ... 3, truncate the label's range to 0 ... 1. */
9968 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
9969 && CASE_HIGH (min_label) != NULL_TREE
9970 && tree_int_cst_compare (CASE_HIGH (min_label), vr_min) >= 0)
9971 CASE_HIGH (min_label)
9972 = int_const_binop (MINUS_EXPR, vr_min, one_cst);
9974 /* If OP's value range is ~[2,8] and the high label range is
9975 7 ... 10, truncate the label's range to 9 ... 10. */
9976 if (tree_int_cst_compare (CASE_LOW (max_label), vr_max) <= 0
9977 && CASE_HIGH (max_label) != NULL_TREE
9978 && tree_int_cst_compare (CASE_HIGH (max_label), vr_max) > 0)
9979 CASE_LOW (max_label)
9980 = int_const_binop (PLUS_EXPR, vr_max, one_cst);
9984 /* Canonicalize singleton case ranges. */
9985 if (tree_int_cst_equal (CASE_LOW (min_label), CASE_HIGH (min_label)))
9986 CASE_HIGH (min_label) = NULL_TREE;
9987 if (tree_int_cst_equal (CASE_LOW (max_label), CASE_HIGH (max_label)))
9988 CASE_HIGH (max_label) = NULL_TREE;
9991 /* We can also eliminate case labels that lie completely outside OP's value
9992 range. */
9994 /* Bail out if this is just all edges taken. */
9995 if (i == 1
9996 && j == n - 1
9997 && take_default)
9998 return false;
10000 /* Build a new vector of taken case labels. */
10001 vec2 = make_tree_vec (j - i + 1 + l - k + 1 + (int)take_default);
10002 n2 = 0;
10004 /* Add the default edge, if necessary. */
10005 if (take_default)
10006 TREE_VEC_ELT (vec2, n2++) = gimple_switch_default_label (stmt);
10008 for (; i <= j; ++i, ++n2)
10009 TREE_VEC_ELT (vec2, n2) = gimple_switch_label (stmt, i);
10011 for (; k <= l; ++k, ++n2)
10012 TREE_VEC_ELT (vec2, n2) = gimple_switch_label (stmt, k);
10014 /* Mark needed edges. */
10015 for (i = 0; i < n2; ++i)
10017 e = find_edge (gimple_bb (stmt),
10018 label_to_block (CASE_LABEL (TREE_VEC_ELT (vec2, i))));
10019 e->aux = (void *)-1;
10022 /* Queue not needed edges for later removal. */
10023 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
10025 if (e->aux == (void *)-1)
10027 e->aux = NULL;
10028 continue;
10031 if (dump_file && (dump_flags & TDF_DETAILS))
10033 fprintf (dump_file, "removing unreachable case label\n");
10035 to_remove_edges.safe_push (e);
10036 e->flags &= ~EDGE_EXECUTABLE;
10039 /* And queue an update for the stmt. */
10040 su.stmt = stmt;
10041 su.vec = vec2;
10042 to_update_switch_stmts.safe_push (su);
10043 return false;
10046 /* Simplify an integral conversion from an SSA name in STMT. */
10048 static bool
10049 simplify_conversion_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
10051 tree innerop, middleop, finaltype;
10052 gimple *def_stmt;
10053 signop inner_sgn, middle_sgn, final_sgn;
10054 unsigned inner_prec, middle_prec, final_prec;
10055 widest_int innermin, innermed, innermax, middlemin, middlemed, middlemax;
10057 finaltype = TREE_TYPE (gimple_assign_lhs (stmt));
10058 if (!INTEGRAL_TYPE_P (finaltype))
10059 return false;
10060 middleop = gimple_assign_rhs1 (stmt);
10061 def_stmt = SSA_NAME_DEF_STMT (middleop);
10062 if (!is_gimple_assign (def_stmt)
10063 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)))
10064 return false;
10065 innerop = gimple_assign_rhs1 (def_stmt);
10066 if (TREE_CODE (innerop) != SSA_NAME
10067 || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (innerop))
10068 return false;
10070 /* Get the value-range of the inner operand. Use get_range_info in
10071 case innerop was created during substitute-and-fold. */
10072 wide_int imin, imax;
10073 if (!INTEGRAL_TYPE_P (TREE_TYPE (innerop))
10074 || get_range_info (innerop, &imin, &imax) != VR_RANGE)
10075 return false;
10076 innermin = widest_int::from (imin, TYPE_SIGN (TREE_TYPE (innerop)));
10077 innermax = widest_int::from (imax, TYPE_SIGN (TREE_TYPE (innerop)));
10079 /* Simulate the conversion chain to check if the result is equal if
10080 the middle conversion is removed. */
10081 inner_prec = TYPE_PRECISION (TREE_TYPE (innerop));
10082 middle_prec = TYPE_PRECISION (TREE_TYPE (middleop));
10083 final_prec = TYPE_PRECISION (finaltype);
10085 /* If the first conversion is not injective, the second must not
10086 be widening. */
10087 if (wi::gtu_p (innermax - innermin,
10088 wi::mask <widest_int> (middle_prec, false))
10089 && middle_prec < final_prec)
10090 return false;
10091 /* We also want a medium value so that we can track the effect that
10092 narrowing conversions with sign change have. */
10093 inner_sgn = TYPE_SIGN (TREE_TYPE (innerop));
10094 if (inner_sgn == UNSIGNED)
10095 innermed = wi::shifted_mask <widest_int> (1, inner_prec - 1, false);
10096 else
10097 innermed = 0;
10098 if (wi::cmp (innermin, innermed, inner_sgn) >= 0
10099 || wi::cmp (innermed, innermax, inner_sgn) >= 0)
10100 innermed = innermin;
10102 middle_sgn = TYPE_SIGN (TREE_TYPE (middleop));
10103 middlemin = wi::ext (innermin, middle_prec, middle_sgn);
10104 middlemed = wi::ext (innermed, middle_prec, middle_sgn);
10105 middlemax = wi::ext (innermax, middle_prec, middle_sgn);
10107 /* Require that the final conversion applied to both the original
10108 and the intermediate range produces the same result. */
10109 final_sgn = TYPE_SIGN (finaltype);
10110 if (wi::ext (middlemin, final_prec, final_sgn)
10111 != wi::ext (innermin, final_prec, final_sgn)
10112 || wi::ext (middlemed, final_prec, final_sgn)
10113 != wi::ext (innermed, final_prec, final_sgn)
10114 || wi::ext (middlemax, final_prec, final_sgn)
10115 != wi::ext (innermax, final_prec, final_sgn))
10116 return false;
10118 gimple_assign_set_rhs1 (stmt, innerop);
10119 fold_stmt (gsi, follow_single_use_edges);
10120 return true;
10123 /* Simplify a conversion from integral SSA name to float in STMT. */
10125 static bool
10126 simplify_float_conversion_using_ranges (gimple_stmt_iterator *gsi,
10127 gimple *stmt)
10129 tree rhs1 = gimple_assign_rhs1 (stmt);
10130 value_range *vr = get_value_range (rhs1);
10131 scalar_float_mode fltmode
10132 = SCALAR_FLOAT_TYPE_MODE (TREE_TYPE (gimple_assign_lhs (stmt)));
10133 scalar_int_mode mode;
10134 tree tem;
10135 gassign *conv;
10137 /* We can only handle constant ranges. */
10138 if (vr->type != VR_RANGE
10139 || TREE_CODE (vr->min) != INTEGER_CST
10140 || TREE_CODE (vr->max) != INTEGER_CST)
10141 return false;
10143 /* First check if we can use a signed type in place of an unsigned. */
10144 scalar_int_mode rhs_mode = SCALAR_INT_TYPE_MODE (TREE_TYPE (rhs1));
10145 if (TYPE_UNSIGNED (TREE_TYPE (rhs1))
10146 && can_float_p (fltmode, rhs_mode, 0) != CODE_FOR_nothing
10147 && range_fits_type_p (vr, TYPE_PRECISION (TREE_TYPE (rhs1)), SIGNED))
10148 mode = rhs_mode;
10149 /* If we can do the conversion in the current input mode do nothing. */
10150 else if (can_float_p (fltmode, rhs_mode,
10151 TYPE_UNSIGNED (TREE_TYPE (rhs1))) != CODE_FOR_nothing)
10152 return false;
10153 /* Otherwise search for a mode we can use, starting from the narrowest
10154 integer mode available. */
10155 else
10157 mode = NARROWEST_INT_MODE;
10158 for (;;)
10160 /* If we cannot do a signed conversion to float from mode
10161 or if the value-range does not fit in the signed type
10162 try with a wider mode. */
10163 if (can_float_p (fltmode, mode, 0) != CODE_FOR_nothing
10164 && range_fits_type_p (vr, GET_MODE_PRECISION (mode), SIGNED))
10165 break;
10167 /* But do not widen the input. Instead leave that to the
10168 optabs expansion code. */
10169 if (!GET_MODE_WIDER_MODE (mode).exists (&mode)
10170 || GET_MODE_PRECISION (mode) > TYPE_PRECISION (TREE_TYPE (rhs1)))
10171 return false;
10175 /* It works, insert a truncation or sign-change before the
10176 float conversion. */
10177 tem = make_ssa_name (build_nonstandard_integer_type
10178 (GET_MODE_PRECISION (mode), 0));
10179 conv = gimple_build_assign (tem, NOP_EXPR, rhs1);
10180 gsi_insert_before (gsi, conv, GSI_SAME_STMT);
10181 gimple_assign_set_rhs1 (stmt, tem);
10182 fold_stmt (gsi, follow_single_use_edges);
10184 return true;
10187 /* Simplify an internal fn call using ranges if possible. */
10189 static bool
10190 simplify_internal_call_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
10192 enum tree_code subcode;
10193 bool is_ubsan = false;
10194 bool ovf = false;
10195 switch (gimple_call_internal_fn (stmt))
10197 case IFN_UBSAN_CHECK_ADD:
10198 subcode = PLUS_EXPR;
10199 is_ubsan = true;
10200 break;
10201 case IFN_UBSAN_CHECK_SUB:
10202 subcode = MINUS_EXPR;
10203 is_ubsan = true;
10204 break;
10205 case IFN_UBSAN_CHECK_MUL:
10206 subcode = MULT_EXPR;
10207 is_ubsan = true;
10208 break;
10209 case IFN_ADD_OVERFLOW:
10210 subcode = PLUS_EXPR;
10211 break;
10212 case IFN_SUB_OVERFLOW:
10213 subcode = MINUS_EXPR;
10214 break;
10215 case IFN_MUL_OVERFLOW:
10216 subcode = MULT_EXPR;
10217 break;
10218 default:
10219 return false;
10222 tree op0 = gimple_call_arg (stmt, 0);
10223 tree op1 = gimple_call_arg (stmt, 1);
10224 tree type;
10225 if (is_ubsan)
10227 type = TREE_TYPE (op0);
10228 if (VECTOR_TYPE_P (type))
10229 return false;
10231 else if (gimple_call_lhs (stmt) == NULL_TREE)
10232 return false;
10233 else
10234 type = TREE_TYPE (TREE_TYPE (gimple_call_lhs (stmt)));
10235 if (!check_for_binary_op_overflow (subcode, type, op0, op1, &ovf)
10236 || (is_ubsan && ovf))
10237 return false;
10239 gimple *g;
10240 location_t loc = gimple_location (stmt);
10241 if (is_ubsan)
10242 g = gimple_build_assign (gimple_call_lhs (stmt), subcode, op0, op1);
10243 else
10245 int prec = TYPE_PRECISION (type);
10246 tree utype = type;
10247 if (ovf
10248 || !useless_type_conversion_p (type, TREE_TYPE (op0))
10249 || !useless_type_conversion_p (type, TREE_TYPE (op1)))
10250 utype = build_nonstandard_integer_type (prec, 1);
10251 if (TREE_CODE (op0) == INTEGER_CST)
10252 op0 = fold_convert (utype, op0);
10253 else if (!useless_type_conversion_p (utype, TREE_TYPE (op0)))
10255 g = gimple_build_assign (make_ssa_name (utype), NOP_EXPR, op0);
10256 gimple_set_location (g, loc);
10257 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10258 op0 = gimple_assign_lhs (g);
10260 if (TREE_CODE (op1) == INTEGER_CST)
10261 op1 = fold_convert (utype, op1);
10262 else if (!useless_type_conversion_p (utype, TREE_TYPE (op1)))
10264 g = gimple_build_assign (make_ssa_name (utype), NOP_EXPR, op1);
10265 gimple_set_location (g, loc);
10266 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10267 op1 = gimple_assign_lhs (g);
10269 g = gimple_build_assign (make_ssa_name (utype), subcode, op0, op1);
10270 gimple_set_location (g, loc);
10271 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10272 if (utype != type)
10274 g = gimple_build_assign (make_ssa_name (type), NOP_EXPR,
10275 gimple_assign_lhs (g));
10276 gimple_set_location (g, loc);
10277 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10279 g = gimple_build_assign (gimple_call_lhs (stmt), COMPLEX_EXPR,
10280 gimple_assign_lhs (g),
10281 build_int_cst (type, ovf));
10283 gimple_set_location (g, loc);
10284 gsi_replace (gsi, g, false);
10285 return true;
10288 /* Return true if VAR is a two-valued variable. Set a and b with the
10289 two-values when it is true. Return false otherwise. */
10291 static bool
10292 two_valued_val_range_p (tree var, tree *a, tree *b)
10294 value_range *vr = get_value_range (var);
10295 if ((vr->type != VR_RANGE
10296 && vr->type != VR_ANTI_RANGE)
10297 || TREE_CODE (vr->min) != INTEGER_CST
10298 || TREE_CODE (vr->max) != INTEGER_CST)
10299 return false;
10301 if (vr->type == VR_RANGE
10302 && wi::to_wide (vr->max) - wi::to_wide (vr->min) == 1)
10304 *a = vr->min;
10305 *b = vr->max;
10306 return true;
10309 /* ~[TYPE_MIN + 1, TYPE_MAX - 1] */
10310 if (vr->type == VR_ANTI_RANGE
10311 && (wi::to_wide (vr->min)
10312 - wi::to_wide (vrp_val_min (TREE_TYPE (var)))) == 1
10313 && (wi::to_wide (vrp_val_max (TREE_TYPE (var)))
10314 - wi::to_wide (vr->max)) == 1)
10316 *a = vrp_val_min (TREE_TYPE (var));
10317 *b = vrp_val_max (TREE_TYPE (var));
10318 return true;
10321 return false;
10324 /* Simplify STMT using ranges if possible. */
10326 static bool
10327 simplify_stmt_using_ranges (gimple_stmt_iterator *gsi)
10329 gimple *stmt = gsi_stmt (*gsi);
10330 if (is_gimple_assign (stmt))
10332 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
10333 tree rhs1 = gimple_assign_rhs1 (stmt);
10334 tree rhs2 = gimple_assign_rhs2 (stmt);
10335 tree lhs = gimple_assign_lhs (stmt);
10336 tree val1 = NULL_TREE, val2 = NULL_TREE;
10337 use_operand_p use_p;
10338 gimple *use_stmt;
10340 /* Convert:
10341 LHS = CST BINOP VAR
10342 Where VAR is two-valued and LHS is used in GIMPLE_COND only
10344 LHS = VAR == VAL1 ? (CST BINOP VAL1) : (CST BINOP VAL2)
10346 Also handles:
10347 LHS = VAR BINOP CST
10348 Where VAR is two-valued and LHS is used in GIMPLE_COND only
10350 LHS = VAR == VAL1 ? (VAL1 BINOP CST) : (VAL2 BINOP CST) */
10352 if (TREE_CODE_CLASS (rhs_code) == tcc_binary
10353 && INTEGRAL_TYPE_P (TREE_TYPE (lhs))
10354 && ((TREE_CODE (rhs1) == INTEGER_CST
10355 && TREE_CODE (rhs2) == SSA_NAME)
10356 || (TREE_CODE (rhs2) == INTEGER_CST
10357 && TREE_CODE (rhs1) == SSA_NAME))
10358 && single_imm_use (lhs, &use_p, &use_stmt)
10359 && gimple_code (use_stmt) == GIMPLE_COND)
10362 tree new_rhs1 = NULL_TREE;
10363 tree new_rhs2 = NULL_TREE;
10364 tree cmp_var = NULL_TREE;
10366 if (TREE_CODE (rhs2) == SSA_NAME
10367 && two_valued_val_range_p (rhs2, &val1, &val2))
10369 /* Optimize RHS1 OP [VAL1, VAL2]. */
10370 new_rhs1 = int_const_binop (rhs_code, rhs1, val1);
10371 new_rhs2 = int_const_binop (rhs_code, rhs1, val2);
10372 cmp_var = rhs2;
10374 else if (TREE_CODE (rhs1) == SSA_NAME
10375 && two_valued_val_range_p (rhs1, &val1, &val2))
10377 /* Optimize [VAL1, VAL2] OP RHS2. */
10378 new_rhs1 = int_const_binop (rhs_code, val1, rhs2);
10379 new_rhs2 = int_const_binop (rhs_code, val2, rhs2);
10380 cmp_var = rhs1;
10383 /* If we could not find two-vals or the optimzation is invalid as
10384 in divide by zero, new_rhs1 / new_rhs will be NULL_TREE. */
10385 if (new_rhs1 && new_rhs2)
10387 tree cond = build2 (EQ_EXPR, boolean_type_node, cmp_var, val1);
10388 gimple_assign_set_rhs_with_ops (gsi,
10389 COND_EXPR, cond,
10390 new_rhs1,
10391 new_rhs2);
10392 update_stmt (gsi_stmt (*gsi));
10393 fold_stmt (gsi, follow_single_use_edges);
10394 return true;
10398 switch (rhs_code)
10400 case EQ_EXPR:
10401 case NE_EXPR:
10402 /* Transform EQ_EXPR, NE_EXPR into BIT_XOR_EXPR or identity
10403 if the RHS is zero or one, and the LHS are known to be boolean
10404 values. */
10405 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10406 return simplify_truth_ops_using_ranges (gsi, stmt);
10407 break;
10409 /* Transform TRUNC_DIV_EXPR and TRUNC_MOD_EXPR into RSHIFT_EXPR
10410 and BIT_AND_EXPR respectively if the first operand is greater
10411 than zero and the second operand is an exact power of two.
10412 Also optimize TRUNC_MOD_EXPR away if the second operand is
10413 constant and the first operand already has the right value
10414 range. */
10415 case TRUNC_DIV_EXPR:
10416 case TRUNC_MOD_EXPR:
10417 if ((TREE_CODE (rhs1) == SSA_NAME
10418 || TREE_CODE (rhs1) == INTEGER_CST)
10419 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10420 return simplify_div_or_mod_using_ranges (gsi, stmt);
10421 break;
10423 /* Transform ABS (X) into X or -X as appropriate. */
10424 case ABS_EXPR:
10425 if (TREE_CODE (rhs1) == SSA_NAME
10426 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10427 return simplify_abs_using_ranges (gsi, stmt);
10428 break;
10430 case BIT_AND_EXPR:
10431 case BIT_IOR_EXPR:
10432 /* Optimize away BIT_AND_EXPR and BIT_IOR_EXPR
10433 if all the bits being cleared are already cleared or
10434 all the bits being set are already set. */
10435 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10436 return simplify_bit_ops_using_ranges (gsi, stmt);
10437 break;
10439 CASE_CONVERT:
10440 if (TREE_CODE (rhs1) == SSA_NAME
10441 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10442 return simplify_conversion_using_ranges (gsi, stmt);
10443 break;
10445 case FLOAT_EXPR:
10446 if (TREE_CODE (rhs1) == SSA_NAME
10447 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10448 return simplify_float_conversion_using_ranges (gsi, stmt);
10449 break;
10451 case MIN_EXPR:
10452 case MAX_EXPR:
10453 return simplify_min_or_max_using_ranges (gsi, stmt);
10455 default:
10456 break;
10459 else if (gimple_code (stmt) == GIMPLE_COND)
10460 return simplify_cond_using_ranges_1 (as_a <gcond *> (stmt));
10461 else if (gimple_code (stmt) == GIMPLE_SWITCH)
10462 return simplify_switch_using_ranges (as_a <gswitch *> (stmt));
10463 else if (is_gimple_call (stmt)
10464 && gimple_call_internal_p (stmt))
10465 return simplify_internal_call_using_ranges (gsi, stmt);
10467 return false;
10470 /* If the statement pointed by SI has a predicate whose value can be
10471 computed using the value range information computed by VRP, compute
10472 its value and return true. Otherwise, return false. */
10474 static bool
10475 fold_predicate_in (gimple_stmt_iterator *si)
10477 bool assignment_p = false;
10478 tree val;
10479 gimple *stmt = gsi_stmt (*si);
10481 if (is_gimple_assign (stmt)
10482 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
10484 assignment_p = true;
10485 val = vrp_evaluate_conditional (gimple_assign_rhs_code (stmt),
10486 gimple_assign_rhs1 (stmt),
10487 gimple_assign_rhs2 (stmt),
10488 stmt);
10490 else if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
10491 val = vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
10492 gimple_cond_lhs (cond_stmt),
10493 gimple_cond_rhs (cond_stmt),
10494 stmt);
10495 else
10496 return false;
10498 if (val)
10500 if (assignment_p)
10501 val = fold_convert (gimple_expr_type (stmt), val);
10503 if (dump_file)
10505 fprintf (dump_file, "Folding predicate ");
10506 print_gimple_expr (dump_file, stmt, 0);
10507 fprintf (dump_file, " to ");
10508 print_generic_expr (dump_file, val);
10509 fprintf (dump_file, "\n");
10512 if (is_gimple_assign (stmt))
10513 gimple_assign_set_rhs_from_tree (si, val);
10514 else
10516 gcc_assert (gimple_code (stmt) == GIMPLE_COND);
10517 gcond *cond_stmt = as_a <gcond *> (stmt);
10518 if (integer_zerop (val))
10519 gimple_cond_make_false (cond_stmt);
10520 else if (integer_onep (val))
10521 gimple_cond_make_true (cond_stmt);
10522 else
10523 gcc_unreachable ();
10526 return true;
10529 return false;
10532 /* Callback for substitute_and_fold folding the stmt at *SI. */
10534 static bool
10535 vrp_fold_stmt (gimple_stmt_iterator *si)
10537 if (fold_predicate_in (si))
10538 return true;
10540 return simplify_stmt_using_ranges (si);
10543 /* Return the LHS of any ASSERT_EXPR where OP appears as the first
10544 argument to the ASSERT_EXPR and in which the ASSERT_EXPR dominates
10545 BB. If no such ASSERT_EXPR is found, return OP. */
10547 static tree
10548 lhs_of_dominating_assert (tree op, basic_block bb, gimple *stmt)
10550 imm_use_iterator imm_iter;
10551 gimple *use_stmt;
10552 use_operand_p use_p;
10554 if (TREE_CODE (op) == SSA_NAME)
10556 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, op)
10558 use_stmt = USE_STMT (use_p);
10559 if (use_stmt != stmt
10560 && gimple_assign_single_p (use_stmt)
10561 && TREE_CODE (gimple_assign_rhs1 (use_stmt)) == ASSERT_EXPR
10562 && TREE_OPERAND (gimple_assign_rhs1 (use_stmt), 0) == op
10563 && dominated_by_p (CDI_DOMINATORS, bb, gimple_bb (use_stmt)))
10564 return gimple_assign_lhs (use_stmt);
10567 return op;
10570 /* A trivial wrapper so that we can present the generic jump threading
10571 code with a simple API for simplifying statements. STMT is the
10572 statement we want to simplify, WITHIN_STMT provides the location
10573 for any overflow warnings. */
10575 static tree
10576 simplify_stmt_for_jump_threading (gimple *stmt, gimple *within_stmt,
10577 class avail_exprs_stack *avail_exprs_stack ATTRIBUTE_UNUSED,
10578 basic_block bb)
10580 /* First see if the conditional is in the hash table. */
10581 tree cached_lhs = avail_exprs_stack->lookup_avail_expr (stmt, false, true);
10582 if (cached_lhs && is_gimple_min_invariant (cached_lhs))
10583 return cached_lhs;
10585 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
10587 tree op0 = gimple_cond_lhs (cond_stmt);
10588 op0 = lhs_of_dominating_assert (op0, bb, stmt);
10590 tree op1 = gimple_cond_rhs (cond_stmt);
10591 op1 = lhs_of_dominating_assert (op1, bb, stmt);
10593 return vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
10594 op0, op1, within_stmt);
10597 /* We simplify a switch statement by trying to determine which case label
10598 will be taken. If we are successful then we return the corresponding
10599 CASE_LABEL_EXPR. */
10600 if (gswitch *switch_stmt = dyn_cast <gswitch *> (stmt))
10602 tree op = gimple_switch_index (switch_stmt);
10603 if (TREE_CODE (op) != SSA_NAME)
10604 return NULL_TREE;
10606 op = lhs_of_dominating_assert (op, bb, stmt);
10608 value_range *vr = get_value_range (op);
10609 if ((vr->type != VR_RANGE && vr->type != VR_ANTI_RANGE)
10610 || symbolic_range_p (vr))
10611 return NULL_TREE;
10613 if (vr->type == VR_RANGE)
10615 size_t i, j;
10616 /* Get the range of labels that contain a part of the operand's
10617 value range. */
10618 find_case_label_range (switch_stmt, vr->min, vr->max, &i, &j);
10620 /* Is there only one such label? */
10621 if (i == j)
10623 tree label = gimple_switch_label (switch_stmt, i);
10625 /* The i'th label will be taken only if the value range of the
10626 operand is entirely within the bounds of this label. */
10627 if (CASE_HIGH (label) != NULL_TREE
10628 ? (tree_int_cst_compare (CASE_LOW (label), vr->min) <= 0
10629 && tree_int_cst_compare (CASE_HIGH (label), vr->max) >= 0)
10630 : (tree_int_cst_equal (CASE_LOW (label), vr->min)
10631 && tree_int_cst_equal (vr->min, vr->max)))
10632 return label;
10635 /* If there are no such labels then the default label will be
10636 taken. */
10637 if (i > j)
10638 return gimple_switch_label (switch_stmt, 0);
10641 if (vr->type == VR_ANTI_RANGE)
10643 unsigned n = gimple_switch_num_labels (switch_stmt);
10644 tree min_label = gimple_switch_label (switch_stmt, 1);
10645 tree max_label = gimple_switch_label (switch_stmt, n - 1);
10647 /* The default label will be taken only if the anti-range of the
10648 operand is entirely outside the bounds of all the (non-default)
10649 case labels. */
10650 if (tree_int_cst_compare (vr->min, CASE_LOW (min_label)) <= 0
10651 && (CASE_HIGH (max_label) != NULL_TREE
10652 ? tree_int_cst_compare (vr->max, CASE_HIGH (max_label)) >= 0
10653 : tree_int_cst_compare (vr->max, CASE_LOW (max_label)) >= 0))
10654 return gimple_switch_label (switch_stmt, 0);
10657 return NULL_TREE;
10660 if (gassign *assign_stmt = dyn_cast <gassign *> (stmt))
10662 value_range new_vr = VR_INITIALIZER;
10663 tree lhs = gimple_assign_lhs (assign_stmt);
10665 if (TREE_CODE (lhs) == SSA_NAME
10666 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
10667 || POINTER_TYPE_P (TREE_TYPE (lhs))))
10669 extract_range_from_assignment (&new_vr, assign_stmt);
10670 if (range_int_cst_singleton_p (&new_vr))
10671 return new_vr.min;
10675 return NULL_TREE;
10678 class vrp_dom_walker : public dom_walker
10680 public:
10681 vrp_dom_walker (cdi_direction direction,
10682 class const_and_copies *const_and_copies,
10683 class avail_exprs_stack *avail_exprs_stack)
10684 : dom_walker (direction, true),
10685 m_const_and_copies (const_and_copies),
10686 m_avail_exprs_stack (avail_exprs_stack),
10687 m_dummy_cond (NULL) {}
10689 virtual edge before_dom_children (basic_block);
10690 virtual void after_dom_children (basic_block);
10692 private:
10693 class const_and_copies *m_const_and_copies;
10694 class avail_exprs_stack *m_avail_exprs_stack;
10696 gcond *m_dummy_cond;
10699 /* Called before processing dominator children of BB. We want to look
10700 at ASSERT_EXPRs and record information from them in the appropriate
10701 tables.
10703 We could look at other statements here. It's not seen as likely
10704 to significantly increase the jump threads we discover. */
10706 edge
10707 vrp_dom_walker::before_dom_children (basic_block bb)
10709 gimple_stmt_iterator gsi;
10711 m_avail_exprs_stack->push_marker ();
10712 m_const_and_copies->push_marker ();
10713 for (gsi = gsi_start_nondebug_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
10715 gimple *stmt = gsi_stmt (gsi);
10716 if (gimple_assign_single_p (stmt)
10717 && TREE_CODE (gimple_assign_rhs1 (stmt)) == ASSERT_EXPR)
10719 tree rhs1 = gimple_assign_rhs1 (stmt);
10720 tree cond = TREE_OPERAND (rhs1, 1);
10721 tree inverted = invert_truthvalue (cond);
10722 vec<cond_equivalence> p;
10723 p.create (3);
10724 record_conditions (&p, cond, inverted);
10725 for (unsigned int i = 0; i < p.length (); i++)
10726 m_avail_exprs_stack->record_cond (&p[i]);
10728 tree lhs = gimple_assign_lhs (stmt);
10729 m_const_and_copies->record_const_or_copy (lhs,
10730 TREE_OPERAND (rhs1, 0));
10731 p.release ();
10732 continue;
10734 break;
10736 return NULL;
10739 /* Called after processing dominator children of BB. This is where we
10740 actually call into the threader. */
10741 void
10742 vrp_dom_walker::after_dom_children (basic_block bb)
10744 if (!m_dummy_cond)
10745 m_dummy_cond = gimple_build_cond (NE_EXPR,
10746 integer_zero_node, integer_zero_node,
10747 NULL, NULL);
10749 thread_outgoing_edges (bb, m_dummy_cond, m_const_and_copies,
10750 m_avail_exprs_stack,
10751 simplify_stmt_for_jump_threading);
10753 m_avail_exprs_stack->pop_to_marker ();
10754 m_const_and_copies->pop_to_marker ();
10757 /* Blocks which have more than one predecessor and more than
10758 one successor present jump threading opportunities, i.e.,
10759 when the block is reached from a specific predecessor, we
10760 may be able to determine which of the outgoing edges will
10761 be traversed. When this optimization applies, we are able
10762 to avoid conditionals at runtime and we may expose secondary
10763 optimization opportunities.
10765 This routine is effectively a driver for the generic jump
10766 threading code. It basically just presents the generic code
10767 with edges that may be suitable for jump threading.
10769 Unlike DOM, we do not iterate VRP if jump threading was successful.
10770 While iterating may expose new opportunities for VRP, it is expected
10771 those opportunities would be very limited and the compile time cost
10772 to expose those opportunities would be significant.
10774 As jump threading opportunities are discovered, they are registered
10775 for later realization. */
10777 static void
10778 identify_jump_threads (void)
10780 int i;
10781 edge e;
10783 /* Ugh. When substituting values earlier in this pass we can
10784 wipe the dominance information. So rebuild the dominator
10785 information as we need it within the jump threading code. */
10786 calculate_dominance_info (CDI_DOMINATORS);
10788 /* We do not allow VRP information to be used for jump threading
10789 across a back edge in the CFG. Otherwise it becomes too
10790 difficult to avoid eliminating loop exit tests. Of course
10791 EDGE_DFS_BACK is not accurate at this time so we have to
10792 recompute it. */
10793 mark_dfs_back_edges ();
10795 /* Do not thread across edges we are about to remove. Just marking
10796 them as EDGE_IGNORE will do. */
10797 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
10798 e->flags |= EDGE_IGNORE;
10800 /* Allocate our unwinder stack to unwind any temporary equivalences
10801 that might be recorded. */
10802 const_and_copies *equiv_stack = new const_and_copies ();
10804 hash_table<expr_elt_hasher> *avail_exprs
10805 = new hash_table<expr_elt_hasher> (1024);
10806 avail_exprs_stack *avail_exprs_stack
10807 = new class avail_exprs_stack (avail_exprs);
10809 vrp_dom_walker walker (CDI_DOMINATORS, equiv_stack, avail_exprs_stack);
10810 walker.walk (cfun->cfg->x_entry_block_ptr);
10812 /* Clear EDGE_IGNORE. */
10813 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
10814 e->flags &= ~EDGE_IGNORE;
10816 /* We do not actually update the CFG or SSA graphs at this point as
10817 ASSERT_EXPRs are still in the IL and cfg cleanup code does not yet
10818 handle ASSERT_EXPRs gracefully. */
10819 delete equiv_stack;
10820 delete avail_exprs;
10821 delete avail_exprs_stack;
10824 /* Free VRP lattice. */
10826 static void
10827 vrp_free_lattice ()
10829 /* Free allocated memory. */
10830 free (vr_value);
10831 free (vr_phi_edge_counts);
10832 bitmap_obstack_release (&vrp_equiv_obstack);
10833 vrp_value_range_pool.release ();
10835 /* So that we can distinguish between VRP data being available
10836 and not available. */
10837 vr_value = NULL;
10838 vr_phi_edge_counts = NULL;
10841 /* Traverse all the blocks folding conditionals with known ranges. */
10843 static void
10844 vrp_finalize (bool warn_array_bounds_p)
10846 size_t i;
10848 values_propagated = true;
10850 if (dump_file)
10852 fprintf (dump_file, "\nValue ranges after VRP:\n\n");
10853 dump_all_value_ranges (dump_file);
10854 fprintf (dump_file, "\n");
10857 /* Set value range to non pointer SSA_NAMEs. */
10858 for (i = 0; i < num_vr_values; i++)
10859 if (vr_value[i])
10861 tree name = ssa_name (i);
10863 if (!name
10864 || (vr_value[i]->type == VR_VARYING)
10865 || (vr_value[i]->type == VR_UNDEFINED)
10866 || (TREE_CODE (vr_value[i]->min) != INTEGER_CST)
10867 || (TREE_CODE (vr_value[i]->max) != INTEGER_CST))
10868 continue;
10870 if (POINTER_TYPE_P (TREE_TYPE (name))
10871 && ((vr_value[i]->type == VR_RANGE
10872 && range_includes_zero_p (vr_value[i]->min,
10873 vr_value[i]->max) == 0)
10874 || (vr_value[i]->type == VR_ANTI_RANGE
10875 && range_includes_zero_p (vr_value[i]->min,
10876 vr_value[i]->max) == 1)))
10877 set_ptr_nonnull (name);
10878 else if (!POINTER_TYPE_P (TREE_TYPE (name)))
10879 set_range_info (name, vr_value[i]->type,
10880 wi::to_wide (vr_value[i]->min),
10881 wi::to_wide (vr_value[i]->max));
10884 substitute_and_fold (op_with_constant_singleton_value_range, vrp_fold_stmt);
10886 if (warn_array_bounds && warn_array_bounds_p)
10887 check_all_array_refs ();
10890 /* evrp_dom_walker visits the basic blocks in the dominance order and set
10891 the Value Ranges (VR) for SSA_NAMEs in the scope. Use this VR to
10892 discover more VRs. */
10894 class evrp_dom_walker : public dom_walker
10896 public:
10897 evrp_dom_walker ()
10898 : dom_walker (CDI_DOMINATORS), stack (10)
10900 need_eh_cleanup = BITMAP_ALLOC (NULL);
10902 ~evrp_dom_walker ()
10904 BITMAP_FREE (need_eh_cleanup);
10906 virtual edge before_dom_children (basic_block);
10907 virtual void after_dom_children (basic_block);
10908 void push_value_range (tree var, value_range *vr);
10909 value_range *pop_value_range (tree var);
10910 value_range *try_find_new_range (tree, tree op, tree_code code, tree limit);
10912 /* Cond_stack holds the old VR. */
10913 auto_vec<std::pair <tree, value_range*> > stack;
10914 bitmap need_eh_cleanup;
10915 auto_vec<gimple *> stmts_to_fixup;
10916 auto_vec<gimple *> stmts_to_remove;
10919 /* Find new range for NAME such that (OP CODE LIMIT) is true. */
10921 value_range *
10922 evrp_dom_walker::try_find_new_range (tree name,
10923 tree op, tree_code code, tree limit)
10925 value_range vr = VR_INITIALIZER;
10926 value_range *old_vr = get_value_range (name);
10928 /* Discover VR when condition is true. */
10929 extract_range_for_var_from_comparison_expr (name, code, op,
10930 limit, &vr);
10931 /* If we found any usable VR, set the VR to ssa_name and create a
10932 PUSH old value in the stack with the old VR. */
10933 if (vr.type == VR_RANGE || vr.type == VR_ANTI_RANGE)
10935 if (old_vr->type == vr.type
10936 && vrp_operand_equal_p (old_vr->min, vr.min)
10937 && vrp_operand_equal_p (old_vr->max, vr.max))
10938 return NULL;
10939 value_range *new_vr = vrp_value_range_pool.allocate ();
10940 *new_vr = vr;
10941 return new_vr;
10943 return NULL;
10946 /* See if there is any new scope is entered with new VR and set that VR to
10947 ssa_name before visiting the statements in the scope. */
10949 edge
10950 evrp_dom_walker::before_dom_children (basic_block bb)
10952 tree op0 = NULL_TREE;
10953 edge_iterator ei;
10954 edge e;
10956 if (dump_file && (dump_flags & TDF_DETAILS))
10957 fprintf (dump_file, "Visiting BB%d\n", bb->index);
10959 stack.safe_push (std::make_pair (NULL_TREE, (value_range *)NULL));
10961 edge pred_e = NULL;
10962 FOR_EACH_EDGE (e, ei, bb->preds)
10964 /* Ignore simple backedges from this to allow recording conditions
10965 in loop headers. */
10966 if (dominated_by_p (CDI_DOMINATORS, e->src, e->dest))
10967 continue;
10968 if (! pred_e)
10969 pred_e = e;
10970 else
10972 pred_e = NULL;
10973 break;
10976 if (pred_e)
10978 gimple *stmt = last_stmt (pred_e->src);
10979 if (stmt
10980 && gimple_code (stmt) == GIMPLE_COND
10981 && (op0 = gimple_cond_lhs (stmt))
10982 && TREE_CODE (op0) == SSA_NAME
10983 && (INTEGRAL_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)))
10984 || POINTER_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)))))
10986 if (dump_file && (dump_flags & TDF_DETAILS))
10988 fprintf (dump_file, "Visiting controlling predicate ");
10989 print_gimple_stmt (dump_file, stmt, 0);
10991 /* Entering a new scope. Try to see if we can find a VR
10992 here. */
10993 tree op1 = gimple_cond_rhs (stmt);
10994 if (TREE_OVERFLOW_P (op1))
10995 op1 = drop_tree_overflow (op1);
10996 tree_code code = gimple_cond_code (stmt);
10998 auto_vec<assert_info, 8> asserts;
10999 register_edge_assert_for (op0, pred_e, code, op0, op1, asserts);
11000 if (TREE_CODE (op1) == SSA_NAME)
11001 register_edge_assert_for (op1, pred_e, code, op0, op1, asserts);
11003 auto_vec<std::pair<tree, value_range *>, 8> vrs;
11004 for (unsigned i = 0; i < asserts.length (); ++i)
11006 value_range *vr = try_find_new_range (asserts[i].name,
11007 asserts[i].expr,
11008 asserts[i].comp_code,
11009 asserts[i].val);
11010 if (vr)
11011 vrs.safe_push (std::make_pair (asserts[i].name, vr));
11013 /* Push updated ranges only after finding all of them to avoid
11014 ordering issues that can lead to worse ranges. */
11015 for (unsigned i = 0; i < vrs.length (); ++i)
11016 push_value_range (vrs[i].first, vrs[i].second);
11020 /* Visit PHI stmts and discover any new VRs possible. */
11021 bool has_unvisited_preds = false;
11022 FOR_EACH_EDGE (e, ei, bb->preds)
11023 if (e->flags & EDGE_EXECUTABLE
11024 && !(e->src->flags & BB_VISITED))
11026 has_unvisited_preds = true;
11027 break;
11030 for (gphi_iterator gpi = gsi_start_phis (bb);
11031 !gsi_end_p (gpi); gsi_next (&gpi))
11033 gphi *phi = gpi.phi ();
11034 tree lhs = PHI_RESULT (phi);
11035 if (virtual_operand_p (lhs))
11036 continue;
11037 value_range vr_result = VR_INITIALIZER;
11038 bool interesting = stmt_interesting_for_vrp (phi);
11039 if (interesting && dump_file && (dump_flags & TDF_DETAILS))
11041 fprintf (dump_file, "Visiting PHI node ");
11042 print_gimple_stmt (dump_file, phi, 0);
11044 if (!has_unvisited_preds
11045 && interesting)
11046 extract_range_from_phi_node (phi, &vr_result);
11047 else
11049 set_value_range_to_varying (&vr_result);
11050 /* When we have an unvisited executable predecessor we can't
11051 use PHI arg ranges which may be still UNDEFINED but have
11052 to use VARYING for them. But we can still resort to
11053 SCEV for loop header PHIs. */
11054 struct loop *l;
11055 if (interesting
11056 && (l = loop_containing_stmt (phi))
11057 && l->header == gimple_bb (phi))
11058 adjust_range_with_scev (&vr_result, l, phi, lhs);
11060 update_value_range (lhs, &vr_result);
11062 /* Mark PHIs whose lhs we fully propagate for removal. */
11063 tree val = op_with_constant_singleton_value_range (lhs);
11064 if (val && may_propagate_copy (lhs, val))
11066 stmts_to_remove.safe_push (phi);
11067 continue;
11070 /* Set the SSA with the value range. */
11071 if (INTEGRAL_TYPE_P (TREE_TYPE (lhs)))
11073 if ((vr_result.type == VR_RANGE
11074 || vr_result.type == VR_ANTI_RANGE)
11075 && (TREE_CODE (vr_result.min) == INTEGER_CST)
11076 && (TREE_CODE (vr_result.max) == INTEGER_CST))
11077 set_range_info (lhs, vr_result.type,
11078 wi::to_wide (vr_result.min),
11079 wi::to_wide (vr_result.max));
11081 else if (POINTER_TYPE_P (TREE_TYPE (lhs))
11082 && ((vr_result.type == VR_RANGE
11083 && range_includes_zero_p (vr_result.min,
11084 vr_result.max) == 0)
11085 || (vr_result.type == VR_ANTI_RANGE
11086 && range_includes_zero_p (vr_result.min,
11087 vr_result.max) == 1)))
11088 set_ptr_nonnull (lhs);
11091 edge taken_edge = NULL;
11093 /* Visit all other stmts and discover any new VRs possible. */
11094 for (gimple_stmt_iterator gsi = gsi_start_bb (bb);
11095 !gsi_end_p (gsi); gsi_next (&gsi))
11097 gimple *stmt = gsi_stmt (gsi);
11098 tree output = NULL_TREE;
11099 gimple *old_stmt = stmt;
11100 bool was_noreturn = (is_gimple_call (stmt)
11101 && gimple_call_noreturn_p (stmt));
11103 if (dump_file && (dump_flags & TDF_DETAILS))
11105 fprintf (dump_file, "Visiting stmt ");
11106 print_gimple_stmt (dump_file, stmt, 0);
11109 if (gcond *cond = dyn_cast <gcond *> (stmt))
11111 vrp_visit_cond_stmt (cond, &taken_edge);
11112 if (taken_edge)
11114 if (taken_edge->flags & EDGE_TRUE_VALUE)
11115 gimple_cond_make_true (cond);
11116 else if (taken_edge->flags & EDGE_FALSE_VALUE)
11117 gimple_cond_make_false (cond);
11118 else
11119 gcc_unreachable ();
11120 update_stmt (stmt);
11123 else if (stmt_interesting_for_vrp (stmt))
11125 edge taken_edge;
11126 value_range vr = VR_INITIALIZER;
11127 extract_range_from_stmt (stmt, &taken_edge, &output, &vr);
11128 if (output
11129 && (vr.type == VR_RANGE || vr.type == VR_ANTI_RANGE))
11131 update_value_range (output, &vr);
11132 vr = *get_value_range (output);
11134 /* Mark stmts whose output we fully propagate for removal. */
11135 tree val;
11136 if ((val = op_with_constant_singleton_value_range (output))
11137 && may_propagate_copy (output, val)
11138 && !stmt_could_throw_p (stmt)
11139 && !gimple_has_side_effects (stmt))
11141 stmts_to_remove.safe_push (stmt);
11142 continue;
11145 /* Set the SSA with the value range. */
11146 if (INTEGRAL_TYPE_P (TREE_TYPE (output)))
11148 if ((vr.type == VR_RANGE
11149 || vr.type == VR_ANTI_RANGE)
11150 && (TREE_CODE (vr.min) == INTEGER_CST)
11151 && (TREE_CODE (vr.max) == INTEGER_CST))
11152 set_range_info (output, vr.type,
11153 wi::to_wide (vr.min),
11154 wi::to_wide (vr.max));
11156 else if (POINTER_TYPE_P (TREE_TYPE (output))
11157 && ((vr.type == VR_RANGE
11158 && range_includes_zero_p (vr.min,
11159 vr.max) == 0)
11160 || (vr.type == VR_ANTI_RANGE
11161 && range_includes_zero_p (vr.min,
11162 vr.max) == 1)))
11163 set_ptr_nonnull (output);
11165 else
11166 set_defs_to_varying (stmt);
11168 else
11169 set_defs_to_varying (stmt);
11171 /* See if we can derive a range for any of STMT's operands. */
11172 tree op;
11173 ssa_op_iter i;
11174 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
11176 tree value;
11177 enum tree_code comp_code;
11179 /* If OP is used in such a way that we can infer a value
11180 range for it, and we don't find a previous assertion for
11181 it, create a new assertion location node for OP. */
11182 if (infer_value_range (stmt, op, &comp_code, &value))
11184 /* If we are able to infer a nonzero value range for OP,
11185 then walk backwards through the use-def chain to see if OP
11186 was set via a typecast.
11187 If so, then we can also infer a nonzero value range
11188 for the operand of the NOP_EXPR. */
11189 if (comp_code == NE_EXPR && integer_zerop (value))
11191 tree t = op;
11192 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
11193 while (is_gimple_assign (def_stmt)
11194 && CONVERT_EXPR_CODE_P
11195 (gimple_assign_rhs_code (def_stmt))
11196 && TREE_CODE
11197 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
11198 && POINTER_TYPE_P
11199 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
11201 t = gimple_assign_rhs1 (def_stmt);
11202 def_stmt = SSA_NAME_DEF_STMT (t);
11204 /* Add VR when (T COMP_CODE value) condition is
11205 true. */
11206 value_range *op_range
11207 = try_find_new_range (t, t, comp_code, value);
11208 if (op_range)
11209 push_value_range (t, op_range);
11212 /* Add VR when (OP COMP_CODE value) condition is true. */
11213 value_range *op_range = try_find_new_range (op, op,
11214 comp_code, value);
11215 if (op_range)
11216 push_value_range (op, op_range);
11220 /* Try folding stmts with the VR discovered. */
11221 bool did_replace
11222 = replace_uses_in (stmt, op_with_constant_singleton_value_range);
11223 if (fold_stmt (&gsi, follow_single_use_edges)
11224 || did_replace)
11226 stmt = gsi_stmt (gsi);
11227 update_stmt (stmt);
11228 did_replace = true;
11231 if (did_replace)
11233 /* If we cleaned up EH information from the statement,
11234 remove EH edges. */
11235 if (maybe_clean_or_replace_eh_stmt (old_stmt, stmt))
11236 bitmap_set_bit (need_eh_cleanup, bb->index);
11238 /* If we turned a not noreturn call into a noreturn one
11239 schedule it for fixup. */
11240 if (!was_noreturn
11241 && is_gimple_call (stmt)
11242 && gimple_call_noreturn_p (stmt))
11243 stmts_to_fixup.safe_push (stmt);
11245 if (gimple_assign_single_p (stmt))
11247 tree rhs = gimple_assign_rhs1 (stmt);
11248 if (TREE_CODE (rhs) == ADDR_EXPR)
11249 recompute_tree_invariant_for_addr_expr (rhs);
11254 /* Visit BB successor PHI nodes and replace PHI args. */
11255 FOR_EACH_EDGE (e, ei, bb->succs)
11257 for (gphi_iterator gpi = gsi_start_phis (e->dest);
11258 !gsi_end_p (gpi); gsi_next (&gpi))
11260 gphi *phi = gpi.phi ();
11261 use_operand_p use_p = PHI_ARG_DEF_PTR_FROM_EDGE (phi, e);
11262 tree arg = USE_FROM_PTR (use_p);
11263 if (TREE_CODE (arg) != SSA_NAME
11264 || virtual_operand_p (arg))
11265 continue;
11266 tree val = op_with_constant_singleton_value_range (arg);
11267 if (val && may_propagate_copy (arg, val))
11268 propagate_value (use_p, val);
11272 bb->flags |= BB_VISITED;
11274 return taken_edge;
11277 /* Restore/pop VRs valid only for BB when we leave BB. */
11279 void
11280 evrp_dom_walker::after_dom_children (basic_block bb ATTRIBUTE_UNUSED)
11282 gcc_checking_assert (!stack.is_empty ());
11283 while (stack.last ().first != NULL_TREE)
11284 pop_value_range (stack.last ().first);
11285 stack.pop ();
11288 /* Push the Value Range of VAR to the stack and update it with new VR. */
11290 void
11291 evrp_dom_walker::push_value_range (tree var, value_range *vr)
11293 if (SSA_NAME_VERSION (var) >= num_vr_values)
11294 return;
11295 if (dump_file && (dump_flags & TDF_DETAILS))
11297 fprintf (dump_file, "pushing new range for ");
11298 print_generic_expr (dump_file, var);
11299 fprintf (dump_file, ": ");
11300 dump_value_range (dump_file, vr);
11301 fprintf (dump_file, "\n");
11303 stack.safe_push (std::make_pair (var, get_value_range (var)));
11304 vr_value[SSA_NAME_VERSION (var)] = vr;
11307 /* Pop the Value Range from the vrp_stack and update VAR with it. */
11309 value_range *
11310 evrp_dom_walker::pop_value_range (tree var)
11312 value_range *vr = stack.last ().second;
11313 gcc_checking_assert (var == stack.last ().first);
11314 if (dump_file && (dump_flags & TDF_DETAILS))
11316 fprintf (dump_file, "popping range for ");
11317 print_generic_expr (dump_file, var);
11318 fprintf (dump_file, ", restoring ");
11319 dump_value_range (dump_file, vr);
11320 fprintf (dump_file, "\n");
11322 vr_value[SSA_NAME_VERSION (var)] = vr;
11323 stack.pop ();
11324 return vr;
11328 /* Main entry point for the early vrp pass which is a simplified non-iterative
11329 version of vrp where basic blocks are visited in dominance order. Value
11330 ranges discovered in early vrp will also be used by ipa-vrp. */
11332 static unsigned int
11333 execute_early_vrp ()
11335 edge e;
11336 edge_iterator ei;
11337 basic_block bb;
11339 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
11340 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
11341 scev_initialize ();
11342 calculate_dominance_info (CDI_DOMINATORS);
11343 FOR_EACH_BB_FN (bb, cfun)
11345 bb->flags &= ~BB_VISITED;
11346 FOR_EACH_EDGE (e, ei, bb->preds)
11347 e->flags |= EDGE_EXECUTABLE;
11349 vrp_initialize_lattice ();
11351 /* Walk stmts in dominance order and propagate VRP. */
11352 evrp_dom_walker walker;
11353 walker.walk (ENTRY_BLOCK_PTR_FOR_FN (cfun));
11355 if (dump_file)
11357 fprintf (dump_file, "\nValue ranges after Early VRP:\n\n");
11358 dump_all_value_ranges (dump_file);
11359 fprintf (dump_file, "\n");
11362 /* Remove stmts in reverse order to make debug stmt creation possible. */
11363 while (! walker.stmts_to_remove.is_empty ())
11365 gimple *stmt = walker.stmts_to_remove.pop ();
11366 if (dump_file && dump_flags & TDF_DETAILS)
11368 fprintf (dump_file, "Removing dead stmt ");
11369 print_gimple_stmt (dump_file, stmt, 0);
11370 fprintf (dump_file, "\n");
11372 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
11373 if (gimple_code (stmt) == GIMPLE_PHI)
11374 remove_phi_node (&gsi, true);
11375 else
11377 unlink_stmt_vdef (stmt);
11378 gsi_remove (&gsi, true);
11379 release_defs (stmt);
11383 if (!bitmap_empty_p (walker.need_eh_cleanup))
11384 gimple_purge_all_dead_eh_edges (walker.need_eh_cleanup);
11386 /* Fixup stmts that became noreturn calls. This may require splitting
11387 blocks and thus isn't possible during the dominator walk. Do this
11388 in reverse order so we don't inadvertedly remove a stmt we want to
11389 fixup by visiting a dominating now noreturn call first. */
11390 while (!walker.stmts_to_fixup.is_empty ())
11392 gimple *stmt = walker.stmts_to_fixup.pop ();
11393 fixup_noreturn_call (stmt);
11396 vrp_free_lattice ();
11397 scev_finalize ();
11398 loop_optimizer_finalize ();
11399 return 0;
11403 /* Main entry point to VRP (Value Range Propagation). This pass is
11404 loosely based on J. R. C. Patterson, ``Accurate Static Branch
11405 Prediction by Value Range Propagation,'' in SIGPLAN Conference on
11406 Programming Language Design and Implementation, pp. 67-78, 1995.
11407 Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
11409 This is essentially an SSA-CCP pass modified to deal with ranges
11410 instead of constants.
11412 While propagating ranges, we may find that two or more SSA name
11413 have equivalent, though distinct ranges. For instance,
11415 1 x_9 = p_3->a;
11416 2 p_4 = ASSERT_EXPR <p_3, p_3 != 0>
11417 3 if (p_4 == q_2)
11418 4 p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
11419 5 endif
11420 6 if (q_2)
11422 In the code above, pointer p_5 has range [q_2, q_2], but from the
11423 code we can also determine that p_5 cannot be NULL and, if q_2 had
11424 a non-varying range, p_5's range should also be compatible with it.
11426 These equivalences are created by two expressions: ASSERT_EXPR and
11427 copy operations. Since p_5 is an assertion on p_4, and p_4 was the
11428 result of another assertion, then we can use the fact that p_5 and
11429 p_4 are equivalent when evaluating p_5's range.
11431 Together with value ranges, we also propagate these equivalences
11432 between names so that we can take advantage of information from
11433 multiple ranges when doing final replacement. Note that this
11434 equivalency relation is transitive but not symmetric.
11436 In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
11437 cannot assert that q_2 is equivalent to p_5 because q_2 may be used
11438 in contexts where that assertion does not hold (e.g., in line 6).
11440 TODO, the main difference between this pass and Patterson's is that
11441 we do not propagate edge probabilities. We only compute whether
11442 edges can be taken or not. That is, instead of having a spectrum
11443 of jump probabilities between 0 and 1, we only deal with 0, 1 and
11444 DON'T KNOW. In the future, it may be worthwhile to propagate
11445 probabilities to aid branch prediction. */
11447 static unsigned int
11448 execute_vrp (bool warn_array_bounds_p)
11450 int i;
11451 edge e;
11452 switch_update *su;
11454 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
11455 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
11456 scev_initialize ();
11458 /* ??? This ends up using stale EDGE_DFS_BACK for liveness computation.
11459 Inserting assertions may split edges which will invalidate
11460 EDGE_DFS_BACK. */
11461 insert_range_assertions ();
11463 to_remove_edges.create (10);
11464 to_update_switch_stmts.create (5);
11465 threadedge_initialize_values ();
11467 /* For visiting PHI nodes we need EDGE_DFS_BACK computed. */
11468 mark_dfs_back_edges ();
11470 vrp_initialize_lattice ();
11471 vrp_initialize ();
11472 ssa_propagate (vrp_visit_stmt, vrp_visit_phi_node);
11473 vrp_finalize (warn_array_bounds_p);
11475 /* We must identify jump threading opportunities before we release
11476 the datastructures built by VRP. */
11477 identify_jump_threads ();
11479 /* A comparison of an SSA_NAME against a constant where the SSA_NAME
11480 was set by a type conversion can often be rewritten to use the
11481 RHS of the type conversion.
11483 However, doing so inhibits jump threading through the comparison.
11484 So that transformation is not performed until after jump threading
11485 is complete. */
11486 basic_block bb;
11487 FOR_EACH_BB_FN (bb, cfun)
11489 gimple *last = last_stmt (bb);
11490 if (last && gimple_code (last) == GIMPLE_COND)
11491 simplify_cond_using_ranges_2 (as_a <gcond *> (last));
11494 vrp_free_lattice ();
11496 free_numbers_of_iterations_estimates (cfun);
11498 /* ASSERT_EXPRs must be removed before finalizing jump threads
11499 as finalizing jump threads calls the CFG cleanup code which
11500 does not properly handle ASSERT_EXPRs. */
11501 remove_range_assertions ();
11503 /* If we exposed any new variables, go ahead and put them into
11504 SSA form now, before we handle jump threading. This simplifies
11505 interactions between rewriting of _DECL nodes into SSA form
11506 and rewriting SSA_NAME nodes into SSA form after block
11507 duplication and CFG manipulation. */
11508 update_ssa (TODO_update_ssa);
11510 /* We identified all the jump threading opportunities earlier, but could
11511 not transform the CFG at that time. This routine transforms the
11512 CFG and arranges for the dominator tree to be rebuilt if necessary.
11514 Note the SSA graph update will occur during the normal TODO
11515 processing by the pass manager. */
11516 thread_through_all_blocks (false);
11518 /* Remove dead edges from SWITCH_EXPR optimization. This leaves the
11519 CFG in a broken state and requires a cfg_cleanup run. */
11520 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
11521 remove_edge (e);
11522 /* Update SWITCH_EXPR case label vector. */
11523 FOR_EACH_VEC_ELT (to_update_switch_stmts, i, su)
11525 size_t j;
11526 size_t n = TREE_VEC_LENGTH (su->vec);
11527 tree label;
11528 gimple_switch_set_num_labels (su->stmt, n);
11529 for (j = 0; j < n; j++)
11530 gimple_switch_set_label (su->stmt, j, TREE_VEC_ELT (su->vec, j));
11531 /* As we may have replaced the default label with a regular one
11532 make sure to make it a real default label again. This ensures
11533 optimal expansion. */
11534 label = gimple_switch_label (su->stmt, 0);
11535 CASE_LOW (label) = NULL_TREE;
11536 CASE_HIGH (label) = NULL_TREE;
11539 if (to_remove_edges.length () > 0)
11541 free_dominance_info (CDI_DOMINATORS);
11542 loops_state_set (LOOPS_NEED_FIXUP);
11545 to_remove_edges.release ();
11546 to_update_switch_stmts.release ();
11547 threadedge_finalize_values ();
11549 scev_finalize ();
11550 loop_optimizer_finalize ();
11551 return 0;
11554 namespace {
11556 const pass_data pass_data_vrp =
11558 GIMPLE_PASS, /* type */
11559 "vrp", /* name */
11560 OPTGROUP_NONE, /* optinfo_flags */
11561 TV_TREE_VRP, /* tv_id */
11562 PROP_ssa, /* properties_required */
11563 0, /* properties_provided */
11564 0, /* properties_destroyed */
11565 0, /* todo_flags_start */
11566 ( TODO_cleanup_cfg | TODO_update_ssa ), /* todo_flags_finish */
11569 class pass_vrp : public gimple_opt_pass
11571 public:
11572 pass_vrp (gcc::context *ctxt)
11573 : gimple_opt_pass (pass_data_vrp, ctxt), warn_array_bounds_p (false)
11576 /* opt_pass methods: */
11577 opt_pass * clone () { return new pass_vrp (m_ctxt); }
11578 void set_pass_param (unsigned int n, bool param)
11580 gcc_assert (n == 0);
11581 warn_array_bounds_p = param;
11583 virtual bool gate (function *) { return flag_tree_vrp != 0; }
11584 virtual unsigned int execute (function *)
11585 { return execute_vrp (warn_array_bounds_p); }
11587 private:
11588 bool warn_array_bounds_p;
11589 }; // class pass_vrp
11591 } // anon namespace
11593 gimple_opt_pass *
11594 make_pass_vrp (gcc::context *ctxt)
11596 return new pass_vrp (ctxt);
11599 namespace {
11601 const pass_data pass_data_early_vrp =
11603 GIMPLE_PASS, /* type */
11604 "evrp", /* name */
11605 OPTGROUP_NONE, /* optinfo_flags */
11606 TV_TREE_EARLY_VRP, /* tv_id */
11607 PROP_ssa, /* properties_required */
11608 0, /* properties_provided */
11609 0, /* properties_destroyed */
11610 0, /* todo_flags_start */
11611 ( TODO_cleanup_cfg | TODO_update_ssa | TODO_verify_all ),
11614 class pass_early_vrp : public gimple_opt_pass
11616 public:
11617 pass_early_vrp (gcc::context *ctxt)
11618 : gimple_opt_pass (pass_data_early_vrp, ctxt)
11621 /* opt_pass methods: */
11622 opt_pass * clone () { return new pass_early_vrp (m_ctxt); }
11623 virtual bool gate (function *)
11625 return flag_tree_vrp != 0;
11627 virtual unsigned int execute (function *)
11628 { return execute_early_vrp (); }
11630 }; // class pass_vrp
11631 } // anon namespace
11633 gimple_opt_pass *
11634 make_pass_early_vrp (gcc::context *ctxt)
11636 return new pass_early_vrp (ctxt);