2017-11-04 Thomas Koenig <tkoenig@gcc.gnu.org>
[official-gcc.git] / gcc / tree-vrp.c
blob541c5c4eaf955eda4c457d7e4ebe8c531dfcb25a
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
6840 location = gimple_location (wi->stmt);
6842 *walk_subtree = TRUE;
6844 if (TREE_CODE (t) == ARRAY_REF)
6845 check_array_ref (location, t, false /*ignore_off_by_one*/);
6847 else if (TREE_CODE (t) == ADDR_EXPR)
6849 search_for_addr_array (t, location);
6850 *walk_subtree = FALSE;
6853 return NULL_TREE;
6856 /* Walk over all statements of all reachable BBs and call check_array_bounds
6857 on them. */
6859 static void
6860 check_all_array_refs (void)
6862 basic_block bb;
6863 gimple_stmt_iterator si;
6865 FOR_EACH_BB_FN (bb, cfun)
6867 edge_iterator ei;
6868 edge e;
6869 bool executable = false;
6871 /* Skip blocks that were found to be unreachable. */
6872 FOR_EACH_EDGE (e, ei, bb->preds)
6873 executable |= !!(e->flags & EDGE_EXECUTABLE);
6874 if (!executable)
6875 continue;
6877 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
6879 gimple *stmt = gsi_stmt (si);
6880 struct walk_stmt_info wi;
6881 if (!gimple_has_location (stmt)
6882 || is_gimple_debug (stmt))
6883 continue;
6885 memset (&wi, 0, sizeof (wi));
6887 walk_gimple_op (gsi_stmt (si),
6888 check_array_bounds,
6889 &wi);
6894 /* Return true if all imm uses of VAR are either in STMT, or
6895 feed (optionally through a chain of single imm uses) GIMPLE_COND
6896 in basic block COND_BB. */
6898 static bool
6899 all_imm_uses_in_stmt_or_feed_cond (tree var, gimple *stmt, basic_block cond_bb)
6901 use_operand_p use_p, use2_p;
6902 imm_use_iterator iter;
6904 FOR_EACH_IMM_USE_FAST (use_p, iter, var)
6905 if (USE_STMT (use_p) != stmt)
6907 gimple *use_stmt = USE_STMT (use_p), *use_stmt2;
6908 if (is_gimple_debug (use_stmt))
6909 continue;
6910 while (is_gimple_assign (use_stmt)
6911 && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
6912 && single_imm_use (gimple_assign_lhs (use_stmt),
6913 &use2_p, &use_stmt2))
6914 use_stmt = use_stmt2;
6915 if (gimple_code (use_stmt) != GIMPLE_COND
6916 || gimple_bb (use_stmt) != cond_bb)
6917 return false;
6919 return true;
6922 /* Handle
6923 _4 = x_3 & 31;
6924 if (_4 != 0)
6925 goto <bb 6>;
6926 else
6927 goto <bb 7>;
6928 <bb 6>:
6929 __builtin_unreachable ();
6930 <bb 7>:
6931 x_5 = ASSERT_EXPR <x_3, ...>;
6932 If x_3 has no other immediate uses (checked by caller),
6933 var is the x_3 var from ASSERT_EXPR, we can clear low 5 bits
6934 from the non-zero bitmask. */
6936 static void
6937 maybe_set_nonzero_bits (basic_block bb, tree var)
6939 edge e = single_pred_edge (bb);
6940 basic_block cond_bb = e->src;
6941 gimple *stmt = last_stmt (cond_bb);
6942 tree cst;
6944 if (stmt == NULL
6945 || gimple_code (stmt) != GIMPLE_COND
6946 || gimple_cond_code (stmt) != ((e->flags & EDGE_TRUE_VALUE)
6947 ? EQ_EXPR : NE_EXPR)
6948 || TREE_CODE (gimple_cond_lhs (stmt)) != SSA_NAME
6949 || !integer_zerop (gimple_cond_rhs (stmt)))
6950 return;
6952 stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt));
6953 if (!is_gimple_assign (stmt)
6954 || gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
6955 || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
6956 return;
6957 if (gimple_assign_rhs1 (stmt) != var)
6959 gimple *stmt2;
6961 if (TREE_CODE (gimple_assign_rhs1 (stmt)) != SSA_NAME)
6962 return;
6963 stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
6964 if (!gimple_assign_cast_p (stmt2)
6965 || gimple_assign_rhs1 (stmt2) != var
6966 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt2))
6967 || (TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (stmt)))
6968 != TYPE_PRECISION (TREE_TYPE (var))))
6969 return;
6971 cst = gimple_assign_rhs2 (stmt);
6972 set_nonzero_bits (var, wi::bit_and_not (get_nonzero_bits (var),
6973 wi::to_wide (cst)));
6976 /* Convert range assertion expressions into the implied copies and
6977 copy propagate away the copies. Doing the trivial copy propagation
6978 here avoids the need to run the full copy propagation pass after
6979 VRP.
6981 FIXME, this will eventually lead to copy propagation removing the
6982 names that had useful range information attached to them. For
6983 instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
6984 then N_i will have the range [3, +INF].
6986 However, by converting the assertion into the implied copy
6987 operation N_i = N_j, we will then copy-propagate N_j into the uses
6988 of N_i and lose the range information. We may want to hold on to
6989 ASSERT_EXPRs a little while longer as the ranges could be used in
6990 things like jump threading.
6992 The problem with keeping ASSERT_EXPRs around is that passes after
6993 VRP need to handle them appropriately.
6995 Another approach would be to make the range information a first
6996 class property of the SSA_NAME so that it can be queried from
6997 any pass. This is made somewhat more complex by the need for
6998 multiple ranges to be associated with one SSA_NAME. */
7000 static void
7001 remove_range_assertions (void)
7003 basic_block bb;
7004 gimple_stmt_iterator si;
7005 /* 1 if looking at ASSERT_EXPRs immediately at the beginning of
7006 a basic block preceeded by GIMPLE_COND branching to it and
7007 __builtin_trap, -1 if not yet checked, 0 otherwise. */
7008 int is_unreachable;
7010 /* Note that the BSI iterator bump happens at the bottom of the
7011 loop and no bump is necessary if we're removing the statement
7012 referenced by the current BSI. */
7013 FOR_EACH_BB_FN (bb, cfun)
7014 for (si = gsi_after_labels (bb), is_unreachable = -1; !gsi_end_p (si);)
7016 gimple *stmt = gsi_stmt (si);
7018 if (is_gimple_assign (stmt)
7019 && gimple_assign_rhs_code (stmt) == ASSERT_EXPR)
7021 tree lhs = gimple_assign_lhs (stmt);
7022 tree rhs = gimple_assign_rhs1 (stmt);
7023 tree var;
7025 var = ASSERT_EXPR_VAR (rhs);
7027 if (TREE_CODE (var) == SSA_NAME
7028 && !POINTER_TYPE_P (TREE_TYPE (lhs))
7029 && SSA_NAME_RANGE_INFO (lhs))
7031 if (is_unreachable == -1)
7033 is_unreachable = 0;
7034 if (single_pred_p (bb)
7035 && assert_unreachable_fallthru_edge_p
7036 (single_pred_edge (bb)))
7037 is_unreachable = 1;
7039 /* Handle
7040 if (x_7 >= 10 && x_7 < 20)
7041 __builtin_unreachable ();
7042 x_8 = ASSERT_EXPR <x_7, ...>;
7043 if the only uses of x_7 are in the ASSERT_EXPR and
7044 in the condition. In that case, we can copy the
7045 range info from x_8 computed in this pass also
7046 for x_7. */
7047 if (is_unreachable
7048 && all_imm_uses_in_stmt_or_feed_cond (var, stmt,
7049 single_pred (bb)))
7051 set_range_info (var, SSA_NAME_RANGE_TYPE (lhs),
7052 SSA_NAME_RANGE_INFO (lhs)->get_min (),
7053 SSA_NAME_RANGE_INFO (lhs)->get_max ());
7054 maybe_set_nonzero_bits (bb, var);
7058 /* Propagate the RHS into every use of the LHS. For SSA names
7059 also propagate abnormals as it merely restores the original
7060 IL in this case (an replace_uses_by would assert). */
7061 if (TREE_CODE (var) == SSA_NAME)
7063 imm_use_iterator iter;
7064 use_operand_p use_p;
7065 gimple *use_stmt;
7066 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
7067 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
7068 SET_USE (use_p, var);
7070 else
7071 replace_uses_by (lhs, var);
7073 /* And finally, remove the copy, it is not needed. */
7074 gsi_remove (&si, true);
7075 release_defs (stmt);
7077 else
7079 if (!is_gimple_debug (gsi_stmt (si)))
7080 is_unreachable = 0;
7081 gsi_next (&si);
7087 /* Return true if STMT is interesting for VRP. */
7089 static bool
7090 stmt_interesting_for_vrp (gimple *stmt)
7092 if (gimple_code (stmt) == GIMPLE_PHI)
7094 tree res = gimple_phi_result (stmt);
7095 return (!virtual_operand_p (res)
7096 && (INTEGRAL_TYPE_P (TREE_TYPE (res))
7097 || POINTER_TYPE_P (TREE_TYPE (res))));
7099 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
7101 tree lhs = gimple_get_lhs (stmt);
7103 /* In general, assignments with virtual operands are not useful
7104 for deriving ranges, with the obvious exception of calls to
7105 builtin functions. */
7106 if (lhs && TREE_CODE (lhs) == SSA_NAME
7107 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
7108 || POINTER_TYPE_P (TREE_TYPE (lhs)))
7109 && (is_gimple_call (stmt)
7110 || !gimple_vuse (stmt)))
7111 return true;
7112 else if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
7113 switch (gimple_call_internal_fn (stmt))
7115 case IFN_ADD_OVERFLOW:
7116 case IFN_SUB_OVERFLOW:
7117 case IFN_MUL_OVERFLOW:
7118 case IFN_ATOMIC_COMPARE_EXCHANGE:
7119 /* These internal calls return _Complex integer type,
7120 but are interesting to VRP nevertheless. */
7121 if (lhs && TREE_CODE (lhs) == SSA_NAME)
7122 return true;
7123 break;
7124 default:
7125 break;
7128 else if (gimple_code (stmt) == GIMPLE_COND
7129 || gimple_code (stmt) == GIMPLE_SWITCH)
7130 return true;
7132 return false;
7135 /* Initialize VRP lattice. */
7137 static void
7138 vrp_initialize_lattice ()
7140 values_propagated = false;
7141 num_vr_values = num_ssa_names;
7142 vr_value = XCNEWVEC (value_range *, num_vr_values);
7143 vr_phi_edge_counts = XCNEWVEC (int, num_ssa_names);
7144 bitmap_obstack_initialize (&vrp_equiv_obstack);
7147 /* Initialization required by ssa_propagate engine. */
7149 static void
7150 vrp_initialize ()
7152 basic_block bb;
7154 FOR_EACH_BB_FN (bb, cfun)
7156 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
7157 gsi_next (&si))
7159 gphi *phi = si.phi ();
7160 if (!stmt_interesting_for_vrp (phi))
7162 tree lhs = PHI_RESULT (phi);
7163 set_value_range_to_varying (get_value_range (lhs));
7164 prop_set_simulate_again (phi, false);
7166 else
7167 prop_set_simulate_again (phi, true);
7170 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
7171 gsi_next (&si))
7173 gimple *stmt = gsi_stmt (si);
7175 /* If the statement is a control insn, then we do not
7176 want to avoid simulating the statement once. Failure
7177 to do so means that those edges will never get added. */
7178 if (stmt_ends_bb_p (stmt))
7179 prop_set_simulate_again (stmt, true);
7180 else if (!stmt_interesting_for_vrp (stmt))
7182 set_defs_to_varying (stmt);
7183 prop_set_simulate_again (stmt, false);
7185 else
7186 prop_set_simulate_again (stmt, true);
7191 /* Return the singleton value-range for NAME or NAME. */
7193 static inline tree
7194 vrp_valueize (tree name)
7196 if (TREE_CODE (name) == SSA_NAME)
7198 value_range *vr = get_value_range (name);
7199 if (vr->type == VR_RANGE
7200 && (TREE_CODE (vr->min) == SSA_NAME
7201 || is_gimple_min_invariant (vr->min))
7202 && vrp_operand_equal_p (vr->min, vr->max))
7203 return vr->min;
7205 return name;
7208 /* Return the singleton value-range for NAME if that is a constant
7209 but signal to not follow SSA edges. */
7211 static inline tree
7212 vrp_valueize_1 (tree name)
7214 if (TREE_CODE (name) == SSA_NAME)
7216 /* If the definition may be simulated again we cannot follow
7217 this SSA edge as the SSA propagator does not necessarily
7218 re-visit the use. */
7219 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
7220 if (!gimple_nop_p (def_stmt)
7221 && prop_simulate_again_p (def_stmt))
7222 return NULL_TREE;
7223 value_range *vr = get_value_range (name);
7224 if (range_int_cst_singleton_p (vr))
7225 return vr->min;
7227 return name;
7230 /* Visit assignment STMT. If it produces an interesting range, record
7231 the range in VR and set LHS to OUTPUT_P. */
7233 static void
7234 vrp_visit_assignment_or_call (gimple *stmt, tree *output_p, value_range *vr)
7236 tree lhs;
7237 enum gimple_code code = gimple_code (stmt);
7238 lhs = gimple_get_lhs (stmt);
7239 *output_p = NULL_TREE;
7241 /* We only keep track of ranges in integral and pointer types. */
7242 if (TREE_CODE (lhs) == SSA_NAME
7243 && ((INTEGRAL_TYPE_P (TREE_TYPE (lhs))
7244 /* It is valid to have NULL MIN/MAX values on a type. See
7245 build_range_type. */
7246 && TYPE_MIN_VALUE (TREE_TYPE (lhs))
7247 && TYPE_MAX_VALUE (TREE_TYPE (lhs)))
7248 || POINTER_TYPE_P (TREE_TYPE (lhs))))
7250 *output_p = lhs;
7252 /* Try folding the statement to a constant first. */
7253 tree tem = gimple_fold_stmt_to_constant_1 (stmt, vrp_valueize,
7254 vrp_valueize_1);
7255 if (tem)
7257 if (TREE_CODE (tem) == SSA_NAME
7258 && (SSA_NAME_IS_DEFAULT_DEF (tem)
7259 || ! prop_simulate_again_p (SSA_NAME_DEF_STMT (tem))))
7261 extract_range_from_ssa_name (vr, tem);
7262 return;
7264 else if (is_gimple_min_invariant (tem))
7266 set_value_range_to_value (vr, tem, NULL);
7267 return;
7270 /* Then dispatch to value-range extracting functions. */
7271 if (code == GIMPLE_CALL)
7272 extract_range_basic (vr, stmt);
7273 else
7274 extract_range_from_assignment (vr, as_a <gassign *> (stmt));
7278 /* Helper that gets the value range of the SSA_NAME with version I
7279 or a symbolic range containing the SSA_NAME only if the value range
7280 is varying or undefined. */
7282 static inline value_range
7283 get_vr_for_comparison (int i)
7285 value_range vr = *get_value_range (ssa_name (i));
7287 /* If name N_i does not have a valid range, use N_i as its own
7288 range. This allows us to compare against names that may
7289 have N_i in their ranges. */
7290 if (vr.type == VR_VARYING || vr.type == VR_UNDEFINED)
7292 vr.type = VR_RANGE;
7293 vr.min = ssa_name (i);
7294 vr.max = ssa_name (i);
7297 return vr;
7300 /* Compare all the value ranges for names equivalent to VAR with VAL
7301 using comparison code COMP. Return the same value returned by
7302 compare_range_with_value, including the setting of
7303 *STRICT_OVERFLOW_P. */
7305 static tree
7306 compare_name_with_value (enum tree_code comp, tree var, tree val,
7307 bool *strict_overflow_p, bool use_equiv_p)
7309 bitmap_iterator bi;
7310 unsigned i;
7311 bitmap e;
7312 tree retval, t;
7313 int used_strict_overflow;
7314 bool sop;
7315 value_range equiv_vr;
7317 /* Get the set of equivalences for VAR. */
7318 e = get_value_range (var)->equiv;
7320 /* Start at -1. Set it to 0 if we do a comparison without relying
7321 on overflow, or 1 if all comparisons rely on overflow. */
7322 used_strict_overflow = -1;
7324 /* Compare vars' value range with val. */
7325 equiv_vr = get_vr_for_comparison (SSA_NAME_VERSION (var));
7326 sop = false;
7327 retval = compare_range_with_value (comp, &equiv_vr, val, &sop);
7328 if (retval)
7329 used_strict_overflow = sop ? 1 : 0;
7331 /* If the equiv set is empty we have done all work we need to do. */
7332 if (e == NULL)
7334 if (retval
7335 && used_strict_overflow > 0)
7336 *strict_overflow_p = true;
7337 return retval;
7340 EXECUTE_IF_SET_IN_BITMAP (e, 0, i, bi)
7342 tree name = ssa_name (i);
7343 if (! name)
7344 continue;
7346 if (! use_equiv_p
7347 && ! SSA_NAME_IS_DEFAULT_DEF (name)
7348 && prop_simulate_again_p (SSA_NAME_DEF_STMT (name)))
7349 continue;
7351 equiv_vr = get_vr_for_comparison (i);
7352 sop = false;
7353 t = compare_range_with_value (comp, &equiv_vr, val, &sop);
7354 if (t)
7356 /* If we get different answers from different members
7357 of the equivalence set this check must be in a dead
7358 code region. Folding it to a trap representation
7359 would be correct here. For now just return don't-know. */
7360 if (retval != NULL
7361 && t != retval)
7363 retval = NULL_TREE;
7364 break;
7366 retval = t;
7368 if (!sop)
7369 used_strict_overflow = 0;
7370 else if (used_strict_overflow < 0)
7371 used_strict_overflow = 1;
7375 if (retval
7376 && used_strict_overflow > 0)
7377 *strict_overflow_p = true;
7379 return retval;
7383 /* Given a comparison code COMP and names N1 and N2, compare all the
7384 ranges equivalent to N1 against all the ranges equivalent to N2
7385 to determine the value of N1 COMP N2. Return the same value
7386 returned by compare_ranges. Set *STRICT_OVERFLOW_P to indicate
7387 whether we relied on undefined signed overflow in the comparison. */
7390 static tree
7391 compare_names (enum tree_code comp, tree n1, tree n2,
7392 bool *strict_overflow_p)
7394 tree t, retval;
7395 bitmap e1, e2;
7396 bitmap_iterator bi1, bi2;
7397 unsigned i1, i2;
7398 int used_strict_overflow;
7399 static bitmap_obstack *s_obstack = NULL;
7400 static bitmap s_e1 = NULL, s_e2 = NULL;
7402 /* Compare the ranges of every name equivalent to N1 against the
7403 ranges of every name equivalent to N2. */
7404 e1 = get_value_range (n1)->equiv;
7405 e2 = get_value_range (n2)->equiv;
7407 /* Use the fake bitmaps if e1 or e2 are not available. */
7408 if (s_obstack == NULL)
7410 s_obstack = XNEW (bitmap_obstack);
7411 bitmap_obstack_initialize (s_obstack);
7412 s_e1 = BITMAP_ALLOC (s_obstack);
7413 s_e2 = BITMAP_ALLOC (s_obstack);
7415 if (e1 == NULL)
7416 e1 = s_e1;
7417 if (e2 == NULL)
7418 e2 = s_e2;
7420 /* Add N1 and N2 to their own set of equivalences to avoid
7421 duplicating the body of the loop just to check N1 and N2
7422 ranges. */
7423 bitmap_set_bit (e1, SSA_NAME_VERSION (n1));
7424 bitmap_set_bit (e2, SSA_NAME_VERSION (n2));
7426 /* If the equivalence sets have a common intersection, then the two
7427 names can be compared without checking their ranges. */
7428 if (bitmap_intersect_p (e1, e2))
7430 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7431 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7433 return (comp == EQ_EXPR || comp == GE_EXPR || comp == LE_EXPR)
7434 ? boolean_true_node
7435 : boolean_false_node;
7438 /* Start at -1. Set it to 0 if we do a comparison without relying
7439 on overflow, or 1 if all comparisons rely on overflow. */
7440 used_strict_overflow = -1;
7442 /* Otherwise, compare all the equivalent ranges. First, add N1 and
7443 N2 to their own set of equivalences to avoid duplicating the body
7444 of the loop just to check N1 and N2 ranges. */
7445 EXECUTE_IF_SET_IN_BITMAP (e1, 0, i1, bi1)
7447 if (! ssa_name (i1))
7448 continue;
7450 value_range vr1 = get_vr_for_comparison (i1);
7452 t = retval = NULL_TREE;
7453 EXECUTE_IF_SET_IN_BITMAP (e2, 0, i2, bi2)
7455 if (! ssa_name (i2))
7456 continue;
7458 bool sop = false;
7460 value_range vr2 = get_vr_for_comparison (i2);
7462 t = compare_ranges (comp, &vr1, &vr2, &sop);
7463 if (t)
7465 /* If we get different answers from different members
7466 of the equivalence set this check must be in a dead
7467 code region. Folding it to a trap representation
7468 would be correct here. For now just return don't-know. */
7469 if (retval != NULL
7470 && t != retval)
7472 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7473 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7474 return NULL_TREE;
7476 retval = t;
7478 if (!sop)
7479 used_strict_overflow = 0;
7480 else if (used_strict_overflow < 0)
7481 used_strict_overflow = 1;
7485 if (retval)
7487 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7488 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7489 if (used_strict_overflow > 0)
7490 *strict_overflow_p = true;
7491 return retval;
7495 /* None of the equivalent ranges are useful in computing this
7496 comparison. */
7497 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7498 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7499 return NULL_TREE;
7502 /* Helper function for vrp_evaluate_conditional_warnv & other
7503 optimizers. */
7505 static tree
7506 vrp_evaluate_conditional_warnv_with_ops_using_ranges (enum tree_code code,
7507 tree op0, tree op1,
7508 bool * strict_overflow_p)
7510 value_range *vr0, *vr1;
7512 vr0 = (TREE_CODE (op0) == SSA_NAME) ? get_value_range (op0) : NULL;
7513 vr1 = (TREE_CODE (op1) == SSA_NAME) ? get_value_range (op1) : NULL;
7515 tree res = NULL_TREE;
7516 if (vr0 && vr1)
7517 res = compare_ranges (code, vr0, vr1, strict_overflow_p);
7518 if (!res && vr0)
7519 res = compare_range_with_value (code, vr0, op1, strict_overflow_p);
7520 if (!res && vr1)
7521 res = (compare_range_with_value
7522 (swap_tree_comparison (code), vr1, op0, strict_overflow_p));
7523 return res;
7526 /* Helper function for vrp_evaluate_conditional_warnv. */
7528 static tree
7529 vrp_evaluate_conditional_warnv_with_ops (enum tree_code code, tree op0,
7530 tree op1, bool use_equiv_p,
7531 bool *strict_overflow_p, bool *only_ranges)
7533 tree ret;
7534 if (only_ranges)
7535 *only_ranges = true;
7537 /* We only deal with integral and pointer types. */
7538 if (!INTEGRAL_TYPE_P (TREE_TYPE (op0))
7539 && !POINTER_TYPE_P (TREE_TYPE (op0)))
7540 return NULL_TREE;
7542 /* If OP0 CODE OP1 is an overflow comparison, if it can be expressed
7543 as a simple equality test, then prefer that over its current form
7544 for evaluation.
7546 An overflow test which collapses to an equality test can always be
7547 expressed as a comparison of one argument against zero. Overflow
7548 occurs when the chosen argument is zero and does not occur if the
7549 chosen argument is not zero. */
7550 tree x;
7551 if (overflow_comparison_p (code, op0, op1, use_equiv_p, &x))
7553 wide_int max = wi::max_value (TYPE_PRECISION (TREE_TYPE (op0)), UNSIGNED);
7554 /* B = A - 1; if (A < B) -> B = A - 1; if (A == 0)
7555 B = A - 1; if (A > B) -> B = A - 1; if (A != 0)
7556 B = A + 1; if (B < A) -> B = A + 1; if (B == 0)
7557 B = A + 1; if (B > A) -> B = A + 1; if (B != 0) */
7558 if (integer_zerop (x))
7560 op1 = x;
7561 code = (code == LT_EXPR || code == LE_EXPR) ? EQ_EXPR : NE_EXPR;
7563 /* B = A + 1; if (A > B) -> B = A + 1; if (B == 0)
7564 B = A + 1; if (A < B) -> B = A + 1; if (B != 0)
7565 B = A - 1; if (B > A) -> B = A - 1; if (A == 0)
7566 B = A - 1; if (B < A) -> B = A - 1; if (A != 0) */
7567 else if (wi::to_wide (x) == max - 1)
7569 op0 = op1;
7570 op1 = wide_int_to_tree (TREE_TYPE (op0), 0);
7571 code = (code == GT_EXPR || code == GE_EXPR) ? EQ_EXPR : NE_EXPR;
7575 if ((ret = vrp_evaluate_conditional_warnv_with_ops_using_ranges
7576 (code, op0, op1, strict_overflow_p)))
7577 return ret;
7578 if (only_ranges)
7579 *only_ranges = false;
7580 /* Do not use compare_names during propagation, it's quadratic. */
7581 if (TREE_CODE (op0) == SSA_NAME && TREE_CODE (op1) == SSA_NAME
7582 && use_equiv_p)
7583 return compare_names (code, op0, op1, strict_overflow_p);
7584 else if (TREE_CODE (op0) == SSA_NAME)
7585 return compare_name_with_value (code, op0, op1,
7586 strict_overflow_p, use_equiv_p);
7587 else if (TREE_CODE (op1) == SSA_NAME)
7588 return compare_name_with_value (swap_tree_comparison (code), op1, op0,
7589 strict_overflow_p, use_equiv_p);
7590 return NULL_TREE;
7593 /* Given (CODE OP0 OP1) within STMT, try to simplify it based on value range
7594 information. Return NULL if the conditional can not be evaluated.
7595 The ranges of all the names equivalent with the operands in COND
7596 will be used when trying to compute the value. If the result is
7597 based on undefined signed overflow, issue a warning if
7598 appropriate. */
7600 static tree
7601 vrp_evaluate_conditional (tree_code code, tree op0, tree op1, gimple *stmt)
7603 bool sop;
7604 tree ret;
7605 bool only_ranges;
7607 /* Some passes and foldings leak constants with overflow flag set
7608 into the IL. Avoid doing wrong things with these and bail out. */
7609 if ((TREE_CODE (op0) == INTEGER_CST
7610 && TREE_OVERFLOW (op0))
7611 || (TREE_CODE (op1) == INTEGER_CST
7612 && TREE_OVERFLOW (op1)))
7613 return NULL_TREE;
7615 sop = false;
7616 ret = vrp_evaluate_conditional_warnv_with_ops (code, op0, op1, true, &sop,
7617 &only_ranges);
7619 if (ret && sop)
7621 enum warn_strict_overflow_code wc;
7622 const char* warnmsg;
7624 if (is_gimple_min_invariant (ret))
7626 wc = WARN_STRICT_OVERFLOW_CONDITIONAL;
7627 warnmsg = G_("assuming signed overflow does not occur when "
7628 "simplifying conditional to constant");
7630 else
7632 wc = WARN_STRICT_OVERFLOW_COMPARISON;
7633 warnmsg = G_("assuming signed overflow does not occur when "
7634 "simplifying conditional");
7637 if (issue_strict_overflow_warning (wc))
7639 location_t location;
7641 if (!gimple_has_location (stmt))
7642 location = input_location;
7643 else
7644 location = gimple_location (stmt);
7645 warning_at (location, OPT_Wstrict_overflow, "%s", warnmsg);
7649 if (warn_type_limits
7650 && ret && only_ranges
7651 && TREE_CODE_CLASS (code) == tcc_comparison
7652 && TREE_CODE (op0) == SSA_NAME)
7654 /* If the comparison is being folded and the operand on the LHS
7655 is being compared against a constant value that is outside of
7656 the natural range of OP0's type, then the predicate will
7657 always fold regardless of the value of OP0. If -Wtype-limits
7658 was specified, emit a warning. */
7659 tree type = TREE_TYPE (op0);
7660 value_range *vr0 = get_value_range (op0);
7662 if (vr0->type == VR_RANGE
7663 && INTEGRAL_TYPE_P (type)
7664 && vrp_val_is_min (vr0->min)
7665 && vrp_val_is_max (vr0->max)
7666 && is_gimple_min_invariant (op1))
7668 location_t location;
7670 if (!gimple_has_location (stmt))
7671 location = input_location;
7672 else
7673 location = gimple_location (stmt);
7675 warning_at (location, OPT_Wtype_limits,
7676 integer_zerop (ret)
7677 ? G_("comparison always false "
7678 "due to limited range of data type")
7679 : G_("comparison always true "
7680 "due to limited range of data type"));
7684 return ret;
7688 /* Visit conditional statement STMT. If we can determine which edge
7689 will be taken out of STMT's basic block, record it in
7690 *TAKEN_EDGE_P. Otherwise, set *TAKEN_EDGE_P to NULL. */
7692 static void
7693 vrp_visit_cond_stmt (gcond *stmt, edge *taken_edge_p)
7695 tree val;
7697 *taken_edge_p = NULL;
7699 if (dump_file && (dump_flags & TDF_DETAILS))
7701 tree use;
7702 ssa_op_iter i;
7704 fprintf (dump_file, "\nVisiting conditional with predicate: ");
7705 print_gimple_stmt (dump_file, stmt, 0);
7706 fprintf (dump_file, "\nWith known ranges\n");
7708 FOR_EACH_SSA_TREE_OPERAND (use, stmt, i, SSA_OP_USE)
7710 fprintf (dump_file, "\t");
7711 print_generic_expr (dump_file, use);
7712 fprintf (dump_file, ": ");
7713 dump_value_range (dump_file, vr_value[SSA_NAME_VERSION (use)]);
7716 fprintf (dump_file, "\n");
7719 /* Compute the value of the predicate COND by checking the known
7720 ranges of each of its operands.
7722 Note that we cannot evaluate all the equivalent ranges here
7723 because those ranges may not yet be final and with the current
7724 propagation strategy, we cannot determine when the value ranges
7725 of the names in the equivalence set have changed.
7727 For instance, given the following code fragment
7729 i_5 = PHI <8, i_13>
7731 i_14 = ASSERT_EXPR <i_5, i_5 != 0>
7732 if (i_14 == 1)
7735 Assume that on the first visit to i_14, i_5 has the temporary
7736 range [8, 8] because the second argument to the PHI function is
7737 not yet executable. We derive the range ~[0, 0] for i_14 and the
7738 equivalence set { i_5 }. So, when we visit 'if (i_14 == 1)' for
7739 the first time, since i_14 is equivalent to the range [8, 8], we
7740 determine that the predicate is always false.
7742 On the next round of propagation, i_13 is determined to be
7743 VARYING, which causes i_5 to drop down to VARYING. So, another
7744 visit to i_14 is scheduled. In this second visit, we compute the
7745 exact same range and equivalence set for i_14, namely ~[0, 0] and
7746 { i_5 }. But we did not have the previous range for i_5
7747 registered, so vrp_visit_assignment thinks that the range for
7748 i_14 has not changed. Therefore, the predicate 'if (i_14 == 1)'
7749 is not visited again, which stops propagation from visiting
7750 statements in the THEN clause of that if().
7752 To properly fix this we would need to keep the previous range
7753 value for the names in the equivalence set. This way we would've
7754 discovered that from one visit to the other i_5 changed from
7755 range [8, 8] to VR_VARYING.
7757 However, fixing this apparent limitation may not be worth the
7758 additional checking. Testing on several code bases (GCC, DLV,
7759 MICO, TRAMP3D and SPEC2000) showed that doing this results in
7760 4 more predicates folded in SPEC. */
7762 bool sop;
7763 val = vrp_evaluate_conditional_warnv_with_ops (gimple_cond_code (stmt),
7764 gimple_cond_lhs (stmt),
7765 gimple_cond_rhs (stmt),
7766 false, &sop, NULL);
7767 if (val)
7768 *taken_edge_p = find_taken_edge (gimple_bb (stmt), val);
7770 if (dump_file && (dump_flags & TDF_DETAILS))
7772 fprintf (dump_file, "\nPredicate evaluates to: ");
7773 if (val == NULL_TREE)
7774 fprintf (dump_file, "DON'T KNOW\n");
7775 else
7776 print_generic_stmt (dump_file, val);
7780 /* Searches the case label vector VEC for the index *IDX of the CASE_LABEL
7781 that includes the value VAL. The search is restricted to the range
7782 [START_IDX, n - 1] where n is the size of VEC.
7784 If there is a CASE_LABEL for VAL, its index is placed in IDX and true is
7785 returned.
7787 If there is no CASE_LABEL for VAL and there is one that is larger than VAL,
7788 it is placed in IDX and false is returned.
7790 If VAL is larger than any CASE_LABEL, n is placed on IDX and false is
7791 returned. */
7793 static bool
7794 find_case_label_index (gswitch *stmt, size_t start_idx, tree val, size_t *idx)
7796 size_t n = gimple_switch_num_labels (stmt);
7797 size_t low, high;
7799 /* Find case label for minimum of the value range or the next one.
7800 At each iteration we are searching in [low, high - 1]. */
7802 for (low = start_idx, high = n; high != low; )
7804 tree t;
7805 int cmp;
7806 /* Note that i != high, so we never ask for n. */
7807 size_t i = (high + low) / 2;
7808 t = gimple_switch_label (stmt, i);
7810 /* Cache the result of comparing CASE_LOW and val. */
7811 cmp = tree_int_cst_compare (CASE_LOW (t), val);
7813 if (cmp == 0)
7815 /* Ranges cannot be empty. */
7816 *idx = i;
7817 return true;
7819 else if (cmp > 0)
7820 high = i;
7821 else
7823 low = i + 1;
7824 if (CASE_HIGH (t) != NULL
7825 && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
7827 *idx = i;
7828 return true;
7833 *idx = high;
7834 return false;
7837 /* Searches the case label vector VEC for the range of CASE_LABELs that is used
7838 for values between MIN and MAX. The first index is placed in MIN_IDX. The
7839 last index is placed in MAX_IDX. If the range of CASE_LABELs is empty
7840 then MAX_IDX < MIN_IDX.
7841 Returns true if the default label is not needed. */
7843 static bool
7844 find_case_label_range (gswitch *stmt, tree min, tree max, size_t *min_idx,
7845 size_t *max_idx)
7847 size_t i, j;
7848 bool min_take_default = !find_case_label_index (stmt, 1, min, &i);
7849 bool max_take_default = !find_case_label_index (stmt, i, max, &j);
7851 if (i == j
7852 && min_take_default
7853 && max_take_default)
7855 /* Only the default case label reached.
7856 Return an empty range. */
7857 *min_idx = 1;
7858 *max_idx = 0;
7859 return false;
7861 else
7863 bool take_default = min_take_default || max_take_default;
7864 tree low, high;
7865 size_t k;
7867 if (max_take_default)
7868 j--;
7870 /* If the case label range is continuous, we do not need
7871 the default case label. Verify that. */
7872 high = CASE_LOW (gimple_switch_label (stmt, i));
7873 if (CASE_HIGH (gimple_switch_label (stmt, i)))
7874 high = CASE_HIGH (gimple_switch_label (stmt, i));
7875 for (k = i + 1; k <= j; ++k)
7877 low = CASE_LOW (gimple_switch_label (stmt, k));
7878 if (!integer_onep (int_const_binop (MINUS_EXPR, low, high)))
7880 take_default = true;
7881 break;
7883 high = low;
7884 if (CASE_HIGH (gimple_switch_label (stmt, k)))
7885 high = CASE_HIGH (gimple_switch_label (stmt, k));
7888 *min_idx = i;
7889 *max_idx = j;
7890 return !take_default;
7894 /* Searches the case label vector VEC for the ranges of CASE_LABELs that are
7895 used in range VR. The indices are placed in MIN_IDX1, MAX_IDX, MIN_IDX2 and
7896 MAX_IDX2. If the ranges of CASE_LABELs are empty then MAX_IDX1 < MIN_IDX1.
7897 Returns true if the default label is not needed. */
7899 static bool
7900 find_case_label_ranges (gswitch *stmt, value_range *vr, size_t *min_idx1,
7901 size_t *max_idx1, size_t *min_idx2,
7902 size_t *max_idx2)
7904 size_t i, j, k, l;
7905 unsigned int n = gimple_switch_num_labels (stmt);
7906 bool take_default;
7907 tree case_low, case_high;
7908 tree min = vr->min, max = vr->max;
7910 gcc_checking_assert (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE);
7912 take_default = !find_case_label_range (stmt, min, max, &i, &j);
7914 /* Set second range to emtpy. */
7915 *min_idx2 = 1;
7916 *max_idx2 = 0;
7918 if (vr->type == VR_RANGE)
7920 *min_idx1 = i;
7921 *max_idx1 = j;
7922 return !take_default;
7925 /* Set first range to all case labels. */
7926 *min_idx1 = 1;
7927 *max_idx1 = n - 1;
7929 if (i > j)
7930 return false;
7932 /* Make sure all the values of case labels [i , j] are contained in
7933 range [MIN, MAX]. */
7934 case_low = CASE_LOW (gimple_switch_label (stmt, i));
7935 case_high = CASE_HIGH (gimple_switch_label (stmt, j));
7936 if (tree_int_cst_compare (case_low, min) < 0)
7937 i += 1;
7938 if (case_high != NULL_TREE
7939 && tree_int_cst_compare (max, case_high) < 0)
7940 j -= 1;
7942 if (i > j)
7943 return false;
7945 /* If the range spans case labels [i, j], the corresponding anti-range spans
7946 the labels [1, i - 1] and [j + 1, n - 1]. */
7947 k = j + 1;
7948 l = n - 1;
7949 if (k > l)
7951 k = 1;
7952 l = 0;
7955 j = i - 1;
7956 i = 1;
7957 if (i > j)
7959 i = k;
7960 j = l;
7961 k = 1;
7962 l = 0;
7965 *min_idx1 = i;
7966 *max_idx1 = j;
7967 *min_idx2 = k;
7968 *max_idx2 = l;
7969 return false;
7972 /* Visit switch statement STMT. If we can determine which edge
7973 will be taken out of STMT's basic block, record it in
7974 *TAKEN_EDGE_P. Otherwise, *TAKEN_EDGE_P set to NULL. */
7976 static void
7977 vrp_visit_switch_stmt (gswitch *stmt, edge *taken_edge_p)
7979 tree op, val;
7980 value_range *vr;
7981 size_t i = 0, j = 0, k, l;
7982 bool take_default;
7984 *taken_edge_p = NULL;
7985 op = gimple_switch_index (stmt);
7986 if (TREE_CODE (op) != SSA_NAME)
7987 return;
7989 vr = get_value_range (op);
7990 if (dump_file && (dump_flags & TDF_DETAILS))
7992 fprintf (dump_file, "\nVisiting switch expression with operand ");
7993 print_generic_expr (dump_file, op);
7994 fprintf (dump_file, " with known range ");
7995 dump_value_range (dump_file, vr);
7996 fprintf (dump_file, "\n");
7999 if ((vr->type != VR_RANGE
8000 && vr->type != VR_ANTI_RANGE)
8001 || symbolic_range_p (vr))
8002 return;
8004 /* Find the single edge that is taken from the switch expression. */
8005 take_default = !find_case_label_ranges (stmt, vr, &i, &j, &k, &l);
8007 /* Check if the range spans no CASE_LABEL. If so, we only reach the default
8008 label */
8009 if (j < i)
8011 gcc_assert (take_default);
8012 val = gimple_switch_default_label (stmt);
8014 else
8016 /* Check if labels with index i to j and maybe the default label
8017 are all reaching the same label. */
8019 val = gimple_switch_label (stmt, i);
8020 if (take_default
8021 && CASE_LABEL (gimple_switch_default_label (stmt))
8022 != CASE_LABEL (val))
8024 if (dump_file && (dump_flags & TDF_DETAILS))
8025 fprintf (dump_file, " not a single destination for this "
8026 "range\n");
8027 return;
8029 for (++i; i <= j; ++i)
8031 if (CASE_LABEL (gimple_switch_label (stmt, i)) != CASE_LABEL (val))
8033 if (dump_file && (dump_flags & TDF_DETAILS))
8034 fprintf (dump_file, " not a single destination for this "
8035 "range\n");
8036 return;
8039 for (; k <= l; ++k)
8041 if (CASE_LABEL (gimple_switch_label (stmt, k)) != CASE_LABEL (val))
8043 if (dump_file && (dump_flags & TDF_DETAILS))
8044 fprintf (dump_file, " not a single destination for this "
8045 "range\n");
8046 return;
8051 *taken_edge_p = find_edge (gimple_bb (stmt),
8052 label_to_block (CASE_LABEL (val)));
8054 if (dump_file && (dump_flags & TDF_DETAILS))
8056 fprintf (dump_file, " will take edge to ");
8057 print_generic_stmt (dump_file, CASE_LABEL (val));
8062 /* Evaluate statement STMT. If the statement produces a useful range,
8063 set VR and corepsponding OUTPUT_P.
8065 If STMT is a conditional branch and we can determine its truth
8066 value, the taken edge is recorded in *TAKEN_EDGE_P. */
8068 static void
8069 extract_range_from_stmt (gimple *stmt, edge *taken_edge_p,
8070 tree *output_p, value_range *vr)
8073 if (dump_file && (dump_flags & TDF_DETAILS))
8075 fprintf (dump_file, "\nVisiting statement:\n");
8076 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
8079 if (!stmt_interesting_for_vrp (stmt))
8080 gcc_assert (stmt_ends_bb_p (stmt));
8081 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
8082 vrp_visit_assignment_or_call (stmt, output_p, vr);
8083 else if (gimple_code (stmt) == GIMPLE_COND)
8084 vrp_visit_cond_stmt (as_a <gcond *> (stmt), taken_edge_p);
8085 else if (gimple_code (stmt) == GIMPLE_SWITCH)
8086 vrp_visit_switch_stmt (as_a <gswitch *> (stmt), taken_edge_p);
8089 class vrp_prop : public ssa_propagation_engine
8091 public:
8092 enum ssa_prop_result visit_stmt (gimple *, edge *, tree *) FINAL OVERRIDE;
8093 enum ssa_prop_result visit_phi (gphi *) FINAL OVERRIDE;
8096 /* Evaluate statement STMT. If the statement produces a useful range,
8097 return SSA_PROP_INTERESTING and record the SSA name with the
8098 interesting range into *OUTPUT_P.
8100 If STMT is a conditional branch and we can determine its truth
8101 value, the taken edge is recorded in *TAKEN_EDGE_P.
8103 If STMT produces a varying value, return SSA_PROP_VARYING. */
8105 enum ssa_prop_result
8106 vrp_prop::visit_stmt (gimple *stmt, edge *taken_edge_p, tree *output_p)
8108 value_range vr = VR_INITIALIZER;
8109 tree lhs = gimple_get_lhs (stmt);
8110 extract_range_from_stmt (stmt, taken_edge_p, output_p, &vr);
8112 if (*output_p)
8114 if (update_value_range (*output_p, &vr))
8116 if (dump_file && (dump_flags & TDF_DETAILS))
8118 fprintf (dump_file, "Found new range for ");
8119 print_generic_expr (dump_file, *output_p);
8120 fprintf (dump_file, ": ");
8121 dump_value_range (dump_file, &vr);
8122 fprintf (dump_file, "\n");
8125 if (vr.type == VR_VARYING)
8126 return SSA_PROP_VARYING;
8128 return SSA_PROP_INTERESTING;
8130 return SSA_PROP_NOT_INTERESTING;
8133 if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
8134 switch (gimple_call_internal_fn (stmt))
8136 case IFN_ADD_OVERFLOW:
8137 case IFN_SUB_OVERFLOW:
8138 case IFN_MUL_OVERFLOW:
8139 case IFN_ATOMIC_COMPARE_EXCHANGE:
8140 /* These internal calls return _Complex integer type,
8141 which VRP does not track, but the immediate uses
8142 thereof might be interesting. */
8143 if (lhs && TREE_CODE (lhs) == SSA_NAME)
8145 imm_use_iterator iter;
8146 use_operand_p use_p;
8147 enum ssa_prop_result res = SSA_PROP_VARYING;
8149 set_value_range_to_varying (get_value_range (lhs));
8151 FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
8153 gimple *use_stmt = USE_STMT (use_p);
8154 if (!is_gimple_assign (use_stmt))
8155 continue;
8156 enum tree_code rhs_code = gimple_assign_rhs_code (use_stmt);
8157 if (rhs_code != REALPART_EXPR && rhs_code != IMAGPART_EXPR)
8158 continue;
8159 tree rhs1 = gimple_assign_rhs1 (use_stmt);
8160 tree use_lhs = gimple_assign_lhs (use_stmt);
8161 if (TREE_CODE (rhs1) != rhs_code
8162 || TREE_OPERAND (rhs1, 0) != lhs
8163 || TREE_CODE (use_lhs) != SSA_NAME
8164 || !stmt_interesting_for_vrp (use_stmt)
8165 || (!INTEGRAL_TYPE_P (TREE_TYPE (use_lhs))
8166 || !TYPE_MIN_VALUE (TREE_TYPE (use_lhs))
8167 || !TYPE_MAX_VALUE (TREE_TYPE (use_lhs))))
8168 continue;
8170 /* If there is a change in the value range for any of the
8171 REALPART_EXPR/IMAGPART_EXPR immediate uses, return
8172 SSA_PROP_INTERESTING. If there are any REALPART_EXPR
8173 or IMAGPART_EXPR immediate uses, but none of them have
8174 a change in their value ranges, return
8175 SSA_PROP_NOT_INTERESTING. If there are no
8176 {REAL,IMAG}PART_EXPR uses at all,
8177 return SSA_PROP_VARYING. */
8178 value_range new_vr = VR_INITIALIZER;
8179 extract_range_basic (&new_vr, use_stmt);
8180 value_range *old_vr = get_value_range (use_lhs);
8181 if (old_vr->type != new_vr.type
8182 || !vrp_operand_equal_p (old_vr->min, new_vr.min)
8183 || !vrp_operand_equal_p (old_vr->max, new_vr.max)
8184 || !vrp_bitmap_equal_p (old_vr->equiv, new_vr.equiv))
8185 res = SSA_PROP_INTERESTING;
8186 else
8187 res = SSA_PROP_NOT_INTERESTING;
8188 BITMAP_FREE (new_vr.equiv);
8189 if (res == SSA_PROP_INTERESTING)
8191 *output_p = lhs;
8192 return res;
8196 return res;
8198 break;
8199 default:
8200 break;
8203 /* All other statements produce nothing of interest for VRP, so mark
8204 their outputs varying and prevent further simulation. */
8205 set_defs_to_varying (stmt);
8207 return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
8210 /* Union the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
8211 { VR1TYPE, VR0MIN, VR0MAX } and store the result
8212 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
8213 possible such range. The resulting range is not canonicalized. */
8215 static void
8216 union_ranges (enum value_range_type *vr0type,
8217 tree *vr0min, tree *vr0max,
8218 enum value_range_type vr1type,
8219 tree vr1min, tree vr1max)
8221 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
8222 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
8224 /* [] is vr0, () is vr1 in the following classification comments. */
8225 if (mineq && maxeq)
8227 /* [( )] */
8228 if (*vr0type == vr1type)
8229 /* Nothing to do for equal ranges. */
8231 else if ((*vr0type == VR_RANGE
8232 && vr1type == VR_ANTI_RANGE)
8233 || (*vr0type == VR_ANTI_RANGE
8234 && vr1type == VR_RANGE))
8236 /* For anti-range with range union the result is varying. */
8237 goto give_up;
8239 else
8240 gcc_unreachable ();
8242 else if (operand_less_p (*vr0max, vr1min) == 1
8243 || operand_less_p (vr1max, *vr0min) == 1)
8245 /* [ ] ( ) or ( ) [ ]
8246 If the ranges have an empty intersection, result of the union
8247 operation is the anti-range or if both are anti-ranges
8248 it covers all. */
8249 if (*vr0type == VR_ANTI_RANGE
8250 && vr1type == VR_ANTI_RANGE)
8251 goto give_up;
8252 else if (*vr0type == VR_ANTI_RANGE
8253 && vr1type == VR_RANGE)
8255 else if (*vr0type == VR_RANGE
8256 && vr1type == VR_ANTI_RANGE)
8258 *vr0type = vr1type;
8259 *vr0min = vr1min;
8260 *vr0max = vr1max;
8262 else if (*vr0type == VR_RANGE
8263 && vr1type == VR_RANGE)
8265 /* The result is the convex hull of both ranges. */
8266 if (operand_less_p (*vr0max, vr1min) == 1)
8268 /* If the result can be an anti-range, create one. */
8269 if (TREE_CODE (*vr0max) == INTEGER_CST
8270 && TREE_CODE (vr1min) == INTEGER_CST
8271 && vrp_val_is_min (*vr0min)
8272 && vrp_val_is_max (vr1max))
8274 tree min = int_const_binop (PLUS_EXPR,
8275 *vr0max,
8276 build_int_cst (TREE_TYPE (*vr0max), 1));
8277 tree max = int_const_binop (MINUS_EXPR,
8278 vr1min,
8279 build_int_cst (TREE_TYPE (vr1min), 1));
8280 if (!operand_less_p (max, min))
8282 *vr0type = VR_ANTI_RANGE;
8283 *vr0min = min;
8284 *vr0max = max;
8286 else
8287 *vr0max = vr1max;
8289 else
8290 *vr0max = vr1max;
8292 else
8294 /* If the result can be an anti-range, create one. */
8295 if (TREE_CODE (vr1max) == INTEGER_CST
8296 && TREE_CODE (*vr0min) == INTEGER_CST
8297 && vrp_val_is_min (vr1min)
8298 && vrp_val_is_max (*vr0max))
8300 tree min = int_const_binop (PLUS_EXPR,
8301 vr1max,
8302 build_int_cst (TREE_TYPE (vr1max), 1));
8303 tree max = int_const_binop (MINUS_EXPR,
8304 *vr0min,
8305 build_int_cst (TREE_TYPE (*vr0min), 1));
8306 if (!operand_less_p (max, min))
8308 *vr0type = VR_ANTI_RANGE;
8309 *vr0min = min;
8310 *vr0max = max;
8312 else
8313 *vr0min = vr1min;
8315 else
8316 *vr0min = vr1min;
8319 else
8320 gcc_unreachable ();
8322 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
8323 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
8325 /* [ ( ) ] or [( ) ] or [ ( )] */
8326 if (*vr0type == VR_RANGE
8327 && vr1type == VR_RANGE)
8329 else if (*vr0type == VR_ANTI_RANGE
8330 && vr1type == VR_ANTI_RANGE)
8332 *vr0type = vr1type;
8333 *vr0min = vr1min;
8334 *vr0max = vr1max;
8336 else if (*vr0type == VR_ANTI_RANGE
8337 && vr1type == VR_RANGE)
8339 /* Arbitrarily choose the right or left gap. */
8340 if (!mineq && TREE_CODE (vr1min) == INTEGER_CST)
8341 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8342 build_int_cst (TREE_TYPE (vr1min), 1));
8343 else if (!maxeq && TREE_CODE (vr1max) == INTEGER_CST)
8344 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
8345 build_int_cst (TREE_TYPE (vr1max), 1));
8346 else
8347 goto give_up;
8349 else if (*vr0type == VR_RANGE
8350 && vr1type == VR_ANTI_RANGE)
8351 /* The result covers everything. */
8352 goto give_up;
8353 else
8354 gcc_unreachable ();
8356 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
8357 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
8359 /* ( [ ] ) or ([ ] ) or ( [ ]) */
8360 if (*vr0type == VR_RANGE
8361 && vr1type == VR_RANGE)
8363 *vr0type = vr1type;
8364 *vr0min = vr1min;
8365 *vr0max = vr1max;
8367 else if (*vr0type == VR_ANTI_RANGE
8368 && vr1type == VR_ANTI_RANGE)
8370 else if (*vr0type == VR_RANGE
8371 && vr1type == VR_ANTI_RANGE)
8373 *vr0type = VR_ANTI_RANGE;
8374 if (!mineq && TREE_CODE (*vr0min) == INTEGER_CST)
8376 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
8377 build_int_cst (TREE_TYPE (*vr0min), 1));
8378 *vr0min = vr1min;
8380 else if (!maxeq && TREE_CODE (*vr0max) == INTEGER_CST)
8382 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8383 build_int_cst (TREE_TYPE (*vr0max), 1));
8384 *vr0max = vr1max;
8386 else
8387 goto give_up;
8389 else if (*vr0type == VR_ANTI_RANGE
8390 && vr1type == VR_RANGE)
8391 /* The result covers everything. */
8392 goto give_up;
8393 else
8394 gcc_unreachable ();
8396 else if ((operand_less_p (vr1min, *vr0max) == 1
8397 || operand_equal_p (vr1min, *vr0max, 0))
8398 && operand_less_p (*vr0min, vr1min) == 1
8399 && operand_less_p (*vr0max, vr1max) == 1)
8401 /* [ ( ] ) or [ ]( ) */
8402 if (*vr0type == VR_RANGE
8403 && vr1type == VR_RANGE)
8404 *vr0max = vr1max;
8405 else if (*vr0type == VR_ANTI_RANGE
8406 && vr1type == VR_ANTI_RANGE)
8407 *vr0min = vr1min;
8408 else if (*vr0type == VR_ANTI_RANGE
8409 && vr1type == VR_RANGE)
8411 if (TREE_CODE (vr1min) == INTEGER_CST)
8412 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8413 build_int_cst (TREE_TYPE (vr1min), 1));
8414 else
8415 goto give_up;
8417 else if (*vr0type == VR_RANGE
8418 && vr1type == VR_ANTI_RANGE)
8420 if (TREE_CODE (*vr0max) == INTEGER_CST)
8422 *vr0type = vr1type;
8423 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8424 build_int_cst (TREE_TYPE (*vr0max), 1));
8425 *vr0max = vr1max;
8427 else
8428 goto give_up;
8430 else
8431 gcc_unreachable ();
8433 else if ((operand_less_p (*vr0min, vr1max) == 1
8434 || operand_equal_p (*vr0min, vr1max, 0))
8435 && operand_less_p (vr1min, *vr0min) == 1
8436 && operand_less_p (vr1max, *vr0max) == 1)
8438 /* ( [ ) ] or ( )[ ] */
8439 if (*vr0type == VR_RANGE
8440 && vr1type == VR_RANGE)
8441 *vr0min = vr1min;
8442 else if (*vr0type == VR_ANTI_RANGE
8443 && vr1type == VR_ANTI_RANGE)
8444 *vr0max = vr1max;
8445 else if (*vr0type == VR_ANTI_RANGE
8446 && vr1type == VR_RANGE)
8448 if (TREE_CODE (vr1max) == INTEGER_CST)
8449 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
8450 build_int_cst (TREE_TYPE (vr1max), 1));
8451 else
8452 goto give_up;
8454 else if (*vr0type == VR_RANGE
8455 && vr1type == VR_ANTI_RANGE)
8457 if (TREE_CODE (*vr0min) == INTEGER_CST)
8459 *vr0type = vr1type;
8460 *vr0min = vr1min;
8461 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
8462 build_int_cst (TREE_TYPE (*vr0min), 1));
8464 else
8465 goto give_up;
8467 else
8468 gcc_unreachable ();
8470 else
8471 goto give_up;
8473 return;
8475 give_up:
8476 *vr0type = VR_VARYING;
8477 *vr0min = NULL_TREE;
8478 *vr0max = NULL_TREE;
8481 /* Intersect the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
8482 { VR1TYPE, VR0MIN, VR0MAX } and store the result
8483 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
8484 possible such range. The resulting range is not canonicalized. */
8486 static void
8487 intersect_ranges (enum value_range_type *vr0type,
8488 tree *vr0min, tree *vr0max,
8489 enum value_range_type vr1type,
8490 tree vr1min, tree vr1max)
8492 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
8493 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
8495 /* [] is vr0, () is vr1 in the following classification comments. */
8496 if (mineq && maxeq)
8498 /* [( )] */
8499 if (*vr0type == vr1type)
8500 /* Nothing to do for equal ranges. */
8502 else if ((*vr0type == VR_RANGE
8503 && vr1type == VR_ANTI_RANGE)
8504 || (*vr0type == VR_ANTI_RANGE
8505 && vr1type == VR_RANGE))
8507 /* For anti-range with range intersection the result is empty. */
8508 *vr0type = VR_UNDEFINED;
8509 *vr0min = NULL_TREE;
8510 *vr0max = NULL_TREE;
8512 else
8513 gcc_unreachable ();
8515 else if (operand_less_p (*vr0max, vr1min) == 1
8516 || operand_less_p (vr1max, *vr0min) == 1)
8518 /* [ ] ( ) or ( ) [ ]
8519 If the ranges have an empty intersection, the result of the
8520 intersect operation is the range for intersecting an
8521 anti-range with a range or empty when intersecting two ranges. */
8522 if (*vr0type == VR_RANGE
8523 && vr1type == VR_ANTI_RANGE)
8525 else if (*vr0type == VR_ANTI_RANGE
8526 && vr1type == VR_RANGE)
8528 *vr0type = vr1type;
8529 *vr0min = vr1min;
8530 *vr0max = vr1max;
8532 else if (*vr0type == VR_RANGE
8533 && vr1type == VR_RANGE)
8535 *vr0type = VR_UNDEFINED;
8536 *vr0min = NULL_TREE;
8537 *vr0max = NULL_TREE;
8539 else if (*vr0type == VR_ANTI_RANGE
8540 && vr1type == VR_ANTI_RANGE)
8542 /* If the anti-ranges are adjacent to each other merge them. */
8543 if (TREE_CODE (*vr0max) == INTEGER_CST
8544 && TREE_CODE (vr1min) == INTEGER_CST
8545 && operand_less_p (*vr0max, vr1min) == 1
8546 && integer_onep (int_const_binop (MINUS_EXPR,
8547 vr1min, *vr0max)))
8548 *vr0max = vr1max;
8549 else if (TREE_CODE (vr1max) == INTEGER_CST
8550 && TREE_CODE (*vr0min) == INTEGER_CST
8551 && operand_less_p (vr1max, *vr0min) == 1
8552 && integer_onep (int_const_binop (MINUS_EXPR,
8553 *vr0min, vr1max)))
8554 *vr0min = vr1min;
8555 /* Else arbitrarily take VR0. */
8558 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
8559 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
8561 /* [ ( ) ] or [( ) ] or [ ( )] */
8562 if (*vr0type == VR_RANGE
8563 && vr1type == VR_RANGE)
8565 /* If both are ranges the result is the inner one. */
8566 *vr0type = vr1type;
8567 *vr0min = vr1min;
8568 *vr0max = vr1max;
8570 else if (*vr0type == VR_RANGE
8571 && vr1type == VR_ANTI_RANGE)
8573 /* Choose the right gap if the left one is empty. */
8574 if (mineq)
8576 if (TREE_CODE (vr1max) != INTEGER_CST)
8577 *vr0min = vr1max;
8578 else if (TYPE_PRECISION (TREE_TYPE (vr1max)) == 1
8579 && !TYPE_UNSIGNED (TREE_TYPE (vr1max)))
8580 *vr0min
8581 = int_const_binop (MINUS_EXPR, vr1max,
8582 build_int_cst (TREE_TYPE (vr1max), -1));
8583 else
8584 *vr0min
8585 = int_const_binop (PLUS_EXPR, vr1max,
8586 build_int_cst (TREE_TYPE (vr1max), 1));
8588 /* Choose the left gap if the right one is empty. */
8589 else if (maxeq)
8591 if (TREE_CODE (vr1min) != INTEGER_CST)
8592 *vr0max = vr1min;
8593 else if (TYPE_PRECISION (TREE_TYPE (vr1min)) == 1
8594 && !TYPE_UNSIGNED (TREE_TYPE (vr1min)))
8595 *vr0max
8596 = int_const_binop (PLUS_EXPR, vr1min,
8597 build_int_cst (TREE_TYPE (vr1min), -1));
8598 else
8599 *vr0max
8600 = int_const_binop (MINUS_EXPR, vr1min,
8601 build_int_cst (TREE_TYPE (vr1min), 1));
8603 /* Choose the anti-range if the range is effectively varying. */
8604 else if (vrp_val_is_min (*vr0min)
8605 && vrp_val_is_max (*vr0max))
8607 *vr0type = vr1type;
8608 *vr0min = vr1min;
8609 *vr0max = vr1max;
8611 /* Else choose the range. */
8613 else if (*vr0type == VR_ANTI_RANGE
8614 && vr1type == VR_ANTI_RANGE)
8615 /* If both are anti-ranges the result is the outer one. */
8617 else if (*vr0type == VR_ANTI_RANGE
8618 && vr1type == VR_RANGE)
8620 /* The intersection is empty. */
8621 *vr0type = VR_UNDEFINED;
8622 *vr0min = NULL_TREE;
8623 *vr0max = NULL_TREE;
8625 else
8626 gcc_unreachable ();
8628 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
8629 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
8631 /* ( [ ] ) or ([ ] ) or ( [ ]) */
8632 if (*vr0type == VR_RANGE
8633 && vr1type == VR_RANGE)
8634 /* Choose the inner range. */
8636 else if (*vr0type == VR_ANTI_RANGE
8637 && vr1type == VR_RANGE)
8639 /* Choose the right gap if the left is empty. */
8640 if (mineq)
8642 *vr0type = VR_RANGE;
8643 if (TREE_CODE (*vr0max) != INTEGER_CST)
8644 *vr0min = *vr0max;
8645 else if (TYPE_PRECISION (TREE_TYPE (*vr0max)) == 1
8646 && !TYPE_UNSIGNED (TREE_TYPE (*vr0max)))
8647 *vr0min
8648 = int_const_binop (MINUS_EXPR, *vr0max,
8649 build_int_cst (TREE_TYPE (*vr0max), -1));
8650 else
8651 *vr0min
8652 = int_const_binop (PLUS_EXPR, *vr0max,
8653 build_int_cst (TREE_TYPE (*vr0max), 1));
8654 *vr0max = vr1max;
8656 /* Choose the left gap if the right is empty. */
8657 else if (maxeq)
8659 *vr0type = VR_RANGE;
8660 if (TREE_CODE (*vr0min) != INTEGER_CST)
8661 *vr0max = *vr0min;
8662 else if (TYPE_PRECISION (TREE_TYPE (*vr0min)) == 1
8663 && !TYPE_UNSIGNED (TREE_TYPE (*vr0min)))
8664 *vr0max
8665 = int_const_binop (PLUS_EXPR, *vr0min,
8666 build_int_cst (TREE_TYPE (*vr0min), -1));
8667 else
8668 *vr0max
8669 = int_const_binop (MINUS_EXPR, *vr0min,
8670 build_int_cst (TREE_TYPE (*vr0min), 1));
8671 *vr0min = vr1min;
8673 /* Choose the anti-range if the range is effectively varying. */
8674 else if (vrp_val_is_min (vr1min)
8675 && vrp_val_is_max (vr1max))
8677 /* Choose the anti-range if it is ~[0,0], that range is special
8678 enough to special case when vr1's range is relatively wide. */
8679 else if (*vr0min == *vr0max
8680 && integer_zerop (*vr0min)
8681 && (TYPE_PRECISION (TREE_TYPE (*vr0min))
8682 == TYPE_PRECISION (ptr_type_node))
8683 && TREE_CODE (vr1max) == INTEGER_CST
8684 && TREE_CODE (vr1min) == INTEGER_CST
8685 && (wi::clz (wi::to_wide (vr1max) - wi::to_wide (vr1min))
8686 < TYPE_PRECISION (TREE_TYPE (*vr0min)) / 2))
8688 /* Else choose the range. */
8689 else
8691 *vr0type = vr1type;
8692 *vr0min = vr1min;
8693 *vr0max = vr1max;
8696 else if (*vr0type == VR_ANTI_RANGE
8697 && vr1type == VR_ANTI_RANGE)
8699 /* If both are anti-ranges the result is the outer one. */
8700 *vr0type = vr1type;
8701 *vr0min = vr1min;
8702 *vr0max = vr1max;
8704 else if (vr1type == VR_ANTI_RANGE
8705 && *vr0type == VR_RANGE)
8707 /* The intersection is empty. */
8708 *vr0type = VR_UNDEFINED;
8709 *vr0min = NULL_TREE;
8710 *vr0max = NULL_TREE;
8712 else
8713 gcc_unreachable ();
8715 else if ((operand_less_p (vr1min, *vr0max) == 1
8716 || operand_equal_p (vr1min, *vr0max, 0))
8717 && operand_less_p (*vr0min, vr1min) == 1)
8719 /* [ ( ] ) or [ ]( ) */
8720 if (*vr0type == VR_ANTI_RANGE
8721 && vr1type == VR_ANTI_RANGE)
8722 *vr0max = vr1max;
8723 else if (*vr0type == VR_RANGE
8724 && vr1type == VR_RANGE)
8725 *vr0min = vr1min;
8726 else if (*vr0type == VR_RANGE
8727 && vr1type == VR_ANTI_RANGE)
8729 if (TREE_CODE (vr1min) == INTEGER_CST)
8730 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8731 build_int_cst (TREE_TYPE (vr1min), 1));
8732 else
8733 *vr0max = vr1min;
8735 else if (*vr0type == VR_ANTI_RANGE
8736 && vr1type == VR_RANGE)
8738 *vr0type = VR_RANGE;
8739 if (TREE_CODE (*vr0max) == INTEGER_CST)
8740 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8741 build_int_cst (TREE_TYPE (*vr0max), 1));
8742 else
8743 *vr0min = *vr0max;
8744 *vr0max = vr1max;
8746 else
8747 gcc_unreachable ();
8749 else if ((operand_less_p (*vr0min, vr1max) == 1
8750 || operand_equal_p (*vr0min, vr1max, 0))
8751 && operand_less_p (vr1min, *vr0min) == 1)
8753 /* ( [ ) ] or ( )[ ] */
8754 if (*vr0type == VR_ANTI_RANGE
8755 && vr1type == VR_ANTI_RANGE)
8756 *vr0min = vr1min;
8757 else if (*vr0type == VR_RANGE
8758 && vr1type == VR_RANGE)
8759 *vr0max = vr1max;
8760 else if (*vr0type == VR_RANGE
8761 && vr1type == VR_ANTI_RANGE)
8763 if (TREE_CODE (vr1max) == INTEGER_CST)
8764 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
8765 build_int_cst (TREE_TYPE (vr1max), 1));
8766 else
8767 *vr0min = vr1max;
8769 else if (*vr0type == VR_ANTI_RANGE
8770 && vr1type == VR_RANGE)
8772 *vr0type = VR_RANGE;
8773 if (TREE_CODE (*vr0min) == INTEGER_CST)
8774 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
8775 build_int_cst (TREE_TYPE (*vr0min), 1));
8776 else
8777 *vr0max = *vr0min;
8778 *vr0min = vr1min;
8780 else
8781 gcc_unreachable ();
8784 /* As a fallback simply use { *VRTYPE, *VR0MIN, *VR0MAX } as
8785 result for the intersection. That's always a conservative
8786 correct estimate unless VR1 is a constant singleton range
8787 in which case we choose that. */
8788 if (vr1type == VR_RANGE
8789 && is_gimple_min_invariant (vr1min)
8790 && vrp_operand_equal_p (vr1min, vr1max))
8792 *vr0type = vr1type;
8793 *vr0min = vr1min;
8794 *vr0max = vr1max;
8797 return;
8801 /* Intersect the two value-ranges *VR0 and *VR1 and store the result
8802 in *VR0. This may not be the smallest possible such range. */
8804 static void
8805 vrp_intersect_ranges_1 (value_range *vr0, value_range *vr1)
8807 value_range saved;
8809 /* If either range is VR_VARYING the other one wins. */
8810 if (vr1->type == VR_VARYING)
8811 return;
8812 if (vr0->type == VR_VARYING)
8814 copy_value_range (vr0, vr1);
8815 return;
8818 /* When either range is VR_UNDEFINED the resulting range is
8819 VR_UNDEFINED, too. */
8820 if (vr0->type == VR_UNDEFINED)
8821 return;
8822 if (vr1->type == VR_UNDEFINED)
8824 set_value_range_to_undefined (vr0);
8825 return;
8828 /* Save the original vr0 so we can return it as conservative intersection
8829 result when our worker turns things to varying. */
8830 saved = *vr0;
8831 intersect_ranges (&vr0->type, &vr0->min, &vr0->max,
8832 vr1->type, vr1->min, vr1->max);
8833 /* Make sure to canonicalize the result though as the inversion of a
8834 VR_RANGE can still be a VR_RANGE. */
8835 set_and_canonicalize_value_range (vr0, vr0->type,
8836 vr0->min, vr0->max, vr0->equiv);
8837 /* If that failed, use the saved original VR0. */
8838 if (vr0->type == VR_VARYING)
8840 *vr0 = saved;
8841 return;
8843 /* If the result is VR_UNDEFINED there is no need to mess with
8844 the equivalencies. */
8845 if (vr0->type == VR_UNDEFINED)
8846 return;
8848 /* The resulting set of equivalences for range intersection is the union of
8849 the two sets. */
8850 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
8851 bitmap_ior_into (vr0->equiv, vr1->equiv);
8852 else if (vr1->equiv && !vr0->equiv)
8854 vr0->equiv = BITMAP_ALLOC (&vrp_equiv_obstack);
8855 bitmap_copy (vr0->equiv, vr1->equiv);
8859 void
8860 vrp_intersect_ranges (value_range *vr0, value_range *vr1)
8862 if (dump_file && (dump_flags & TDF_DETAILS))
8864 fprintf (dump_file, "Intersecting\n ");
8865 dump_value_range (dump_file, vr0);
8866 fprintf (dump_file, "\nand\n ");
8867 dump_value_range (dump_file, vr1);
8868 fprintf (dump_file, "\n");
8870 vrp_intersect_ranges_1 (vr0, vr1);
8871 if (dump_file && (dump_flags & TDF_DETAILS))
8873 fprintf (dump_file, "to\n ");
8874 dump_value_range (dump_file, vr0);
8875 fprintf (dump_file, "\n");
8879 /* Meet operation for value ranges. Given two value ranges VR0 and
8880 VR1, store in VR0 a range that contains both VR0 and VR1. This
8881 may not be the smallest possible such range. */
8883 static void
8884 vrp_meet_1 (value_range *vr0, const value_range *vr1)
8886 value_range saved;
8888 if (vr0->type == VR_UNDEFINED)
8890 set_value_range (vr0, vr1->type, vr1->min, vr1->max, vr1->equiv);
8891 return;
8894 if (vr1->type == VR_UNDEFINED)
8896 /* VR0 already has the resulting range. */
8897 return;
8900 if (vr0->type == VR_VARYING)
8902 /* Nothing to do. VR0 already has the resulting range. */
8903 return;
8906 if (vr1->type == VR_VARYING)
8908 set_value_range_to_varying (vr0);
8909 return;
8912 saved = *vr0;
8913 union_ranges (&vr0->type, &vr0->min, &vr0->max,
8914 vr1->type, vr1->min, vr1->max);
8915 if (vr0->type == VR_VARYING)
8917 /* Failed to find an efficient meet. Before giving up and setting
8918 the result to VARYING, see if we can at least derive a useful
8919 anti-range. FIXME, all this nonsense about distinguishing
8920 anti-ranges from ranges is necessary because of the odd
8921 semantics of range_includes_zero_p and friends. */
8922 if (((saved.type == VR_RANGE
8923 && range_includes_zero_p (saved.min, saved.max) == 0)
8924 || (saved.type == VR_ANTI_RANGE
8925 && range_includes_zero_p (saved.min, saved.max) == 1))
8926 && ((vr1->type == VR_RANGE
8927 && range_includes_zero_p (vr1->min, vr1->max) == 0)
8928 || (vr1->type == VR_ANTI_RANGE
8929 && range_includes_zero_p (vr1->min, vr1->max) == 1)))
8931 set_value_range_to_nonnull (vr0, TREE_TYPE (saved.min));
8933 /* Since this meet operation did not result from the meeting of
8934 two equivalent names, VR0 cannot have any equivalences. */
8935 if (vr0->equiv)
8936 bitmap_clear (vr0->equiv);
8937 return;
8940 set_value_range_to_varying (vr0);
8941 return;
8943 set_and_canonicalize_value_range (vr0, vr0->type, vr0->min, vr0->max,
8944 vr0->equiv);
8945 if (vr0->type == VR_VARYING)
8946 return;
8948 /* The resulting set of equivalences is always the intersection of
8949 the two sets. */
8950 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
8951 bitmap_and_into (vr0->equiv, vr1->equiv);
8952 else if (vr0->equiv && !vr1->equiv)
8953 bitmap_clear (vr0->equiv);
8956 void
8957 vrp_meet (value_range *vr0, const value_range *vr1)
8959 if (dump_file && (dump_flags & TDF_DETAILS))
8961 fprintf (dump_file, "Meeting\n ");
8962 dump_value_range (dump_file, vr0);
8963 fprintf (dump_file, "\nand\n ");
8964 dump_value_range (dump_file, vr1);
8965 fprintf (dump_file, "\n");
8967 vrp_meet_1 (vr0, vr1);
8968 if (dump_file && (dump_flags & TDF_DETAILS))
8970 fprintf (dump_file, "to\n ");
8971 dump_value_range (dump_file, vr0);
8972 fprintf (dump_file, "\n");
8977 /* Visit all arguments for PHI node PHI that flow through executable
8978 edges. If a valid value range can be derived from all the incoming
8979 value ranges, set a new range in VR_RESULT. */
8981 static void
8982 extract_range_from_phi_node (gphi *phi, value_range *vr_result)
8984 size_t i;
8985 tree lhs = PHI_RESULT (phi);
8986 value_range *lhs_vr = get_value_range (lhs);
8987 bool first = true;
8988 int edges, old_edges;
8989 struct loop *l;
8991 if (dump_file && (dump_flags & TDF_DETAILS))
8993 fprintf (dump_file, "\nVisiting PHI node: ");
8994 print_gimple_stmt (dump_file, phi, 0, dump_flags);
8997 bool may_simulate_backedge_again = false;
8998 edges = 0;
8999 for (i = 0; i < gimple_phi_num_args (phi); i++)
9001 edge e = gimple_phi_arg_edge (phi, i);
9003 if (dump_file && (dump_flags & TDF_DETAILS))
9005 fprintf (dump_file,
9006 " Argument #%d (%d -> %d %sexecutable)\n",
9007 (int) i, e->src->index, e->dest->index,
9008 (e->flags & EDGE_EXECUTABLE) ? "" : "not ");
9011 if (e->flags & EDGE_EXECUTABLE)
9013 tree arg = PHI_ARG_DEF (phi, i);
9014 value_range vr_arg;
9016 ++edges;
9018 if (TREE_CODE (arg) == SSA_NAME)
9020 /* See if we are eventually going to change one of the args. */
9021 gimple *def_stmt = SSA_NAME_DEF_STMT (arg);
9022 if (! gimple_nop_p (def_stmt)
9023 && prop_simulate_again_p (def_stmt)
9024 && e->flags & EDGE_DFS_BACK)
9025 may_simulate_backedge_again = true;
9027 vr_arg = *(get_value_range (arg));
9028 /* Do not allow equivalences or symbolic ranges to leak in from
9029 backedges. That creates invalid equivalencies.
9030 See PR53465 and PR54767. */
9031 if (e->flags & EDGE_DFS_BACK)
9033 if (vr_arg.type == VR_RANGE
9034 || vr_arg.type == VR_ANTI_RANGE)
9036 vr_arg.equiv = NULL;
9037 if (symbolic_range_p (&vr_arg))
9039 vr_arg.type = VR_VARYING;
9040 vr_arg.min = NULL_TREE;
9041 vr_arg.max = NULL_TREE;
9045 else
9047 /* If the non-backedge arguments range is VR_VARYING then
9048 we can still try recording a simple equivalence. */
9049 if (vr_arg.type == VR_VARYING)
9051 vr_arg.type = VR_RANGE;
9052 vr_arg.min = arg;
9053 vr_arg.max = arg;
9054 vr_arg.equiv = NULL;
9058 else
9060 if (TREE_OVERFLOW_P (arg))
9061 arg = drop_tree_overflow (arg);
9063 vr_arg.type = VR_RANGE;
9064 vr_arg.min = arg;
9065 vr_arg.max = arg;
9066 vr_arg.equiv = NULL;
9069 if (dump_file && (dump_flags & TDF_DETAILS))
9071 fprintf (dump_file, "\t");
9072 print_generic_expr (dump_file, arg, dump_flags);
9073 fprintf (dump_file, ": ");
9074 dump_value_range (dump_file, &vr_arg);
9075 fprintf (dump_file, "\n");
9078 if (first)
9079 copy_value_range (vr_result, &vr_arg);
9080 else
9081 vrp_meet (vr_result, &vr_arg);
9082 first = false;
9084 if (vr_result->type == VR_VARYING)
9085 break;
9089 if (vr_result->type == VR_VARYING)
9090 goto varying;
9091 else if (vr_result->type == VR_UNDEFINED)
9092 goto update_range;
9094 old_edges = vr_phi_edge_counts[SSA_NAME_VERSION (lhs)];
9095 vr_phi_edge_counts[SSA_NAME_VERSION (lhs)] = edges;
9097 /* To prevent infinite iterations in the algorithm, derive ranges
9098 when the new value is slightly bigger or smaller than the
9099 previous one. We don't do this if we have seen a new executable
9100 edge; this helps us avoid an infinity for conditionals
9101 which are not in a loop. If the old value-range was VR_UNDEFINED
9102 use the updated range and iterate one more time. If we will not
9103 simulate this PHI again via the backedge allow us to iterate. */
9104 if (edges > 0
9105 && gimple_phi_num_args (phi) > 1
9106 && edges == old_edges
9107 && lhs_vr->type != VR_UNDEFINED
9108 && may_simulate_backedge_again)
9110 /* Compare old and new ranges, fall back to varying if the
9111 values are not comparable. */
9112 int cmp_min = compare_values (lhs_vr->min, vr_result->min);
9113 if (cmp_min == -2)
9114 goto varying;
9115 int cmp_max = compare_values (lhs_vr->max, vr_result->max);
9116 if (cmp_max == -2)
9117 goto varying;
9119 /* For non VR_RANGE or for pointers fall back to varying if
9120 the range changed. */
9121 if ((lhs_vr->type != VR_RANGE || vr_result->type != VR_RANGE
9122 || POINTER_TYPE_P (TREE_TYPE (lhs)))
9123 && (cmp_min != 0 || cmp_max != 0))
9124 goto varying;
9126 /* If the new minimum is larger than the previous one
9127 retain the old value. If the new minimum value is smaller
9128 than the previous one and not -INF go all the way to -INF + 1.
9129 In the first case, to avoid infinite bouncing between different
9130 minimums, and in the other case to avoid iterating millions of
9131 times to reach -INF. Going to -INF + 1 also lets the following
9132 iteration compute whether there will be any overflow, at the
9133 expense of one additional iteration. */
9134 if (cmp_min < 0)
9135 vr_result->min = lhs_vr->min;
9136 else if (cmp_min > 0
9137 && !vrp_val_is_min (vr_result->min))
9138 vr_result->min
9139 = int_const_binop (PLUS_EXPR,
9140 vrp_val_min (TREE_TYPE (vr_result->min)),
9141 build_int_cst (TREE_TYPE (vr_result->min), 1));
9143 /* Similarly for the maximum value. */
9144 if (cmp_max > 0)
9145 vr_result->max = lhs_vr->max;
9146 else if (cmp_max < 0
9147 && !vrp_val_is_max (vr_result->max))
9148 vr_result->max
9149 = int_const_binop (MINUS_EXPR,
9150 vrp_val_max (TREE_TYPE (vr_result->min)),
9151 build_int_cst (TREE_TYPE (vr_result->min), 1));
9153 /* If we dropped either bound to +-INF then if this is a loop
9154 PHI node SCEV may known more about its value-range. */
9155 if (cmp_min > 0 || cmp_min < 0
9156 || cmp_max < 0 || cmp_max > 0)
9157 goto scev_check;
9159 goto infinite_check;
9162 goto update_range;
9164 varying:
9165 set_value_range_to_varying (vr_result);
9167 scev_check:
9168 /* If this is a loop PHI node SCEV may known more about its value-range.
9169 scev_check can be reached from two paths, one is a fall through from above
9170 "varying" label, the other is direct goto from code block which tries to
9171 avoid infinite simulation. */
9172 if ((l = loop_containing_stmt (phi))
9173 && l->header == gimple_bb (phi))
9174 adjust_range_with_scev (vr_result, l, phi, lhs);
9176 infinite_check:
9177 /* If we will end up with a (-INF, +INF) range, set it to
9178 VARYING. Same if the previous max value was invalid for
9179 the type and we end up with vr_result.min > vr_result.max. */
9180 if ((vr_result->type == VR_RANGE || vr_result->type == VR_ANTI_RANGE)
9181 && !((vrp_val_is_max (vr_result->max) && vrp_val_is_min (vr_result->min))
9182 || compare_values (vr_result->min, vr_result->max) > 0))
9184 else
9185 set_value_range_to_varying (vr_result);
9187 /* If the new range is different than the previous value, keep
9188 iterating. */
9189 update_range:
9190 return;
9193 /* Visit all arguments for PHI node PHI that flow through executable
9194 edges. If a valid value range can be derived from all the incoming
9195 value ranges, set a new range for the LHS of PHI. */
9197 enum ssa_prop_result
9198 vrp_prop::visit_phi (gphi *phi)
9200 tree lhs = PHI_RESULT (phi);
9201 value_range vr_result = VR_INITIALIZER;
9202 extract_range_from_phi_node (phi, &vr_result);
9203 if (update_value_range (lhs, &vr_result))
9205 if (dump_file && (dump_flags & TDF_DETAILS))
9207 fprintf (dump_file, "Found new range for ");
9208 print_generic_expr (dump_file, lhs);
9209 fprintf (dump_file, ": ");
9210 dump_value_range (dump_file, &vr_result);
9211 fprintf (dump_file, "\n");
9214 if (vr_result.type == VR_VARYING)
9215 return SSA_PROP_VARYING;
9217 return SSA_PROP_INTERESTING;
9220 /* Nothing changed, don't add outgoing edges. */
9221 return SSA_PROP_NOT_INTERESTING;
9224 /* Simplify boolean operations if the source is known
9225 to be already a boolean. */
9226 static bool
9227 simplify_truth_ops_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9229 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
9230 tree lhs, op0, op1;
9231 bool need_conversion;
9233 /* We handle only !=/== case here. */
9234 gcc_assert (rhs_code == EQ_EXPR || rhs_code == NE_EXPR);
9236 op0 = gimple_assign_rhs1 (stmt);
9237 if (!op_with_boolean_value_range_p (op0))
9238 return false;
9240 op1 = gimple_assign_rhs2 (stmt);
9241 if (!op_with_boolean_value_range_p (op1))
9242 return false;
9244 /* Reduce number of cases to handle to NE_EXPR. As there is no
9245 BIT_XNOR_EXPR we cannot replace A == B with a single statement. */
9246 if (rhs_code == EQ_EXPR)
9248 if (TREE_CODE (op1) == INTEGER_CST)
9249 op1 = int_const_binop (BIT_XOR_EXPR, op1,
9250 build_int_cst (TREE_TYPE (op1), 1));
9251 else
9252 return false;
9255 lhs = gimple_assign_lhs (stmt);
9256 need_conversion
9257 = !useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (op0));
9259 /* Make sure to not sign-extend a 1-bit 1 when converting the result. */
9260 if (need_conversion
9261 && !TYPE_UNSIGNED (TREE_TYPE (op0))
9262 && TYPE_PRECISION (TREE_TYPE (op0)) == 1
9263 && TYPE_PRECISION (TREE_TYPE (lhs)) > 1)
9264 return false;
9266 /* For A != 0 we can substitute A itself. */
9267 if (integer_zerop (op1))
9268 gimple_assign_set_rhs_with_ops (gsi,
9269 need_conversion
9270 ? NOP_EXPR : TREE_CODE (op0), op0);
9271 /* For A != B we substitute A ^ B. Either with conversion. */
9272 else if (need_conversion)
9274 tree tem = make_ssa_name (TREE_TYPE (op0));
9275 gassign *newop
9276 = gimple_build_assign (tem, BIT_XOR_EXPR, op0, op1);
9277 gsi_insert_before (gsi, newop, GSI_SAME_STMT);
9278 if (INTEGRAL_TYPE_P (TREE_TYPE (tem))
9279 && TYPE_PRECISION (TREE_TYPE (tem)) > 1)
9280 set_range_info (tem, VR_RANGE,
9281 wi::zero (TYPE_PRECISION (TREE_TYPE (tem))),
9282 wi::one (TYPE_PRECISION (TREE_TYPE (tem))));
9283 gimple_assign_set_rhs_with_ops (gsi, NOP_EXPR, tem);
9285 /* Or without. */
9286 else
9287 gimple_assign_set_rhs_with_ops (gsi, BIT_XOR_EXPR, op0, op1);
9288 update_stmt (gsi_stmt (*gsi));
9289 fold_stmt (gsi, follow_single_use_edges);
9291 return true;
9294 /* Simplify a division or modulo operator to a right shift or bitwise and
9295 if the first operand is unsigned or is greater than zero and the second
9296 operand is an exact power of two. For TRUNC_MOD_EXPR op0 % op1 with
9297 constant op1 (op1min = op1) or with op1 in [op1min, op1max] range,
9298 optimize it into just op0 if op0's range is known to be a subset of
9299 [-op1min + 1, op1min - 1] for signed and [0, op1min - 1] for unsigned
9300 modulo. */
9302 static bool
9303 simplify_div_or_mod_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9305 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
9306 tree val = NULL;
9307 tree op0 = gimple_assign_rhs1 (stmt);
9308 tree op1 = gimple_assign_rhs2 (stmt);
9309 tree op0min = NULL_TREE, op0max = NULL_TREE;
9310 tree op1min = op1;
9311 value_range *vr = NULL;
9313 if (TREE_CODE (op0) == INTEGER_CST)
9315 op0min = op0;
9316 op0max = op0;
9318 else
9320 vr = get_value_range (op0);
9321 if (range_int_cst_p (vr))
9323 op0min = vr->min;
9324 op0max = vr->max;
9328 if (rhs_code == TRUNC_MOD_EXPR
9329 && TREE_CODE (op1) == SSA_NAME)
9331 value_range *vr1 = get_value_range (op1);
9332 if (range_int_cst_p (vr1))
9333 op1min = vr1->min;
9335 if (rhs_code == TRUNC_MOD_EXPR
9336 && TREE_CODE (op1min) == INTEGER_CST
9337 && tree_int_cst_sgn (op1min) == 1
9338 && op0max
9339 && tree_int_cst_lt (op0max, op1min))
9341 if (TYPE_UNSIGNED (TREE_TYPE (op0))
9342 || tree_int_cst_sgn (op0min) >= 0
9343 || tree_int_cst_lt (fold_unary (NEGATE_EXPR, TREE_TYPE (op1min), op1min),
9344 op0min))
9346 /* If op0 already has the range op0 % op1 has,
9347 then TRUNC_MOD_EXPR won't change anything. */
9348 gimple_assign_set_rhs_from_tree (gsi, op0);
9349 return true;
9353 if (TREE_CODE (op0) != SSA_NAME)
9354 return false;
9356 if (!integer_pow2p (op1))
9358 /* X % -Y can be only optimized into X % Y either if
9359 X is not INT_MIN, or Y is not -1. Fold it now, as after
9360 remove_range_assertions the range info might be not available
9361 anymore. */
9362 if (rhs_code == TRUNC_MOD_EXPR
9363 && fold_stmt (gsi, follow_single_use_edges))
9364 return true;
9365 return false;
9368 if (TYPE_UNSIGNED (TREE_TYPE (op0)))
9369 val = integer_one_node;
9370 else
9372 bool sop = false;
9374 val = compare_range_with_value (GE_EXPR, vr, integer_zero_node, &sop);
9376 if (val
9377 && sop
9378 && integer_onep (val)
9379 && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
9381 location_t location;
9383 if (!gimple_has_location (stmt))
9384 location = input_location;
9385 else
9386 location = gimple_location (stmt);
9387 warning_at (location, OPT_Wstrict_overflow,
9388 "assuming signed overflow does not occur when "
9389 "simplifying %</%> or %<%%%> to %<>>%> or %<&%>");
9393 if (val && integer_onep (val))
9395 tree t;
9397 if (rhs_code == TRUNC_DIV_EXPR)
9399 t = build_int_cst (integer_type_node, tree_log2 (op1));
9400 gimple_assign_set_rhs_code (stmt, RSHIFT_EXPR);
9401 gimple_assign_set_rhs1 (stmt, op0);
9402 gimple_assign_set_rhs2 (stmt, t);
9404 else
9406 t = build_int_cst (TREE_TYPE (op1), 1);
9407 t = int_const_binop (MINUS_EXPR, op1, t);
9408 t = fold_convert (TREE_TYPE (op0), t);
9410 gimple_assign_set_rhs_code (stmt, BIT_AND_EXPR);
9411 gimple_assign_set_rhs1 (stmt, op0);
9412 gimple_assign_set_rhs2 (stmt, t);
9415 update_stmt (stmt);
9416 fold_stmt (gsi, follow_single_use_edges);
9417 return true;
9420 return false;
9423 /* Simplify a min or max if the ranges of the two operands are
9424 disjoint. Return true if we do simplify. */
9426 static bool
9427 simplify_min_or_max_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9429 tree op0 = gimple_assign_rhs1 (stmt);
9430 tree op1 = gimple_assign_rhs2 (stmt);
9431 bool sop = false;
9432 tree val;
9434 val = (vrp_evaluate_conditional_warnv_with_ops_using_ranges
9435 (LE_EXPR, op0, op1, &sop));
9436 if (!val)
9438 sop = false;
9439 val = (vrp_evaluate_conditional_warnv_with_ops_using_ranges
9440 (LT_EXPR, op0, op1, &sop));
9443 if (val)
9445 if (sop && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
9447 location_t location;
9449 if (!gimple_has_location (stmt))
9450 location = input_location;
9451 else
9452 location = gimple_location (stmt);
9453 warning_at (location, OPT_Wstrict_overflow,
9454 "assuming signed overflow does not occur when "
9455 "simplifying %<min/max (X,Y)%> to %<X%> or %<Y%>");
9458 /* VAL == TRUE -> OP0 < or <= op1
9459 VAL == FALSE -> OP0 > or >= op1. */
9460 tree res = ((gimple_assign_rhs_code (stmt) == MAX_EXPR)
9461 == integer_zerop (val)) ? op0 : op1;
9462 gimple_assign_set_rhs_from_tree (gsi, res);
9463 return true;
9466 return false;
9469 /* If the operand to an ABS_EXPR is >= 0, then eliminate the
9470 ABS_EXPR. If the operand is <= 0, then simplify the
9471 ABS_EXPR into a NEGATE_EXPR. */
9473 static bool
9474 simplify_abs_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9476 tree op = gimple_assign_rhs1 (stmt);
9477 value_range *vr = get_value_range (op);
9479 if (vr)
9481 tree val = NULL;
9482 bool sop = false;
9484 val = compare_range_with_value (LE_EXPR, vr, integer_zero_node, &sop);
9485 if (!val)
9487 /* The range is neither <= 0 nor > 0. Now see if it is
9488 either < 0 or >= 0. */
9489 sop = false;
9490 val = compare_range_with_value (LT_EXPR, vr, integer_zero_node,
9491 &sop);
9494 if (val)
9496 if (sop && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
9498 location_t location;
9500 if (!gimple_has_location (stmt))
9501 location = input_location;
9502 else
9503 location = gimple_location (stmt);
9504 warning_at (location, OPT_Wstrict_overflow,
9505 "assuming signed overflow does not occur when "
9506 "simplifying %<abs (X)%> to %<X%> or %<-X%>");
9509 gimple_assign_set_rhs1 (stmt, op);
9510 if (integer_zerop (val))
9511 gimple_assign_set_rhs_code (stmt, SSA_NAME);
9512 else
9513 gimple_assign_set_rhs_code (stmt, NEGATE_EXPR);
9514 update_stmt (stmt);
9515 fold_stmt (gsi, follow_single_use_edges);
9516 return true;
9520 return false;
9523 /* Optimize away redundant BIT_AND_EXPR and BIT_IOR_EXPR.
9524 If all the bits that are being cleared by & are already
9525 known to be zero from VR, or all the bits that are being
9526 set by | are already known to be one from VR, the bit
9527 operation is redundant. */
9529 static bool
9530 simplify_bit_ops_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9532 tree op0 = gimple_assign_rhs1 (stmt);
9533 tree op1 = gimple_assign_rhs2 (stmt);
9534 tree op = NULL_TREE;
9535 value_range vr0 = VR_INITIALIZER;
9536 value_range vr1 = VR_INITIALIZER;
9537 wide_int may_be_nonzero0, may_be_nonzero1;
9538 wide_int must_be_nonzero0, must_be_nonzero1;
9539 wide_int mask;
9541 if (TREE_CODE (op0) == SSA_NAME)
9542 vr0 = *(get_value_range (op0));
9543 else if (is_gimple_min_invariant (op0))
9544 set_value_range_to_value (&vr0, op0, NULL);
9545 else
9546 return false;
9548 if (TREE_CODE (op1) == SSA_NAME)
9549 vr1 = *(get_value_range (op1));
9550 else if (is_gimple_min_invariant (op1))
9551 set_value_range_to_value (&vr1, op1, NULL);
9552 else
9553 return false;
9555 if (!zero_nonzero_bits_from_vr (TREE_TYPE (op0), &vr0, &may_be_nonzero0,
9556 &must_be_nonzero0))
9557 return false;
9558 if (!zero_nonzero_bits_from_vr (TREE_TYPE (op1), &vr1, &may_be_nonzero1,
9559 &must_be_nonzero1))
9560 return false;
9562 switch (gimple_assign_rhs_code (stmt))
9564 case BIT_AND_EXPR:
9565 mask = wi::bit_and_not (may_be_nonzero0, must_be_nonzero1);
9566 if (mask == 0)
9568 op = op0;
9569 break;
9571 mask = wi::bit_and_not (may_be_nonzero1, must_be_nonzero0);
9572 if (mask == 0)
9574 op = op1;
9575 break;
9577 break;
9578 case BIT_IOR_EXPR:
9579 mask = wi::bit_and_not (may_be_nonzero0, must_be_nonzero1);
9580 if (mask == 0)
9582 op = op1;
9583 break;
9585 mask = wi::bit_and_not (may_be_nonzero1, must_be_nonzero0);
9586 if (mask == 0)
9588 op = op0;
9589 break;
9591 break;
9592 default:
9593 gcc_unreachable ();
9596 if (op == NULL_TREE)
9597 return false;
9599 gimple_assign_set_rhs_with_ops (gsi, TREE_CODE (op), op);
9600 update_stmt (gsi_stmt (*gsi));
9601 return true;
9604 /* We are comparing trees OP0 and OP1 using COND_CODE. OP0 has
9605 a known value range VR.
9607 If there is one and only one value which will satisfy the
9608 conditional, then return that value. Else return NULL.
9610 If signed overflow must be undefined for the value to satisfy
9611 the conditional, then set *STRICT_OVERFLOW_P to true. */
9613 static tree
9614 test_for_singularity (enum tree_code cond_code, tree op0,
9615 tree op1, value_range *vr)
9617 tree min = NULL;
9618 tree max = NULL;
9620 /* Extract minimum/maximum values which satisfy the conditional as it was
9621 written. */
9622 if (cond_code == LE_EXPR || cond_code == LT_EXPR)
9624 min = TYPE_MIN_VALUE (TREE_TYPE (op0));
9626 max = op1;
9627 if (cond_code == LT_EXPR)
9629 tree one = build_int_cst (TREE_TYPE (op0), 1);
9630 max = fold_build2 (MINUS_EXPR, TREE_TYPE (op0), max, one);
9631 /* Signal to compare_values_warnv this expr doesn't overflow. */
9632 if (EXPR_P (max))
9633 TREE_NO_WARNING (max) = 1;
9636 else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
9638 max = TYPE_MAX_VALUE (TREE_TYPE (op0));
9640 min = op1;
9641 if (cond_code == GT_EXPR)
9643 tree one = build_int_cst (TREE_TYPE (op0), 1);
9644 min = fold_build2 (PLUS_EXPR, TREE_TYPE (op0), min, one);
9645 /* Signal to compare_values_warnv this expr doesn't overflow. */
9646 if (EXPR_P (min))
9647 TREE_NO_WARNING (min) = 1;
9651 /* Now refine the minimum and maximum values using any
9652 value range information we have for op0. */
9653 if (min && max)
9655 if (compare_values (vr->min, min) == 1)
9656 min = vr->min;
9657 if (compare_values (vr->max, max) == -1)
9658 max = vr->max;
9660 /* If the new min/max values have converged to a single value,
9661 then there is only one value which can satisfy the condition,
9662 return that value. */
9663 if (operand_equal_p (min, max, 0) && is_gimple_min_invariant (min))
9664 return min;
9666 return NULL;
9669 /* Return whether the value range *VR fits in an integer type specified
9670 by PRECISION and UNSIGNED_P. */
9672 static bool
9673 range_fits_type_p (value_range *vr, unsigned dest_precision, signop dest_sgn)
9675 tree src_type;
9676 unsigned src_precision;
9677 widest_int tem;
9678 signop src_sgn;
9680 /* We can only handle integral and pointer types. */
9681 src_type = TREE_TYPE (vr->min);
9682 if (!INTEGRAL_TYPE_P (src_type)
9683 && !POINTER_TYPE_P (src_type))
9684 return false;
9686 /* An extension is fine unless VR is SIGNED and dest_sgn is UNSIGNED,
9687 and so is an identity transform. */
9688 src_precision = TYPE_PRECISION (TREE_TYPE (vr->min));
9689 src_sgn = TYPE_SIGN (src_type);
9690 if ((src_precision < dest_precision
9691 && !(dest_sgn == UNSIGNED && src_sgn == SIGNED))
9692 || (src_precision == dest_precision && src_sgn == dest_sgn))
9693 return true;
9695 /* Now we can only handle ranges with constant bounds. */
9696 if (vr->type != VR_RANGE
9697 || TREE_CODE (vr->min) != INTEGER_CST
9698 || TREE_CODE (vr->max) != INTEGER_CST)
9699 return false;
9701 /* For sign changes, the MSB of the wide_int has to be clear.
9702 An unsigned value with its MSB set cannot be represented by
9703 a signed wide_int, while a negative value cannot be represented
9704 by an unsigned wide_int. */
9705 if (src_sgn != dest_sgn
9706 && (wi::lts_p (wi::to_wide (vr->min), 0)
9707 || wi::lts_p (wi::to_wide (vr->max), 0)))
9708 return false;
9710 /* Then we can perform the conversion on both ends and compare
9711 the result for equality. */
9712 tem = wi::ext (wi::to_widest (vr->min), dest_precision, dest_sgn);
9713 if (tem != wi::to_widest (vr->min))
9714 return false;
9715 tem = wi::ext (wi::to_widest (vr->max), dest_precision, dest_sgn);
9716 if (tem != wi::to_widest (vr->max))
9717 return false;
9719 return true;
9722 /* Simplify a conditional using a relational operator to an equality
9723 test if the range information indicates only one value can satisfy
9724 the original conditional. */
9726 static bool
9727 simplify_cond_using_ranges_1 (gcond *stmt)
9729 tree op0 = gimple_cond_lhs (stmt);
9730 tree op1 = gimple_cond_rhs (stmt);
9731 enum tree_code cond_code = gimple_cond_code (stmt);
9733 if (cond_code != NE_EXPR
9734 && cond_code != EQ_EXPR
9735 && TREE_CODE (op0) == SSA_NAME
9736 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
9737 && is_gimple_min_invariant (op1))
9739 value_range *vr = get_value_range (op0);
9741 /* If we have range information for OP0, then we might be
9742 able to simplify this conditional. */
9743 if (vr->type == VR_RANGE)
9745 tree new_tree = test_for_singularity (cond_code, op0, op1, vr);
9746 if (new_tree)
9748 if (dump_file)
9750 fprintf (dump_file, "Simplified relational ");
9751 print_gimple_stmt (dump_file, stmt, 0);
9752 fprintf (dump_file, " into ");
9755 gimple_cond_set_code (stmt, EQ_EXPR);
9756 gimple_cond_set_lhs (stmt, op0);
9757 gimple_cond_set_rhs (stmt, new_tree);
9759 update_stmt (stmt);
9761 if (dump_file)
9763 print_gimple_stmt (dump_file, stmt, 0);
9764 fprintf (dump_file, "\n");
9767 return true;
9770 /* Try again after inverting the condition. We only deal
9771 with integral types here, so no need to worry about
9772 issues with inverting FP comparisons. */
9773 new_tree = test_for_singularity
9774 (invert_tree_comparison (cond_code, false),
9775 op0, op1, vr);
9776 if (new_tree)
9778 if (dump_file)
9780 fprintf (dump_file, "Simplified relational ");
9781 print_gimple_stmt (dump_file, stmt, 0);
9782 fprintf (dump_file, " into ");
9785 gimple_cond_set_code (stmt, NE_EXPR);
9786 gimple_cond_set_lhs (stmt, op0);
9787 gimple_cond_set_rhs (stmt, new_tree);
9789 update_stmt (stmt);
9791 if (dump_file)
9793 print_gimple_stmt (dump_file, stmt, 0);
9794 fprintf (dump_file, "\n");
9797 return true;
9801 return false;
9804 /* STMT is a conditional at the end of a basic block.
9806 If the conditional is of the form SSA_NAME op constant and the SSA_NAME
9807 was set via a type conversion, try to replace the SSA_NAME with the RHS
9808 of the type conversion. Doing so makes the conversion dead which helps
9809 subsequent passes. */
9811 static void
9812 simplify_cond_using_ranges_2 (gcond *stmt)
9814 tree op0 = gimple_cond_lhs (stmt);
9815 tree op1 = gimple_cond_rhs (stmt);
9817 /* If we have a comparison of an SSA_NAME (OP0) against a constant,
9818 see if OP0 was set by a type conversion where the source of
9819 the conversion is another SSA_NAME with a range that fits
9820 into the range of OP0's type.
9822 If so, the conversion is redundant as the earlier SSA_NAME can be
9823 used for the comparison directly if we just massage the constant in the
9824 comparison. */
9825 if (TREE_CODE (op0) == SSA_NAME
9826 && TREE_CODE (op1) == INTEGER_CST)
9828 gimple *def_stmt = SSA_NAME_DEF_STMT (op0);
9829 tree innerop;
9831 if (!is_gimple_assign (def_stmt)
9832 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)))
9833 return;
9835 innerop = gimple_assign_rhs1 (def_stmt);
9837 if (TREE_CODE (innerop) == SSA_NAME
9838 && !POINTER_TYPE_P (TREE_TYPE (innerop))
9839 && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (innerop)
9840 && desired_pro_or_demotion_p (TREE_TYPE (innerop), TREE_TYPE (op0)))
9842 value_range *vr = get_value_range (innerop);
9844 if (range_int_cst_p (vr)
9845 && range_fits_type_p (vr,
9846 TYPE_PRECISION (TREE_TYPE (op0)),
9847 TYPE_SIGN (TREE_TYPE (op0)))
9848 && int_fits_type_p (op1, TREE_TYPE (innerop)))
9850 tree newconst = fold_convert (TREE_TYPE (innerop), op1);
9851 gimple_cond_set_lhs (stmt, innerop);
9852 gimple_cond_set_rhs (stmt, newconst);
9853 update_stmt (stmt);
9854 if (dump_file && (dump_flags & TDF_DETAILS))
9856 fprintf (dump_file, "Folded into: ");
9857 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
9858 fprintf (dump_file, "\n");
9865 /* Simplify a switch statement using the value range of the switch
9866 argument. */
9868 static bool
9869 simplify_switch_using_ranges (gswitch *stmt)
9871 tree op = gimple_switch_index (stmt);
9872 value_range *vr = NULL;
9873 bool take_default;
9874 edge e;
9875 edge_iterator ei;
9876 size_t i = 0, j = 0, n, n2;
9877 tree vec2;
9878 switch_update su;
9879 size_t k = 1, l = 0;
9881 if (TREE_CODE (op) == SSA_NAME)
9883 vr = get_value_range (op);
9885 /* We can only handle integer ranges. */
9886 if ((vr->type != VR_RANGE
9887 && vr->type != VR_ANTI_RANGE)
9888 || symbolic_range_p (vr))
9889 return false;
9891 /* Find case label for min/max of the value range. */
9892 take_default = !find_case_label_ranges (stmt, vr, &i, &j, &k, &l);
9894 else if (TREE_CODE (op) == INTEGER_CST)
9896 take_default = !find_case_label_index (stmt, 1, op, &i);
9897 if (take_default)
9899 i = 1;
9900 j = 0;
9902 else
9904 j = i;
9907 else
9908 return false;
9910 n = gimple_switch_num_labels (stmt);
9912 /* We can truncate the case label ranges that partially overlap with OP's
9913 value range. */
9914 size_t min_idx = 1, max_idx = 0;
9915 if (vr != NULL)
9916 find_case_label_range (stmt, vr->min, vr->max, &min_idx, &max_idx);
9917 if (min_idx <= max_idx)
9919 tree min_label = gimple_switch_label (stmt, min_idx);
9920 tree max_label = gimple_switch_label (stmt, max_idx);
9922 /* Avoid changing the type of the case labels when truncating. */
9923 tree case_label_type = TREE_TYPE (CASE_LOW (min_label));
9924 tree vr_min = fold_convert (case_label_type, vr->min);
9925 tree vr_max = fold_convert (case_label_type, vr->max);
9927 if (vr->type == VR_RANGE)
9929 /* If OP's value range is [2,8] and the low label range is
9930 0 ... 3, truncate the label's range to 2 .. 3. */
9931 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
9932 && CASE_HIGH (min_label) != NULL_TREE
9933 && tree_int_cst_compare (CASE_HIGH (min_label), vr_min) >= 0)
9934 CASE_LOW (min_label) = vr_min;
9936 /* If OP's value range is [2,8] and the high label range is
9937 7 ... 10, truncate the label's range to 7 .. 8. */
9938 if (tree_int_cst_compare (CASE_LOW (max_label), vr_max) <= 0
9939 && CASE_HIGH (max_label) != NULL_TREE
9940 && tree_int_cst_compare (CASE_HIGH (max_label), vr_max) > 0)
9941 CASE_HIGH (max_label) = vr_max;
9943 else if (vr->type == VR_ANTI_RANGE)
9945 tree one_cst = build_one_cst (case_label_type);
9947 if (min_label == max_label)
9949 /* If OP's value range is ~[7,8] and the label's range is
9950 7 ... 10, truncate the label's range to 9 ... 10. */
9951 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) == 0
9952 && CASE_HIGH (min_label) != NULL_TREE
9953 && tree_int_cst_compare (CASE_HIGH (min_label), vr_max) > 0)
9954 CASE_LOW (min_label)
9955 = int_const_binop (PLUS_EXPR, vr_max, one_cst);
9957 /* If OP's value range is ~[7,8] and the label's range is
9958 5 ... 8, truncate the label's range to 5 ... 6. */
9959 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
9960 && CASE_HIGH (min_label) != NULL_TREE
9961 && tree_int_cst_compare (CASE_HIGH (min_label), vr_max) == 0)
9962 CASE_HIGH (min_label)
9963 = int_const_binop (MINUS_EXPR, vr_min, one_cst);
9965 else
9967 /* If OP's value range is ~[2,8] and the low label range is
9968 0 ... 3, truncate the label's range to 0 ... 1. */
9969 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
9970 && CASE_HIGH (min_label) != NULL_TREE
9971 && tree_int_cst_compare (CASE_HIGH (min_label), vr_min) >= 0)
9972 CASE_HIGH (min_label)
9973 = int_const_binop (MINUS_EXPR, vr_min, one_cst);
9975 /* If OP's value range is ~[2,8] and the high label range is
9976 7 ... 10, truncate the label's range to 9 ... 10. */
9977 if (tree_int_cst_compare (CASE_LOW (max_label), vr_max) <= 0
9978 && CASE_HIGH (max_label) != NULL_TREE
9979 && tree_int_cst_compare (CASE_HIGH (max_label), vr_max) > 0)
9980 CASE_LOW (max_label)
9981 = int_const_binop (PLUS_EXPR, vr_max, one_cst);
9985 /* Canonicalize singleton case ranges. */
9986 if (tree_int_cst_equal (CASE_LOW (min_label), CASE_HIGH (min_label)))
9987 CASE_HIGH (min_label) = NULL_TREE;
9988 if (tree_int_cst_equal (CASE_LOW (max_label), CASE_HIGH (max_label)))
9989 CASE_HIGH (max_label) = NULL_TREE;
9992 /* We can also eliminate case labels that lie completely outside OP's value
9993 range. */
9995 /* Bail out if this is just all edges taken. */
9996 if (i == 1
9997 && j == n - 1
9998 && take_default)
9999 return false;
10001 /* Build a new vector of taken case labels. */
10002 vec2 = make_tree_vec (j - i + 1 + l - k + 1 + (int)take_default);
10003 n2 = 0;
10005 /* Add the default edge, if necessary. */
10006 if (take_default)
10007 TREE_VEC_ELT (vec2, n2++) = gimple_switch_default_label (stmt);
10009 for (; i <= j; ++i, ++n2)
10010 TREE_VEC_ELT (vec2, n2) = gimple_switch_label (stmt, i);
10012 for (; k <= l; ++k, ++n2)
10013 TREE_VEC_ELT (vec2, n2) = gimple_switch_label (stmt, k);
10015 /* Mark needed edges. */
10016 for (i = 0; i < n2; ++i)
10018 e = find_edge (gimple_bb (stmt),
10019 label_to_block (CASE_LABEL (TREE_VEC_ELT (vec2, i))));
10020 e->aux = (void *)-1;
10023 /* Queue not needed edges for later removal. */
10024 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
10026 if (e->aux == (void *)-1)
10028 e->aux = NULL;
10029 continue;
10032 if (dump_file && (dump_flags & TDF_DETAILS))
10034 fprintf (dump_file, "removing unreachable case label\n");
10036 to_remove_edges.safe_push (e);
10037 e->flags &= ~EDGE_EXECUTABLE;
10040 /* And queue an update for the stmt. */
10041 su.stmt = stmt;
10042 su.vec = vec2;
10043 to_update_switch_stmts.safe_push (su);
10044 return false;
10047 /* Simplify an integral conversion from an SSA name in STMT. */
10049 static bool
10050 simplify_conversion_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
10052 tree innerop, middleop, finaltype;
10053 gimple *def_stmt;
10054 signop inner_sgn, middle_sgn, final_sgn;
10055 unsigned inner_prec, middle_prec, final_prec;
10056 widest_int innermin, innermed, innermax, middlemin, middlemed, middlemax;
10058 finaltype = TREE_TYPE (gimple_assign_lhs (stmt));
10059 if (!INTEGRAL_TYPE_P (finaltype))
10060 return false;
10061 middleop = gimple_assign_rhs1 (stmt);
10062 def_stmt = SSA_NAME_DEF_STMT (middleop);
10063 if (!is_gimple_assign (def_stmt)
10064 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)))
10065 return false;
10066 innerop = gimple_assign_rhs1 (def_stmt);
10067 if (TREE_CODE (innerop) != SSA_NAME
10068 || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (innerop))
10069 return false;
10071 /* Get the value-range of the inner operand. Use get_range_info in
10072 case innerop was created during substitute-and-fold. */
10073 wide_int imin, imax;
10074 if (!INTEGRAL_TYPE_P (TREE_TYPE (innerop))
10075 || get_range_info (innerop, &imin, &imax) != VR_RANGE)
10076 return false;
10077 innermin = widest_int::from (imin, TYPE_SIGN (TREE_TYPE (innerop)));
10078 innermax = widest_int::from (imax, TYPE_SIGN (TREE_TYPE (innerop)));
10080 /* Simulate the conversion chain to check if the result is equal if
10081 the middle conversion is removed. */
10082 inner_prec = TYPE_PRECISION (TREE_TYPE (innerop));
10083 middle_prec = TYPE_PRECISION (TREE_TYPE (middleop));
10084 final_prec = TYPE_PRECISION (finaltype);
10086 /* If the first conversion is not injective, the second must not
10087 be widening. */
10088 if (wi::gtu_p (innermax - innermin,
10089 wi::mask <widest_int> (middle_prec, false))
10090 && middle_prec < final_prec)
10091 return false;
10092 /* We also want a medium value so that we can track the effect that
10093 narrowing conversions with sign change have. */
10094 inner_sgn = TYPE_SIGN (TREE_TYPE (innerop));
10095 if (inner_sgn == UNSIGNED)
10096 innermed = wi::shifted_mask <widest_int> (1, inner_prec - 1, false);
10097 else
10098 innermed = 0;
10099 if (wi::cmp (innermin, innermed, inner_sgn) >= 0
10100 || wi::cmp (innermed, innermax, inner_sgn) >= 0)
10101 innermed = innermin;
10103 middle_sgn = TYPE_SIGN (TREE_TYPE (middleop));
10104 middlemin = wi::ext (innermin, middle_prec, middle_sgn);
10105 middlemed = wi::ext (innermed, middle_prec, middle_sgn);
10106 middlemax = wi::ext (innermax, middle_prec, middle_sgn);
10108 /* Require that the final conversion applied to both the original
10109 and the intermediate range produces the same result. */
10110 final_sgn = TYPE_SIGN (finaltype);
10111 if (wi::ext (middlemin, final_prec, final_sgn)
10112 != wi::ext (innermin, final_prec, final_sgn)
10113 || wi::ext (middlemed, final_prec, final_sgn)
10114 != wi::ext (innermed, final_prec, final_sgn)
10115 || wi::ext (middlemax, final_prec, final_sgn)
10116 != wi::ext (innermax, final_prec, final_sgn))
10117 return false;
10119 gimple_assign_set_rhs1 (stmt, innerop);
10120 fold_stmt (gsi, follow_single_use_edges);
10121 return true;
10124 /* Simplify a conversion from integral SSA name to float in STMT. */
10126 static bool
10127 simplify_float_conversion_using_ranges (gimple_stmt_iterator *gsi,
10128 gimple *stmt)
10130 tree rhs1 = gimple_assign_rhs1 (stmt);
10131 value_range *vr = get_value_range (rhs1);
10132 scalar_float_mode fltmode
10133 = SCALAR_FLOAT_TYPE_MODE (TREE_TYPE (gimple_assign_lhs (stmt)));
10134 scalar_int_mode mode;
10135 tree tem;
10136 gassign *conv;
10138 /* We can only handle constant ranges. */
10139 if (vr->type != VR_RANGE
10140 || TREE_CODE (vr->min) != INTEGER_CST
10141 || TREE_CODE (vr->max) != INTEGER_CST)
10142 return false;
10144 /* First check if we can use a signed type in place of an unsigned. */
10145 scalar_int_mode rhs_mode = SCALAR_INT_TYPE_MODE (TREE_TYPE (rhs1));
10146 if (TYPE_UNSIGNED (TREE_TYPE (rhs1))
10147 && can_float_p (fltmode, rhs_mode, 0) != CODE_FOR_nothing
10148 && range_fits_type_p (vr, TYPE_PRECISION (TREE_TYPE (rhs1)), SIGNED))
10149 mode = rhs_mode;
10150 /* If we can do the conversion in the current input mode do nothing. */
10151 else if (can_float_p (fltmode, rhs_mode,
10152 TYPE_UNSIGNED (TREE_TYPE (rhs1))) != CODE_FOR_nothing)
10153 return false;
10154 /* Otherwise search for a mode we can use, starting from the narrowest
10155 integer mode available. */
10156 else
10158 mode = NARROWEST_INT_MODE;
10159 for (;;)
10161 /* If we cannot do a signed conversion to float from mode
10162 or if the value-range does not fit in the signed type
10163 try with a wider mode. */
10164 if (can_float_p (fltmode, mode, 0) != CODE_FOR_nothing
10165 && range_fits_type_p (vr, GET_MODE_PRECISION (mode), SIGNED))
10166 break;
10168 /* But do not widen the input. Instead leave that to the
10169 optabs expansion code. */
10170 if (!GET_MODE_WIDER_MODE (mode).exists (&mode)
10171 || GET_MODE_PRECISION (mode) > TYPE_PRECISION (TREE_TYPE (rhs1)))
10172 return false;
10176 /* It works, insert a truncation or sign-change before the
10177 float conversion. */
10178 tem = make_ssa_name (build_nonstandard_integer_type
10179 (GET_MODE_PRECISION (mode), 0));
10180 conv = gimple_build_assign (tem, NOP_EXPR, rhs1);
10181 gsi_insert_before (gsi, conv, GSI_SAME_STMT);
10182 gimple_assign_set_rhs1 (stmt, tem);
10183 fold_stmt (gsi, follow_single_use_edges);
10185 return true;
10188 /* Simplify an internal fn call using ranges if possible. */
10190 static bool
10191 simplify_internal_call_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
10193 enum tree_code subcode;
10194 bool is_ubsan = false;
10195 bool ovf = false;
10196 switch (gimple_call_internal_fn (stmt))
10198 case IFN_UBSAN_CHECK_ADD:
10199 subcode = PLUS_EXPR;
10200 is_ubsan = true;
10201 break;
10202 case IFN_UBSAN_CHECK_SUB:
10203 subcode = MINUS_EXPR;
10204 is_ubsan = true;
10205 break;
10206 case IFN_UBSAN_CHECK_MUL:
10207 subcode = MULT_EXPR;
10208 is_ubsan = true;
10209 break;
10210 case IFN_ADD_OVERFLOW:
10211 subcode = PLUS_EXPR;
10212 break;
10213 case IFN_SUB_OVERFLOW:
10214 subcode = MINUS_EXPR;
10215 break;
10216 case IFN_MUL_OVERFLOW:
10217 subcode = MULT_EXPR;
10218 break;
10219 default:
10220 return false;
10223 tree op0 = gimple_call_arg (stmt, 0);
10224 tree op1 = gimple_call_arg (stmt, 1);
10225 tree type;
10226 if (is_ubsan)
10228 type = TREE_TYPE (op0);
10229 if (VECTOR_TYPE_P (type))
10230 return false;
10232 else if (gimple_call_lhs (stmt) == NULL_TREE)
10233 return false;
10234 else
10235 type = TREE_TYPE (TREE_TYPE (gimple_call_lhs (stmt)));
10236 if (!check_for_binary_op_overflow (subcode, type, op0, op1, &ovf)
10237 || (is_ubsan && ovf))
10238 return false;
10240 gimple *g;
10241 location_t loc = gimple_location (stmt);
10242 if (is_ubsan)
10243 g = gimple_build_assign (gimple_call_lhs (stmt), subcode, op0, op1);
10244 else
10246 int prec = TYPE_PRECISION (type);
10247 tree utype = type;
10248 if (ovf
10249 || !useless_type_conversion_p (type, TREE_TYPE (op0))
10250 || !useless_type_conversion_p (type, TREE_TYPE (op1)))
10251 utype = build_nonstandard_integer_type (prec, 1);
10252 if (TREE_CODE (op0) == INTEGER_CST)
10253 op0 = fold_convert (utype, op0);
10254 else if (!useless_type_conversion_p (utype, TREE_TYPE (op0)))
10256 g = gimple_build_assign (make_ssa_name (utype), NOP_EXPR, op0);
10257 gimple_set_location (g, loc);
10258 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10259 op0 = gimple_assign_lhs (g);
10261 if (TREE_CODE (op1) == INTEGER_CST)
10262 op1 = fold_convert (utype, op1);
10263 else if (!useless_type_conversion_p (utype, TREE_TYPE (op1)))
10265 g = gimple_build_assign (make_ssa_name (utype), NOP_EXPR, op1);
10266 gimple_set_location (g, loc);
10267 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10268 op1 = gimple_assign_lhs (g);
10270 g = gimple_build_assign (make_ssa_name (utype), subcode, op0, op1);
10271 gimple_set_location (g, loc);
10272 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10273 if (utype != type)
10275 g = gimple_build_assign (make_ssa_name (type), NOP_EXPR,
10276 gimple_assign_lhs (g));
10277 gimple_set_location (g, loc);
10278 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10280 g = gimple_build_assign (gimple_call_lhs (stmt), COMPLEX_EXPR,
10281 gimple_assign_lhs (g),
10282 build_int_cst (type, ovf));
10284 gimple_set_location (g, loc);
10285 gsi_replace (gsi, g, false);
10286 return true;
10289 /* Return true if VAR is a two-valued variable. Set a and b with the
10290 two-values when it is true. Return false otherwise. */
10292 static bool
10293 two_valued_val_range_p (tree var, tree *a, tree *b)
10295 value_range *vr = get_value_range (var);
10296 if ((vr->type != VR_RANGE
10297 && vr->type != VR_ANTI_RANGE)
10298 || TREE_CODE (vr->min) != INTEGER_CST
10299 || TREE_CODE (vr->max) != INTEGER_CST)
10300 return false;
10302 if (vr->type == VR_RANGE
10303 && wi::to_wide (vr->max) - wi::to_wide (vr->min) == 1)
10305 *a = vr->min;
10306 *b = vr->max;
10307 return true;
10310 /* ~[TYPE_MIN + 1, TYPE_MAX - 1] */
10311 if (vr->type == VR_ANTI_RANGE
10312 && (wi::to_wide (vr->min)
10313 - wi::to_wide (vrp_val_min (TREE_TYPE (var)))) == 1
10314 && (wi::to_wide (vrp_val_max (TREE_TYPE (var)))
10315 - wi::to_wide (vr->max)) == 1)
10317 *a = vrp_val_min (TREE_TYPE (var));
10318 *b = vrp_val_max (TREE_TYPE (var));
10319 return true;
10322 return false;
10325 /* Simplify STMT using ranges if possible. */
10327 static bool
10328 simplify_stmt_using_ranges (gimple_stmt_iterator *gsi)
10330 gimple *stmt = gsi_stmt (*gsi);
10331 if (is_gimple_assign (stmt))
10333 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
10334 tree rhs1 = gimple_assign_rhs1 (stmt);
10335 tree rhs2 = gimple_assign_rhs2 (stmt);
10336 tree lhs = gimple_assign_lhs (stmt);
10337 tree val1 = NULL_TREE, val2 = NULL_TREE;
10338 use_operand_p use_p;
10339 gimple *use_stmt;
10341 /* Convert:
10342 LHS = CST BINOP VAR
10343 Where VAR is two-valued and LHS is used in GIMPLE_COND only
10345 LHS = VAR == VAL1 ? (CST BINOP VAL1) : (CST BINOP VAL2)
10347 Also handles:
10348 LHS = VAR BINOP CST
10349 Where VAR is two-valued and LHS is used in GIMPLE_COND only
10351 LHS = VAR == VAL1 ? (VAL1 BINOP CST) : (VAL2 BINOP CST) */
10353 if (TREE_CODE_CLASS (rhs_code) == tcc_binary
10354 && INTEGRAL_TYPE_P (TREE_TYPE (lhs))
10355 && ((TREE_CODE (rhs1) == INTEGER_CST
10356 && TREE_CODE (rhs2) == SSA_NAME)
10357 || (TREE_CODE (rhs2) == INTEGER_CST
10358 && TREE_CODE (rhs1) == SSA_NAME))
10359 && single_imm_use (lhs, &use_p, &use_stmt)
10360 && gimple_code (use_stmt) == GIMPLE_COND)
10363 tree new_rhs1 = NULL_TREE;
10364 tree new_rhs2 = NULL_TREE;
10365 tree cmp_var = NULL_TREE;
10367 if (TREE_CODE (rhs2) == SSA_NAME
10368 && two_valued_val_range_p (rhs2, &val1, &val2))
10370 /* Optimize RHS1 OP [VAL1, VAL2]. */
10371 new_rhs1 = int_const_binop (rhs_code, rhs1, val1);
10372 new_rhs2 = int_const_binop (rhs_code, rhs1, val2);
10373 cmp_var = rhs2;
10375 else if (TREE_CODE (rhs1) == SSA_NAME
10376 && two_valued_val_range_p (rhs1, &val1, &val2))
10378 /* Optimize [VAL1, VAL2] OP RHS2. */
10379 new_rhs1 = int_const_binop (rhs_code, val1, rhs2);
10380 new_rhs2 = int_const_binop (rhs_code, val2, rhs2);
10381 cmp_var = rhs1;
10384 /* If we could not find two-vals or the optimzation is invalid as
10385 in divide by zero, new_rhs1 / new_rhs will be NULL_TREE. */
10386 if (new_rhs1 && new_rhs2)
10388 tree cond = build2 (EQ_EXPR, boolean_type_node, cmp_var, val1);
10389 gimple_assign_set_rhs_with_ops (gsi,
10390 COND_EXPR, cond,
10391 new_rhs1,
10392 new_rhs2);
10393 update_stmt (gsi_stmt (*gsi));
10394 fold_stmt (gsi, follow_single_use_edges);
10395 return true;
10399 switch (rhs_code)
10401 case EQ_EXPR:
10402 case NE_EXPR:
10403 /* Transform EQ_EXPR, NE_EXPR into BIT_XOR_EXPR or identity
10404 if the RHS is zero or one, and the LHS are known to be boolean
10405 values. */
10406 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10407 return simplify_truth_ops_using_ranges (gsi, stmt);
10408 break;
10410 /* Transform TRUNC_DIV_EXPR and TRUNC_MOD_EXPR into RSHIFT_EXPR
10411 and BIT_AND_EXPR respectively if the first operand is greater
10412 than zero and the second operand is an exact power of two.
10413 Also optimize TRUNC_MOD_EXPR away if the second operand is
10414 constant and the first operand already has the right value
10415 range. */
10416 case TRUNC_DIV_EXPR:
10417 case TRUNC_MOD_EXPR:
10418 if ((TREE_CODE (rhs1) == SSA_NAME
10419 || TREE_CODE (rhs1) == INTEGER_CST)
10420 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10421 return simplify_div_or_mod_using_ranges (gsi, stmt);
10422 break;
10424 /* Transform ABS (X) into X or -X as appropriate. */
10425 case ABS_EXPR:
10426 if (TREE_CODE (rhs1) == SSA_NAME
10427 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10428 return simplify_abs_using_ranges (gsi, stmt);
10429 break;
10431 case BIT_AND_EXPR:
10432 case BIT_IOR_EXPR:
10433 /* Optimize away BIT_AND_EXPR and BIT_IOR_EXPR
10434 if all the bits being cleared are already cleared or
10435 all the bits being set are already set. */
10436 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10437 return simplify_bit_ops_using_ranges (gsi, stmt);
10438 break;
10440 CASE_CONVERT:
10441 if (TREE_CODE (rhs1) == SSA_NAME
10442 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10443 return simplify_conversion_using_ranges (gsi, stmt);
10444 break;
10446 case FLOAT_EXPR:
10447 if (TREE_CODE (rhs1) == SSA_NAME
10448 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10449 return simplify_float_conversion_using_ranges (gsi, stmt);
10450 break;
10452 case MIN_EXPR:
10453 case MAX_EXPR:
10454 return simplify_min_or_max_using_ranges (gsi, stmt);
10456 default:
10457 break;
10460 else if (gimple_code (stmt) == GIMPLE_COND)
10461 return simplify_cond_using_ranges_1 (as_a <gcond *> (stmt));
10462 else if (gimple_code (stmt) == GIMPLE_SWITCH)
10463 return simplify_switch_using_ranges (as_a <gswitch *> (stmt));
10464 else if (is_gimple_call (stmt)
10465 && gimple_call_internal_p (stmt))
10466 return simplify_internal_call_using_ranges (gsi, stmt);
10468 return false;
10471 /* If the statement pointed by SI has a predicate whose value can be
10472 computed using the value range information computed by VRP, compute
10473 its value and return true. Otherwise, return false. */
10475 static bool
10476 fold_predicate_in (gimple_stmt_iterator *si)
10478 bool assignment_p = false;
10479 tree val;
10480 gimple *stmt = gsi_stmt (*si);
10482 if (is_gimple_assign (stmt)
10483 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
10485 assignment_p = true;
10486 val = vrp_evaluate_conditional (gimple_assign_rhs_code (stmt),
10487 gimple_assign_rhs1 (stmt),
10488 gimple_assign_rhs2 (stmt),
10489 stmt);
10491 else if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
10492 val = vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
10493 gimple_cond_lhs (cond_stmt),
10494 gimple_cond_rhs (cond_stmt),
10495 stmt);
10496 else
10497 return false;
10499 if (val)
10501 if (assignment_p)
10502 val = fold_convert (gimple_expr_type (stmt), val);
10504 if (dump_file)
10506 fprintf (dump_file, "Folding predicate ");
10507 print_gimple_expr (dump_file, stmt, 0);
10508 fprintf (dump_file, " to ");
10509 print_generic_expr (dump_file, val);
10510 fprintf (dump_file, "\n");
10513 if (is_gimple_assign (stmt))
10514 gimple_assign_set_rhs_from_tree (si, val);
10515 else
10517 gcc_assert (gimple_code (stmt) == GIMPLE_COND);
10518 gcond *cond_stmt = as_a <gcond *> (stmt);
10519 if (integer_zerop (val))
10520 gimple_cond_make_false (cond_stmt);
10521 else if (integer_onep (val))
10522 gimple_cond_make_true (cond_stmt);
10523 else
10524 gcc_unreachable ();
10527 return true;
10530 return false;
10533 class vrp_folder : public substitute_and_fold_engine
10535 public:
10536 tree get_value (tree) FINAL OVERRIDE;
10537 bool fold_stmt (gimple_stmt_iterator *) FINAL OVERRIDE;
10540 /* Callback for substitute_and_fold folding the stmt at *SI. */
10542 bool
10543 vrp_folder::fold_stmt (gimple_stmt_iterator *si)
10545 if (fold_predicate_in (si))
10546 return true;
10548 return simplify_stmt_using_ranges (si);
10551 /* If OP has a value range with a single constant value return that,
10552 otherwise return NULL_TREE. This returns OP itself if OP is a
10553 constant.
10555 Implemented as a pure wrapper right now, but this will change. */
10557 tree
10558 vrp_folder::get_value (tree op)
10560 return op_with_constant_singleton_value_range (op);
10563 /* Return the LHS of any ASSERT_EXPR where OP appears as the first
10564 argument to the ASSERT_EXPR and in which the ASSERT_EXPR dominates
10565 BB. If no such ASSERT_EXPR is found, return OP. */
10567 static tree
10568 lhs_of_dominating_assert (tree op, basic_block bb, gimple *stmt)
10570 imm_use_iterator imm_iter;
10571 gimple *use_stmt;
10572 use_operand_p use_p;
10574 if (TREE_CODE (op) == SSA_NAME)
10576 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, op)
10578 use_stmt = USE_STMT (use_p);
10579 if (use_stmt != stmt
10580 && gimple_assign_single_p (use_stmt)
10581 && TREE_CODE (gimple_assign_rhs1 (use_stmt)) == ASSERT_EXPR
10582 && TREE_OPERAND (gimple_assign_rhs1 (use_stmt), 0) == op
10583 && dominated_by_p (CDI_DOMINATORS, bb, gimple_bb (use_stmt)))
10584 return gimple_assign_lhs (use_stmt);
10587 return op;
10590 /* A trivial wrapper so that we can present the generic jump threading
10591 code with a simple API for simplifying statements. STMT is the
10592 statement we want to simplify, WITHIN_STMT provides the location
10593 for any overflow warnings. */
10595 static tree
10596 simplify_stmt_for_jump_threading (gimple *stmt, gimple *within_stmt,
10597 class avail_exprs_stack *avail_exprs_stack ATTRIBUTE_UNUSED,
10598 basic_block bb)
10600 /* First see if the conditional is in the hash table. */
10601 tree cached_lhs = avail_exprs_stack->lookup_avail_expr (stmt, false, true);
10602 if (cached_lhs && is_gimple_min_invariant (cached_lhs))
10603 return cached_lhs;
10605 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
10607 tree op0 = gimple_cond_lhs (cond_stmt);
10608 op0 = lhs_of_dominating_assert (op0, bb, stmt);
10610 tree op1 = gimple_cond_rhs (cond_stmt);
10611 op1 = lhs_of_dominating_assert (op1, bb, stmt);
10613 return vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
10614 op0, op1, within_stmt);
10617 /* We simplify a switch statement by trying to determine which case label
10618 will be taken. If we are successful then we return the corresponding
10619 CASE_LABEL_EXPR. */
10620 if (gswitch *switch_stmt = dyn_cast <gswitch *> (stmt))
10622 tree op = gimple_switch_index (switch_stmt);
10623 if (TREE_CODE (op) != SSA_NAME)
10624 return NULL_TREE;
10626 op = lhs_of_dominating_assert (op, bb, stmt);
10628 value_range *vr = get_value_range (op);
10629 if ((vr->type != VR_RANGE && vr->type != VR_ANTI_RANGE)
10630 || symbolic_range_p (vr))
10631 return NULL_TREE;
10633 if (vr->type == VR_RANGE)
10635 size_t i, j;
10636 /* Get the range of labels that contain a part of the operand's
10637 value range. */
10638 find_case_label_range (switch_stmt, vr->min, vr->max, &i, &j);
10640 /* Is there only one such label? */
10641 if (i == j)
10643 tree label = gimple_switch_label (switch_stmt, i);
10645 /* The i'th label will be taken only if the value range of the
10646 operand is entirely within the bounds of this label. */
10647 if (CASE_HIGH (label) != NULL_TREE
10648 ? (tree_int_cst_compare (CASE_LOW (label), vr->min) <= 0
10649 && tree_int_cst_compare (CASE_HIGH (label), vr->max) >= 0)
10650 : (tree_int_cst_equal (CASE_LOW (label), vr->min)
10651 && tree_int_cst_equal (vr->min, vr->max)))
10652 return label;
10655 /* If there are no such labels then the default label will be
10656 taken. */
10657 if (i > j)
10658 return gimple_switch_label (switch_stmt, 0);
10661 if (vr->type == VR_ANTI_RANGE)
10663 unsigned n = gimple_switch_num_labels (switch_stmt);
10664 tree min_label = gimple_switch_label (switch_stmt, 1);
10665 tree max_label = gimple_switch_label (switch_stmt, n - 1);
10667 /* The default label will be taken only if the anti-range of the
10668 operand is entirely outside the bounds of all the (non-default)
10669 case labels. */
10670 if (tree_int_cst_compare (vr->min, CASE_LOW (min_label)) <= 0
10671 && (CASE_HIGH (max_label) != NULL_TREE
10672 ? tree_int_cst_compare (vr->max, CASE_HIGH (max_label)) >= 0
10673 : tree_int_cst_compare (vr->max, CASE_LOW (max_label)) >= 0))
10674 return gimple_switch_label (switch_stmt, 0);
10677 return NULL_TREE;
10680 if (gassign *assign_stmt = dyn_cast <gassign *> (stmt))
10682 value_range new_vr = VR_INITIALIZER;
10683 tree lhs = gimple_assign_lhs (assign_stmt);
10685 if (TREE_CODE (lhs) == SSA_NAME
10686 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
10687 || POINTER_TYPE_P (TREE_TYPE (lhs))))
10689 extract_range_from_assignment (&new_vr, assign_stmt);
10690 if (range_int_cst_singleton_p (&new_vr))
10691 return new_vr.min;
10695 return NULL_TREE;
10698 class vrp_dom_walker : public dom_walker
10700 public:
10701 vrp_dom_walker (cdi_direction direction,
10702 class const_and_copies *const_and_copies,
10703 class avail_exprs_stack *avail_exprs_stack)
10704 : dom_walker (direction, true),
10705 m_const_and_copies (const_and_copies),
10706 m_avail_exprs_stack (avail_exprs_stack),
10707 m_dummy_cond (NULL) {}
10709 virtual edge before_dom_children (basic_block);
10710 virtual void after_dom_children (basic_block);
10712 private:
10713 class const_and_copies *m_const_and_copies;
10714 class avail_exprs_stack *m_avail_exprs_stack;
10716 gcond *m_dummy_cond;
10719 /* Called before processing dominator children of BB. We want to look
10720 at ASSERT_EXPRs and record information from them in the appropriate
10721 tables.
10723 We could look at other statements here. It's not seen as likely
10724 to significantly increase the jump threads we discover. */
10726 edge
10727 vrp_dom_walker::before_dom_children (basic_block bb)
10729 gimple_stmt_iterator gsi;
10731 m_avail_exprs_stack->push_marker ();
10732 m_const_and_copies->push_marker ();
10733 for (gsi = gsi_start_nondebug_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
10735 gimple *stmt = gsi_stmt (gsi);
10736 if (gimple_assign_single_p (stmt)
10737 && TREE_CODE (gimple_assign_rhs1 (stmt)) == ASSERT_EXPR)
10739 tree rhs1 = gimple_assign_rhs1 (stmt);
10740 tree cond = TREE_OPERAND (rhs1, 1);
10741 tree inverted = invert_truthvalue (cond);
10742 vec<cond_equivalence> p;
10743 p.create (3);
10744 record_conditions (&p, cond, inverted);
10745 for (unsigned int i = 0; i < p.length (); i++)
10746 m_avail_exprs_stack->record_cond (&p[i]);
10748 tree lhs = gimple_assign_lhs (stmt);
10749 m_const_and_copies->record_const_or_copy (lhs,
10750 TREE_OPERAND (rhs1, 0));
10751 p.release ();
10752 continue;
10754 break;
10756 return NULL;
10759 /* Called after processing dominator children of BB. This is where we
10760 actually call into the threader. */
10761 void
10762 vrp_dom_walker::after_dom_children (basic_block bb)
10764 if (!m_dummy_cond)
10765 m_dummy_cond = gimple_build_cond (NE_EXPR,
10766 integer_zero_node, integer_zero_node,
10767 NULL, NULL);
10769 thread_outgoing_edges (bb, m_dummy_cond, m_const_and_copies,
10770 m_avail_exprs_stack,
10771 simplify_stmt_for_jump_threading);
10773 m_avail_exprs_stack->pop_to_marker ();
10774 m_const_and_copies->pop_to_marker ();
10777 /* Blocks which have more than one predecessor and more than
10778 one successor present jump threading opportunities, i.e.,
10779 when the block is reached from a specific predecessor, we
10780 may be able to determine which of the outgoing edges will
10781 be traversed. When this optimization applies, we are able
10782 to avoid conditionals at runtime and we may expose secondary
10783 optimization opportunities.
10785 This routine is effectively a driver for the generic jump
10786 threading code. It basically just presents the generic code
10787 with edges that may be suitable for jump threading.
10789 Unlike DOM, we do not iterate VRP if jump threading was successful.
10790 While iterating may expose new opportunities for VRP, it is expected
10791 those opportunities would be very limited and the compile time cost
10792 to expose those opportunities would be significant.
10794 As jump threading opportunities are discovered, they are registered
10795 for later realization. */
10797 static void
10798 identify_jump_threads (void)
10800 int i;
10801 edge e;
10803 /* Ugh. When substituting values earlier in this pass we can
10804 wipe the dominance information. So rebuild the dominator
10805 information as we need it within the jump threading code. */
10806 calculate_dominance_info (CDI_DOMINATORS);
10808 /* We do not allow VRP information to be used for jump threading
10809 across a back edge in the CFG. Otherwise it becomes too
10810 difficult to avoid eliminating loop exit tests. Of course
10811 EDGE_DFS_BACK is not accurate at this time so we have to
10812 recompute it. */
10813 mark_dfs_back_edges ();
10815 /* Do not thread across edges we are about to remove. Just marking
10816 them as EDGE_IGNORE will do. */
10817 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
10818 e->flags |= EDGE_IGNORE;
10820 /* Allocate our unwinder stack to unwind any temporary equivalences
10821 that might be recorded. */
10822 const_and_copies *equiv_stack = new const_and_copies ();
10824 hash_table<expr_elt_hasher> *avail_exprs
10825 = new hash_table<expr_elt_hasher> (1024);
10826 avail_exprs_stack *avail_exprs_stack
10827 = new class avail_exprs_stack (avail_exprs);
10829 vrp_dom_walker walker (CDI_DOMINATORS, equiv_stack, avail_exprs_stack);
10830 walker.walk (cfun->cfg->x_entry_block_ptr);
10832 /* Clear EDGE_IGNORE. */
10833 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
10834 e->flags &= ~EDGE_IGNORE;
10836 /* We do not actually update the CFG or SSA graphs at this point as
10837 ASSERT_EXPRs are still in the IL and cfg cleanup code does not yet
10838 handle ASSERT_EXPRs gracefully. */
10839 delete equiv_stack;
10840 delete avail_exprs;
10841 delete avail_exprs_stack;
10844 /* Free VRP lattice. */
10846 static void
10847 vrp_free_lattice ()
10849 /* Free allocated memory. */
10850 free (vr_value);
10851 free (vr_phi_edge_counts);
10852 bitmap_obstack_release (&vrp_equiv_obstack);
10853 vrp_value_range_pool.release ();
10855 /* So that we can distinguish between VRP data being available
10856 and not available. */
10857 vr_value = NULL;
10858 vr_phi_edge_counts = NULL;
10861 /* Traverse all the blocks folding conditionals with known ranges. */
10863 static void
10864 vrp_finalize (bool warn_array_bounds_p)
10866 size_t i;
10868 values_propagated = true;
10870 if (dump_file)
10872 fprintf (dump_file, "\nValue ranges after VRP:\n\n");
10873 dump_all_value_ranges (dump_file);
10874 fprintf (dump_file, "\n");
10877 /* Set value range to non pointer SSA_NAMEs. */
10878 for (i = 0; i < num_vr_values; i++)
10879 if (vr_value[i])
10881 tree name = ssa_name (i);
10883 if (!name
10884 || (vr_value[i]->type == VR_VARYING)
10885 || (vr_value[i]->type == VR_UNDEFINED)
10886 || (TREE_CODE (vr_value[i]->min) != INTEGER_CST)
10887 || (TREE_CODE (vr_value[i]->max) != INTEGER_CST))
10888 continue;
10890 if (POINTER_TYPE_P (TREE_TYPE (name))
10891 && ((vr_value[i]->type == VR_RANGE
10892 && range_includes_zero_p (vr_value[i]->min,
10893 vr_value[i]->max) == 0)
10894 || (vr_value[i]->type == VR_ANTI_RANGE
10895 && range_includes_zero_p (vr_value[i]->min,
10896 vr_value[i]->max) == 1)))
10897 set_ptr_nonnull (name);
10898 else if (!POINTER_TYPE_P (TREE_TYPE (name)))
10899 set_range_info (name, vr_value[i]->type,
10900 wi::to_wide (vr_value[i]->min),
10901 wi::to_wide (vr_value[i]->max));
10904 class vrp_folder vrp_folder;
10905 vrp_folder.substitute_and_fold ();
10907 if (warn_array_bounds && warn_array_bounds_p)
10908 check_all_array_refs ();
10911 /* evrp_dom_walker visits the basic blocks in the dominance order and set
10912 the Value Ranges (VR) for SSA_NAMEs in the scope. Use this VR to
10913 discover more VRs. */
10915 class evrp_dom_walker : public dom_walker
10917 public:
10918 evrp_dom_walker ()
10919 : dom_walker (CDI_DOMINATORS), stack (10)
10921 need_eh_cleanup = BITMAP_ALLOC (NULL);
10923 ~evrp_dom_walker ()
10925 BITMAP_FREE (need_eh_cleanup);
10927 virtual edge before_dom_children (basic_block);
10928 virtual void after_dom_children (basic_block);
10929 void push_value_range (tree var, value_range *vr);
10930 value_range *pop_value_range (tree var);
10931 value_range *try_find_new_range (tree, tree op, tree_code code, tree limit);
10933 /* Cond_stack holds the old VR. */
10934 auto_vec<std::pair <tree, value_range*> > stack;
10935 bitmap need_eh_cleanup;
10936 auto_vec<gimple *> stmts_to_fixup;
10937 auto_vec<gimple *> stmts_to_remove;
10940 /* Find new range for NAME such that (OP CODE LIMIT) is true. */
10942 value_range *
10943 evrp_dom_walker::try_find_new_range (tree name,
10944 tree op, tree_code code, tree limit)
10946 value_range vr = VR_INITIALIZER;
10947 value_range *old_vr = get_value_range (name);
10949 /* Discover VR when condition is true. */
10950 extract_range_for_var_from_comparison_expr (name, code, op,
10951 limit, &vr);
10952 /* If we found any usable VR, set the VR to ssa_name and create a
10953 PUSH old value in the stack with the old VR. */
10954 if (vr.type == VR_RANGE || vr.type == VR_ANTI_RANGE)
10956 if (old_vr->type == vr.type
10957 && vrp_operand_equal_p (old_vr->min, vr.min)
10958 && vrp_operand_equal_p (old_vr->max, vr.max))
10959 return NULL;
10960 value_range *new_vr = vrp_value_range_pool.allocate ();
10961 *new_vr = vr;
10962 return new_vr;
10964 return NULL;
10967 /* See if there is any new scope is entered with new VR and set that VR to
10968 ssa_name before visiting the statements in the scope. */
10970 edge
10971 evrp_dom_walker::before_dom_children (basic_block bb)
10973 if (dump_file && (dump_flags & TDF_DETAILS))
10974 fprintf (dump_file, "Visiting BB%d\n", bb->index);
10976 stack.safe_push (std::make_pair (NULL_TREE, (value_range *)NULL));
10978 edge pred_e = single_pred_edge_ignoring_loop_edges (bb, false);
10979 if (pred_e)
10981 gimple *stmt = last_stmt (pred_e->src);
10982 tree op0 = NULL_TREE;
10984 if (stmt
10985 && gimple_code (stmt) == GIMPLE_COND
10986 && (op0 = gimple_cond_lhs (stmt))
10987 && TREE_CODE (op0) == SSA_NAME
10988 && (INTEGRAL_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)))
10989 || POINTER_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)))))
10991 if (dump_file && (dump_flags & TDF_DETAILS))
10993 fprintf (dump_file, "Visiting controlling predicate ");
10994 print_gimple_stmt (dump_file, stmt, 0);
10996 /* Entering a new scope. Try to see if we can find a VR
10997 here. */
10998 tree op1 = gimple_cond_rhs (stmt);
10999 if (TREE_OVERFLOW_P (op1))
11000 op1 = drop_tree_overflow (op1);
11001 tree_code code = gimple_cond_code (stmt);
11003 auto_vec<assert_info, 8> asserts;
11004 register_edge_assert_for (op0, pred_e, code, op0, op1, asserts);
11005 if (TREE_CODE (op1) == SSA_NAME)
11006 register_edge_assert_for (op1, pred_e, code, op0, op1, asserts);
11008 auto_vec<std::pair<tree, value_range *>, 8> vrs;
11009 for (unsigned i = 0; i < asserts.length (); ++i)
11011 value_range *vr = try_find_new_range (asserts[i].name,
11012 asserts[i].expr,
11013 asserts[i].comp_code,
11014 asserts[i].val);
11015 if (vr)
11016 vrs.safe_push (std::make_pair (asserts[i].name, vr));
11018 /* Push updated ranges only after finding all of them to avoid
11019 ordering issues that can lead to worse ranges. */
11020 for (unsigned i = 0; i < vrs.length (); ++i)
11021 push_value_range (vrs[i].first, vrs[i].second);
11025 /* Visit PHI stmts and discover any new VRs possible. */
11026 bool has_unvisited_preds = false;
11027 edge_iterator ei;
11028 edge e;
11029 FOR_EACH_EDGE (e, ei, bb->preds)
11030 if (e->flags & EDGE_EXECUTABLE
11031 && !(e->src->flags & BB_VISITED))
11033 has_unvisited_preds = true;
11034 break;
11037 for (gphi_iterator gpi = gsi_start_phis (bb);
11038 !gsi_end_p (gpi); gsi_next (&gpi))
11040 gphi *phi = gpi.phi ();
11041 tree lhs = PHI_RESULT (phi);
11042 if (virtual_operand_p (lhs))
11043 continue;
11044 value_range vr_result = VR_INITIALIZER;
11045 bool interesting = stmt_interesting_for_vrp (phi);
11046 if (interesting && dump_file && (dump_flags & TDF_DETAILS))
11048 fprintf (dump_file, "Visiting PHI node ");
11049 print_gimple_stmt (dump_file, phi, 0);
11051 if (!has_unvisited_preds
11052 && interesting)
11053 extract_range_from_phi_node (phi, &vr_result);
11054 else
11056 set_value_range_to_varying (&vr_result);
11057 /* When we have an unvisited executable predecessor we can't
11058 use PHI arg ranges which may be still UNDEFINED but have
11059 to use VARYING for them. But we can still resort to
11060 SCEV for loop header PHIs. */
11061 struct loop *l;
11062 if (interesting
11063 && (l = loop_containing_stmt (phi))
11064 && l->header == gimple_bb (phi))
11065 adjust_range_with_scev (&vr_result, l, phi, lhs);
11067 update_value_range (lhs, &vr_result);
11069 /* Mark PHIs whose lhs we fully propagate for removal. */
11070 tree val = op_with_constant_singleton_value_range (lhs);
11071 if (val && may_propagate_copy (lhs, val))
11073 stmts_to_remove.safe_push (phi);
11074 continue;
11077 /* Set the SSA with the value range. */
11078 if (INTEGRAL_TYPE_P (TREE_TYPE (lhs)))
11080 if ((vr_result.type == VR_RANGE
11081 || vr_result.type == VR_ANTI_RANGE)
11082 && (TREE_CODE (vr_result.min) == INTEGER_CST)
11083 && (TREE_CODE (vr_result.max) == INTEGER_CST))
11084 set_range_info (lhs, vr_result.type,
11085 wi::to_wide (vr_result.min),
11086 wi::to_wide (vr_result.max));
11088 else if (POINTER_TYPE_P (TREE_TYPE (lhs))
11089 && ((vr_result.type == VR_RANGE
11090 && range_includes_zero_p (vr_result.min,
11091 vr_result.max) == 0)
11092 || (vr_result.type == VR_ANTI_RANGE
11093 && range_includes_zero_p (vr_result.min,
11094 vr_result.max) == 1)))
11095 set_ptr_nonnull (lhs);
11098 edge taken_edge = NULL;
11100 /* Visit all other stmts and discover any new VRs possible. */
11101 for (gimple_stmt_iterator gsi = gsi_start_bb (bb);
11102 !gsi_end_p (gsi); gsi_next (&gsi))
11104 gimple *stmt = gsi_stmt (gsi);
11105 tree output = NULL_TREE;
11106 gimple *old_stmt = stmt;
11107 bool was_noreturn = (is_gimple_call (stmt)
11108 && gimple_call_noreturn_p (stmt));
11110 if (dump_file && (dump_flags & TDF_DETAILS))
11112 fprintf (dump_file, "Visiting stmt ");
11113 print_gimple_stmt (dump_file, stmt, 0);
11116 if (gcond *cond = dyn_cast <gcond *> (stmt))
11118 vrp_visit_cond_stmt (cond, &taken_edge);
11119 if (taken_edge)
11121 if (taken_edge->flags & EDGE_TRUE_VALUE)
11122 gimple_cond_make_true (cond);
11123 else if (taken_edge->flags & EDGE_FALSE_VALUE)
11124 gimple_cond_make_false (cond);
11125 else
11126 gcc_unreachable ();
11127 update_stmt (stmt);
11130 else if (stmt_interesting_for_vrp (stmt))
11132 edge taken_edge;
11133 value_range vr = VR_INITIALIZER;
11134 extract_range_from_stmt (stmt, &taken_edge, &output, &vr);
11135 if (output
11136 && (vr.type == VR_RANGE || vr.type == VR_ANTI_RANGE))
11138 update_value_range (output, &vr);
11139 vr = *get_value_range (output);
11141 /* Mark stmts whose output we fully propagate for removal. */
11142 tree val;
11143 if ((val = op_with_constant_singleton_value_range (output))
11144 && may_propagate_copy (output, val)
11145 && !stmt_could_throw_p (stmt)
11146 && !gimple_has_side_effects (stmt))
11148 stmts_to_remove.safe_push (stmt);
11149 continue;
11152 /* Set the SSA with the value range. */
11153 if (INTEGRAL_TYPE_P (TREE_TYPE (output)))
11155 if ((vr.type == VR_RANGE
11156 || vr.type == VR_ANTI_RANGE)
11157 && (TREE_CODE (vr.min) == INTEGER_CST)
11158 && (TREE_CODE (vr.max) == INTEGER_CST))
11159 set_range_info (output, vr.type,
11160 wi::to_wide (vr.min),
11161 wi::to_wide (vr.max));
11163 else if (POINTER_TYPE_P (TREE_TYPE (output))
11164 && ((vr.type == VR_RANGE
11165 && range_includes_zero_p (vr.min,
11166 vr.max) == 0)
11167 || (vr.type == VR_ANTI_RANGE
11168 && range_includes_zero_p (vr.min,
11169 vr.max) == 1)))
11170 set_ptr_nonnull (output);
11172 else
11173 set_defs_to_varying (stmt);
11175 else
11176 set_defs_to_varying (stmt);
11178 /* See if we can derive a range for any of STMT's operands. */
11179 tree op;
11180 ssa_op_iter i;
11181 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
11183 tree value;
11184 enum tree_code comp_code;
11186 /* If OP is used in such a way that we can infer a value
11187 range for it, and we don't find a previous assertion for
11188 it, create a new assertion location node for OP. */
11189 if (infer_value_range (stmt, op, &comp_code, &value))
11191 /* If we are able to infer a nonzero value range for OP,
11192 then walk backwards through the use-def chain to see if OP
11193 was set via a typecast.
11194 If so, then we can also infer a nonzero value range
11195 for the operand of the NOP_EXPR. */
11196 if (comp_code == NE_EXPR && integer_zerop (value))
11198 tree t = op;
11199 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
11200 while (is_gimple_assign (def_stmt)
11201 && CONVERT_EXPR_CODE_P
11202 (gimple_assign_rhs_code (def_stmt))
11203 && TREE_CODE
11204 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
11205 && POINTER_TYPE_P
11206 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
11208 t = gimple_assign_rhs1 (def_stmt);
11209 def_stmt = SSA_NAME_DEF_STMT (t);
11211 /* Add VR when (T COMP_CODE value) condition is
11212 true. */
11213 value_range *op_range
11214 = try_find_new_range (t, t, comp_code, value);
11215 if (op_range)
11216 push_value_range (t, op_range);
11219 /* Add VR when (OP COMP_CODE value) condition is true. */
11220 value_range *op_range = try_find_new_range (op, op,
11221 comp_code, value);
11222 if (op_range)
11223 push_value_range (op, op_range);
11227 /* Try folding stmts with the VR discovered. */
11228 class vrp_folder vrp_folder;
11229 bool did_replace = vrp_folder.replace_uses_in (stmt);
11230 if (fold_stmt (&gsi, follow_single_use_edges)
11231 || did_replace)
11233 stmt = gsi_stmt (gsi);
11234 update_stmt (stmt);
11235 did_replace = true;
11238 if (did_replace)
11240 /* If we cleaned up EH information from the statement,
11241 remove EH edges. */
11242 if (maybe_clean_or_replace_eh_stmt (old_stmt, stmt))
11243 bitmap_set_bit (need_eh_cleanup, bb->index);
11245 /* If we turned a not noreturn call into a noreturn one
11246 schedule it for fixup. */
11247 if (!was_noreturn
11248 && is_gimple_call (stmt)
11249 && gimple_call_noreturn_p (stmt))
11250 stmts_to_fixup.safe_push (stmt);
11252 if (gimple_assign_single_p (stmt))
11254 tree rhs = gimple_assign_rhs1 (stmt);
11255 if (TREE_CODE (rhs) == ADDR_EXPR)
11256 recompute_tree_invariant_for_addr_expr (rhs);
11261 /* Visit BB successor PHI nodes and replace PHI args. */
11262 FOR_EACH_EDGE (e, ei, bb->succs)
11264 for (gphi_iterator gpi = gsi_start_phis (e->dest);
11265 !gsi_end_p (gpi); gsi_next (&gpi))
11267 gphi *phi = gpi.phi ();
11268 use_operand_p use_p = PHI_ARG_DEF_PTR_FROM_EDGE (phi, e);
11269 tree arg = USE_FROM_PTR (use_p);
11270 if (TREE_CODE (arg) != SSA_NAME
11271 || virtual_operand_p (arg))
11272 continue;
11273 tree val = op_with_constant_singleton_value_range (arg);
11274 if (val && may_propagate_copy (arg, val))
11275 propagate_value (use_p, val);
11279 bb->flags |= BB_VISITED;
11281 return taken_edge;
11284 /* Restore/pop VRs valid only for BB when we leave BB. */
11286 void
11287 evrp_dom_walker::after_dom_children (basic_block bb ATTRIBUTE_UNUSED)
11289 gcc_checking_assert (!stack.is_empty ());
11290 while (stack.last ().first != NULL_TREE)
11291 pop_value_range (stack.last ().first);
11292 stack.pop ();
11295 /* Push the Value Range of VAR to the stack and update it with new VR. */
11297 void
11298 evrp_dom_walker::push_value_range (tree var, value_range *vr)
11300 if (SSA_NAME_VERSION (var) >= num_vr_values)
11301 return;
11302 if (dump_file && (dump_flags & TDF_DETAILS))
11304 fprintf (dump_file, "pushing new range for ");
11305 print_generic_expr (dump_file, var);
11306 fprintf (dump_file, ": ");
11307 dump_value_range (dump_file, vr);
11308 fprintf (dump_file, "\n");
11310 stack.safe_push (std::make_pair (var, get_value_range (var)));
11311 vr_value[SSA_NAME_VERSION (var)] = vr;
11314 /* Pop the Value Range from the vrp_stack and update VAR with it. */
11316 value_range *
11317 evrp_dom_walker::pop_value_range (tree var)
11319 value_range *vr = stack.last ().second;
11320 gcc_checking_assert (var == stack.last ().first);
11321 if (dump_file && (dump_flags & TDF_DETAILS))
11323 fprintf (dump_file, "popping range for ");
11324 print_generic_expr (dump_file, var);
11325 fprintf (dump_file, ", restoring ");
11326 dump_value_range (dump_file, vr);
11327 fprintf (dump_file, "\n");
11329 vr_value[SSA_NAME_VERSION (var)] = vr;
11330 stack.pop ();
11331 return vr;
11335 /* Main entry point for the early vrp pass which is a simplified non-iterative
11336 version of vrp where basic blocks are visited in dominance order. Value
11337 ranges discovered in early vrp will also be used by ipa-vrp. */
11339 static unsigned int
11340 execute_early_vrp ()
11342 edge e;
11343 edge_iterator ei;
11344 basic_block bb;
11346 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
11347 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
11348 scev_initialize ();
11349 calculate_dominance_info (CDI_DOMINATORS);
11350 FOR_EACH_BB_FN (bb, cfun)
11352 bb->flags &= ~BB_VISITED;
11353 FOR_EACH_EDGE (e, ei, bb->preds)
11354 e->flags |= EDGE_EXECUTABLE;
11356 vrp_initialize_lattice ();
11358 /* Walk stmts in dominance order and propagate VRP. */
11359 evrp_dom_walker walker;
11360 walker.walk (ENTRY_BLOCK_PTR_FOR_FN (cfun));
11362 if (dump_file)
11364 fprintf (dump_file, "\nValue ranges after Early VRP:\n\n");
11365 dump_all_value_ranges (dump_file);
11366 fprintf (dump_file, "\n");
11369 /* Remove stmts in reverse order to make debug stmt creation possible. */
11370 while (! walker.stmts_to_remove.is_empty ())
11372 gimple *stmt = walker.stmts_to_remove.pop ();
11373 if (dump_file && dump_flags & TDF_DETAILS)
11375 fprintf (dump_file, "Removing dead stmt ");
11376 print_gimple_stmt (dump_file, stmt, 0);
11377 fprintf (dump_file, "\n");
11379 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
11380 if (gimple_code (stmt) == GIMPLE_PHI)
11381 remove_phi_node (&gsi, true);
11382 else
11384 unlink_stmt_vdef (stmt);
11385 gsi_remove (&gsi, true);
11386 release_defs (stmt);
11390 if (!bitmap_empty_p (walker.need_eh_cleanup))
11391 gimple_purge_all_dead_eh_edges (walker.need_eh_cleanup);
11393 /* Fixup stmts that became noreturn calls. This may require splitting
11394 blocks and thus isn't possible during the dominator walk. Do this
11395 in reverse order so we don't inadvertedly remove a stmt we want to
11396 fixup by visiting a dominating now noreturn call first. */
11397 while (!walker.stmts_to_fixup.is_empty ())
11399 gimple *stmt = walker.stmts_to_fixup.pop ();
11400 fixup_noreturn_call (stmt);
11403 vrp_free_lattice ();
11404 scev_finalize ();
11405 loop_optimizer_finalize ();
11406 return 0;
11410 /* Main entry point to VRP (Value Range Propagation). This pass is
11411 loosely based on J. R. C. Patterson, ``Accurate Static Branch
11412 Prediction by Value Range Propagation,'' in SIGPLAN Conference on
11413 Programming Language Design and Implementation, pp. 67-78, 1995.
11414 Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
11416 This is essentially an SSA-CCP pass modified to deal with ranges
11417 instead of constants.
11419 While propagating ranges, we may find that two or more SSA name
11420 have equivalent, though distinct ranges. For instance,
11422 1 x_9 = p_3->a;
11423 2 p_4 = ASSERT_EXPR <p_3, p_3 != 0>
11424 3 if (p_4 == q_2)
11425 4 p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
11426 5 endif
11427 6 if (q_2)
11429 In the code above, pointer p_5 has range [q_2, q_2], but from the
11430 code we can also determine that p_5 cannot be NULL and, if q_2 had
11431 a non-varying range, p_5's range should also be compatible with it.
11433 These equivalences are created by two expressions: ASSERT_EXPR and
11434 copy operations. Since p_5 is an assertion on p_4, and p_4 was the
11435 result of another assertion, then we can use the fact that p_5 and
11436 p_4 are equivalent when evaluating p_5's range.
11438 Together with value ranges, we also propagate these equivalences
11439 between names so that we can take advantage of information from
11440 multiple ranges when doing final replacement. Note that this
11441 equivalency relation is transitive but not symmetric.
11443 In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
11444 cannot assert that q_2 is equivalent to p_5 because q_2 may be used
11445 in contexts where that assertion does not hold (e.g., in line 6).
11447 TODO, the main difference between this pass and Patterson's is that
11448 we do not propagate edge probabilities. We only compute whether
11449 edges can be taken or not. That is, instead of having a spectrum
11450 of jump probabilities between 0 and 1, we only deal with 0, 1 and
11451 DON'T KNOW. In the future, it may be worthwhile to propagate
11452 probabilities to aid branch prediction. */
11454 static unsigned int
11455 execute_vrp (bool warn_array_bounds_p)
11457 int i;
11458 edge e;
11459 switch_update *su;
11461 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
11462 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
11463 scev_initialize ();
11465 /* ??? This ends up using stale EDGE_DFS_BACK for liveness computation.
11466 Inserting assertions may split edges which will invalidate
11467 EDGE_DFS_BACK. */
11468 insert_range_assertions ();
11470 to_remove_edges.create (10);
11471 to_update_switch_stmts.create (5);
11472 threadedge_initialize_values ();
11474 /* For visiting PHI nodes we need EDGE_DFS_BACK computed. */
11475 mark_dfs_back_edges ();
11477 vrp_initialize_lattice ();
11478 vrp_initialize ();
11479 class vrp_prop vrp_prop;
11480 vrp_prop.ssa_propagate ();
11481 vrp_finalize (warn_array_bounds_p);
11483 /* We must identify jump threading opportunities before we release
11484 the datastructures built by VRP. */
11485 identify_jump_threads ();
11487 /* A comparison of an SSA_NAME against a constant where the SSA_NAME
11488 was set by a type conversion can often be rewritten to use the
11489 RHS of the type conversion.
11491 However, doing so inhibits jump threading through the comparison.
11492 So that transformation is not performed until after jump threading
11493 is complete. */
11494 basic_block bb;
11495 FOR_EACH_BB_FN (bb, cfun)
11497 gimple *last = last_stmt (bb);
11498 if (last && gimple_code (last) == GIMPLE_COND)
11499 simplify_cond_using_ranges_2 (as_a <gcond *> (last));
11502 vrp_free_lattice ();
11504 free_numbers_of_iterations_estimates (cfun);
11506 /* ASSERT_EXPRs must be removed before finalizing jump threads
11507 as finalizing jump threads calls the CFG cleanup code which
11508 does not properly handle ASSERT_EXPRs. */
11509 remove_range_assertions ();
11511 /* If we exposed any new variables, go ahead and put them into
11512 SSA form now, before we handle jump threading. This simplifies
11513 interactions between rewriting of _DECL nodes into SSA form
11514 and rewriting SSA_NAME nodes into SSA form after block
11515 duplication and CFG manipulation. */
11516 update_ssa (TODO_update_ssa);
11518 /* We identified all the jump threading opportunities earlier, but could
11519 not transform the CFG at that time. This routine transforms the
11520 CFG and arranges for the dominator tree to be rebuilt if necessary.
11522 Note the SSA graph update will occur during the normal TODO
11523 processing by the pass manager. */
11524 thread_through_all_blocks (false);
11526 /* Remove dead edges from SWITCH_EXPR optimization. This leaves the
11527 CFG in a broken state and requires a cfg_cleanup run. */
11528 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
11529 remove_edge (e);
11530 /* Update SWITCH_EXPR case label vector. */
11531 FOR_EACH_VEC_ELT (to_update_switch_stmts, i, su)
11533 size_t j;
11534 size_t n = TREE_VEC_LENGTH (su->vec);
11535 tree label;
11536 gimple_switch_set_num_labels (su->stmt, n);
11537 for (j = 0; j < n; j++)
11538 gimple_switch_set_label (su->stmt, j, TREE_VEC_ELT (su->vec, j));
11539 /* As we may have replaced the default label with a regular one
11540 make sure to make it a real default label again. This ensures
11541 optimal expansion. */
11542 label = gimple_switch_label (su->stmt, 0);
11543 CASE_LOW (label) = NULL_TREE;
11544 CASE_HIGH (label) = NULL_TREE;
11547 if (to_remove_edges.length () > 0)
11549 free_dominance_info (CDI_DOMINATORS);
11550 loops_state_set (LOOPS_NEED_FIXUP);
11553 to_remove_edges.release ();
11554 to_update_switch_stmts.release ();
11555 threadedge_finalize_values ();
11557 scev_finalize ();
11558 loop_optimizer_finalize ();
11559 return 0;
11562 namespace {
11564 const pass_data pass_data_vrp =
11566 GIMPLE_PASS, /* type */
11567 "vrp", /* name */
11568 OPTGROUP_NONE, /* optinfo_flags */
11569 TV_TREE_VRP, /* tv_id */
11570 PROP_ssa, /* properties_required */
11571 0, /* properties_provided */
11572 0, /* properties_destroyed */
11573 0, /* todo_flags_start */
11574 ( TODO_cleanup_cfg | TODO_update_ssa ), /* todo_flags_finish */
11577 class pass_vrp : public gimple_opt_pass
11579 public:
11580 pass_vrp (gcc::context *ctxt)
11581 : gimple_opt_pass (pass_data_vrp, ctxt), warn_array_bounds_p (false)
11584 /* opt_pass methods: */
11585 opt_pass * clone () { return new pass_vrp (m_ctxt); }
11586 void set_pass_param (unsigned int n, bool param)
11588 gcc_assert (n == 0);
11589 warn_array_bounds_p = param;
11591 virtual bool gate (function *) { return flag_tree_vrp != 0; }
11592 virtual unsigned int execute (function *)
11593 { return execute_vrp (warn_array_bounds_p); }
11595 private:
11596 bool warn_array_bounds_p;
11597 }; // class pass_vrp
11599 } // anon namespace
11601 gimple_opt_pass *
11602 make_pass_vrp (gcc::context *ctxt)
11604 return new pass_vrp (ctxt);
11607 namespace {
11609 const pass_data pass_data_early_vrp =
11611 GIMPLE_PASS, /* type */
11612 "evrp", /* name */
11613 OPTGROUP_NONE, /* optinfo_flags */
11614 TV_TREE_EARLY_VRP, /* tv_id */
11615 PROP_ssa, /* properties_required */
11616 0, /* properties_provided */
11617 0, /* properties_destroyed */
11618 0, /* todo_flags_start */
11619 ( TODO_cleanup_cfg | TODO_update_ssa | TODO_verify_all ),
11622 class pass_early_vrp : public gimple_opt_pass
11624 public:
11625 pass_early_vrp (gcc::context *ctxt)
11626 : gimple_opt_pass (pass_data_early_vrp, ctxt)
11629 /* opt_pass methods: */
11630 opt_pass * clone () { return new pass_early_vrp (m_ctxt); }
11631 virtual bool gate (function *)
11633 return flag_tree_vrp != 0;
11635 virtual unsigned int execute (function *)
11636 { return execute_early_vrp (); }
11638 }; // class pass_vrp
11639 } // anon namespace
11641 gimple_opt_pass *
11642 make_pass_early_vrp (gcc::context *ctxt)
11644 return new pass_early_vrp (ctxt);