2017-11-09 Paul Thomas <pault@gcc.gnu.org>
[official-gcc.git] / gcc / tree-vrp.c
blob2b7d9622f691226739e2cc3da6e5d927fe584013
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. Return true if we can compute the
1606 result; i.e. if the operation doesn't overflow or if the overflow is
1607 undefined. In the latter case (if the operation overflows and
1608 overflow is undefined), then adjust the result to be -INF or +INF
1609 depending on CODE, VAL1 and VAL2. Return the value in *RES.
1611 Return false for division by zero, for which the result is
1612 indeterminate. */
1614 static bool
1615 vrp_int_const_binop (enum tree_code code, tree val1, tree val2, wide_int *res)
1617 bool overflow = false;
1618 signop sign = TYPE_SIGN (TREE_TYPE (val1));
1620 switch (code)
1622 case RSHIFT_EXPR:
1623 case LSHIFT_EXPR:
1625 wide_int wval2 = wi::to_wide (val2, TYPE_PRECISION (TREE_TYPE (val1)));
1626 if (wi::neg_p (wval2))
1628 wval2 = -wval2;
1629 if (code == RSHIFT_EXPR)
1630 code = LSHIFT_EXPR;
1631 else
1632 code = RSHIFT_EXPR;
1635 if (code == RSHIFT_EXPR)
1636 /* It's unclear from the C standard whether shifts can overflow.
1637 The following code ignores overflow; perhaps a C standard
1638 interpretation ruling is needed. */
1639 *res = wi::rshift (wi::to_wide (val1), wval2, sign);
1640 else
1641 *res = wi::lshift (wi::to_wide (val1), wval2);
1642 break;
1645 case MULT_EXPR:
1646 *res = wi::mul (wi::to_wide (val1),
1647 wi::to_wide (val2), sign, &overflow);
1648 break;
1650 case TRUNC_DIV_EXPR:
1651 case EXACT_DIV_EXPR:
1652 if (val2 == 0)
1653 return false;
1654 else
1655 *res = wi::div_trunc (wi::to_wide (val1),
1656 wi::to_wide (val2), sign, &overflow);
1657 break;
1659 case FLOOR_DIV_EXPR:
1660 if (val2 == 0)
1661 return false;
1662 *res = wi::div_floor (wi::to_wide (val1),
1663 wi::to_wide (val2), sign, &overflow);
1664 break;
1666 case CEIL_DIV_EXPR:
1667 if (val2 == 0)
1668 return false;
1669 *res = wi::div_ceil (wi::to_wide (val1),
1670 wi::to_wide (val2), sign, &overflow);
1671 break;
1673 case ROUND_DIV_EXPR:
1674 if (val2 == 0)
1675 return false;
1676 *res = wi::div_round (wi::to_wide (val1),
1677 wi::to_wide (val2), sign, &overflow);
1678 break;
1680 default:
1681 gcc_unreachable ();
1684 if (overflow
1685 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1)))
1687 /* If the operation overflowed return -INF or +INF depending
1688 on the operation and the combination of signs of the operands. */
1689 int sgn1 = tree_int_cst_sgn (val1);
1690 int sgn2 = tree_int_cst_sgn (val2);
1692 /* Notice that we only need to handle the restricted set of
1693 operations handled by extract_range_from_binary_expr.
1694 Among them, only multiplication, addition and subtraction
1695 can yield overflow without overflown operands because we
1696 are working with integral types only... except in the
1697 case VAL1 = -INF and VAL2 = -1 which overflows to +INF
1698 for division too. */
1700 /* For multiplication, the sign of the overflow is given
1701 by the comparison of the signs of the operands. */
1702 if ((code == MULT_EXPR && sgn1 == sgn2)
1703 /* For addition, the operands must be of the same sign
1704 to yield an overflow. Its sign is therefore that
1705 of one of the operands, for example the first. */
1706 || (code == PLUS_EXPR && sgn1 >= 0)
1707 /* For subtraction, operands must be of
1708 different signs to yield an overflow. Its sign is
1709 therefore that of the first operand or the opposite of
1710 that of the second operand. A first operand of 0 counts
1711 as positive here, for the corner case 0 - (-INF), which
1712 overflows, but must yield +INF. */
1713 || (code == MINUS_EXPR && sgn1 >= 0)
1714 /* For division, the only case is -INF / -1 = +INF. */
1715 || code == TRUNC_DIV_EXPR
1716 || code == FLOOR_DIV_EXPR
1717 || code == CEIL_DIV_EXPR
1718 || code == EXACT_DIV_EXPR
1719 || code == ROUND_DIV_EXPR)
1720 *res = wi::max_value (TYPE_PRECISION (TREE_TYPE (val1)),
1721 TYPE_SIGN (TREE_TYPE (val1)));
1722 else
1723 *res = wi::min_value (TYPE_PRECISION (TREE_TYPE (val1)),
1724 TYPE_SIGN (TREE_TYPE (val1)));
1725 return true;
1728 return !overflow;
1732 /* For range VR compute two wide_int bitmasks. In *MAY_BE_NONZERO
1733 bitmask if some bit is unset, it means for all numbers in the range
1734 the bit is 0, otherwise it might be 0 or 1. In *MUST_BE_NONZERO
1735 bitmask if some bit is set, it means for all numbers in the range
1736 the bit is 1, otherwise it might be 0 or 1. */
1738 static bool
1739 zero_nonzero_bits_from_vr (const tree expr_type,
1740 value_range *vr,
1741 wide_int *may_be_nonzero,
1742 wide_int *must_be_nonzero)
1744 *may_be_nonzero = wi::minus_one (TYPE_PRECISION (expr_type));
1745 *must_be_nonzero = wi::zero (TYPE_PRECISION (expr_type));
1746 if (!range_int_cst_p (vr))
1747 return false;
1749 if (range_int_cst_singleton_p (vr))
1751 *may_be_nonzero = wi::to_wide (vr->min);
1752 *must_be_nonzero = *may_be_nonzero;
1754 else if (tree_int_cst_sgn (vr->min) >= 0
1755 || tree_int_cst_sgn (vr->max) < 0)
1757 wide_int xor_mask = wi::to_wide (vr->min) ^ wi::to_wide (vr->max);
1758 *may_be_nonzero = wi::to_wide (vr->min) | wi::to_wide (vr->max);
1759 *must_be_nonzero = wi::to_wide (vr->min) & wi::to_wide (vr->max);
1760 if (xor_mask != 0)
1762 wide_int mask = wi::mask (wi::floor_log2 (xor_mask), false,
1763 may_be_nonzero->get_precision ());
1764 *may_be_nonzero = *may_be_nonzero | mask;
1765 *must_be_nonzero = wi::bit_and_not (*must_be_nonzero, mask);
1769 return true;
1772 /* Create two value-ranges in *VR0 and *VR1 from the anti-range *AR
1773 so that *VR0 U *VR1 == *AR. Returns true if that is possible,
1774 false otherwise. If *AR can be represented with a single range
1775 *VR1 will be VR_UNDEFINED. */
1777 static bool
1778 ranges_from_anti_range (value_range *ar,
1779 value_range *vr0, value_range *vr1)
1781 tree type = TREE_TYPE (ar->min);
1783 vr0->type = VR_UNDEFINED;
1784 vr1->type = VR_UNDEFINED;
1786 if (ar->type != VR_ANTI_RANGE
1787 || TREE_CODE (ar->min) != INTEGER_CST
1788 || TREE_CODE (ar->max) != INTEGER_CST
1789 || !vrp_val_min (type)
1790 || !vrp_val_max (type))
1791 return false;
1793 if (!vrp_val_is_min (ar->min))
1795 vr0->type = VR_RANGE;
1796 vr0->min = vrp_val_min (type);
1797 vr0->max = wide_int_to_tree (type, wi::to_wide (ar->min) - 1);
1799 if (!vrp_val_is_max (ar->max))
1801 vr1->type = VR_RANGE;
1802 vr1->min = wide_int_to_tree (type, wi::to_wide (ar->max) + 1);
1803 vr1->max = vrp_val_max (type);
1805 if (vr0->type == VR_UNDEFINED)
1807 *vr0 = *vr1;
1808 vr1->type = VR_UNDEFINED;
1811 return vr0->type != VR_UNDEFINED;
1814 /* Helper to extract a value-range *VR for a multiplicative operation
1815 *VR0 CODE *VR1. */
1817 static void
1818 extract_range_from_multiplicative_op_1 (value_range *vr,
1819 enum tree_code code,
1820 value_range *vr0, value_range *vr1)
1822 enum value_range_type rtype;
1823 wide_int val, min, max;
1824 tree type;
1826 /* Multiplications, divisions and shifts are a bit tricky to handle,
1827 depending on the mix of signs we have in the two ranges, we
1828 need to operate on different values to get the minimum and
1829 maximum values for the new range. One approach is to figure
1830 out all the variations of range combinations and do the
1831 operations.
1833 However, this involves several calls to compare_values and it
1834 is pretty convoluted. It's simpler to do the 4 operations
1835 (MIN0 OP MIN1, MIN0 OP MAX1, MAX0 OP MIN1 and MAX0 OP MAX0 OP
1836 MAX1) and then figure the smallest and largest values to form
1837 the new range. */
1838 gcc_assert (code == MULT_EXPR
1839 || code == TRUNC_DIV_EXPR
1840 || code == FLOOR_DIV_EXPR
1841 || code == CEIL_DIV_EXPR
1842 || code == EXACT_DIV_EXPR
1843 || code == ROUND_DIV_EXPR
1844 || code == RSHIFT_EXPR
1845 || code == LSHIFT_EXPR);
1846 gcc_assert (vr0->type == VR_RANGE
1847 && vr0->type == vr1->type);
1849 rtype = vr0->type;
1850 type = TREE_TYPE (vr0->min);
1851 signop sgn = TYPE_SIGN (type);
1853 /* Compute the 4 cross operations and their minimum and maximum value. */
1854 if (!vrp_int_const_binop (code, vr0->min, vr1->min, &val))
1856 set_value_range_to_varying (vr);
1857 return;
1859 min = max = val;
1861 if (vr1->max != vr1->min)
1863 if (!vrp_int_const_binop (code, vr0->min, vr1->max, &val))
1865 set_value_range_to_varying (vr);
1866 return;
1868 if (wi::lt_p (val, min, sgn))
1869 min = val;
1870 else if (wi::gt_p (val, max, sgn))
1871 max = val;
1874 if (vr0->max != vr0->min)
1876 if (!vrp_int_const_binop (code, vr0->max, vr1->min, &val))
1878 set_value_range_to_varying (vr);
1879 return;
1881 if (wi::lt_p (val, min, sgn))
1882 min = val;
1883 else if (wi::gt_p (val, max, sgn))
1884 max = val;
1887 if (vr0->min != vr0->max && vr1->min != vr1->max)
1889 if (!vrp_int_const_binop (code, vr0->max, vr1->max, &val))
1891 set_value_range_to_varying (vr);
1892 return;
1894 if (wi::lt_p (val, min, sgn))
1895 min = val;
1896 else if (wi::gt_p (val, max, sgn))
1897 max = val;
1900 /* If the new range has its limits swapped around (MIN > MAX),
1901 then the operation caused one of them to wrap around, mark
1902 the new range VARYING. */
1903 if (wi::gt_p (min, max, sgn))
1905 set_value_range_to_varying (vr);
1906 return;
1909 /* We punt for [-INF, +INF].
1910 We learn nothing when we have INF on both sides.
1911 Note that we do accept [-INF, -INF] and [+INF, +INF]. */
1912 if (wi::eq_p (min, wi::min_value (TYPE_PRECISION (type), sgn))
1913 && wi::eq_p (max, wi::max_value (TYPE_PRECISION (type), sgn)))
1915 set_value_range_to_varying (vr);
1916 return;
1919 set_value_range (vr, rtype,
1920 wide_int_to_tree (type, min),
1921 wide_int_to_tree (type, max), NULL);
1924 /* Extract range information from a binary operation CODE based on
1925 the ranges of each of its operands *VR0 and *VR1 with resulting
1926 type EXPR_TYPE. The resulting range is stored in *VR. */
1928 static void
1929 extract_range_from_binary_expr_1 (value_range *vr,
1930 enum tree_code code, tree expr_type,
1931 value_range *vr0_, value_range *vr1_)
1933 value_range vr0 = *vr0_, vr1 = *vr1_;
1934 value_range vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
1935 enum value_range_type type;
1936 tree min = NULL_TREE, max = NULL_TREE;
1937 int cmp;
1939 if (!INTEGRAL_TYPE_P (expr_type)
1940 && !POINTER_TYPE_P (expr_type))
1942 set_value_range_to_varying (vr);
1943 return;
1946 /* Not all binary expressions can be applied to ranges in a
1947 meaningful way. Handle only arithmetic operations. */
1948 if (code != PLUS_EXPR
1949 && code != MINUS_EXPR
1950 && code != POINTER_PLUS_EXPR
1951 && code != MULT_EXPR
1952 && code != TRUNC_DIV_EXPR
1953 && code != FLOOR_DIV_EXPR
1954 && code != CEIL_DIV_EXPR
1955 && code != EXACT_DIV_EXPR
1956 && code != ROUND_DIV_EXPR
1957 && code != TRUNC_MOD_EXPR
1958 && code != RSHIFT_EXPR
1959 && code != LSHIFT_EXPR
1960 && code != MIN_EXPR
1961 && code != MAX_EXPR
1962 && code != BIT_AND_EXPR
1963 && code != BIT_IOR_EXPR
1964 && code != BIT_XOR_EXPR)
1966 set_value_range_to_varying (vr);
1967 return;
1970 /* If both ranges are UNDEFINED, so is the result. */
1971 if (vr0.type == VR_UNDEFINED && vr1.type == VR_UNDEFINED)
1973 set_value_range_to_undefined (vr);
1974 return;
1976 /* If one of the ranges is UNDEFINED drop it to VARYING for the following
1977 code. At some point we may want to special-case operations that
1978 have UNDEFINED result for all or some value-ranges of the not UNDEFINED
1979 operand. */
1980 else if (vr0.type == VR_UNDEFINED)
1981 set_value_range_to_varying (&vr0);
1982 else if (vr1.type == VR_UNDEFINED)
1983 set_value_range_to_varying (&vr1);
1985 /* We get imprecise results from ranges_from_anti_range when
1986 code is EXACT_DIV_EXPR. We could mask out bits in the resulting
1987 range, but then we also need to hack up vrp_meet. It's just
1988 easier to special case when vr0 is ~[0,0] for EXACT_DIV_EXPR. */
1989 if (code == EXACT_DIV_EXPR
1990 && vr0.type == VR_ANTI_RANGE
1991 && vr0.min == vr0.max
1992 && integer_zerop (vr0.min))
1994 set_value_range_to_nonnull (vr, expr_type);
1995 return;
1998 /* Now canonicalize anti-ranges to ranges when they are not symbolic
1999 and express ~[] op X as ([]' op X) U ([]'' op X). */
2000 if (vr0.type == VR_ANTI_RANGE
2001 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
2003 extract_range_from_binary_expr_1 (vr, code, expr_type, &vrtem0, vr1_);
2004 if (vrtem1.type != VR_UNDEFINED)
2006 value_range vrres = VR_INITIALIZER;
2007 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
2008 &vrtem1, vr1_);
2009 vrp_meet (vr, &vrres);
2011 return;
2013 /* Likewise for X op ~[]. */
2014 if (vr1.type == VR_ANTI_RANGE
2015 && ranges_from_anti_range (&vr1, &vrtem0, &vrtem1))
2017 extract_range_from_binary_expr_1 (vr, code, expr_type, vr0_, &vrtem0);
2018 if (vrtem1.type != VR_UNDEFINED)
2020 value_range vrres = VR_INITIALIZER;
2021 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
2022 vr0_, &vrtem1);
2023 vrp_meet (vr, &vrres);
2025 return;
2028 /* The type of the resulting value range defaults to VR0.TYPE. */
2029 type = vr0.type;
2031 /* Refuse to operate on VARYING ranges, ranges of different kinds
2032 and symbolic ranges. As an exception, we allow BIT_{AND,IOR}
2033 because we may be able to derive a useful range even if one of
2034 the operands is VR_VARYING or symbolic range. Similarly for
2035 divisions, MIN/MAX and PLUS/MINUS.
2037 TODO, we may be able to derive anti-ranges in some cases. */
2038 if (code != BIT_AND_EXPR
2039 && code != BIT_IOR_EXPR
2040 && code != TRUNC_DIV_EXPR
2041 && code != FLOOR_DIV_EXPR
2042 && code != CEIL_DIV_EXPR
2043 && code != EXACT_DIV_EXPR
2044 && code != ROUND_DIV_EXPR
2045 && code != TRUNC_MOD_EXPR
2046 && code != MIN_EXPR
2047 && code != MAX_EXPR
2048 && code != PLUS_EXPR
2049 && code != MINUS_EXPR
2050 && code != RSHIFT_EXPR
2051 && (vr0.type == VR_VARYING
2052 || vr1.type == VR_VARYING
2053 || vr0.type != vr1.type
2054 || symbolic_range_p (&vr0)
2055 || symbolic_range_p (&vr1)))
2057 set_value_range_to_varying (vr);
2058 return;
2061 /* Now evaluate the expression to determine the new range. */
2062 if (POINTER_TYPE_P (expr_type))
2064 if (code == MIN_EXPR || code == MAX_EXPR)
2066 /* For MIN/MAX expressions with pointers, we only care about
2067 nullness, if both are non null, then the result is nonnull.
2068 If both are null, then the result is null. Otherwise they
2069 are varying. */
2070 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
2071 set_value_range_to_nonnull (vr, expr_type);
2072 else if (range_is_null (&vr0) && range_is_null (&vr1))
2073 set_value_range_to_null (vr, expr_type);
2074 else
2075 set_value_range_to_varying (vr);
2077 else if (code == POINTER_PLUS_EXPR)
2079 /* For pointer types, we are really only interested in asserting
2080 whether the expression evaluates to non-NULL. */
2081 if (range_is_nonnull (&vr0) || range_is_nonnull (&vr1))
2082 set_value_range_to_nonnull (vr, expr_type);
2083 else if (range_is_null (&vr0) && range_is_null (&vr1))
2084 set_value_range_to_null (vr, expr_type);
2085 else
2086 set_value_range_to_varying (vr);
2088 else if (code == BIT_AND_EXPR)
2090 /* For pointer types, we are really only interested in asserting
2091 whether the expression evaluates to non-NULL. */
2092 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
2093 set_value_range_to_nonnull (vr, expr_type);
2094 else if (range_is_null (&vr0) || range_is_null (&vr1))
2095 set_value_range_to_null (vr, expr_type);
2096 else
2097 set_value_range_to_varying (vr);
2099 else
2100 set_value_range_to_varying (vr);
2102 return;
2105 /* For integer ranges, apply the operation to each end of the
2106 range and see what we end up with. */
2107 if (code == PLUS_EXPR || code == MINUS_EXPR)
2109 const bool minus_p = (code == MINUS_EXPR);
2110 tree min_op0 = vr0.min;
2111 tree min_op1 = minus_p ? vr1.max : vr1.min;
2112 tree max_op0 = vr0.max;
2113 tree max_op1 = minus_p ? vr1.min : vr1.max;
2114 tree sym_min_op0 = NULL_TREE;
2115 tree sym_min_op1 = NULL_TREE;
2116 tree sym_max_op0 = NULL_TREE;
2117 tree sym_max_op1 = NULL_TREE;
2118 bool neg_min_op0, neg_min_op1, neg_max_op0, neg_max_op1;
2120 /* If we have a PLUS or MINUS with two VR_RANGEs, either constant or
2121 single-symbolic ranges, try to compute the precise resulting range,
2122 but only if we know that this resulting range will also be constant
2123 or single-symbolic. */
2124 if (vr0.type == VR_RANGE && vr1.type == VR_RANGE
2125 && (TREE_CODE (min_op0) == INTEGER_CST
2126 || (sym_min_op0
2127 = get_single_symbol (min_op0, &neg_min_op0, &min_op0)))
2128 && (TREE_CODE (min_op1) == INTEGER_CST
2129 || (sym_min_op1
2130 = get_single_symbol (min_op1, &neg_min_op1, &min_op1)))
2131 && (!(sym_min_op0 && sym_min_op1)
2132 || (sym_min_op0 == sym_min_op1
2133 && neg_min_op0 == (minus_p ? neg_min_op1 : !neg_min_op1)))
2134 && (TREE_CODE (max_op0) == INTEGER_CST
2135 || (sym_max_op0
2136 = get_single_symbol (max_op0, &neg_max_op0, &max_op0)))
2137 && (TREE_CODE (max_op1) == INTEGER_CST
2138 || (sym_max_op1
2139 = get_single_symbol (max_op1, &neg_max_op1, &max_op1)))
2140 && (!(sym_max_op0 && sym_max_op1)
2141 || (sym_max_op0 == sym_max_op1
2142 && neg_max_op0 == (minus_p ? neg_max_op1 : !neg_max_op1))))
2144 const signop sgn = TYPE_SIGN (expr_type);
2145 const unsigned int prec = TYPE_PRECISION (expr_type);
2146 wide_int type_min, type_max, wmin, wmax;
2147 int min_ovf = 0;
2148 int max_ovf = 0;
2150 /* Get the lower and upper bounds of the type. */
2151 if (TYPE_OVERFLOW_WRAPS (expr_type))
2153 type_min = wi::min_value (prec, sgn);
2154 type_max = wi::max_value (prec, sgn);
2156 else
2158 type_min = wi::to_wide (vrp_val_min (expr_type));
2159 type_max = wi::to_wide (vrp_val_max (expr_type));
2162 /* Combine the lower bounds, if any. */
2163 if (min_op0 && min_op1)
2165 if (minus_p)
2167 wmin = wi::to_wide (min_op0) - wi::to_wide (min_op1);
2169 /* Check for overflow. */
2170 if (wi::cmp (0, wi::to_wide (min_op1), sgn)
2171 != wi::cmp (wmin, wi::to_wide (min_op0), sgn))
2172 min_ovf = wi::cmp (wi::to_wide (min_op0),
2173 wi::to_wide (min_op1), sgn);
2175 else
2177 wmin = wi::to_wide (min_op0) + wi::to_wide (min_op1);
2179 /* Check for overflow. */
2180 if (wi::cmp (wi::to_wide (min_op1), 0, sgn)
2181 != wi::cmp (wmin, wi::to_wide (min_op0), sgn))
2182 min_ovf = wi::cmp (wi::to_wide (min_op0), wmin, sgn);
2185 else if (min_op0)
2186 wmin = wi::to_wide (min_op0);
2187 else if (min_op1)
2189 if (minus_p)
2191 wmin = -wi::to_wide (min_op1);
2193 /* Check for overflow. */
2194 if (sgn == SIGNED
2195 && wi::neg_p (wi::to_wide (min_op1))
2196 && wi::neg_p (wmin))
2197 min_ovf = 1;
2198 else if (sgn == UNSIGNED && wi::to_wide (min_op1) != 0)
2199 min_ovf = -1;
2201 else
2202 wmin = wi::to_wide (min_op1);
2204 else
2205 wmin = wi::shwi (0, prec);
2207 /* Combine the upper bounds, if any. */
2208 if (max_op0 && max_op1)
2210 if (minus_p)
2212 wmax = wi::to_wide (max_op0) - wi::to_wide (max_op1);
2214 /* Check for overflow. */
2215 if (wi::cmp (0, wi::to_wide (max_op1), sgn)
2216 != wi::cmp (wmax, wi::to_wide (max_op0), sgn))
2217 max_ovf = wi::cmp (wi::to_wide (max_op0),
2218 wi::to_wide (max_op1), sgn);
2220 else
2222 wmax = wi::to_wide (max_op0) + wi::to_wide (max_op1);
2224 if (wi::cmp (wi::to_wide (max_op1), 0, sgn)
2225 != wi::cmp (wmax, wi::to_wide (max_op0), sgn))
2226 max_ovf = wi::cmp (wi::to_wide (max_op0), wmax, sgn);
2229 else if (max_op0)
2230 wmax = wi::to_wide (max_op0);
2231 else if (max_op1)
2233 if (minus_p)
2235 wmax = -wi::to_wide (max_op1);
2237 /* Check for overflow. */
2238 if (sgn == SIGNED
2239 && wi::neg_p (wi::to_wide (max_op1))
2240 && wi::neg_p (wmax))
2241 max_ovf = 1;
2242 else if (sgn == UNSIGNED && wi::to_wide (max_op1) != 0)
2243 max_ovf = -1;
2245 else
2246 wmax = wi::to_wide (max_op1);
2248 else
2249 wmax = wi::shwi (0, prec);
2251 /* Check for type overflow. */
2252 if (min_ovf == 0)
2254 if (wi::cmp (wmin, type_min, sgn) == -1)
2255 min_ovf = -1;
2256 else if (wi::cmp (wmin, type_max, sgn) == 1)
2257 min_ovf = 1;
2259 if (max_ovf == 0)
2261 if (wi::cmp (wmax, type_min, sgn) == -1)
2262 max_ovf = -1;
2263 else if (wi::cmp (wmax, type_max, sgn) == 1)
2264 max_ovf = 1;
2267 /* If we have overflow for the constant part and the resulting
2268 range will be symbolic, drop to VR_VARYING. */
2269 if ((min_ovf && sym_min_op0 != sym_min_op1)
2270 || (max_ovf && sym_max_op0 != sym_max_op1))
2272 set_value_range_to_varying (vr);
2273 return;
2276 if (TYPE_OVERFLOW_WRAPS (expr_type))
2278 /* If overflow wraps, truncate the values and adjust the
2279 range kind and bounds appropriately. */
2280 wide_int tmin = wide_int::from (wmin, prec, sgn);
2281 wide_int tmax = wide_int::from (wmax, prec, sgn);
2282 if (min_ovf == max_ovf)
2284 /* No overflow or both overflow or underflow. The
2285 range kind stays VR_RANGE. */
2286 min = wide_int_to_tree (expr_type, tmin);
2287 max = wide_int_to_tree (expr_type, tmax);
2289 else if ((min_ovf == -1 && max_ovf == 0)
2290 || (max_ovf == 1 && min_ovf == 0))
2292 /* Min underflow or max overflow. The range kind
2293 changes to VR_ANTI_RANGE. */
2294 bool covers = false;
2295 wide_int tem = tmin;
2296 type = VR_ANTI_RANGE;
2297 tmin = tmax + 1;
2298 if (wi::cmp (tmin, tmax, sgn) < 0)
2299 covers = true;
2300 tmax = tem - 1;
2301 if (wi::cmp (tmax, tem, sgn) > 0)
2302 covers = true;
2303 /* If the anti-range would cover nothing, drop to varying.
2304 Likewise if the anti-range bounds are outside of the
2305 types values. */
2306 if (covers || wi::cmp (tmin, tmax, sgn) > 0)
2308 set_value_range_to_varying (vr);
2309 return;
2311 min = wide_int_to_tree (expr_type, tmin);
2312 max = wide_int_to_tree (expr_type, tmax);
2314 else
2316 /* Other underflow and/or overflow, drop to VR_VARYING. */
2317 set_value_range_to_varying (vr);
2318 return;
2321 else
2323 /* If overflow does not wrap, saturate to the types min/max
2324 value. */
2325 if (min_ovf == -1)
2326 min = wide_int_to_tree (expr_type, type_min);
2327 else if (min_ovf == 1)
2328 min = wide_int_to_tree (expr_type, type_max);
2329 else
2330 min = wide_int_to_tree (expr_type, wmin);
2332 if (max_ovf == -1)
2333 max = wide_int_to_tree (expr_type, type_min);
2334 else if (max_ovf == 1)
2335 max = wide_int_to_tree (expr_type, type_max);
2336 else
2337 max = wide_int_to_tree (expr_type, wmax);
2340 /* If the result lower bound is constant, we're done;
2341 otherwise, build the symbolic lower bound. */
2342 if (sym_min_op0 == sym_min_op1)
2344 else if (sym_min_op0)
2345 min = build_symbolic_expr (expr_type, sym_min_op0,
2346 neg_min_op0, min);
2347 else if (sym_min_op1)
2349 /* We may not negate if that might introduce
2350 undefined overflow. */
2351 if (! minus_p
2352 || neg_min_op1
2353 || TYPE_OVERFLOW_WRAPS (expr_type))
2354 min = build_symbolic_expr (expr_type, sym_min_op1,
2355 neg_min_op1 ^ minus_p, min);
2356 else
2357 min = NULL_TREE;
2360 /* Likewise for the upper bound. */
2361 if (sym_max_op0 == sym_max_op1)
2363 else if (sym_max_op0)
2364 max = build_symbolic_expr (expr_type, sym_max_op0,
2365 neg_max_op0, max);
2366 else if (sym_max_op1)
2368 /* We may not negate if that might introduce
2369 undefined overflow. */
2370 if (! minus_p
2371 || neg_max_op1
2372 || TYPE_OVERFLOW_WRAPS (expr_type))
2373 max = build_symbolic_expr (expr_type, sym_max_op1,
2374 neg_max_op1 ^ minus_p, max);
2375 else
2376 max = NULL_TREE;
2379 else
2381 /* For other cases, for example if we have a PLUS_EXPR with two
2382 VR_ANTI_RANGEs, drop to VR_VARYING. It would take more effort
2383 to compute a precise range for such a case.
2384 ??? General even mixed range kind operations can be expressed
2385 by for example transforming ~[3, 5] + [1, 2] to range-only
2386 operations and a union primitive:
2387 [-INF, 2] + [1, 2] U [5, +INF] + [1, 2]
2388 [-INF+1, 4] U [6, +INF(OVF)]
2389 though usually the union is not exactly representable with
2390 a single range or anti-range as the above is
2391 [-INF+1, +INF(OVF)] intersected with ~[5, 5]
2392 but one could use a scheme similar to equivalences for this. */
2393 set_value_range_to_varying (vr);
2394 return;
2397 else if (code == MIN_EXPR
2398 || code == MAX_EXPR)
2400 if (vr0.type == VR_RANGE
2401 && !symbolic_range_p (&vr0))
2403 type = VR_RANGE;
2404 if (vr1.type == VR_RANGE
2405 && !symbolic_range_p (&vr1))
2407 /* For operations that make the resulting range directly
2408 proportional to the original ranges, apply the operation to
2409 the same end of each range. */
2410 min = int_const_binop (code, vr0.min, vr1.min);
2411 max = int_const_binop (code, vr0.max, vr1.max);
2413 else if (code == MIN_EXPR)
2415 min = vrp_val_min (expr_type);
2416 max = vr0.max;
2418 else if (code == MAX_EXPR)
2420 min = vr0.min;
2421 max = vrp_val_max (expr_type);
2424 else if (vr1.type == VR_RANGE
2425 && !symbolic_range_p (&vr1))
2427 type = VR_RANGE;
2428 if (code == MIN_EXPR)
2430 min = vrp_val_min (expr_type);
2431 max = vr1.max;
2433 else if (code == MAX_EXPR)
2435 min = vr1.min;
2436 max = vrp_val_max (expr_type);
2439 else
2441 set_value_range_to_varying (vr);
2442 return;
2445 else if (code == MULT_EXPR)
2447 /* Fancy code so that with unsigned, [-3,-1]*[-3,-1] does not
2448 drop to varying. This test requires 2*prec bits if both
2449 operands are signed and 2*prec + 2 bits if either is not. */
2451 signop sign = TYPE_SIGN (expr_type);
2452 unsigned int prec = TYPE_PRECISION (expr_type);
2454 if (!range_int_cst_p (&vr0)
2455 || !range_int_cst_p (&vr1))
2457 set_value_range_to_varying (vr);
2458 return;
2461 if (TYPE_OVERFLOW_WRAPS (expr_type))
2463 typedef FIXED_WIDE_INT (WIDE_INT_MAX_PRECISION * 2) vrp_int;
2464 typedef generic_wide_int
2465 <wi::extended_tree <WIDE_INT_MAX_PRECISION * 2> > vrp_int_cst;
2466 vrp_int sizem1 = wi::mask <vrp_int> (prec, false);
2467 vrp_int size = sizem1 + 1;
2469 /* Extend the values using the sign of the result to PREC2.
2470 From here on out, everthing is just signed math no matter
2471 what the input types were. */
2472 vrp_int min0 = vrp_int_cst (vr0.min);
2473 vrp_int max0 = vrp_int_cst (vr0.max);
2474 vrp_int min1 = vrp_int_cst (vr1.min);
2475 vrp_int max1 = vrp_int_cst (vr1.max);
2476 /* Canonicalize the intervals. */
2477 if (sign == UNSIGNED)
2479 if (wi::ltu_p (size, min0 + max0))
2481 min0 -= size;
2482 max0 -= size;
2485 if (wi::ltu_p (size, min1 + max1))
2487 min1 -= size;
2488 max1 -= size;
2492 vrp_int prod0 = min0 * min1;
2493 vrp_int prod1 = min0 * max1;
2494 vrp_int prod2 = max0 * min1;
2495 vrp_int prod3 = max0 * max1;
2497 /* Sort the 4 products so that min is in prod0 and max is in
2498 prod3. */
2499 /* min0min1 > max0max1 */
2500 if (prod0 > prod3)
2501 std::swap (prod0, prod3);
2503 /* min0max1 > max0min1 */
2504 if (prod1 > prod2)
2505 std::swap (prod1, prod2);
2507 if (prod0 > prod1)
2508 std::swap (prod0, prod1);
2510 if (prod2 > prod3)
2511 std::swap (prod2, prod3);
2513 /* diff = max - min. */
2514 prod2 = prod3 - prod0;
2515 if (wi::geu_p (prod2, sizem1))
2517 /* the range covers all values. */
2518 set_value_range_to_varying (vr);
2519 return;
2522 /* The following should handle the wrapping and selecting
2523 VR_ANTI_RANGE for us. */
2524 min = wide_int_to_tree (expr_type, prod0);
2525 max = wide_int_to_tree (expr_type, prod3);
2526 set_and_canonicalize_value_range (vr, VR_RANGE, min, max, NULL);
2527 return;
2530 /* If we have an unsigned MULT_EXPR with two VR_ANTI_RANGEs,
2531 drop to VR_VARYING. It would take more effort to compute a
2532 precise range for such a case. For example, if we have
2533 op0 == 65536 and op1 == 65536 with their ranges both being
2534 ~[0,0] on a 32-bit machine, we would have op0 * op1 == 0, so
2535 we cannot claim that the product is in ~[0,0]. Note that we
2536 are guaranteed to have vr0.type == vr1.type at this
2537 point. */
2538 if (vr0.type == VR_ANTI_RANGE
2539 && !TYPE_OVERFLOW_UNDEFINED (expr_type))
2541 set_value_range_to_varying (vr);
2542 return;
2545 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2546 return;
2548 else if (code == RSHIFT_EXPR
2549 || code == LSHIFT_EXPR)
2551 /* If we have a RSHIFT_EXPR with any shift values outside [0..prec-1],
2552 then drop to VR_VARYING. Outside of this range we get undefined
2553 behavior from the shift operation. We cannot even trust
2554 SHIFT_COUNT_TRUNCATED at this stage, because that applies to rtl
2555 shifts, and the operation at the tree level may be widened. */
2556 if (range_int_cst_p (&vr1)
2557 && compare_tree_int (vr1.min, 0) >= 0
2558 && compare_tree_int (vr1.max, TYPE_PRECISION (expr_type)) == -1)
2560 if (code == RSHIFT_EXPR)
2562 /* Even if vr0 is VARYING or otherwise not usable, we can derive
2563 useful ranges just from the shift count. E.g.
2564 x >> 63 for signed 64-bit x is always [-1, 0]. */
2565 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
2567 vr0.type = type = VR_RANGE;
2568 vr0.min = vrp_val_min (expr_type);
2569 vr0.max = vrp_val_max (expr_type);
2571 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2572 return;
2574 /* We can map lshifts by constants to MULT_EXPR handling. */
2575 else if (code == LSHIFT_EXPR
2576 && range_int_cst_singleton_p (&vr1))
2578 bool saved_flag_wrapv;
2579 value_range vr1p = VR_INITIALIZER;
2580 vr1p.type = VR_RANGE;
2581 vr1p.min = (wide_int_to_tree
2582 (expr_type,
2583 wi::set_bit_in_zero (tree_to_shwi (vr1.min),
2584 TYPE_PRECISION (expr_type))));
2585 vr1p.max = vr1p.min;
2586 /* We have to use a wrapping multiply though as signed overflow
2587 on lshifts is implementation defined in C89. */
2588 saved_flag_wrapv = flag_wrapv;
2589 flag_wrapv = 1;
2590 extract_range_from_binary_expr_1 (vr, MULT_EXPR, expr_type,
2591 &vr0, &vr1p);
2592 flag_wrapv = saved_flag_wrapv;
2593 return;
2595 else if (code == LSHIFT_EXPR
2596 && range_int_cst_p (&vr0))
2598 int prec = TYPE_PRECISION (expr_type);
2599 int overflow_pos = prec;
2600 int bound_shift;
2601 wide_int low_bound, high_bound;
2602 bool uns = TYPE_UNSIGNED (expr_type);
2603 bool in_bounds = false;
2605 if (!uns)
2606 overflow_pos -= 1;
2608 bound_shift = overflow_pos - tree_to_shwi (vr1.max);
2609 /* If bound_shift == HOST_BITS_PER_WIDE_INT, the llshift can
2610 overflow. However, for that to happen, vr1.max needs to be
2611 zero, which means vr1 is a singleton range of zero, which
2612 means it should be handled by the previous LSHIFT_EXPR
2613 if-clause. */
2614 wide_int bound = wi::set_bit_in_zero (bound_shift, prec);
2615 wide_int complement = ~(bound - 1);
2617 if (uns)
2619 low_bound = bound;
2620 high_bound = complement;
2621 if (wi::ltu_p (wi::to_wide (vr0.max), low_bound))
2623 /* [5, 6] << [1, 2] == [10, 24]. */
2624 /* We're shifting out only zeroes, the value increases
2625 monotonically. */
2626 in_bounds = true;
2628 else if (wi::ltu_p (high_bound, wi::to_wide (vr0.min)))
2630 /* [0xffffff00, 0xffffffff] << [1, 2]
2631 == [0xfffffc00, 0xfffffffe]. */
2632 /* We're shifting out only ones, the value decreases
2633 monotonically. */
2634 in_bounds = true;
2637 else
2639 /* [-1, 1] << [1, 2] == [-4, 4]. */
2640 low_bound = complement;
2641 high_bound = bound;
2642 if (wi::lts_p (wi::to_wide (vr0.max), high_bound)
2643 && wi::lts_p (low_bound, wi::to_wide (vr0.min)))
2645 /* For non-negative numbers, we're shifting out only
2646 zeroes, the value increases monotonically.
2647 For negative numbers, we're shifting out only ones, the
2648 value decreases monotomically. */
2649 in_bounds = true;
2653 if (in_bounds)
2655 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2656 return;
2660 set_value_range_to_varying (vr);
2661 return;
2663 else if (code == TRUNC_DIV_EXPR
2664 || code == FLOOR_DIV_EXPR
2665 || code == CEIL_DIV_EXPR
2666 || code == EXACT_DIV_EXPR
2667 || code == ROUND_DIV_EXPR)
2669 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
2671 /* For division, if op1 has VR_RANGE but op0 does not, something
2672 can be deduced just from that range. Say [min, max] / [4, max]
2673 gives [min / 4, max / 4] range. */
2674 if (vr1.type == VR_RANGE
2675 && !symbolic_range_p (&vr1)
2676 && range_includes_zero_p (vr1.min, vr1.max) == 0)
2678 vr0.type = type = VR_RANGE;
2679 vr0.min = vrp_val_min (expr_type);
2680 vr0.max = vrp_val_max (expr_type);
2682 else
2684 set_value_range_to_varying (vr);
2685 return;
2689 /* For divisions, if flag_non_call_exceptions is true, we must
2690 not eliminate a division by zero. */
2691 if (cfun->can_throw_non_call_exceptions
2692 && (vr1.type != VR_RANGE
2693 || range_includes_zero_p (vr1.min, vr1.max) != 0))
2695 set_value_range_to_varying (vr);
2696 return;
2699 /* For divisions, if op0 is VR_RANGE, we can deduce a range
2700 even if op1 is VR_VARYING, VR_ANTI_RANGE, symbolic or can
2701 include 0. */
2702 if (vr0.type == VR_RANGE
2703 && (vr1.type != VR_RANGE
2704 || range_includes_zero_p (vr1.min, vr1.max) != 0))
2706 tree zero = build_int_cst (TREE_TYPE (vr0.min), 0);
2707 int cmp;
2709 min = NULL_TREE;
2710 max = NULL_TREE;
2711 if (TYPE_UNSIGNED (expr_type)
2712 || value_range_nonnegative_p (&vr1))
2714 /* For unsigned division or when divisor is known
2715 to be non-negative, the range has to cover
2716 all numbers from 0 to max for positive max
2717 and all numbers from min to 0 for negative min. */
2718 cmp = compare_values (vr0.max, zero);
2719 if (cmp == -1)
2721 /* When vr0.max < 0, vr1.min != 0 and value
2722 ranges for dividend and divisor are available. */
2723 if (vr1.type == VR_RANGE
2724 && !symbolic_range_p (&vr0)
2725 && !symbolic_range_p (&vr1)
2726 && compare_values (vr1.min, zero) != 0)
2727 max = int_const_binop (code, vr0.max, vr1.min);
2728 else
2729 max = zero;
2731 else if (cmp == 0 || cmp == 1)
2732 max = vr0.max;
2733 else
2734 type = VR_VARYING;
2735 cmp = compare_values (vr0.min, zero);
2736 if (cmp == 1)
2738 /* For unsigned division when value ranges for dividend
2739 and divisor are available. */
2740 if (vr1.type == VR_RANGE
2741 && !symbolic_range_p (&vr0)
2742 && !symbolic_range_p (&vr1)
2743 && compare_values (vr1.max, zero) != 0)
2744 min = int_const_binop (code, vr0.min, vr1.max);
2745 else
2746 min = zero;
2748 else if (cmp == 0 || cmp == -1)
2749 min = vr0.min;
2750 else
2751 type = VR_VARYING;
2753 else
2755 /* Otherwise the range is -max .. max or min .. -min
2756 depending on which bound is bigger in absolute value,
2757 as the division can change the sign. */
2758 abs_extent_range (vr, vr0.min, vr0.max);
2759 return;
2761 if (type == VR_VARYING)
2763 set_value_range_to_varying (vr);
2764 return;
2767 else if (!symbolic_range_p (&vr0) && !symbolic_range_p (&vr1))
2769 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2770 return;
2773 else if (code == TRUNC_MOD_EXPR)
2775 if (range_is_null (&vr1))
2777 set_value_range_to_undefined (vr);
2778 return;
2780 /* ABS (A % B) < ABS (B) and either
2781 0 <= A % B <= A or A <= A % B <= 0. */
2782 type = VR_RANGE;
2783 signop sgn = TYPE_SIGN (expr_type);
2784 unsigned int prec = TYPE_PRECISION (expr_type);
2785 wide_int wmin, wmax, tmp;
2786 if (vr1.type == VR_RANGE && !symbolic_range_p (&vr1))
2788 wmax = wi::to_wide (vr1.max) - 1;
2789 if (sgn == SIGNED)
2791 tmp = -1 - wi::to_wide (vr1.min);
2792 wmax = wi::smax (wmax, tmp);
2795 else
2797 wmax = wi::max_value (prec, sgn);
2798 /* X % INT_MIN may be INT_MAX. */
2799 if (sgn == UNSIGNED)
2800 wmax = wmax - 1;
2803 if (sgn == UNSIGNED)
2804 wmin = wi::zero (prec);
2805 else
2807 wmin = -wmax;
2808 if (vr0.type == VR_RANGE && TREE_CODE (vr0.min) == INTEGER_CST)
2810 tmp = wi::to_wide (vr0.min);
2811 if (wi::gts_p (tmp, 0))
2812 tmp = wi::zero (prec);
2813 wmin = wi::smax (wmin, tmp);
2817 if (vr0.type == VR_RANGE && TREE_CODE (vr0.max) == INTEGER_CST)
2819 tmp = wi::to_wide (vr0.max);
2820 if (sgn == SIGNED && wi::neg_p (tmp))
2821 tmp = wi::zero (prec);
2822 wmax = wi::min (wmax, tmp, sgn);
2825 min = wide_int_to_tree (expr_type, wmin);
2826 max = wide_int_to_tree (expr_type, wmax);
2828 else if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR || code == BIT_XOR_EXPR)
2830 bool int_cst_range0, int_cst_range1;
2831 wide_int may_be_nonzero0, may_be_nonzero1;
2832 wide_int must_be_nonzero0, must_be_nonzero1;
2834 int_cst_range0 = zero_nonzero_bits_from_vr (expr_type, &vr0,
2835 &may_be_nonzero0,
2836 &must_be_nonzero0);
2837 int_cst_range1 = zero_nonzero_bits_from_vr (expr_type, &vr1,
2838 &may_be_nonzero1,
2839 &must_be_nonzero1);
2841 if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR)
2843 value_range *vr0p = NULL, *vr1p = NULL;
2844 if (range_int_cst_singleton_p (&vr1))
2846 vr0p = &vr0;
2847 vr1p = &vr1;
2849 else if (range_int_cst_singleton_p (&vr0))
2851 vr0p = &vr1;
2852 vr1p = &vr0;
2854 /* For op & or | attempt to optimize:
2855 [x, y] op z into [x op z, y op z]
2856 if z is a constant which (for op | its bitwise not) has n
2857 consecutive least significant bits cleared followed by m 1
2858 consecutive bits set immediately above it and either
2859 m + n == precision, or (x >> (m + n)) == (y >> (m + n)).
2860 The least significant n bits of all the values in the range are
2861 cleared or set, the m bits above it are preserved and any bits
2862 above these are required to be the same for all values in the
2863 range. */
2864 if (vr0p && range_int_cst_p (vr0p))
2866 wide_int w = wi::to_wide (vr1p->min);
2867 int m = 0, n = 0;
2868 if (code == BIT_IOR_EXPR)
2869 w = ~w;
2870 if (wi::eq_p (w, 0))
2871 n = TYPE_PRECISION (expr_type);
2872 else
2874 n = wi::ctz (w);
2875 w = ~(w | wi::mask (n, false, w.get_precision ()));
2876 if (wi::eq_p (w, 0))
2877 m = TYPE_PRECISION (expr_type) - n;
2878 else
2879 m = wi::ctz (w) - n;
2881 wide_int mask = wi::mask (m + n, true, w.get_precision ());
2882 if ((mask & wi::to_wide (vr0p->min))
2883 == (mask & wi::to_wide (vr0p->max)))
2885 min = int_const_binop (code, vr0p->min, vr1p->min);
2886 max = int_const_binop (code, vr0p->max, vr1p->min);
2891 type = VR_RANGE;
2892 if (min && max)
2893 /* Optimized above already. */;
2894 else if (code == BIT_AND_EXPR)
2896 min = wide_int_to_tree (expr_type,
2897 must_be_nonzero0 & must_be_nonzero1);
2898 wide_int wmax = may_be_nonzero0 & may_be_nonzero1;
2899 /* If both input ranges contain only negative values we can
2900 truncate the result range maximum to the minimum of the
2901 input range maxima. */
2902 if (int_cst_range0 && int_cst_range1
2903 && tree_int_cst_sgn (vr0.max) < 0
2904 && tree_int_cst_sgn (vr1.max) < 0)
2906 wmax = wi::min (wmax, wi::to_wide (vr0.max),
2907 TYPE_SIGN (expr_type));
2908 wmax = wi::min (wmax, wi::to_wide (vr1.max),
2909 TYPE_SIGN (expr_type));
2911 /* If either input range contains only non-negative values
2912 we can truncate the result range maximum to the respective
2913 maximum of the input range. */
2914 if (int_cst_range0 && tree_int_cst_sgn (vr0.min) >= 0)
2915 wmax = wi::min (wmax, wi::to_wide (vr0.max),
2916 TYPE_SIGN (expr_type));
2917 if (int_cst_range1 && tree_int_cst_sgn (vr1.min) >= 0)
2918 wmax = wi::min (wmax, wi::to_wide (vr1.max),
2919 TYPE_SIGN (expr_type));
2920 max = wide_int_to_tree (expr_type, wmax);
2921 cmp = compare_values (min, max);
2922 /* PR68217: In case of signed & sign-bit-CST should
2923 result in [-INF, 0] instead of [-INF, INF]. */
2924 if (cmp == -2 || cmp == 1)
2926 wide_int sign_bit
2927 = wi::set_bit_in_zero (TYPE_PRECISION (expr_type) - 1,
2928 TYPE_PRECISION (expr_type));
2929 if (!TYPE_UNSIGNED (expr_type)
2930 && ((int_cst_range0
2931 && value_range_constant_singleton (&vr0)
2932 && !wi::cmps (wi::to_wide (vr0.min), sign_bit))
2933 || (int_cst_range1
2934 && value_range_constant_singleton (&vr1)
2935 && !wi::cmps (wi::to_wide (vr1.min), sign_bit))))
2937 min = TYPE_MIN_VALUE (expr_type);
2938 max = build_int_cst (expr_type, 0);
2942 else if (code == BIT_IOR_EXPR)
2944 max = wide_int_to_tree (expr_type,
2945 may_be_nonzero0 | may_be_nonzero1);
2946 wide_int wmin = must_be_nonzero0 | must_be_nonzero1;
2947 /* If the input ranges contain only positive values we can
2948 truncate the minimum of the result range to the maximum
2949 of the input range minima. */
2950 if (int_cst_range0 && int_cst_range1
2951 && tree_int_cst_sgn (vr0.min) >= 0
2952 && tree_int_cst_sgn (vr1.min) >= 0)
2954 wmin = wi::max (wmin, wi::to_wide (vr0.min),
2955 TYPE_SIGN (expr_type));
2956 wmin = wi::max (wmin, wi::to_wide (vr1.min),
2957 TYPE_SIGN (expr_type));
2959 /* If either input range contains only negative values
2960 we can truncate the minimum of the result range to the
2961 respective minimum range. */
2962 if (int_cst_range0 && tree_int_cst_sgn (vr0.max) < 0)
2963 wmin = wi::max (wmin, wi::to_wide (vr0.min),
2964 TYPE_SIGN (expr_type));
2965 if (int_cst_range1 && tree_int_cst_sgn (vr1.max) < 0)
2966 wmin = wi::max (wmin, wi::to_wide (vr1.min),
2967 TYPE_SIGN (expr_type));
2968 min = wide_int_to_tree (expr_type, wmin);
2970 else if (code == BIT_XOR_EXPR)
2972 wide_int result_zero_bits = ((must_be_nonzero0 & must_be_nonzero1)
2973 | ~(may_be_nonzero0 | may_be_nonzero1));
2974 wide_int result_one_bits
2975 = (wi::bit_and_not (must_be_nonzero0, may_be_nonzero1)
2976 | wi::bit_and_not (must_be_nonzero1, may_be_nonzero0));
2977 max = wide_int_to_tree (expr_type, ~result_zero_bits);
2978 min = wide_int_to_tree (expr_type, result_one_bits);
2979 /* If the range has all positive or all negative values the
2980 result is better than VARYING. */
2981 if (tree_int_cst_sgn (min) < 0
2982 || tree_int_cst_sgn (max) >= 0)
2984 else
2985 max = min = NULL_TREE;
2988 else
2989 gcc_unreachable ();
2991 /* If either MIN or MAX overflowed, then set the resulting range to
2992 VARYING. */
2993 if (min == NULL_TREE
2994 || TREE_OVERFLOW_P (min)
2995 || max == NULL_TREE
2996 || TREE_OVERFLOW_P (max))
2998 set_value_range_to_varying (vr);
2999 return;
3002 /* We punt for [-INF, +INF].
3003 We learn nothing when we have INF on both sides.
3004 Note that we do accept [-INF, -INF] and [+INF, +INF]. */
3005 if (vrp_val_is_min (min) && vrp_val_is_max (max))
3007 set_value_range_to_varying (vr);
3008 return;
3011 cmp = compare_values (min, max);
3012 if (cmp == -2 || cmp == 1)
3014 /* If the new range has its limits swapped around (MIN > MAX),
3015 then the operation caused one of them to wrap around, mark
3016 the new range VARYING. */
3017 set_value_range_to_varying (vr);
3019 else
3020 set_value_range (vr, type, min, max, NULL);
3023 /* Extract range information from a binary expression OP0 CODE OP1 based on
3024 the ranges of each of its operands with resulting type EXPR_TYPE.
3025 The resulting range is stored in *VR. */
3027 static void
3028 extract_range_from_binary_expr (value_range *vr,
3029 enum tree_code code,
3030 tree expr_type, tree op0, tree op1)
3032 value_range vr0 = VR_INITIALIZER;
3033 value_range vr1 = VR_INITIALIZER;
3035 /* Get value ranges for each operand. For constant operands, create
3036 a new value range with the operand to simplify processing. */
3037 if (TREE_CODE (op0) == SSA_NAME)
3038 vr0 = *(get_value_range (op0));
3039 else if (is_gimple_min_invariant (op0))
3040 set_value_range_to_value (&vr0, op0, NULL);
3041 else
3042 set_value_range_to_varying (&vr0);
3044 if (TREE_CODE (op1) == SSA_NAME)
3045 vr1 = *(get_value_range (op1));
3046 else if (is_gimple_min_invariant (op1))
3047 set_value_range_to_value (&vr1, op1, NULL);
3048 else
3049 set_value_range_to_varying (&vr1);
3051 extract_range_from_binary_expr_1 (vr, code, expr_type, &vr0, &vr1);
3053 /* Try harder for PLUS and MINUS if the range of one operand is symbolic
3054 and based on the other operand, for example if it was deduced from a
3055 symbolic comparison. When a bound of the range of the first operand
3056 is invariant, we set the corresponding bound of the new range to INF
3057 in order to avoid recursing on the range of the second operand. */
3058 if (vr->type == VR_VARYING
3059 && (code == PLUS_EXPR || code == MINUS_EXPR)
3060 && TREE_CODE (op1) == SSA_NAME
3061 && vr0.type == VR_RANGE
3062 && symbolic_range_based_on_p (&vr0, op1))
3064 const bool minus_p = (code == MINUS_EXPR);
3065 value_range n_vr1 = VR_INITIALIZER;
3067 /* Try with VR0 and [-INF, OP1]. */
3068 if (is_gimple_min_invariant (minus_p ? vr0.max : vr0.min))
3069 set_value_range (&n_vr1, VR_RANGE, vrp_val_min (expr_type), op1, NULL);
3071 /* Try with VR0 and [OP1, +INF]. */
3072 else if (is_gimple_min_invariant (minus_p ? vr0.min : vr0.max))
3073 set_value_range (&n_vr1, VR_RANGE, op1, vrp_val_max (expr_type), NULL);
3075 /* Try with VR0 and [OP1, OP1]. */
3076 else
3077 set_value_range (&n_vr1, VR_RANGE, op1, op1, NULL);
3079 extract_range_from_binary_expr_1 (vr, code, expr_type, &vr0, &n_vr1);
3082 if (vr->type == VR_VARYING
3083 && (code == PLUS_EXPR || code == MINUS_EXPR)
3084 && TREE_CODE (op0) == SSA_NAME
3085 && vr1.type == VR_RANGE
3086 && symbolic_range_based_on_p (&vr1, op0))
3088 const bool minus_p = (code == MINUS_EXPR);
3089 value_range n_vr0 = VR_INITIALIZER;
3091 /* Try with [-INF, OP0] and VR1. */
3092 if (is_gimple_min_invariant (minus_p ? vr1.max : vr1.min))
3093 set_value_range (&n_vr0, VR_RANGE, vrp_val_min (expr_type), op0, NULL);
3095 /* Try with [OP0, +INF] and VR1. */
3096 else if (is_gimple_min_invariant (minus_p ? vr1.min : vr1.max))
3097 set_value_range (&n_vr0, VR_RANGE, op0, vrp_val_max (expr_type), NULL);
3099 /* Try with [OP0, OP0] and VR1. */
3100 else
3101 set_value_range (&n_vr0, VR_RANGE, op0, op0, NULL);
3103 extract_range_from_binary_expr_1 (vr, code, expr_type, &n_vr0, &vr1);
3106 /* If we didn't derive a range for MINUS_EXPR, and
3107 op1's range is ~[op0,op0] or vice-versa, then we
3108 can derive a non-null range. This happens often for
3109 pointer subtraction. */
3110 if (vr->type == VR_VARYING
3111 && code == MINUS_EXPR
3112 && TREE_CODE (op0) == SSA_NAME
3113 && ((vr0.type == VR_ANTI_RANGE
3114 && vr0.min == op1
3115 && vr0.min == vr0.max)
3116 || (vr1.type == VR_ANTI_RANGE
3117 && vr1.min == op0
3118 && vr1.min == vr1.max)))
3119 set_value_range_to_nonnull (vr, TREE_TYPE (op0));
3122 /* Extract range information from a unary operation CODE based on
3123 the range of its operand *VR0 with type OP0_TYPE with resulting type TYPE.
3124 The resulting range is stored in *VR. */
3126 void
3127 extract_range_from_unary_expr (value_range *vr,
3128 enum tree_code code, tree type,
3129 value_range *vr0_, tree op0_type)
3131 value_range vr0 = *vr0_, vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
3133 /* VRP only operates on integral and pointer types. */
3134 if (!(INTEGRAL_TYPE_P (op0_type)
3135 || POINTER_TYPE_P (op0_type))
3136 || !(INTEGRAL_TYPE_P (type)
3137 || POINTER_TYPE_P (type)))
3139 set_value_range_to_varying (vr);
3140 return;
3143 /* If VR0 is UNDEFINED, so is the result. */
3144 if (vr0.type == VR_UNDEFINED)
3146 set_value_range_to_undefined (vr);
3147 return;
3150 /* Handle operations that we express in terms of others. */
3151 if (code == PAREN_EXPR || code == OBJ_TYPE_REF)
3153 /* PAREN_EXPR and OBJ_TYPE_REF are simple copies. */
3154 copy_value_range (vr, &vr0);
3155 return;
3157 else if (code == NEGATE_EXPR)
3159 /* -X is simply 0 - X, so re-use existing code that also handles
3160 anti-ranges fine. */
3161 value_range zero = VR_INITIALIZER;
3162 set_value_range_to_value (&zero, build_int_cst (type, 0), NULL);
3163 extract_range_from_binary_expr_1 (vr, MINUS_EXPR, type, &zero, &vr0);
3164 return;
3166 else if (code == BIT_NOT_EXPR)
3168 /* ~X is simply -1 - X, so re-use existing code that also handles
3169 anti-ranges fine. */
3170 value_range minusone = VR_INITIALIZER;
3171 set_value_range_to_value (&minusone, build_int_cst (type, -1), NULL);
3172 extract_range_from_binary_expr_1 (vr, MINUS_EXPR,
3173 type, &minusone, &vr0);
3174 return;
3177 /* Now canonicalize anti-ranges to ranges when they are not symbolic
3178 and express op ~[] as (op []') U (op []''). */
3179 if (vr0.type == VR_ANTI_RANGE
3180 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
3182 extract_range_from_unary_expr (vr, code, type, &vrtem0, op0_type);
3183 if (vrtem1.type != VR_UNDEFINED)
3185 value_range vrres = VR_INITIALIZER;
3186 extract_range_from_unary_expr (&vrres, code, type,
3187 &vrtem1, op0_type);
3188 vrp_meet (vr, &vrres);
3190 return;
3193 if (CONVERT_EXPR_CODE_P (code))
3195 tree inner_type = op0_type;
3196 tree outer_type = type;
3198 /* If the expression evaluates to a pointer, we are only interested in
3199 determining if it evaluates to NULL [0, 0] or non-NULL (~[0, 0]). */
3200 if (POINTER_TYPE_P (type))
3202 if (range_is_nonnull (&vr0))
3203 set_value_range_to_nonnull (vr, type);
3204 else if (range_is_null (&vr0))
3205 set_value_range_to_null (vr, type);
3206 else
3207 set_value_range_to_varying (vr);
3208 return;
3211 /* If VR0 is varying and we increase the type precision, assume
3212 a full range for the following transformation. */
3213 if (vr0.type == VR_VARYING
3214 && INTEGRAL_TYPE_P (inner_type)
3215 && TYPE_PRECISION (inner_type) < TYPE_PRECISION (outer_type))
3217 vr0.type = VR_RANGE;
3218 vr0.min = TYPE_MIN_VALUE (inner_type);
3219 vr0.max = TYPE_MAX_VALUE (inner_type);
3222 /* If VR0 is a constant range or anti-range and the conversion is
3223 not truncating we can convert the min and max values and
3224 canonicalize the resulting range. Otherwise we can do the
3225 conversion if the size of the range is less than what the
3226 precision of the target type can represent and the range is
3227 not an anti-range. */
3228 if ((vr0.type == VR_RANGE
3229 || vr0.type == VR_ANTI_RANGE)
3230 && TREE_CODE (vr0.min) == INTEGER_CST
3231 && TREE_CODE (vr0.max) == INTEGER_CST
3232 && (TYPE_PRECISION (outer_type) >= TYPE_PRECISION (inner_type)
3233 || (vr0.type == VR_RANGE
3234 && integer_zerop (int_const_binop (RSHIFT_EXPR,
3235 int_const_binop (MINUS_EXPR, vr0.max, vr0.min),
3236 size_int (TYPE_PRECISION (outer_type)))))))
3238 tree new_min, new_max;
3239 new_min = force_fit_type (outer_type, wi::to_widest (vr0.min),
3240 0, false);
3241 new_max = force_fit_type (outer_type, wi::to_widest (vr0.max),
3242 0, false);
3243 set_and_canonicalize_value_range (vr, vr0.type,
3244 new_min, new_max, NULL);
3245 return;
3248 set_value_range_to_varying (vr);
3249 return;
3251 else if (code == ABS_EXPR)
3253 tree min, max;
3254 int cmp;
3256 /* Pass through vr0 in the easy cases. */
3257 if (TYPE_UNSIGNED (type)
3258 || value_range_nonnegative_p (&vr0))
3260 copy_value_range (vr, &vr0);
3261 return;
3264 /* For the remaining varying or symbolic ranges we can't do anything
3265 useful. */
3266 if (vr0.type == VR_VARYING
3267 || symbolic_range_p (&vr0))
3269 set_value_range_to_varying (vr);
3270 return;
3273 /* -TYPE_MIN_VALUE = TYPE_MIN_VALUE with flag_wrapv so we can't get a
3274 useful range. */
3275 if (!TYPE_OVERFLOW_UNDEFINED (type)
3276 && ((vr0.type == VR_RANGE
3277 && vrp_val_is_min (vr0.min))
3278 || (vr0.type == VR_ANTI_RANGE
3279 && !vrp_val_is_min (vr0.min))))
3281 set_value_range_to_varying (vr);
3282 return;
3285 /* ABS_EXPR may flip the range around, if the original range
3286 included negative values. */
3287 if (!vrp_val_is_min (vr0.min))
3288 min = fold_unary_to_constant (code, type, vr0.min);
3289 else
3290 min = TYPE_MAX_VALUE (type);
3292 if (!vrp_val_is_min (vr0.max))
3293 max = fold_unary_to_constant (code, type, vr0.max);
3294 else
3295 max = TYPE_MAX_VALUE (type);
3297 cmp = compare_values (min, max);
3299 /* If a VR_ANTI_RANGEs contains zero, then we have
3300 ~[-INF, min(MIN, MAX)]. */
3301 if (vr0.type == VR_ANTI_RANGE)
3303 if (range_includes_zero_p (vr0.min, vr0.max) == 1)
3305 /* Take the lower of the two values. */
3306 if (cmp != 1)
3307 max = min;
3309 /* Create ~[-INF, min (abs(MIN), abs(MAX))]
3310 or ~[-INF + 1, min (abs(MIN), abs(MAX))] when
3311 flag_wrapv is set and the original anti-range doesn't include
3312 TYPE_MIN_VALUE, remember -TYPE_MIN_VALUE = TYPE_MIN_VALUE. */
3313 if (TYPE_OVERFLOW_WRAPS (type))
3315 tree type_min_value = TYPE_MIN_VALUE (type);
3317 min = (vr0.min != type_min_value
3318 ? int_const_binop (PLUS_EXPR, type_min_value,
3319 build_int_cst (TREE_TYPE (type_min_value), 1))
3320 : type_min_value);
3322 else
3323 min = TYPE_MIN_VALUE (type);
3325 else
3327 /* All else has failed, so create the range [0, INF], even for
3328 flag_wrapv since TYPE_MIN_VALUE is in the original
3329 anti-range. */
3330 vr0.type = VR_RANGE;
3331 min = build_int_cst (type, 0);
3332 max = TYPE_MAX_VALUE (type);
3336 /* If the range contains zero then we know that the minimum value in the
3337 range will be zero. */
3338 else if (range_includes_zero_p (vr0.min, vr0.max) == 1)
3340 if (cmp == 1)
3341 max = min;
3342 min = build_int_cst (type, 0);
3344 else
3346 /* If the range was reversed, swap MIN and MAX. */
3347 if (cmp == 1)
3348 std::swap (min, max);
3351 cmp = compare_values (min, max);
3352 if (cmp == -2 || cmp == 1)
3354 /* If the new range has its limits swapped around (MIN > MAX),
3355 then the operation caused one of them to wrap around, mark
3356 the new range VARYING. */
3357 set_value_range_to_varying (vr);
3359 else
3360 set_value_range (vr, vr0.type, min, max, NULL);
3361 return;
3364 /* For unhandled operations fall back to varying. */
3365 set_value_range_to_varying (vr);
3366 return;
3370 /* Extract range information from a unary expression CODE OP0 based on
3371 the range of its operand with resulting type TYPE.
3372 The resulting range is stored in *VR. */
3374 static void
3375 extract_range_from_unary_expr (value_range *vr, enum tree_code code,
3376 tree type, tree op0)
3378 value_range vr0 = VR_INITIALIZER;
3380 /* Get value ranges for the operand. For constant operands, create
3381 a new value range with the operand to simplify processing. */
3382 if (TREE_CODE (op0) == SSA_NAME)
3383 vr0 = *(get_value_range (op0));
3384 else if (is_gimple_min_invariant (op0))
3385 set_value_range_to_value (&vr0, op0, NULL);
3386 else
3387 set_value_range_to_varying (&vr0);
3389 extract_range_from_unary_expr (vr, code, type, &vr0, TREE_TYPE (op0));
3393 /* Extract range information from a conditional expression STMT based on
3394 the ranges of each of its operands and the expression code. */
3396 static void
3397 extract_range_from_cond_expr (value_range *vr, gassign *stmt)
3399 tree op0, op1;
3400 value_range vr0 = VR_INITIALIZER;
3401 value_range vr1 = VR_INITIALIZER;
3403 /* Get value ranges for each operand. For constant operands, create
3404 a new value range with the operand to simplify processing. */
3405 op0 = gimple_assign_rhs2 (stmt);
3406 if (TREE_CODE (op0) == SSA_NAME)
3407 vr0 = *(get_value_range (op0));
3408 else if (is_gimple_min_invariant (op0))
3409 set_value_range_to_value (&vr0, op0, NULL);
3410 else
3411 set_value_range_to_varying (&vr0);
3413 op1 = gimple_assign_rhs3 (stmt);
3414 if (TREE_CODE (op1) == SSA_NAME)
3415 vr1 = *(get_value_range (op1));
3416 else if (is_gimple_min_invariant (op1))
3417 set_value_range_to_value (&vr1, op1, NULL);
3418 else
3419 set_value_range_to_varying (&vr1);
3421 /* The resulting value range is the union of the operand ranges */
3422 copy_value_range (vr, &vr0);
3423 vrp_meet (vr, &vr1);
3427 /* Extract range information from a comparison expression EXPR based
3428 on the range of its operand and the expression code. */
3430 static void
3431 extract_range_from_comparison (value_range *vr, enum tree_code code,
3432 tree type, tree op0, tree op1)
3434 bool sop;
3435 tree val;
3437 val = vrp_evaluate_conditional_warnv_with_ops (code, op0, op1, false, &sop,
3438 NULL);
3439 if (val)
3441 /* Since this expression was found on the RHS of an assignment,
3442 its type may be different from _Bool. Convert VAL to EXPR's
3443 type. */
3444 val = fold_convert (type, val);
3445 if (is_gimple_min_invariant (val))
3446 set_value_range_to_value (vr, val, vr->equiv);
3447 else
3448 set_value_range (vr, VR_RANGE, val, val, vr->equiv);
3450 else
3451 /* The result of a comparison is always true or false. */
3452 set_value_range_to_truthvalue (vr, type);
3455 /* Helper function for simplify_internal_call_using_ranges and
3456 extract_range_basic. Return true if OP0 SUBCODE OP1 for
3457 SUBCODE {PLUS,MINUS,MULT}_EXPR is known to never overflow or
3458 always overflow. Set *OVF to true if it is known to always
3459 overflow. */
3461 static bool
3462 check_for_binary_op_overflow (enum tree_code subcode, tree type,
3463 tree op0, tree op1, bool *ovf)
3465 value_range vr0 = VR_INITIALIZER;
3466 value_range vr1 = VR_INITIALIZER;
3467 if (TREE_CODE (op0) == SSA_NAME)
3468 vr0 = *get_value_range (op0);
3469 else if (TREE_CODE (op0) == INTEGER_CST)
3470 set_value_range_to_value (&vr0, op0, NULL);
3471 else
3472 set_value_range_to_varying (&vr0);
3474 if (TREE_CODE (op1) == SSA_NAME)
3475 vr1 = *get_value_range (op1);
3476 else if (TREE_CODE (op1) == INTEGER_CST)
3477 set_value_range_to_value (&vr1, op1, NULL);
3478 else
3479 set_value_range_to_varying (&vr1);
3481 if (!range_int_cst_p (&vr0)
3482 || TREE_OVERFLOW (vr0.min)
3483 || TREE_OVERFLOW (vr0.max))
3485 vr0.min = vrp_val_min (TREE_TYPE (op0));
3486 vr0.max = vrp_val_max (TREE_TYPE (op0));
3488 if (!range_int_cst_p (&vr1)
3489 || TREE_OVERFLOW (vr1.min)
3490 || TREE_OVERFLOW (vr1.max))
3492 vr1.min = vrp_val_min (TREE_TYPE (op1));
3493 vr1.max = vrp_val_max (TREE_TYPE (op1));
3495 *ovf = arith_overflowed_p (subcode, type, vr0.min,
3496 subcode == MINUS_EXPR ? vr1.max : vr1.min);
3497 if (arith_overflowed_p (subcode, type, vr0.max,
3498 subcode == MINUS_EXPR ? vr1.min : vr1.max) != *ovf)
3499 return false;
3500 if (subcode == MULT_EXPR)
3502 if (arith_overflowed_p (subcode, type, vr0.min, vr1.max) != *ovf
3503 || arith_overflowed_p (subcode, type, vr0.max, vr1.min) != *ovf)
3504 return false;
3506 if (*ovf)
3508 /* So far we found that there is an overflow on the boundaries.
3509 That doesn't prove that there is an overflow even for all values
3510 in between the boundaries. For that compute widest_int range
3511 of the result and see if it doesn't overlap the range of
3512 type. */
3513 widest_int wmin, wmax;
3514 widest_int w[4];
3515 int i;
3516 w[0] = wi::to_widest (vr0.min);
3517 w[1] = wi::to_widest (vr0.max);
3518 w[2] = wi::to_widest (vr1.min);
3519 w[3] = wi::to_widest (vr1.max);
3520 for (i = 0; i < 4; i++)
3522 widest_int wt;
3523 switch (subcode)
3525 case PLUS_EXPR:
3526 wt = wi::add (w[i & 1], w[2 + (i & 2) / 2]);
3527 break;
3528 case MINUS_EXPR:
3529 wt = wi::sub (w[i & 1], w[2 + (i & 2) / 2]);
3530 break;
3531 case MULT_EXPR:
3532 wt = wi::mul (w[i & 1], w[2 + (i & 2) / 2]);
3533 break;
3534 default:
3535 gcc_unreachable ();
3537 if (i == 0)
3539 wmin = wt;
3540 wmax = wt;
3542 else
3544 wmin = wi::smin (wmin, wt);
3545 wmax = wi::smax (wmax, wt);
3548 /* The result of op0 CODE op1 is known to be in range
3549 [wmin, wmax]. */
3550 widest_int wtmin = wi::to_widest (vrp_val_min (type));
3551 widest_int wtmax = wi::to_widest (vrp_val_max (type));
3552 /* If all values in [wmin, wmax] are smaller than
3553 [wtmin, wtmax] or all are larger than [wtmin, wtmax],
3554 the arithmetic operation will always overflow. */
3555 if (wmax < wtmin || wmin > wtmax)
3556 return true;
3557 return false;
3559 return true;
3562 /* Try to derive a nonnegative or nonzero range out of STMT relying
3563 primarily on generic routines in fold in conjunction with range data.
3564 Store the result in *VR */
3566 static void
3567 extract_range_basic (value_range *vr, gimple *stmt)
3569 bool sop;
3570 tree type = gimple_expr_type (stmt);
3572 if (is_gimple_call (stmt))
3574 tree arg;
3575 int mini, maxi, zerov = 0, prec;
3576 enum tree_code subcode = ERROR_MARK;
3577 combined_fn cfn = gimple_call_combined_fn (stmt);
3578 scalar_int_mode mode;
3580 switch (cfn)
3582 case CFN_BUILT_IN_CONSTANT_P:
3583 /* If the call is __builtin_constant_p and the argument is a
3584 function parameter resolve it to false. This avoids bogus
3585 array bound warnings.
3586 ??? We could do this as early as inlining is finished. */
3587 arg = gimple_call_arg (stmt, 0);
3588 if (TREE_CODE (arg) == SSA_NAME
3589 && SSA_NAME_IS_DEFAULT_DEF (arg)
3590 && TREE_CODE (SSA_NAME_VAR (arg)) == PARM_DECL
3591 && cfun->after_inlining)
3593 set_value_range_to_null (vr, type);
3594 return;
3596 break;
3597 /* Both __builtin_ffs* and __builtin_popcount return
3598 [0, prec]. */
3599 CASE_CFN_FFS:
3600 CASE_CFN_POPCOUNT:
3601 arg = gimple_call_arg (stmt, 0);
3602 prec = TYPE_PRECISION (TREE_TYPE (arg));
3603 mini = 0;
3604 maxi = prec;
3605 if (TREE_CODE (arg) == SSA_NAME)
3607 value_range *vr0 = get_value_range (arg);
3608 /* If arg is non-zero, then ffs or popcount
3609 are non-zero. */
3610 if ((vr0->type == VR_RANGE
3611 && range_includes_zero_p (vr0->min, vr0->max) == 0)
3612 || (vr0->type == VR_ANTI_RANGE
3613 && range_includes_zero_p (vr0->min, vr0->max) == 1))
3614 mini = 1;
3615 /* If some high bits are known to be zero,
3616 we can decrease the maximum. */
3617 if (vr0->type == VR_RANGE
3618 && TREE_CODE (vr0->max) == INTEGER_CST
3619 && !operand_less_p (vr0->min,
3620 build_zero_cst (TREE_TYPE (vr0->min))))
3621 maxi = tree_floor_log2 (vr0->max) + 1;
3623 goto bitop_builtin;
3624 /* __builtin_parity* returns [0, 1]. */
3625 CASE_CFN_PARITY:
3626 mini = 0;
3627 maxi = 1;
3628 goto bitop_builtin;
3629 /* __builtin_c[lt]z* return [0, prec-1], except for
3630 when the argument is 0, but that is undefined behavior.
3631 On many targets where the CLZ RTL or optab value is defined
3632 for 0 the value is prec, so include that in the range
3633 by default. */
3634 CASE_CFN_CLZ:
3635 arg = gimple_call_arg (stmt, 0);
3636 prec = TYPE_PRECISION (TREE_TYPE (arg));
3637 mini = 0;
3638 maxi = prec;
3639 mode = SCALAR_INT_TYPE_MODE (TREE_TYPE (arg));
3640 if (optab_handler (clz_optab, mode) != CODE_FOR_nothing
3641 && CLZ_DEFINED_VALUE_AT_ZERO (mode, zerov)
3642 /* Handle only the single common value. */
3643 && zerov != prec)
3644 /* Magic value to give up, unless vr0 proves
3645 arg is non-zero. */
3646 mini = -2;
3647 if (TREE_CODE (arg) == SSA_NAME)
3649 value_range *vr0 = get_value_range (arg);
3650 /* From clz of VR_RANGE minimum we can compute
3651 result maximum. */
3652 if (vr0->type == VR_RANGE
3653 && TREE_CODE (vr0->min) == INTEGER_CST)
3655 maxi = prec - 1 - tree_floor_log2 (vr0->min);
3656 if (maxi != prec)
3657 mini = 0;
3659 else if (vr0->type == VR_ANTI_RANGE
3660 && integer_zerop (vr0->min))
3662 maxi = prec - 1;
3663 mini = 0;
3665 if (mini == -2)
3666 break;
3667 /* From clz of VR_RANGE maximum we can compute
3668 result minimum. */
3669 if (vr0->type == VR_RANGE
3670 && TREE_CODE (vr0->max) == INTEGER_CST)
3672 mini = prec - 1 - tree_floor_log2 (vr0->max);
3673 if (mini == prec)
3674 break;
3677 if (mini == -2)
3678 break;
3679 goto bitop_builtin;
3680 /* __builtin_ctz* return [0, prec-1], except for
3681 when the argument is 0, but that is undefined behavior.
3682 If there is a ctz optab for this mode and
3683 CTZ_DEFINED_VALUE_AT_ZERO, include that in the range,
3684 otherwise just assume 0 won't be seen. */
3685 CASE_CFN_CTZ:
3686 arg = gimple_call_arg (stmt, 0);
3687 prec = TYPE_PRECISION (TREE_TYPE (arg));
3688 mini = 0;
3689 maxi = prec - 1;
3690 mode = SCALAR_INT_TYPE_MODE (TREE_TYPE (arg));
3691 if (optab_handler (ctz_optab, mode) != CODE_FOR_nothing
3692 && CTZ_DEFINED_VALUE_AT_ZERO (mode, zerov))
3694 /* Handle only the two common values. */
3695 if (zerov == -1)
3696 mini = -1;
3697 else if (zerov == prec)
3698 maxi = prec;
3699 else
3700 /* Magic value to give up, unless vr0 proves
3701 arg is non-zero. */
3702 mini = -2;
3704 if (TREE_CODE (arg) == SSA_NAME)
3706 value_range *vr0 = get_value_range (arg);
3707 /* If arg is non-zero, then use [0, prec - 1]. */
3708 if ((vr0->type == VR_RANGE
3709 && integer_nonzerop (vr0->min))
3710 || (vr0->type == VR_ANTI_RANGE
3711 && integer_zerop (vr0->min)))
3713 mini = 0;
3714 maxi = prec - 1;
3716 /* If some high bits are known to be zero,
3717 we can decrease the result maximum. */
3718 if (vr0->type == VR_RANGE
3719 && TREE_CODE (vr0->max) == INTEGER_CST)
3721 maxi = tree_floor_log2 (vr0->max);
3722 /* For vr0 [0, 0] give up. */
3723 if (maxi == -1)
3724 break;
3727 if (mini == -2)
3728 break;
3729 goto bitop_builtin;
3730 /* __builtin_clrsb* returns [0, prec-1]. */
3731 CASE_CFN_CLRSB:
3732 arg = gimple_call_arg (stmt, 0);
3733 prec = TYPE_PRECISION (TREE_TYPE (arg));
3734 mini = 0;
3735 maxi = prec - 1;
3736 goto bitop_builtin;
3737 bitop_builtin:
3738 set_value_range (vr, VR_RANGE, build_int_cst (type, mini),
3739 build_int_cst (type, maxi), NULL);
3740 return;
3741 case CFN_UBSAN_CHECK_ADD:
3742 subcode = PLUS_EXPR;
3743 break;
3744 case CFN_UBSAN_CHECK_SUB:
3745 subcode = MINUS_EXPR;
3746 break;
3747 case CFN_UBSAN_CHECK_MUL:
3748 subcode = MULT_EXPR;
3749 break;
3750 case CFN_GOACC_DIM_SIZE:
3751 case CFN_GOACC_DIM_POS:
3752 /* Optimizing these two internal functions helps the loop
3753 optimizer eliminate outer comparisons. Size is [1,N]
3754 and pos is [0,N-1]. */
3756 bool is_pos = cfn == CFN_GOACC_DIM_POS;
3757 int axis = oacc_get_ifn_dim_arg (stmt);
3758 int size = oacc_get_fn_dim_size (current_function_decl, axis);
3760 if (!size)
3761 /* If it's dynamic, the backend might know a hardware
3762 limitation. */
3763 size = targetm.goacc.dim_limit (axis);
3765 tree type = TREE_TYPE (gimple_call_lhs (stmt));
3766 set_value_range (vr, VR_RANGE,
3767 build_int_cst (type, is_pos ? 0 : 1),
3768 size ? build_int_cst (type, size - is_pos)
3769 : vrp_val_max (type), NULL);
3771 return;
3772 case CFN_BUILT_IN_STRLEN:
3773 if (tree lhs = gimple_call_lhs (stmt))
3774 if (ptrdiff_type_node
3775 && (TYPE_PRECISION (ptrdiff_type_node)
3776 == TYPE_PRECISION (TREE_TYPE (lhs))))
3778 tree type = TREE_TYPE (lhs);
3779 tree max = vrp_val_max (ptrdiff_type_node);
3780 wide_int wmax = wi::to_wide (max, TYPE_PRECISION (TREE_TYPE (max)));
3781 tree range_min = build_zero_cst (type);
3782 tree range_max = wide_int_to_tree (type, wmax - 1);
3783 set_value_range (vr, VR_RANGE, range_min, range_max, NULL);
3784 return;
3786 break;
3787 default:
3788 break;
3790 if (subcode != ERROR_MARK)
3792 bool saved_flag_wrapv = flag_wrapv;
3793 /* Pretend the arithmetics is wrapping. If there is
3794 any overflow, we'll complain, but will actually do
3795 wrapping operation. */
3796 flag_wrapv = 1;
3797 extract_range_from_binary_expr (vr, subcode, type,
3798 gimple_call_arg (stmt, 0),
3799 gimple_call_arg (stmt, 1));
3800 flag_wrapv = saved_flag_wrapv;
3802 /* If for both arguments vrp_valueize returned non-NULL,
3803 this should have been already folded and if not, it
3804 wasn't folded because of overflow. Avoid removing the
3805 UBSAN_CHECK_* calls in that case. */
3806 if (vr->type == VR_RANGE
3807 && (vr->min == vr->max
3808 || operand_equal_p (vr->min, vr->max, 0)))
3809 set_value_range_to_varying (vr);
3810 return;
3813 /* Handle extraction of the two results (result of arithmetics and
3814 a flag whether arithmetics overflowed) from {ADD,SUB,MUL}_OVERFLOW
3815 internal function. Similarly from ATOMIC_COMPARE_EXCHANGE. */
3816 else if (is_gimple_assign (stmt)
3817 && (gimple_assign_rhs_code (stmt) == REALPART_EXPR
3818 || gimple_assign_rhs_code (stmt) == IMAGPART_EXPR)
3819 && INTEGRAL_TYPE_P (type))
3821 enum tree_code code = gimple_assign_rhs_code (stmt);
3822 tree op = gimple_assign_rhs1 (stmt);
3823 if (TREE_CODE (op) == code && TREE_CODE (TREE_OPERAND (op, 0)) == SSA_NAME)
3825 gimple *g = SSA_NAME_DEF_STMT (TREE_OPERAND (op, 0));
3826 if (is_gimple_call (g) && gimple_call_internal_p (g))
3828 enum tree_code subcode = ERROR_MARK;
3829 switch (gimple_call_internal_fn (g))
3831 case IFN_ADD_OVERFLOW:
3832 subcode = PLUS_EXPR;
3833 break;
3834 case IFN_SUB_OVERFLOW:
3835 subcode = MINUS_EXPR;
3836 break;
3837 case IFN_MUL_OVERFLOW:
3838 subcode = MULT_EXPR;
3839 break;
3840 case IFN_ATOMIC_COMPARE_EXCHANGE:
3841 if (code == IMAGPART_EXPR)
3843 /* This is the boolean return value whether compare and
3844 exchange changed anything or not. */
3845 set_value_range (vr, VR_RANGE, build_int_cst (type, 0),
3846 build_int_cst (type, 1), NULL);
3847 return;
3849 break;
3850 default:
3851 break;
3853 if (subcode != ERROR_MARK)
3855 tree op0 = gimple_call_arg (g, 0);
3856 tree op1 = gimple_call_arg (g, 1);
3857 if (code == IMAGPART_EXPR)
3859 bool ovf = false;
3860 if (check_for_binary_op_overflow (subcode, type,
3861 op0, op1, &ovf))
3862 set_value_range_to_value (vr,
3863 build_int_cst (type, ovf),
3864 NULL);
3865 else if (TYPE_PRECISION (type) == 1
3866 && !TYPE_UNSIGNED (type))
3867 set_value_range_to_varying (vr);
3868 else
3869 set_value_range (vr, VR_RANGE, build_int_cst (type, 0),
3870 build_int_cst (type, 1), NULL);
3872 else if (types_compatible_p (type, TREE_TYPE (op0))
3873 && types_compatible_p (type, TREE_TYPE (op1)))
3875 bool saved_flag_wrapv = flag_wrapv;
3876 /* Pretend the arithmetics is wrapping. If there is
3877 any overflow, IMAGPART_EXPR will be set. */
3878 flag_wrapv = 1;
3879 extract_range_from_binary_expr (vr, subcode, type,
3880 op0, op1);
3881 flag_wrapv = saved_flag_wrapv;
3883 else
3885 value_range vr0 = VR_INITIALIZER;
3886 value_range vr1 = VR_INITIALIZER;
3887 bool saved_flag_wrapv = flag_wrapv;
3888 /* Pretend the arithmetics is wrapping. If there is
3889 any overflow, IMAGPART_EXPR will be set. */
3890 flag_wrapv = 1;
3891 extract_range_from_unary_expr (&vr0, NOP_EXPR,
3892 type, op0);
3893 extract_range_from_unary_expr (&vr1, NOP_EXPR,
3894 type, op1);
3895 extract_range_from_binary_expr_1 (vr, subcode, type,
3896 &vr0, &vr1);
3897 flag_wrapv = saved_flag_wrapv;
3899 return;
3904 if (INTEGRAL_TYPE_P (type)
3905 && gimple_stmt_nonnegative_warnv_p (stmt, &sop))
3906 set_value_range_to_nonnegative (vr, type);
3907 else if (vrp_stmt_computes_nonzero (stmt))
3908 set_value_range_to_nonnull (vr, type);
3909 else
3910 set_value_range_to_varying (vr);
3914 /* Try to compute a useful range out of assignment STMT and store it
3915 in *VR. */
3917 static void
3918 extract_range_from_assignment (value_range *vr, gassign *stmt)
3920 enum tree_code code = gimple_assign_rhs_code (stmt);
3922 if (code == ASSERT_EXPR)
3923 extract_range_from_assert (vr, gimple_assign_rhs1 (stmt));
3924 else if (code == SSA_NAME)
3925 extract_range_from_ssa_name (vr, gimple_assign_rhs1 (stmt));
3926 else if (TREE_CODE_CLASS (code) == tcc_binary)
3927 extract_range_from_binary_expr (vr, gimple_assign_rhs_code (stmt),
3928 gimple_expr_type (stmt),
3929 gimple_assign_rhs1 (stmt),
3930 gimple_assign_rhs2 (stmt));
3931 else if (TREE_CODE_CLASS (code) == tcc_unary)
3932 extract_range_from_unary_expr (vr, gimple_assign_rhs_code (stmt),
3933 gimple_expr_type (stmt),
3934 gimple_assign_rhs1 (stmt));
3935 else if (code == COND_EXPR)
3936 extract_range_from_cond_expr (vr, stmt);
3937 else if (TREE_CODE_CLASS (code) == tcc_comparison)
3938 extract_range_from_comparison (vr, gimple_assign_rhs_code (stmt),
3939 gimple_expr_type (stmt),
3940 gimple_assign_rhs1 (stmt),
3941 gimple_assign_rhs2 (stmt));
3942 else if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS
3943 && is_gimple_min_invariant (gimple_assign_rhs1 (stmt)))
3944 set_value_range_to_value (vr, gimple_assign_rhs1 (stmt), NULL);
3945 else
3946 set_value_range_to_varying (vr);
3948 if (vr->type == VR_VARYING)
3949 extract_range_basic (vr, stmt);
3952 /* Given a range VR, a LOOP and a variable VAR, determine whether it
3953 would be profitable to adjust VR using scalar evolution information
3954 for VAR. If so, update VR with the new limits. */
3956 static void
3957 adjust_range_with_scev (value_range *vr, struct loop *loop,
3958 gimple *stmt, tree var)
3960 tree init, step, chrec, tmin, tmax, min, max, type, tem;
3961 enum ev_direction dir;
3963 /* TODO. Don't adjust anti-ranges. An anti-range may provide
3964 better opportunities than a regular range, but I'm not sure. */
3965 if (vr->type == VR_ANTI_RANGE)
3966 return;
3968 chrec = instantiate_parameters (loop, analyze_scalar_evolution (loop, var));
3970 /* Like in PR19590, scev can return a constant function. */
3971 if (is_gimple_min_invariant (chrec))
3973 set_value_range_to_value (vr, chrec, vr->equiv);
3974 return;
3977 if (TREE_CODE (chrec) != POLYNOMIAL_CHREC)
3978 return;
3980 init = initial_condition_in_loop_num (chrec, loop->num);
3981 tem = op_with_constant_singleton_value_range (init);
3982 if (tem)
3983 init = tem;
3984 step = evolution_part_in_loop_num (chrec, loop->num);
3985 tem = op_with_constant_singleton_value_range (step);
3986 if (tem)
3987 step = tem;
3989 /* If STEP is symbolic, we can't know whether INIT will be the
3990 minimum or maximum value in the range. Also, unless INIT is
3991 a simple expression, compare_values and possibly other functions
3992 in tree-vrp won't be able to handle it. */
3993 if (step == NULL_TREE
3994 || !is_gimple_min_invariant (step)
3995 || !valid_value_p (init))
3996 return;
3998 dir = scev_direction (chrec);
3999 if (/* Do not adjust ranges if we do not know whether the iv increases
4000 or decreases, ... */
4001 dir == EV_DIR_UNKNOWN
4002 /* ... or if it may wrap. */
4003 || scev_probably_wraps_p (NULL_TREE, init, step, stmt,
4004 get_chrec_loop (chrec), true))
4005 return;
4007 type = TREE_TYPE (var);
4008 if (POINTER_TYPE_P (type) || !TYPE_MIN_VALUE (type))
4009 tmin = lower_bound_in_type (type, type);
4010 else
4011 tmin = TYPE_MIN_VALUE (type);
4012 if (POINTER_TYPE_P (type) || !TYPE_MAX_VALUE (type))
4013 tmax = upper_bound_in_type (type, type);
4014 else
4015 tmax = TYPE_MAX_VALUE (type);
4017 /* Try to use estimated number of iterations for the loop to constrain the
4018 final value in the evolution. */
4019 if (TREE_CODE (step) == INTEGER_CST
4020 && is_gimple_val (init)
4021 && (TREE_CODE (init) != SSA_NAME
4022 || get_value_range (init)->type == VR_RANGE))
4024 widest_int nit;
4026 /* We are only entering here for loop header PHI nodes, so using
4027 the number of latch executions is the correct thing to use. */
4028 if (max_loop_iterations (loop, &nit))
4030 value_range maxvr = VR_INITIALIZER;
4031 signop sgn = TYPE_SIGN (TREE_TYPE (step));
4032 bool overflow;
4034 widest_int wtmp = wi::mul (wi::to_widest (step), nit, sgn,
4035 &overflow);
4036 /* If the multiplication overflowed we can't do a meaningful
4037 adjustment. Likewise if the result doesn't fit in the type
4038 of the induction variable. For a signed type we have to
4039 check whether the result has the expected signedness which
4040 is that of the step as number of iterations is unsigned. */
4041 if (!overflow
4042 && wi::fits_to_tree_p (wtmp, TREE_TYPE (init))
4043 && (sgn == UNSIGNED
4044 || wi::gts_p (wtmp, 0) == wi::gts_p (wi::to_wide (step), 0)))
4046 tem = wide_int_to_tree (TREE_TYPE (init), wtmp);
4047 extract_range_from_binary_expr (&maxvr, PLUS_EXPR,
4048 TREE_TYPE (init), init, tem);
4049 /* Likewise if the addition did. */
4050 if (maxvr.type == VR_RANGE)
4052 value_range initvr = VR_INITIALIZER;
4054 if (TREE_CODE (init) == SSA_NAME)
4055 initvr = *(get_value_range (init));
4056 else if (is_gimple_min_invariant (init))
4057 set_value_range_to_value (&initvr, init, NULL);
4058 else
4059 return;
4061 /* Check if init + nit * step overflows. Though we checked
4062 scev {init, step}_loop doesn't wrap, it is not enough
4063 because the loop may exit immediately. Overflow could
4064 happen in the plus expression in this case. */
4065 if ((dir == EV_DIR_DECREASES
4066 && compare_values (maxvr.min, initvr.min) != -1)
4067 || (dir == EV_DIR_GROWS
4068 && compare_values (maxvr.max, initvr.max) != 1))
4069 return;
4071 tmin = maxvr.min;
4072 tmax = maxvr.max;
4078 if (vr->type == VR_VARYING || vr->type == VR_UNDEFINED)
4080 min = tmin;
4081 max = tmax;
4083 /* For VARYING or UNDEFINED ranges, just about anything we get
4084 from scalar evolutions should be better. */
4086 if (dir == EV_DIR_DECREASES)
4087 max = init;
4088 else
4089 min = init;
4091 else if (vr->type == VR_RANGE)
4093 min = vr->min;
4094 max = vr->max;
4096 if (dir == EV_DIR_DECREASES)
4098 /* INIT is the maximum value. If INIT is lower than VR->MAX
4099 but no smaller than VR->MIN, set VR->MAX to INIT. */
4100 if (compare_values (init, max) == -1)
4101 max = init;
4103 /* According to the loop information, the variable does not
4104 overflow. */
4105 if (compare_values (min, tmin) == -1)
4106 min = tmin;
4109 else
4111 /* If INIT is bigger than VR->MIN, set VR->MIN to INIT. */
4112 if (compare_values (init, min) == 1)
4113 min = init;
4115 if (compare_values (tmax, max) == -1)
4116 max = tmax;
4119 else
4120 return;
4122 /* If we just created an invalid range with the minimum
4123 greater than the maximum, we fail conservatively.
4124 This should happen only in unreachable
4125 parts of code, or for invalid programs. */
4126 if (compare_values (min, max) == 1)
4127 return;
4129 /* Even for valid range info, sometimes overflow flag will leak in.
4130 As GIMPLE IL should have no constants with TREE_OVERFLOW set, we
4131 drop them. */
4132 if (TREE_OVERFLOW_P (min))
4133 min = drop_tree_overflow (min);
4134 if (TREE_OVERFLOW_P (max))
4135 max = drop_tree_overflow (max);
4137 set_value_range (vr, VR_RANGE, min, max, vr->equiv);
4141 /* Given two numeric value ranges VR0, VR1 and a comparison code COMP:
4143 - Return BOOLEAN_TRUE_NODE if VR0 COMP VR1 always returns true for
4144 all the values in the ranges.
4146 - Return BOOLEAN_FALSE_NODE if the comparison always returns false.
4148 - Return NULL_TREE if it is not always possible to determine the
4149 value of the comparison.
4151 Also set *STRICT_OVERFLOW_P to indicate whether comparision evaluation
4152 assumed signed overflow is undefined. */
4155 static tree
4156 compare_ranges (enum tree_code comp, value_range *vr0, value_range *vr1,
4157 bool *strict_overflow_p)
4159 /* VARYING or UNDEFINED ranges cannot be compared. */
4160 if (vr0->type == VR_VARYING
4161 || vr0->type == VR_UNDEFINED
4162 || vr1->type == VR_VARYING
4163 || vr1->type == VR_UNDEFINED)
4164 return NULL_TREE;
4166 /* Anti-ranges need to be handled separately. */
4167 if (vr0->type == VR_ANTI_RANGE || vr1->type == VR_ANTI_RANGE)
4169 /* If both are anti-ranges, then we cannot compute any
4170 comparison. */
4171 if (vr0->type == VR_ANTI_RANGE && vr1->type == VR_ANTI_RANGE)
4172 return NULL_TREE;
4174 /* These comparisons are never statically computable. */
4175 if (comp == GT_EXPR
4176 || comp == GE_EXPR
4177 || comp == LT_EXPR
4178 || comp == LE_EXPR)
4179 return NULL_TREE;
4181 /* Equality can be computed only between a range and an
4182 anti-range. ~[VAL1, VAL2] == [VAL1, VAL2] is always false. */
4183 if (vr0->type == VR_RANGE)
4185 /* To simplify processing, make VR0 the anti-range. */
4186 value_range *tmp = vr0;
4187 vr0 = vr1;
4188 vr1 = tmp;
4191 gcc_assert (comp == NE_EXPR || comp == EQ_EXPR);
4193 if (compare_values_warnv (vr0->min, vr1->min, strict_overflow_p) == 0
4194 && compare_values_warnv (vr0->max, vr1->max, strict_overflow_p) == 0)
4195 return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
4197 return NULL_TREE;
4200 /* Simplify processing. If COMP is GT_EXPR or GE_EXPR, switch the
4201 operands around and change the comparison code. */
4202 if (comp == GT_EXPR || comp == GE_EXPR)
4204 comp = (comp == GT_EXPR) ? LT_EXPR : LE_EXPR;
4205 std::swap (vr0, vr1);
4208 if (comp == EQ_EXPR)
4210 /* Equality may only be computed if both ranges represent
4211 exactly one value. */
4212 if (compare_values_warnv (vr0->min, vr0->max, strict_overflow_p) == 0
4213 && compare_values_warnv (vr1->min, vr1->max, strict_overflow_p) == 0)
4215 int cmp_min = compare_values_warnv (vr0->min, vr1->min,
4216 strict_overflow_p);
4217 int cmp_max = compare_values_warnv (vr0->max, vr1->max,
4218 strict_overflow_p);
4219 if (cmp_min == 0 && cmp_max == 0)
4220 return boolean_true_node;
4221 else if (cmp_min != -2 && cmp_max != -2)
4222 return boolean_false_node;
4224 /* If [V0_MIN, V1_MAX] < [V1_MIN, V1_MAX] then V0 != V1. */
4225 else if (compare_values_warnv (vr0->min, vr1->max,
4226 strict_overflow_p) == 1
4227 || compare_values_warnv (vr1->min, vr0->max,
4228 strict_overflow_p) == 1)
4229 return boolean_false_node;
4231 return NULL_TREE;
4233 else if (comp == NE_EXPR)
4235 int cmp1, cmp2;
4237 /* If VR0 is completely to the left or completely to the right
4238 of VR1, they are always different. Notice that we need to
4239 make sure that both comparisons yield similar results to
4240 avoid comparing values that cannot be compared at
4241 compile-time. */
4242 cmp1 = compare_values_warnv (vr0->max, vr1->min, strict_overflow_p);
4243 cmp2 = compare_values_warnv (vr0->min, vr1->max, strict_overflow_p);
4244 if ((cmp1 == -1 && cmp2 == -1) || (cmp1 == 1 && cmp2 == 1))
4245 return boolean_true_node;
4247 /* If VR0 and VR1 represent a single value and are identical,
4248 return false. */
4249 else if (compare_values_warnv (vr0->min, vr0->max,
4250 strict_overflow_p) == 0
4251 && compare_values_warnv (vr1->min, vr1->max,
4252 strict_overflow_p) == 0
4253 && compare_values_warnv (vr0->min, vr1->min,
4254 strict_overflow_p) == 0
4255 && compare_values_warnv (vr0->max, vr1->max,
4256 strict_overflow_p) == 0)
4257 return boolean_false_node;
4259 /* Otherwise, they may or may not be different. */
4260 else
4261 return NULL_TREE;
4263 else if (comp == LT_EXPR || comp == LE_EXPR)
4265 int tst;
4267 /* If VR0 is to the left of VR1, return true. */
4268 tst = compare_values_warnv (vr0->max, vr1->min, strict_overflow_p);
4269 if ((comp == LT_EXPR && tst == -1)
4270 || (comp == LE_EXPR && (tst == -1 || tst == 0)))
4271 return boolean_true_node;
4273 /* If VR0 is to the right of VR1, return false. */
4274 tst = compare_values_warnv (vr0->min, vr1->max, strict_overflow_p);
4275 if ((comp == LT_EXPR && (tst == 0 || tst == 1))
4276 || (comp == LE_EXPR && tst == 1))
4277 return boolean_false_node;
4279 /* Otherwise, we don't know. */
4280 return NULL_TREE;
4283 gcc_unreachable ();
4287 /* Given a value range VR, a value VAL and a comparison code COMP, return
4288 BOOLEAN_TRUE_NODE if VR COMP VAL always returns true for all the
4289 values in VR. Return BOOLEAN_FALSE_NODE if the comparison
4290 always returns false. Return NULL_TREE if it is not always
4291 possible to determine the value of the comparison. Also set
4292 *STRICT_OVERFLOW_P to indicate whether comparision evaluation
4293 assumed signed overflow is undefined. */
4295 static tree
4296 compare_range_with_value (enum tree_code comp, value_range *vr, tree val,
4297 bool *strict_overflow_p)
4299 if (vr->type == VR_VARYING || vr->type == VR_UNDEFINED)
4300 return NULL_TREE;
4302 /* Anti-ranges need to be handled separately. */
4303 if (vr->type == VR_ANTI_RANGE)
4305 /* For anti-ranges, the only predicates that we can compute at
4306 compile time are equality and inequality. */
4307 if (comp == GT_EXPR
4308 || comp == GE_EXPR
4309 || comp == LT_EXPR
4310 || comp == LE_EXPR)
4311 return NULL_TREE;
4313 /* ~[VAL_1, VAL_2] OP VAL is known if VAL_1 <= VAL <= VAL_2. */
4314 if (value_inside_range (val, vr->min, vr->max) == 1)
4315 return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
4317 return NULL_TREE;
4320 if (comp == EQ_EXPR)
4322 /* EQ_EXPR may only be computed if VR represents exactly
4323 one value. */
4324 if (compare_values_warnv (vr->min, vr->max, strict_overflow_p) == 0)
4326 int cmp = compare_values_warnv (vr->min, val, strict_overflow_p);
4327 if (cmp == 0)
4328 return boolean_true_node;
4329 else if (cmp == -1 || cmp == 1 || cmp == 2)
4330 return boolean_false_node;
4332 else if (compare_values_warnv (val, vr->min, strict_overflow_p) == -1
4333 || compare_values_warnv (vr->max, val, strict_overflow_p) == -1)
4334 return boolean_false_node;
4336 return NULL_TREE;
4338 else if (comp == NE_EXPR)
4340 /* If VAL is not inside VR, then they are always different. */
4341 if (compare_values_warnv (vr->max, val, strict_overflow_p) == -1
4342 || compare_values_warnv (vr->min, val, strict_overflow_p) == 1)
4343 return boolean_true_node;
4345 /* If VR represents exactly one value equal to VAL, then return
4346 false. */
4347 if (compare_values_warnv (vr->min, vr->max, strict_overflow_p) == 0
4348 && compare_values_warnv (vr->min, val, strict_overflow_p) == 0)
4349 return boolean_false_node;
4351 /* Otherwise, they may or may not be different. */
4352 return NULL_TREE;
4354 else if (comp == LT_EXPR || comp == LE_EXPR)
4356 int tst;
4358 /* If VR is to the left of VAL, return true. */
4359 tst = compare_values_warnv (vr->max, val, strict_overflow_p);
4360 if ((comp == LT_EXPR && tst == -1)
4361 || (comp == LE_EXPR && (tst == -1 || tst == 0)))
4362 return boolean_true_node;
4364 /* If VR is to the right of VAL, return false. */
4365 tst = compare_values_warnv (vr->min, val, strict_overflow_p);
4366 if ((comp == LT_EXPR && (tst == 0 || tst == 1))
4367 || (comp == LE_EXPR && tst == 1))
4368 return boolean_false_node;
4370 /* Otherwise, we don't know. */
4371 return NULL_TREE;
4373 else if (comp == GT_EXPR || comp == GE_EXPR)
4375 int tst;
4377 /* If VR is to the right of VAL, return true. */
4378 tst = compare_values_warnv (vr->min, val, strict_overflow_p);
4379 if ((comp == GT_EXPR && tst == 1)
4380 || (comp == GE_EXPR && (tst == 0 || tst == 1)))
4381 return boolean_true_node;
4383 /* If VR is to the left of VAL, return false. */
4384 tst = compare_values_warnv (vr->max, val, strict_overflow_p);
4385 if ((comp == GT_EXPR && (tst == -1 || tst == 0))
4386 || (comp == GE_EXPR && tst == -1))
4387 return boolean_false_node;
4389 /* Otherwise, we don't know. */
4390 return NULL_TREE;
4393 gcc_unreachable ();
4397 /* Debugging dumps. */
4399 void dump_value_range (FILE *, const value_range *);
4400 void debug_value_range (value_range *);
4401 void dump_all_value_ranges (FILE *);
4402 void debug_all_value_ranges (void);
4403 void dump_vr_equiv (FILE *, bitmap);
4404 void debug_vr_equiv (bitmap);
4407 /* Dump value range VR to FILE. */
4409 void
4410 dump_value_range (FILE *file, const value_range *vr)
4412 if (vr == NULL)
4413 fprintf (file, "[]");
4414 else if (vr->type == VR_UNDEFINED)
4415 fprintf (file, "UNDEFINED");
4416 else if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
4418 tree type = TREE_TYPE (vr->min);
4420 fprintf (file, "%s[", (vr->type == VR_ANTI_RANGE) ? "~" : "");
4422 if (INTEGRAL_TYPE_P (type)
4423 && !TYPE_UNSIGNED (type)
4424 && vrp_val_is_min (vr->min))
4425 fprintf (file, "-INF");
4426 else
4427 print_generic_expr (file, vr->min);
4429 fprintf (file, ", ");
4431 if (INTEGRAL_TYPE_P (type)
4432 && vrp_val_is_max (vr->max))
4433 fprintf (file, "+INF");
4434 else
4435 print_generic_expr (file, vr->max);
4437 fprintf (file, "]");
4439 if (vr->equiv)
4441 bitmap_iterator bi;
4442 unsigned i, c = 0;
4444 fprintf (file, " EQUIVALENCES: { ");
4446 EXECUTE_IF_SET_IN_BITMAP (vr->equiv, 0, i, bi)
4448 print_generic_expr (file, ssa_name (i));
4449 fprintf (file, " ");
4450 c++;
4453 fprintf (file, "} (%u elements)", c);
4456 else if (vr->type == VR_VARYING)
4457 fprintf (file, "VARYING");
4458 else
4459 fprintf (file, "INVALID RANGE");
4463 /* Dump value range VR to stderr. */
4465 DEBUG_FUNCTION void
4466 debug_value_range (value_range *vr)
4468 dump_value_range (stderr, vr);
4469 fprintf (stderr, "\n");
4473 /* Dump value ranges of all SSA_NAMEs to FILE. */
4475 void
4476 dump_all_value_ranges (FILE *file)
4478 size_t i;
4480 for (i = 0; i < num_vr_values; i++)
4482 if (vr_value[i])
4484 print_generic_expr (file, ssa_name (i));
4485 fprintf (file, ": ");
4486 dump_value_range (file, vr_value[i]);
4487 fprintf (file, "\n");
4491 fprintf (file, "\n");
4495 /* Dump all value ranges to stderr. */
4497 DEBUG_FUNCTION void
4498 debug_all_value_ranges (void)
4500 dump_all_value_ranges (stderr);
4504 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
4505 create a new SSA name N and return the assertion assignment
4506 'N = ASSERT_EXPR <V, V OP W>'. */
4508 static gimple *
4509 build_assert_expr_for (tree cond, tree v)
4511 tree a;
4512 gassign *assertion;
4514 gcc_assert (TREE_CODE (v) == SSA_NAME
4515 && COMPARISON_CLASS_P (cond));
4517 a = build2 (ASSERT_EXPR, TREE_TYPE (v), v, cond);
4518 assertion = gimple_build_assign (NULL_TREE, a);
4520 /* The new ASSERT_EXPR, creates a new SSA name that replaces the
4521 operand of the ASSERT_EXPR. Create it so the new name and the old one
4522 are registered in the replacement table so that we can fix the SSA web
4523 after adding all the ASSERT_EXPRs. */
4524 tree new_def = create_new_def_for (v, assertion, NULL);
4525 /* Make sure we preserve abnormalness throughout an ASSERT_EXPR chain
4526 given we have to be able to fully propagate those out to re-create
4527 valid SSA when removing the asserts. */
4528 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (v))
4529 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_def) = 1;
4531 return assertion;
4535 /* Return false if EXPR is a predicate expression involving floating
4536 point values. */
4538 static inline bool
4539 fp_predicate (gimple *stmt)
4541 GIMPLE_CHECK (stmt, GIMPLE_COND);
4543 return FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)));
4546 /* If the range of values taken by OP can be inferred after STMT executes,
4547 return the comparison code (COMP_CODE_P) and value (VAL_P) that
4548 describes the inferred range. Return true if a range could be
4549 inferred. */
4551 static bool
4552 infer_value_range (gimple *stmt, tree op, tree_code *comp_code_p, tree *val_p)
4554 *val_p = NULL_TREE;
4555 *comp_code_p = ERROR_MARK;
4557 /* Do not attempt to infer anything in names that flow through
4558 abnormal edges. */
4559 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
4560 return false;
4562 /* If STMT is the last statement of a basic block with no normal
4563 successors, there is no point inferring anything about any of its
4564 operands. We would not be able to find a proper insertion point
4565 for the assertion, anyway. */
4566 if (stmt_ends_bb_p (stmt))
4568 edge_iterator ei;
4569 edge e;
4571 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
4572 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
4573 break;
4574 if (e == NULL)
4575 return false;
4578 if (infer_nonnull_range (stmt, op))
4580 *val_p = build_int_cst (TREE_TYPE (op), 0);
4581 *comp_code_p = NE_EXPR;
4582 return true;
4585 return false;
4589 void dump_asserts_for (FILE *, tree);
4590 void debug_asserts_for (tree);
4591 void dump_all_asserts (FILE *);
4592 void debug_all_asserts (void);
4594 /* Dump all the registered assertions for NAME to FILE. */
4596 void
4597 dump_asserts_for (FILE *file, tree name)
4599 assert_locus *loc;
4601 fprintf (file, "Assertions to be inserted for ");
4602 print_generic_expr (file, name);
4603 fprintf (file, "\n");
4605 loc = asserts_for[SSA_NAME_VERSION (name)];
4606 while (loc)
4608 fprintf (file, "\t");
4609 print_gimple_stmt (file, gsi_stmt (loc->si), 0);
4610 fprintf (file, "\n\tBB #%d", loc->bb->index);
4611 if (loc->e)
4613 fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
4614 loc->e->dest->index);
4615 dump_edge_info (file, loc->e, dump_flags, 0);
4617 fprintf (file, "\n\tPREDICATE: ");
4618 print_generic_expr (file, loc->expr);
4619 fprintf (file, " %s ", get_tree_code_name (loc->comp_code));
4620 print_generic_expr (file, loc->val);
4621 fprintf (file, "\n\n");
4622 loc = loc->next;
4625 fprintf (file, "\n");
4629 /* Dump all the registered assertions for NAME to stderr. */
4631 DEBUG_FUNCTION void
4632 debug_asserts_for (tree name)
4634 dump_asserts_for (stderr, name);
4638 /* Dump all the registered assertions for all the names to FILE. */
4640 void
4641 dump_all_asserts (FILE *file)
4643 unsigned i;
4644 bitmap_iterator bi;
4646 fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
4647 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
4648 dump_asserts_for (file, ssa_name (i));
4649 fprintf (file, "\n");
4653 /* Dump all the registered assertions for all the names to stderr. */
4655 DEBUG_FUNCTION void
4656 debug_all_asserts (void)
4658 dump_all_asserts (stderr);
4661 /* Push the assert info for NAME, EXPR, COMP_CODE and VAL to ASSERTS. */
4663 static void
4664 add_assert_info (vec<assert_info> &asserts,
4665 tree name, tree expr, enum tree_code comp_code, tree val)
4667 assert_info info;
4668 info.comp_code = comp_code;
4669 info.name = name;
4670 info.val = val;
4671 info.expr = expr;
4672 asserts.safe_push (info);
4675 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
4676 'EXPR COMP_CODE VAL' at a location that dominates block BB or
4677 E->DEST, then register this location as a possible insertion point
4678 for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
4680 BB, E and SI provide the exact insertion point for the new
4681 ASSERT_EXPR. If BB is NULL, then the ASSERT_EXPR is to be inserted
4682 on edge E. Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
4683 BB. If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
4684 must not be NULL. */
4686 static void
4687 register_new_assert_for (tree name, tree expr,
4688 enum tree_code comp_code,
4689 tree val,
4690 basic_block bb,
4691 edge e,
4692 gimple_stmt_iterator si)
4694 assert_locus *n, *loc, *last_loc;
4695 basic_block dest_bb;
4697 gcc_checking_assert (bb == NULL || e == NULL);
4699 if (e == NULL)
4700 gcc_checking_assert (gimple_code (gsi_stmt (si)) != GIMPLE_COND
4701 && gimple_code (gsi_stmt (si)) != GIMPLE_SWITCH);
4703 /* Never build an assert comparing against an integer constant with
4704 TREE_OVERFLOW set. This confuses our undefined overflow warning
4705 machinery. */
4706 if (TREE_OVERFLOW_P (val))
4707 val = drop_tree_overflow (val);
4709 /* The new assertion A will be inserted at BB or E. We need to
4710 determine if the new location is dominated by a previously
4711 registered location for A. If we are doing an edge insertion,
4712 assume that A will be inserted at E->DEST. Note that this is not
4713 necessarily true.
4715 If E is a critical edge, it will be split. But even if E is
4716 split, the new block will dominate the same set of blocks that
4717 E->DEST dominates.
4719 The reverse, however, is not true, blocks dominated by E->DEST
4720 will not be dominated by the new block created to split E. So,
4721 if the insertion location is on a critical edge, we will not use
4722 the new location to move another assertion previously registered
4723 at a block dominated by E->DEST. */
4724 dest_bb = (bb) ? bb : e->dest;
4726 /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
4727 VAL at a block dominating DEST_BB, then we don't need to insert a new
4728 one. Similarly, if the same assertion already exists at a block
4729 dominated by DEST_BB and the new location is not on a critical
4730 edge, then update the existing location for the assertion (i.e.,
4731 move the assertion up in the dominance tree).
4733 Note, this is implemented as a simple linked list because there
4734 should not be more than a handful of assertions registered per
4735 name. If this becomes a performance problem, a table hashed by
4736 COMP_CODE and VAL could be implemented. */
4737 loc = asserts_for[SSA_NAME_VERSION (name)];
4738 last_loc = loc;
4739 while (loc)
4741 if (loc->comp_code == comp_code
4742 && (loc->val == val
4743 || operand_equal_p (loc->val, val, 0))
4744 && (loc->expr == expr
4745 || operand_equal_p (loc->expr, expr, 0)))
4747 /* If E is not a critical edge and DEST_BB
4748 dominates the existing location for the assertion, move
4749 the assertion up in the dominance tree by updating its
4750 location information. */
4751 if ((e == NULL || !EDGE_CRITICAL_P (e))
4752 && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
4754 loc->bb = dest_bb;
4755 loc->e = e;
4756 loc->si = si;
4757 return;
4761 /* Update the last node of the list and move to the next one. */
4762 last_loc = loc;
4763 loc = loc->next;
4766 /* If we didn't find an assertion already registered for
4767 NAME COMP_CODE VAL, add a new one at the end of the list of
4768 assertions associated with NAME. */
4769 n = XNEW (struct assert_locus);
4770 n->bb = dest_bb;
4771 n->e = e;
4772 n->si = si;
4773 n->comp_code = comp_code;
4774 n->val = val;
4775 n->expr = expr;
4776 n->next = NULL;
4778 if (last_loc)
4779 last_loc->next = n;
4780 else
4781 asserts_for[SSA_NAME_VERSION (name)] = n;
4783 bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
4786 /* (COND_OP0 COND_CODE COND_OP1) is a predicate which uses NAME.
4787 Extract a suitable test code and value and store them into *CODE_P and
4788 *VAL_P so the predicate is normalized to NAME *CODE_P *VAL_P.
4790 If no extraction was possible, return FALSE, otherwise return TRUE.
4792 If INVERT is true, then we invert the result stored into *CODE_P. */
4794 static bool
4795 extract_code_and_val_from_cond_with_ops (tree name, enum tree_code cond_code,
4796 tree cond_op0, tree cond_op1,
4797 bool invert, enum tree_code *code_p,
4798 tree *val_p)
4800 enum tree_code comp_code;
4801 tree val;
4803 /* Otherwise, we have a comparison of the form NAME COMP VAL
4804 or VAL COMP NAME. */
4805 if (name == cond_op1)
4807 /* If the predicate is of the form VAL COMP NAME, flip
4808 COMP around because we need to register NAME as the
4809 first operand in the predicate. */
4810 comp_code = swap_tree_comparison (cond_code);
4811 val = cond_op0;
4813 else if (name == cond_op0)
4815 /* The comparison is of the form NAME COMP VAL, so the
4816 comparison code remains unchanged. */
4817 comp_code = cond_code;
4818 val = cond_op1;
4820 else
4821 gcc_unreachable ();
4823 /* Invert the comparison code as necessary. */
4824 if (invert)
4825 comp_code = invert_tree_comparison (comp_code, 0);
4827 /* VRP only handles integral and pointer types. */
4828 if (! INTEGRAL_TYPE_P (TREE_TYPE (val))
4829 && ! POINTER_TYPE_P (TREE_TYPE (val)))
4830 return false;
4832 /* Do not register always-false predicates.
4833 FIXME: this works around a limitation in fold() when dealing with
4834 enumerations. Given 'enum { N1, N2 } x;', fold will not
4835 fold 'if (x > N2)' to 'if (0)'. */
4836 if ((comp_code == GT_EXPR || comp_code == LT_EXPR)
4837 && INTEGRAL_TYPE_P (TREE_TYPE (val)))
4839 tree min = TYPE_MIN_VALUE (TREE_TYPE (val));
4840 tree max = TYPE_MAX_VALUE (TREE_TYPE (val));
4842 if (comp_code == GT_EXPR
4843 && (!max
4844 || compare_values (val, max) == 0))
4845 return false;
4847 if (comp_code == LT_EXPR
4848 && (!min
4849 || compare_values (val, min) == 0))
4850 return false;
4852 *code_p = comp_code;
4853 *val_p = val;
4854 return true;
4857 /* Find out smallest RES where RES > VAL && (RES & MASK) == RES, if any
4858 (otherwise return VAL). VAL and MASK must be zero-extended for
4859 precision PREC. If SGNBIT is non-zero, first xor VAL with SGNBIT
4860 (to transform signed values into unsigned) and at the end xor
4861 SGNBIT back. */
4863 static wide_int
4864 masked_increment (const wide_int &val_in, const wide_int &mask,
4865 const wide_int &sgnbit, unsigned int prec)
4867 wide_int bit = wi::one (prec), res;
4868 unsigned int i;
4870 wide_int val = val_in ^ sgnbit;
4871 for (i = 0; i < prec; i++, bit += bit)
4873 res = mask;
4874 if ((res & bit) == 0)
4875 continue;
4876 res = bit - 1;
4877 res = wi::bit_and_not (val + bit, res);
4878 res &= mask;
4879 if (wi::gtu_p (res, val))
4880 return res ^ sgnbit;
4882 return val ^ sgnbit;
4885 /* Helper for overflow_comparison_p
4887 OP0 CODE OP1 is a comparison. Examine the comparison and potentially
4888 OP1's defining statement to see if it ultimately has the form
4889 OP0 CODE (OP0 PLUS INTEGER_CST)
4891 If so, return TRUE indicating this is an overflow test and store into
4892 *NEW_CST an updated constant that can be used in a narrowed range test.
4894 REVERSED indicates if the comparison was originally:
4896 OP1 CODE' OP0.
4898 This affects how we build the updated constant. */
4900 static bool
4901 overflow_comparison_p_1 (enum tree_code code, tree op0, tree op1,
4902 bool follow_assert_exprs, bool reversed, tree *new_cst)
4904 /* See if this is a relational operation between two SSA_NAMES with
4905 unsigned, overflow wrapping values. If so, check it more deeply. */
4906 if ((code == LT_EXPR || code == LE_EXPR
4907 || code == GE_EXPR || code == GT_EXPR)
4908 && TREE_CODE (op0) == SSA_NAME
4909 && TREE_CODE (op1) == SSA_NAME
4910 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
4911 && TYPE_UNSIGNED (TREE_TYPE (op0))
4912 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0)))
4914 gimple *op1_def = SSA_NAME_DEF_STMT (op1);
4916 /* If requested, follow any ASSERT_EXPRs backwards for OP1. */
4917 if (follow_assert_exprs)
4919 while (gimple_assign_single_p (op1_def)
4920 && TREE_CODE (gimple_assign_rhs1 (op1_def)) == ASSERT_EXPR)
4922 op1 = TREE_OPERAND (gimple_assign_rhs1 (op1_def), 0);
4923 if (TREE_CODE (op1) != SSA_NAME)
4924 break;
4925 op1_def = SSA_NAME_DEF_STMT (op1);
4929 /* Now look at the defining statement of OP1 to see if it adds
4930 or subtracts a nonzero constant from another operand. */
4931 if (op1_def
4932 && is_gimple_assign (op1_def)
4933 && gimple_assign_rhs_code (op1_def) == PLUS_EXPR
4934 && TREE_CODE (gimple_assign_rhs2 (op1_def)) == INTEGER_CST
4935 && !integer_zerop (gimple_assign_rhs2 (op1_def)))
4937 tree target = gimple_assign_rhs1 (op1_def);
4939 /* If requested, follow ASSERT_EXPRs backwards for op0 looking
4940 for one where TARGET appears on the RHS. */
4941 if (follow_assert_exprs)
4943 /* Now see if that "other operand" is op0, following the chain
4944 of ASSERT_EXPRs if necessary. */
4945 gimple *op0_def = SSA_NAME_DEF_STMT (op0);
4946 while (op0 != target
4947 && gimple_assign_single_p (op0_def)
4948 && TREE_CODE (gimple_assign_rhs1 (op0_def)) == ASSERT_EXPR)
4950 op0 = TREE_OPERAND (gimple_assign_rhs1 (op0_def), 0);
4951 if (TREE_CODE (op0) != SSA_NAME)
4952 break;
4953 op0_def = SSA_NAME_DEF_STMT (op0);
4957 /* If we did not find our target SSA_NAME, then this is not
4958 an overflow test. */
4959 if (op0 != target)
4960 return false;
4962 tree type = TREE_TYPE (op0);
4963 wide_int max = wi::max_value (TYPE_PRECISION (type), UNSIGNED);
4964 tree inc = gimple_assign_rhs2 (op1_def);
4965 if (reversed)
4966 *new_cst = wide_int_to_tree (type, max + wi::to_wide (inc));
4967 else
4968 *new_cst = wide_int_to_tree (type, max - wi::to_wide (inc));
4969 return true;
4972 return false;
4975 /* OP0 CODE OP1 is a comparison. Examine the comparison and potentially
4976 OP1's defining statement to see if it ultimately has the form
4977 OP0 CODE (OP0 PLUS INTEGER_CST)
4979 If so, return TRUE indicating this is an overflow test and store into
4980 *NEW_CST an updated constant that can be used in a narrowed range test.
4982 These statements are left as-is in the IL to facilitate discovery of
4983 {ADD,SUB}_OVERFLOW sequences later in the optimizer pipeline. But
4984 the alternate range representation is often useful within VRP. */
4986 static bool
4987 overflow_comparison_p (tree_code code, tree name, tree val,
4988 bool use_equiv_p, tree *new_cst)
4990 if (overflow_comparison_p_1 (code, name, val, use_equiv_p, false, new_cst))
4991 return true;
4992 return overflow_comparison_p_1 (swap_tree_comparison (code), val, name,
4993 use_equiv_p, true, new_cst);
4997 /* Try to register an edge assertion for SSA name NAME on edge E for
4998 the condition COND contributing to the conditional jump pointed to by BSI.
4999 Invert the condition COND if INVERT is true. */
5001 static void
5002 register_edge_assert_for_2 (tree name, edge e,
5003 enum tree_code cond_code,
5004 tree cond_op0, tree cond_op1, bool invert,
5005 vec<assert_info> &asserts)
5007 tree val;
5008 enum tree_code comp_code;
5010 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
5011 cond_op0,
5012 cond_op1,
5013 invert, &comp_code, &val))
5014 return;
5016 /* Queue the assert. */
5017 tree x;
5018 if (overflow_comparison_p (comp_code, name, val, false, &x))
5020 enum tree_code new_code = ((comp_code == GT_EXPR || comp_code == GE_EXPR)
5021 ? GT_EXPR : LE_EXPR);
5022 add_assert_info (asserts, name, name, new_code, x);
5024 add_assert_info (asserts, name, name, comp_code, val);
5026 /* In the case of NAME <= CST and NAME being defined as
5027 NAME = (unsigned) NAME2 + CST2 we can assert NAME2 >= -CST2
5028 and NAME2 <= CST - CST2. We can do the same for NAME > CST.
5029 This catches range and anti-range tests. */
5030 if ((comp_code == LE_EXPR
5031 || comp_code == GT_EXPR)
5032 && TREE_CODE (val) == INTEGER_CST
5033 && TYPE_UNSIGNED (TREE_TYPE (val)))
5035 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5036 tree cst2 = NULL_TREE, name2 = NULL_TREE, name3 = NULL_TREE;
5038 /* Extract CST2 from the (optional) addition. */
5039 if (is_gimple_assign (def_stmt)
5040 && gimple_assign_rhs_code (def_stmt) == PLUS_EXPR)
5042 name2 = gimple_assign_rhs1 (def_stmt);
5043 cst2 = gimple_assign_rhs2 (def_stmt);
5044 if (TREE_CODE (name2) == SSA_NAME
5045 && TREE_CODE (cst2) == INTEGER_CST)
5046 def_stmt = SSA_NAME_DEF_STMT (name2);
5049 /* Extract NAME2 from the (optional) sign-changing cast. */
5050 if (gimple_assign_cast_p (def_stmt))
5052 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt))
5053 && ! TYPE_UNSIGNED (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
5054 && (TYPE_PRECISION (gimple_expr_type (def_stmt))
5055 == TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))))
5056 name3 = gimple_assign_rhs1 (def_stmt);
5059 /* If name3 is used later, create an ASSERT_EXPR for it. */
5060 if (name3 != NULL_TREE
5061 && TREE_CODE (name3) == SSA_NAME
5062 && (cst2 == NULL_TREE
5063 || TREE_CODE (cst2) == INTEGER_CST)
5064 && INTEGRAL_TYPE_P (TREE_TYPE (name3)))
5066 tree tmp;
5068 /* Build an expression for the range test. */
5069 tmp = build1 (NOP_EXPR, TREE_TYPE (name), name3);
5070 if (cst2 != NULL_TREE)
5071 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
5073 if (dump_file)
5075 fprintf (dump_file, "Adding assert for ");
5076 print_generic_expr (dump_file, name3);
5077 fprintf (dump_file, " from ");
5078 print_generic_expr (dump_file, tmp);
5079 fprintf (dump_file, "\n");
5082 add_assert_info (asserts, name3, tmp, comp_code, val);
5085 /* If name2 is used later, create an ASSERT_EXPR for it. */
5086 if (name2 != NULL_TREE
5087 && TREE_CODE (name2) == SSA_NAME
5088 && TREE_CODE (cst2) == INTEGER_CST
5089 && INTEGRAL_TYPE_P (TREE_TYPE (name2)))
5091 tree tmp;
5093 /* Build an expression for the range test. */
5094 tmp = name2;
5095 if (TREE_TYPE (name) != TREE_TYPE (name2))
5096 tmp = build1 (NOP_EXPR, TREE_TYPE (name), tmp);
5097 if (cst2 != NULL_TREE)
5098 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
5100 if (dump_file)
5102 fprintf (dump_file, "Adding assert for ");
5103 print_generic_expr (dump_file, name2);
5104 fprintf (dump_file, " from ");
5105 print_generic_expr (dump_file, tmp);
5106 fprintf (dump_file, "\n");
5109 add_assert_info (asserts, name2, tmp, comp_code, val);
5113 /* In the case of post-in/decrement tests like if (i++) ... and uses
5114 of the in/decremented value on the edge the extra name we want to
5115 assert for is not on the def chain of the name compared. Instead
5116 it is in the set of use stmts.
5117 Similar cases happen for conversions that were simplified through
5118 fold_{sign_changed,widened}_comparison. */
5119 if ((comp_code == NE_EXPR
5120 || comp_code == EQ_EXPR)
5121 && TREE_CODE (val) == INTEGER_CST)
5123 imm_use_iterator ui;
5124 gimple *use_stmt;
5125 FOR_EACH_IMM_USE_STMT (use_stmt, ui, name)
5127 if (!is_gimple_assign (use_stmt))
5128 continue;
5130 /* Cut off to use-stmts that are dominating the predecessor. */
5131 if (!dominated_by_p (CDI_DOMINATORS, e->src, gimple_bb (use_stmt)))
5132 continue;
5134 tree name2 = gimple_assign_lhs (use_stmt);
5135 if (TREE_CODE (name2) != SSA_NAME)
5136 continue;
5138 enum tree_code code = gimple_assign_rhs_code (use_stmt);
5139 tree cst;
5140 if (code == PLUS_EXPR
5141 || code == MINUS_EXPR)
5143 cst = gimple_assign_rhs2 (use_stmt);
5144 if (TREE_CODE (cst) != INTEGER_CST)
5145 continue;
5146 cst = int_const_binop (code, val, cst);
5148 else if (CONVERT_EXPR_CODE_P (code))
5150 /* For truncating conversions we cannot record
5151 an inequality. */
5152 if (comp_code == NE_EXPR
5153 && (TYPE_PRECISION (TREE_TYPE (name2))
5154 < TYPE_PRECISION (TREE_TYPE (name))))
5155 continue;
5156 cst = fold_convert (TREE_TYPE (name2), val);
5158 else
5159 continue;
5161 if (TREE_OVERFLOW_P (cst))
5162 cst = drop_tree_overflow (cst);
5163 add_assert_info (asserts, name2, name2, comp_code, cst);
5167 if (TREE_CODE_CLASS (comp_code) == tcc_comparison
5168 && TREE_CODE (val) == INTEGER_CST)
5170 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5171 tree name2 = NULL_TREE, names[2], cst2 = NULL_TREE;
5172 tree val2 = NULL_TREE;
5173 unsigned int prec = TYPE_PRECISION (TREE_TYPE (val));
5174 wide_int mask = wi::zero (prec);
5175 unsigned int nprec = prec;
5176 enum tree_code rhs_code = ERROR_MARK;
5178 if (is_gimple_assign (def_stmt))
5179 rhs_code = gimple_assign_rhs_code (def_stmt);
5181 /* In the case of NAME != CST1 where NAME = A +- CST2 we can
5182 assert that A != CST1 -+ CST2. */
5183 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
5184 && (rhs_code == PLUS_EXPR || rhs_code == MINUS_EXPR))
5186 tree op0 = gimple_assign_rhs1 (def_stmt);
5187 tree op1 = gimple_assign_rhs2 (def_stmt);
5188 if (TREE_CODE (op0) == SSA_NAME
5189 && TREE_CODE (op1) == INTEGER_CST)
5191 enum tree_code reverse_op = (rhs_code == PLUS_EXPR
5192 ? MINUS_EXPR : PLUS_EXPR);
5193 op1 = int_const_binop (reverse_op, val, op1);
5194 if (TREE_OVERFLOW (op1))
5195 op1 = drop_tree_overflow (op1);
5196 add_assert_info (asserts, op0, op0, comp_code, op1);
5200 /* Add asserts for NAME cmp CST and NAME being defined
5201 as NAME = (int) NAME2. */
5202 if (!TYPE_UNSIGNED (TREE_TYPE (val))
5203 && (comp_code == LE_EXPR || comp_code == LT_EXPR
5204 || comp_code == GT_EXPR || comp_code == GE_EXPR)
5205 && gimple_assign_cast_p (def_stmt))
5207 name2 = gimple_assign_rhs1 (def_stmt);
5208 if (CONVERT_EXPR_CODE_P (rhs_code)
5209 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
5210 && TYPE_UNSIGNED (TREE_TYPE (name2))
5211 && prec == TYPE_PRECISION (TREE_TYPE (name2))
5212 && (comp_code == LE_EXPR || comp_code == GT_EXPR
5213 || !tree_int_cst_equal (val,
5214 TYPE_MIN_VALUE (TREE_TYPE (val)))))
5216 tree tmp, cst;
5217 enum tree_code new_comp_code = comp_code;
5219 cst = fold_convert (TREE_TYPE (name2),
5220 TYPE_MIN_VALUE (TREE_TYPE (val)));
5221 /* Build an expression for the range test. */
5222 tmp = build2 (PLUS_EXPR, TREE_TYPE (name2), name2, cst);
5223 cst = fold_build2 (PLUS_EXPR, TREE_TYPE (name2), cst,
5224 fold_convert (TREE_TYPE (name2), val));
5225 if (comp_code == LT_EXPR || comp_code == GE_EXPR)
5227 new_comp_code = comp_code == LT_EXPR ? LE_EXPR : GT_EXPR;
5228 cst = fold_build2 (MINUS_EXPR, TREE_TYPE (name2), cst,
5229 build_int_cst (TREE_TYPE (name2), 1));
5232 if (dump_file)
5234 fprintf (dump_file, "Adding assert for ");
5235 print_generic_expr (dump_file, name2);
5236 fprintf (dump_file, " from ");
5237 print_generic_expr (dump_file, tmp);
5238 fprintf (dump_file, "\n");
5241 add_assert_info (asserts, name2, tmp, new_comp_code, cst);
5245 /* Add asserts for NAME cmp CST and NAME being defined as
5246 NAME = NAME2 >> CST2.
5248 Extract CST2 from the right shift. */
5249 if (rhs_code == RSHIFT_EXPR)
5251 name2 = gimple_assign_rhs1 (def_stmt);
5252 cst2 = gimple_assign_rhs2 (def_stmt);
5253 if (TREE_CODE (name2) == SSA_NAME
5254 && tree_fits_uhwi_p (cst2)
5255 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
5256 && IN_RANGE (tree_to_uhwi (cst2), 1, prec - 1)
5257 && type_has_mode_precision_p (TREE_TYPE (val)))
5259 mask = wi::mask (tree_to_uhwi (cst2), false, prec);
5260 val2 = fold_binary (LSHIFT_EXPR, TREE_TYPE (val), val, cst2);
5263 if (val2 != NULL_TREE
5264 && TREE_CODE (val2) == INTEGER_CST
5265 && simple_cst_equal (fold_build2 (RSHIFT_EXPR,
5266 TREE_TYPE (val),
5267 val2, cst2), val))
5269 enum tree_code new_comp_code = comp_code;
5270 tree tmp, new_val;
5272 tmp = name2;
5273 if (comp_code == EQ_EXPR || comp_code == NE_EXPR)
5275 if (!TYPE_UNSIGNED (TREE_TYPE (val)))
5277 tree type = build_nonstandard_integer_type (prec, 1);
5278 tmp = build1 (NOP_EXPR, type, name2);
5279 val2 = fold_convert (type, val2);
5281 tmp = fold_build2 (MINUS_EXPR, TREE_TYPE (tmp), tmp, val2);
5282 new_val = wide_int_to_tree (TREE_TYPE (tmp), mask);
5283 new_comp_code = comp_code == EQ_EXPR ? LE_EXPR : GT_EXPR;
5285 else if (comp_code == LT_EXPR || comp_code == GE_EXPR)
5287 wide_int minval
5288 = wi::min_value (prec, TYPE_SIGN (TREE_TYPE (val)));
5289 new_val = val2;
5290 if (minval == wi::to_wide (new_val))
5291 new_val = NULL_TREE;
5293 else
5295 wide_int maxval
5296 = wi::max_value (prec, TYPE_SIGN (TREE_TYPE (val)));
5297 mask |= wi::to_wide (val2);
5298 if (wi::eq_p (mask, maxval))
5299 new_val = NULL_TREE;
5300 else
5301 new_val = wide_int_to_tree (TREE_TYPE (val2), mask);
5304 if (new_val)
5306 if (dump_file)
5308 fprintf (dump_file, "Adding assert for ");
5309 print_generic_expr (dump_file, name2);
5310 fprintf (dump_file, " from ");
5311 print_generic_expr (dump_file, tmp);
5312 fprintf (dump_file, "\n");
5315 add_assert_info (asserts, name2, tmp, new_comp_code, new_val);
5319 /* Add asserts for NAME cmp CST and NAME being defined as
5320 NAME = NAME2 & CST2.
5322 Extract CST2 from the and.
5324 Also handle
5325 NAME = (unsigned) NAME2;
5326 casts where NAME's type is unsigned and has smaller precision
5327 than NAME2's type as if it was NAME = NAME2 & MASK. */
5328 names[0] = NULL_TREE;
5329 names[1] = NULL_TREE;
5330 cst2 = NULL_TREE;
5331 if (rhs_code == BIT_AND_EXPR
5332 || (CONVERT_EXPR_CODE_P (rhs_code)
5333 && INTEGRAL_TYPE_P (TREE_TYPE (val))
5334 && TYPE_UNSIGNED (TREE_TYPE (val))
5335 && TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
5336 > prec))
5338 name2 = gimple_assign_rhs1 (def_stmt);
5339 if (rhs_code == BIT_AND_EXPR)
5340 cst2 = gimple_assign_rhs2 (def_stmt);
5341 else
5343 cst2 = TYPE_MAX_VALUE (TREE_TYPE (val));
5344 nprec = TYPE_PRECISION (TREE_TYPE (name2));
5346 if (TREE_CODE (name2) == SSA_NAME
5347 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
5348 && TREE_CODE (cst2) == INTEGER_CST
5349 && !integer_zerop (cst2)
5350 && (nprec > 1
5351 || TYPE_UNSIGNED (TREE_TYPE (val))))
5353 gimple *def_stmt2 = SSA_NAME_DEF_STMT (name2);
5354 if (gimple_assign_cast_p (def_stmt2))
5356 names[1] = gimple_assign_rhs1 (def_stmt2);
5357 if (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt2))
5358 || !INTEGRAL_TYPE_P (TREE_TYPE (names[1]))
5359 || (TYPE_PRECISION (TREE_TYPE (name2))
5360 != TYPE_PRECISION (TREE_TYPE (names[1]))))
5361 names[1] = NULL_TREE;
5363 names[0] = name2;
5366 if (names[0] || names[1])
5368 wide_int minv, maxv, valv, cst2v;
5369 wide_int tem, sgnbit;
5370 bool valid_p = false, valn, cst2n;
5371 enum tree_code ccode = comp_code;
5373 valv = wide_int::from (wi::to_wide (val), nprec, UNSIGNED);
5374 cst2v = wide_int::from (wi::to_wide (cst2), nprec, UNSIGNED);
5375 valn = wi::neg_p (valv, TYPE_SIGN (TREE_TYPE (val)));
5376 cst2n = wi::neg_p (cst2v, TYPE_SIGN (TREE_TYPE (val)));
5377 /* If CST2 doesn't have most significant bit set,
5378 but VAL is negative, we have comparison like
5379 if ((x & 0x123) > -4) (always true). Just give up. */
5380 if (!cst2n && valn)
5381 ccode = ERROR_MARK;
5382 if (cst2n)
5383 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
5384 else
5385 sgnbit = wi::zero (nprec);
5386 minv = valv & cst2v;
5387 switch (ccode)
5389 case EQ_EXPR:
5390 /* Minimum unsigned value for equality is VAL & CST2
5391 (should be equal to VAL, otherwise we probably should
5392 have folded the comparison into false) and
5393 maximum unsigned value is VAL | ~CST2. */
5394 maxv = valv | ~cst2v;
5395 valid_p = true;
5396 break;
5398 case NE_EXPR:
5399 tem = valv | ~cst2v;
5400 /* If VAL is 0, handle (X & CST2) != 0 as (X & CST2) > 0U. */
5401 if (valv == 0)
5403 cst2n = false;
5404 sgnbit = wi::zero (nprec);
5405 goto gt_expr;
5407 /* If (VAL | ~CST2) is all ones, handle it as
5408 (X & CST2) < VAL. */
5409 if (tem == -1)
5411 cst2n = false;
5412 valn = false;
5413 sgnbit = wi::zero (nprec);
5414 goto lt_expr;
5416 if (!cst2n && wi::neg_p (cst2v))
5417 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
5418 if (sgnbit != 0)
5420 if (valv == sgnbit)
5422 cst2n = true;
5423 valn = true;
5424 goto gt_expr;
5426 if (tem == wi::mask (nprec - 1, false, nprec))
5428 cst2n = true;
5429 goto lt_expr;
5431 if (!cst2n)
5432 sgnbit = wi::zero (nprec);
5434 break;
5436 case GE_EXPR:
5437 /* Minimum unsigned value for >= if (VAL & CST2) == VAL
5438 is VAL and maximum unsigned value is ~0. For signed
5439 comparison, if CST2 doesn't have most significant bit
5440 set, handle it similarly. If CST2 has MSB set,
5441 the minimum is the same, and maximum is ~0U/2. */
5442 if (minv != valv)
5444 /* If (VAL & CST2) != VAL, X & CST2 can't be equal to
5445 VAL. */
5446 minv = masked_increment (valv, cst2v, sgnbit, nprec);
5447 if (minv == valv)
5448 break;
5450 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
5451 valid_p = true;
5452 break;
5454 case GT_EXPR:
5455 gt_expr:
5456 /* Find out smallest MINV where MINV > VAL
5457 && (MINV & CST2) == MINV, if any. If VAL is signed and
5458 CST2 has MSB set, compute it biased by 1 << (nprec - 1). */
5459 minv = masked_increment (valv, cst2v, sgnbit, nprec);
5460 if (minv == valv)
5461 break;
5462 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
5463 valid_p = true;
5464 break;
5466 case LE_EXPR:
5467 /* Minimum unsigned value for <= is 0 and maximum
5468 unsigned value is VAL | ~CST2 if (VAL & CST2) == VAL.
5469 Otherwise, find smallest VAL2 where VAL2 > VAL
5470 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
5471 as maximum.
5472 For signed comparison, if CST2 doesn't have most
5473 significant bit set, handle it similarly. If CST2 has
5474 MSB set, the maximum is the same and minimum is INT_MIN. */
5475 if (minv == valv)
5476 maxv = valv;
5477 else
5479 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
5480 if (maxv == valv)
5481 break;
5482 maxv -= 1;
5484 maxv |= ~cst2v;
5485 minv = sgnbit;
5486 valid_p = true;
5487 break;
5489 case LT_EXPR:
5490 lt_expr:
5491 /* Minimum unsigned value for < is 0 and maximum
5492 unsigned value is (VAL-1) | ~CST2 if (VAL & CST2) == VAL.
5493 Otherwise, find smallest VAL2 where VAL2 > VAL
5494 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
5495 as maximum.
5496 For signed comparison, if CST2 doesn't have most
5497 significant bit set, handle it similarly. If CST2 has
5498 MSB set, the maximum is the same and minimum is INT_MIN. */
5499 if (minv == valv)
5501 if (valv == sgnbit)
5502 break;
5503 maxv = valv;
5505 else
5507 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
5508 if (maxv == valv)
5509 break;
5511 maxv -= 1;
5512 maxv |= ~cst2v;
5513 minv = sgnbit;
5514 valid_p = true;
5515 break;
5517 default:
5518 break;
5520 if (valid_p
5521 && (maxv - minv) != -1)
5523 tree tmp, new_val, type;
5524 int i;
5526 for (i = 0; i < 2; i++)
5527 if (names[i])
5529 wide_int maxv2 = maxv;
5530 tmp = names[i];
5531 type = TREE_TYPE (names[i]);
5532 if (!TYPE_UNSIGNED (type))
5534 type = build_nonstandard_integer_type (nprec, 1);
5535 tmp = build1 (NOP_EXPR, type, names[i]);
5537 if (minv != 0)
5539 tmp = build2 (PLUS_EXPR, type, tmp,
5540 wide_int_to_tree (type, -minv));
5541 maxv2 = maxv - minv;
5543 new_val = wide_int_to_tree (type, maxv2);
5545 if (dump_file)
5547 fprintf (dump_file, "Adding assert for ");
5548 print_generic_expr (dump_file, names[i]);
5549 fprintf (dump_file, " from ");
5550 print_generic_expr (dump_file, tmp);
5551 fprintf (dump_file, "\n");
5554 add_assert_info (asserts, names[i], tmp, LE_EXPR, new_val);
5561 /* OP is an operand of a truth value expression which is known to have
5562 a particular value. Register any asserts for OP and for any
5563 operands in OP's defining statement.
5565 If CODE is EQ_EXPR, then we want to register OP is zero (false),
5566 if CODE is NE_EXPR, then we want to register OP is nonzero (true). */
5568 static void
5569 register_edge_assert_for_1 (tree op, enum tree_code code,
5570 edge e, vec<assert_info> &asserts)
5572 gimple *op_def;
5573 tree val;
5574 enum tree_code rhs_code;
5576 /* We only care about SSA_NAMEs. */
5577 if (TREE_CODE (op) != SSA_NAME)
5578 return;
5580 /* We know that OP will have a zero or nonzero value. */
5581 val = build_int_cst (TREE_TYPE (op), 0);
5582 add_assert_info (asserts, op, op, code, val);
5584 /* Now look at how OP is set. If it's set from a comparison,
5585 a truth operation or some bit operations, then we may be able
5586 to register information about the operands of that assignment. */
5587 op_def = SSA_NAME_DEF_STMT (op);
5588 if (gimple_code (op_def) != GIMPLE_ASSIGN)
5589 return;
5591 rhs_code = gimple_assign_rhs_code (op_def);
5593 if (TREE_CODE_CLASS (rhs_code) == tcc_comparison)
5595 bool invert = (code == EQ_EXPR ? true : false);
5596 tree op0 = gimple_assign_rhs1 (op_def);
5597 tree op1 = gimple_assign_rhs2 (op_def);
5599 if (TREE_CODE (op0) == SSA_NAME)
5600 register_edge_assert_for_2 (op0, e, rhs_code, op0, op1, invert, asserts);
5601 if (TREE_CODE (op1) == SSA_NAME)
5602 register_edge_assert_for_2 (op1, e, rhs_code, op0, op1, invert, asserts);
5604 else if ((code == NE_EXPR
5605 && gimple_assign_rhs_code (op_def) == BIT_AND_EXPR)
5606 || (code == EQ_EXPR
5607 && gimple_assign_rhs_code (op_def) == BIT_IOR_EXPR))
5609 /* Recurse on each operand. */
5610 tree op0 = gimple_assign_rhs1 (op_def);
5611 tree op1 = gimple_assign_rhs2 (op_def);
5612 if (TREE_CODE (op0) == SSA_NAME
5613 && has_single_use (op0))
5614 register_edge_assert_for_1 (op0, code, e, asserts);
5615 if (TREE_CODE (op1) == SSA_NAME
5616 && has_single_use (op1))
5617 register_edge_assert_for_1 (op1, code, e, asserts);
5619 else if (gimple_assign_rhs_code (op_def) == BIT_NOT_EXPR
5620 && TYPE_PRECISION (TREE_TYPE (gimple_assign_lhs (op_def))) == 1)
5622 /* Recurse, flipping CODE. */
5623 code = invert_tree_comparison (code, false);
5624 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
5626 else if (gimple_assign_rhs_code (op_def) == SSA_NAME)
5628 /* Recurse through the copy. */
5629 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
5631 else if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (op_def)))
5633 /* Recurse through the type conversion, unless it is a narrowing
5634 conversion or conversion from non-integral type. */
5635 tree rhs = gimple_assign_rhs1 (op_def);
5636 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs))
5637 && (TYPE_PRECISION (TREE_TYPE (rhs))
5638 <= TYPE_PRECISION (TREE_TYPE (op))))
5639 register_edge_assert_for_1 (rhs, code, e, asserts);
5643 /* Check if comparison
5644 NAME COND_OP INTEGER_CST
5645 has a form of
5646 (X & 11...100..0) COND_OP XX...X00...0
5647 Such comparison can yield assertions like
5648 X >= XX...X00...0
5649 X <= XX...X11...1
5650 in case of COND_OP being NE_EXPR or
5651 X < XX...X00...0
5652 X > XX...X11...1
5653 in case of EQ_EXPR. */
5655 static bool
5656 is_masked_range_test (tree name, tree valt, enum tree_code cond_code,
5657 tree *new_name, tree *low, enum tree_code *low_code,
5658 tree *high, enum tree_code *high_code)
5660 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5662 if (!is_gimple_assign (def_stmt)
5663 || gimple_assign_rhs_code (def_stmt) != BIT_AND_EXPR)
5664 return false;
5666 tree t = gimple_assign_rhs1 (def_stmt);
5667 tree maskt = gimple_assign_rhs2 (def_stmt);
5668 if (TREE_CODE (t) != SSA_NAME || TREE_CODE (maskt) != INTEGER_CST)
5669 return false;
5671 wi::tree_to_wide_ref mask = wi::to_wide (maskt);
5672 wide_int inv_mask = ~mask;
5673 /* Assume VALT is INTEGER_CST. */
5674 wi::tree_to_wide_ref val = wi::to_wide (valt);
5676 if ((inv_mask & (inv_mask + 1)) != 0
5677 || (val & mask) != val)
5678 return false;
5680 bool is_range = cond_code == EQ_EXPR;
5682 tree type = TREE_TYPE (t);
5683 wide_int min = wi::min_value (type),
5684 max = wi::max_value (type);
5686 if (is_range)
5688 *low_code = val == min ? ERROR_MARK : GE_EXPR;
5689 *high_code = val == max ? ERROR_MARK : LE_EXPR;
5691 else
5693 /* We can still generate assertion if one of alternatives
5694 is known to always be false. */
5695 if (val == min)
5697 *low_code = (enum tree_code) 0;
5698 *high_code = GT_EXPR;
5700 else if ((val | inv_mask) == max)
5702 *low_code = LT_EXPR;
5703 *high_code = (enum tree_code) 0;
5705 else
5706 return false;
5709 *new_name = t;
5710 *low = wide_int_to_tree (type, val);
5711 *high = wide_int_to_tree (type, val | inv_mask);
5713 if (wi::neg_p (val, TYPE_SIGN (type)))
5714 std::swap (*low, *high);
5716 return true;
5719 /* Try to register an edge assertion for SSA name NAME on edge E for
5720 the condition COND contributing to the conditional jump pointed to by
5721 SI. */
5723 static void
5724 register_edge_assert_for (tree name, edge e,
5725 enum tree_code cond_code, tree cond_op0,
5726 tree cond_op1, vec<assert_info> &asserts)
5728 tree val;
5729 enum tree_code comp_code;
5730 bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
5732 /* Do not attempt to infer anything in names that flow through
5733 abnormal edges. */
5734 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
5735 return;
5737 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
5738 cond_op0, cond_op1,
5739 is_else_edge,
5740 &comp_code, &val))
5741 return;
5743 /* Register ASSERT_EXPRs for name. */
5744 register_edge_assert_for_2 (name, e, cond_code, cond_op0,
5745 cond_op1, is_else_edge, asserts);
5748 /* If COND is effectively an equality test of an SSA_NAME against
5749 the value zero or one, then we may be able to assert values
5750 for SSA_NAMEs which flow into COND. */
5752 /* In the case of NAME == 1 or NAME != 0, for BIT_AND_EXPR defining
5753 statement of NAME we can assert both operands of the BIT_AND_EXPR
5754 have nonzero value. */
5755 if (((comp_code == EQ_EXPR && integer_onep (val))
5756 || (comp_code == NE_EXPR && integer_zerop (val))))
5758 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5760 if (is_gimple_assign (def_stmt)
5761 && gimple_assign_rhs_code (def_stmt) == BIT_AND_EXPR)
5763 tree op0 = gimple_assign_rhs1 (def_stmt);
5764 tree op1 = gimple_assign_rhs2 (def_stmt);
5765 register_edge_assert_for_1 (op0, NE_EXPR, e, asserts);
5766 register_edge_assert_for_1 (op1, NE_EXPR, e, asserts);
5770 /* In the case of NAME == 0 or NAME != 1, for BIT_IOR_EXPR defining
5771 statement of NAME we can assert both operands of the BIT_IOR_EXPR
5772 have zero value. */
5773 if (((comp_code == EQ_EXPR && integer_zerop (val))
5774 || (comp_code == NE_EXPR && integer_onep (val))))
5776 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5778 /* For BIT_IOR_EXPR only if NAME == 0 both operands have
5779 necessarily zero value, or if type-precision is one. */
5780 if (is_gimple_assign (def_stmt)
5781 && (gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR
5782 && (TYPE_PRECISION (TREE_TYPE (name)) == 1
5783 || comp_code == EQ_EXPR)))
5785 tree op0 = gimple_assign_rhs1 (def_stmt);
5786 tree op1 = gimple_assign_rhs2 (def_stmt);
5787 register_edge_assert_for_1 (op0, EQ_EXPR, e, asserts);
5788 register_edge_assert_for_1 (op1, EQ_EXPR, e, asserts);
5792 /* Sometimes we can infer ranges from (NAME & MASK) == VALUE. */
5793 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
5794 && TREE_CODE (val) == INTEGER_CST)
5796 enum tree_code low_code, high_code;
5797 tree low, high;
5798 if (is_masked_range_test (name, val, comp_code, &name, &low,
5799 &low_code, &high, &high_code))
5801 if (low_code != ERROR_MARK)
5802 register_edge_assert_for_2 (name, e, low_code, name,
5803 low, /*invert*/false, asserts);
5804 if (high_code != ERROR_MARK)
5805 register_edge_assert_for_2 (name, e, high_code, name,
5806 high, /*invert*/false, asserts);
5811 /* Finish found ASSERTS for E and register them at GSI. */
5813 static void
5814 finish_register_edge_assert_for (edge e, gimple_stmt_iterator gsi,
5815 vec<assert_info> &asserts)
5817 for (unsigned i = 0; i < asserts.length (); ++i)
5818 /* Only register an ASSERT_EXPR if NAME was found in the sub-graph
5819 reachable from E. */
5820 if (live_on_edge (e, asserts[i].name))
5821 register_new_assert_for (asserts[i].name, asserts[i].expr,
5822 asserts[i].comp_code, asserts[i].val,
5823 NULL, e, gsi);
5828 /* Determine whether the outgoing edges of BB should receive an
5829 ASSERT_EXPR for each of the operands of BB's LAST statement.
5830 The last statement of BB must be a COND_EXPR.
5832 If any of the sub-graphs rooted at BB have an interesting use of
5833 the predicate operands, an assert location node is added to the
5834 list of assertions for the corresponding operands. */
5836 static void
5837 find_conditional_asserts (basic_block bb, gcond *last)
5839 gimple_stmt_iterator bsi;
5840 tree op;
5841 edge_iterator ei;
5842 edge e;
5843 ssa_op_iter iter;
5845 bsi = gsi_for_stmt (last);
5847 /* Look for uses of the operands in each of the sub-graphs
5848 rooted at BB. We need to check each of the outgoing edges
5849 separately, so that we know what kind of ASSERT_EXPR to
5850 insert. */
5851 FOR_EACH_EDGE (e, ei, bb->succs)
5853 if (e->dest == bb)
5854 continue;
5856 /* Register the necessary assertions for each operand in the
5857 conditional predicate. */
5858 auto_vec<assert_info, 8> asserts;
5859 FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
5860 register_edge_assert_for (op, e,
5861 gimple_cond_code (last),
5862 gimple_cond_lhs (last),
5863 gimple_cond_rhs (last), asserts);
5864 finish_register_edge_assert_for (e, bsi, asserts);
5868 struct case_info
5870 tree expr;
5871 basic_block bb;
5874 /* Compare two case labels sorting first by the destination bb index
5875 and then by the case value. */
5877 static int
5878 compare_case_labels (const void *p1, const void *p2)
5880 const struct case_info *ci1 = (const struct case_info *) p1;
5881 const struct case_info *ci2 = (const struct case_info *) p2;
5882 int idx1 = ci1->bb->index;
5883 int idx2 = ci2->bb->index;
5885 if (idx1 < idx2)
5886 return -1;
5887 else if (idx1 == idx2)
5889 /* Make sure the default label is first in a group. */
5890 if (!CASE_LOW (ci1->expr))
5891 return -1;
5892 else if (!CASE_LOW (ci2->expr))
5893 return 1;
5894 else
5895 return tree_int_cst_compare (CASE_LOW (ci1->expr),
5896 CASE_LOW (ci2->expr));
5898 else
5899 return 1;
5902 /* Determine whether the outgoing edges of BB should receive an
5903 ASSERT_EXPR for each of the operands of BB's LAST statement.
5904 The last statement of BB must be a SWITCH_EXPR.
5906 If any of the sub-graphs rooted at BB have an interesting use of
5907 the predicate operands, an assert location node is added to the
5908 list of assertions for the corresponding operands. */
5910 static void
5911 find_switch_asserts (basic_block bb, gswitch *last)
5913 gimple_stmt_iterator bsi;
5914 tree op;
5915 edge e;
5916 struct case_info *ci;
5917 size_t n = gimple_switch_num_labels (last);
5918 #if GCC_VERSION >= 4000
5919 unsigned int idx;
5920 #else
5921 /* Work around GCC 3.4 bug (PR 37086). */
5922 volatile unsigned int idx;
5923 #endif
5925 bsi = gsi_for_stmt (last);
5926 op = gimple_switch_index (last);
5927 if (TREE_CODE (op) != SSA_NAME)
5928 return;
5930 /* Build a vector of case labels sorted by destination label. */
5931 ci = XNEWVEC (struct case_info, n);
5932 for (idx = 0; idx < n; ++idx)
5934 ci[idx].expr = gimple_switch_label (last, idx);
5935 ci[idx].bb = label_to_block (CASE_LABEL (ci[idx].expr));
5937 edge default_edge = find_edge (bb, ci[0].bb);
5938 qsort (ci, n, sizeof (struct case_info), compare_case_labels);
5940 for (idx = 0; idx < n; ++idx)
5942 tree min, max;
5943 tree cl = ci[idx].expr;
5944 basic_block cbb = ci[idx].bb;
5946 min = CASE_LOW (cl);
5947 max = CASE_HIGH (cl);
5949 /* If there are multiple case labels with the same destination
5950 we need to combine them to a single value range for the edge. */
5951 if (idx + 1 < n && cbb == ci[idx + 1].bb)
5953 /* Skip labels until the last of the group. */
5954 do {
5955 ++idx;
5956 } while (idx < n && cbb == ci[idx].bb);
5957 --idx;
5959 /* Pick up the maximum of the case label range. */
5960 if (CASE_HIGH (ci[idx].expr))
5961 max = CASE_HIGH (ci[idx].expr);
5962 else
5963 max = CASE_LOW (ci[idx].expr);
5966 /* Can't extract a useful assertion out of a range that includes the
5967 default label. */
5968 if (min == NULL_TREE)
5969 continue;
5971 /* Find the edge to register the assert expr on. */
5972 e = find_edge (bb, cbb);
5974 /* Register the necessary assertions for the operand in the
5975 SWITCH_EXPR. */
5976 auto_vec<assert_info, 8> asserts;
5977 register_edge_assert_for (op, e,
5978 max ? GE_EXPR : EQ_EXPR,
5979 op, fold_convert (TREE_TYPE (op), min),
5980 asserts);
5981 if (max)
5982 register_edge_assert_for (op, e, LE_EXPR, op,
5983 fold_convert (TREE_TYPE (op), max),
5984 asserts);
5985 finish_register_edge_assert_for (e, bsi, asserts);
5988 XDELETEVEC (ci);
5990 if (!live_on_edge (default_edge, op))
5991 return;
5993 /* Now register along the default label assertions that correspond to the
5994 anti-range of each label. */
5995 int insertion_limit = PARAM_VALUE (PARAM_MAX_VRP_SWITCH_ASSERTIONS);
5996 if (insertion_limit == 0)
5997 return;
5999 /* We can't do this if the default case shares a label with another case. */
6000 tree default_cl = gimple_switch_default_label (last);
6001 for (idx = 1; idx < n; idx++)
6003 tree min, max;
6004 tree cl = gimple_switch_label (last, idx);
6005 if (CASE_LABEL (cl) == CASE_LABEL (default_cl))
6006 continue;
6008 min = CASE_LOW (cl);
6009 max = CASE_HIGH (cl);
6011 /* Combine contiguous case ranges to reduce the number of assertions
6012 to insert. */
6013 for (idx = idx + 1; idx < n; idx++)
6015 tree next_min, next_max;
6016 tree next_cl = gimple_switch_label (last, idx);
6017 if (CASE_LABEL (next_cl) == CASE_LABEL (default_cl))
6018 break;
6020 next_min = CASE_LOW (next_cl);
6021 next_max = CASE_HIGH (next_cl);
6023 wide_int difference = (wi::to_wide (next_min)
6024 - wi::to_wide (max ? max : min));
6025 if (wi::eq_p (difference, 1))
6026 max = next_max ? next_max : next_min;
6027 else
6028 break;
6030 idx--;
6032 if (max == NULL_TREE)
6034 /* Register the assertion OP != MIN. */
6035 auto_vec<assert_info, 8> asserts;
6036 min = fold_convert (TREE_TYPE (op), min);
6037 register_edge_assert_for (op, default_edge, NE_EXPR, op, min,
6038 asserts);
6039 finish_register_edge_assert_for (default_edge, bsi, asserts);
6041 else
6043 /* Register the assertion (unsigned)OP - MIN > (MAX - MIN),
6044 which will give OP the anti-range ~[MIN,MAX]. */
6045 tree uop = fold_convert (unsigned_type_for (TREE_TYPE (op)), op);
6046 min = fold_convert (TREE_TYPE (uop), min);
6047 max = fold_convert (TREE_TYPE (uop), max);
6049 tree lhs = fold_build2 (MINUS_EXPR, TREE_TYPE (uop), uop, min);
6050 tree rhs = int_const_binop (MINUS_EXPR, max, min);
6051 register_new_assert_for (op, lhs, GT_EXPR, rhs,
6052 NULL, default_edge, bsi);
6055 if (--insertion_limit == 0)
6056 break;
6061 /* Traverse all the statements in block BB looking for statements that
6062 may generate useful assertions for the SSA names in their operand.
6063 If a statement produces a useful assertion A for name N_i, then the
6064 list of assertions already generated for N_i is scanned to
6065 determine if A is actually needed.
6067 If N_i already had the assertion A at a location dominating the
6068 current location, then nothing needs to be done. Otherwise, the
6069 new location for A is recorded instead.
6071 1- For every statement S in BB, all the variables used by S are
6072 added to bitmap FOUND_IN_SUBGRAPH.
6074 2- If statement S uses an operand N in a way that exposes a known
6075 value range for N, then if N was not already generated by an
6076 ASSERT_EXPR, create a new assert location for N. For instance,
6077 if N is a pointer and the statement dereferences it, we can
6078 assume that N is not NULL.
6080 3- COND_EXPRs are a special case of #2. We can derive range
6081 information from the predicate but need to insert different
6082 ASSERT_EXPRs for each of the sub-graphs rooted at the
6083 conditional block. If the last statement of BB is a conditional
6084 expression of the form 'X op Y', then
6086 a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
6088 b) If the conditional is the only entry point to the sub-graph
6089 corresponding to the THEN_CLAUSE, recurse into it. On
6090 return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
6091 an ASSERT_EXPR is added for the corresponding variable.
6093 c) Repeat step (b) on the ELSE_CLAUSE.
6095 d) Mark X and Y in FOUND_IN_SUBGRAPH.
6097 For instance,
6099 if (a == 9)
6100 b = a;
6101 else
6102 b = c + 1;
6104 In this case, an assertion on the THEN clause is useful to
6105 determine that 'a' is always 9 on that edge. However, an assertion
6106 on the ELSE clause would be unnecessary.
6108 4- If BB does not end in a conditional expression, then we recurse
6109 into BB's dominator children.
6111 At the end of the recursive traversal, every SSA name will have a
6112 list of locations where ASSERT_EXPRs should be added. When a new
6113 location for name N is found, it is registered by calling
6114 register_new_assert_for. That function keeps track of all the
6115 registered assertions to prevent adding unnecessary assertions.
6116 For instance, if a pointer P_4 is dereferenced more than once in a
6117 dominator tree, only the location dominating all the dereference of
6118 P_4 will receive an ASSERT_EXPR. */
6120 static void
6121 find_assert_locations_1 (basic_block bb, sbitmap live)
6123 gimple *last;
6125 last = last_stmt (bb);
6127 /* If BB's last statement is a conditional statement involving integer
6128 operands, determine if we need to add ASSERT_EXPRs. */
6129 if (last
6130 && gimple_code (last) == GIMPLE_COND
6131 && !fp_predicate (last)
6132 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
6133 find_conditional_asserts (bb, as_a <gcond *> (last));
6135 /* If BB's last statement is a switch statement involving integer
6136 operands, determine if we need to add ASSERT_EXPRs. */
6137 if (last
6138 && gimple_code (last) == GIMPLE_SWITCH
6139 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
6140 find_switch_asserts (bb, as_a <gswitch *> (last));
6142 /* Traverse all the statements in BB marking used names and looking
6143 for statements that may infer assertions for their used operands. */
6144 for (gimple_stmt_iterator si = gsi_last_bb (bb); !gsi_end_p (si);
6145 gsi_prev (&si))
6147 gimple *stmt;
6148 tree op;
6149 ssa_op_iter i;
6151 stmt = gsi_stmt (si);
6153 if (is_gimple_debug (stmt))
6154 continue;
6156 /* See if we can derive an assertion for any of STMT's operands. */
6157 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
6159 tree value;
6160 enum tree_code comp_code;
6162 /* If op is not live beyond this stmt, do not bother to insert
6163 asserts for it. */
6164 if (!bitmap_bit_p (live, SSA_NAME_VERSION (op)))
6165 continue;
6167 /* If OP is used in such a way that we can infer a value
6168 range for it, and we don't find a previous assertion for
6169 it, create a new assertion location node for OP. */
6170 if (infer_value_range (stmt, op, &comp_code, &value))
6172 /* If we are able to infer a nonzero value range for OP,
6173 then walk backwards through the use-def chain to see if OP
6174 was set via a typecast.
6176 If so, then we can also infer a nonzero value range
6177 for the operand of the NOP_EXPR. */
6178 if (comp_code == NE_EXPR && integer_zerop (value))
6180 tree t = op;
6181 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
6183 while (is_gimple_assign (def_stmt)
6184 && CONVERT_EXPR_CODE_P
6185 (gimple_assign_rhs_code (def_stmt))
6186 && TREE_CODE
6187 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
6188 && POINTER_TYPE_P
6189 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
6191 t = gimple_assign_rhs1 (def_stmt);
6192 def_stmt = SSA_NAME_DEF_STMT (t);
6194 /* Note we want to register the assert for the
6195 operand of the NOP_EXPR after SI, not after the
6196 conversion. */
6197 if (bitmap_bit_p (live, SSA_NAME_VERSION (t)))
6198 register_new_assert_for (t, t, comp_code, value,
6199 bb, NULL, si);
6203 register_new_assert_for (op, op, comp_code, value, bb, NULL, si);
6207 /* Update live. */
6208 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
6209 bitmap_set_bit (live, SSA_NAME_VERSION (op));
6210 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_DEF)
6211 bitmap_clear_bit (live, SSA_NAME_VERSION (op));
6214 /* Traverse all PHI nodes in BB, updating live. */
6215 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
6216 gsi_next (&si))
6218 use_operand_p arg_p;
6219 ssa_op_iter i;
6220 gphi *phi = si.phi ();
6221 tree res = gimple_phi_result (phi);
6223 if (virtual_operand_p (res))
6224 continue;
6226 FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
6228 tree arg = USE_FROM_PTR (arg_p);
6229 if (TREE_CODE (arg) == SSA_NAME)
6230 bitmap_set_bit (live, SSA_NAME_VERSION (arg));
6233 bitmap_clear_bit (live, SSA_NAME_VERSION (res));
6237 /* Do an RPO walk over the function computing SSA name liveness
6238 on-the-fly and deciding on assert expressions to insert. */
6240 static void
6241 find_assert_locations (void)
6243 int *rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
6244 int *bb_rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
6245 int *last_rpo = XCNEWVEC (int, last_basic_block_for_fn (cfun));
6246 int rpo_cnt, i;
6248 live = XCNEWVEC (sbitmap, last_basic_block_for_fn (cfun));
6249 rpo_cnt = pre_and_rev_post_order_compute (NULL, rpo, false);
6250 for (i = 0; i < rpo_cnt; ++i)
6251 bb_rpo[rpo[i]] = i;
6253 /* Pre-seed loop latch liveness from loop header PHI nodes. Due to
6254 the order we compute liveness and insert asserts we otherwise
6255 fail to insert asserts into the loop latch. */
6256 loop_p loop;
6257 FOR_EACH_LOOP (loop, 0)
6259 i = loop->latch->index;
6260 unsigned int j = single_succ_edge (loop->latch)->dest_idx;
6261 for (gphi_iterator gsi = gsi_start_phis (loop->header);
6262 !gsi_end_p (gsi); gsi_next (&gsi))
6264 gphi *phi = gsi.phi ();
6265 if (virtual_operand_p (gimple_phi_result (phi)))
6266 continue;
6267 tree arg = gimple_phi_arg_def (phi, j);
6268 if (TREE_CODE (arg) == SSA_NAME)
6270 if (live[i] == NULL)
6272 live[i] = sbitmap_alloc (num_ssa_names);
6273 bitmap_clear (live[i]);
6275 bitmap_set_bit (live[i], SSA_NAME_VERSION (arg));
6280 for (i = rpo_cnt - 1; i >= 0; --i)
6282 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, rpo[i]);
6283 edge e;
6284 edge_iterator ei;
6286 if (!live[rpo[i]])
6288 live[rpo[i]] = sbitmap_alloc (num_ssa_names);
6289 bitmap_clear (live[rpo[i]]);
6292 /* Process BB and update the live information with uses in
6293 this block. */
6294 find_assert_locations_1 (bb, live[rpo[i]]);
6296 /* Merge liveness into the predecessor blocks and free it. */
6297 if (!bitmap_empty_p (live[rpo[i]]))
6299 int pred_rpo = i;
6300 FOR_EACH_EDGE (e, ei, bb->preds)
6302 int pred = e->src->index;
6303 if ((e->flags & EDGE_DFS_BACK) || pred == ENTRY_BLOCK)
6304 continue;
6306 if (!live[pred])
6308 live[pred] = sbitmap_alloc (num_ssa_names);
6309 bitmap_clear (live[pred]);
6311 bitmap_ior (live[pred], live[pred], live[rpo[i]]);
6313 if (bb_rpo[pred] < pred_rpo)
6314 pred_rpo = bb_rpo[pred];
6317 /* Record the RPO number of the last visited block that needs
6318 live information from this block. */
6319 last_rpo[rpo[i]] = pred_rpo;
6321 else
6323 sbitmap_free (live[rpo[i]]);
6324 live[rpo[i]] = NULL;
6327 /* We can free all successors live bitmaps if all their
6328 predecessors have been visited already. */
6329 FOR_EACH_EDGE (e, ei, bb->succs)
6330 if (last_rpo[e->dest->index] == i
6331 && live[e->dest->index])
6333 sbitmap_free (live[e->dest->index]);
6334 live[e->dest->index] = NULL;
6338 XDELETEVEC (rpo);
6339 XDELETEVEC (bb_rpo);
6340 XDELETEVEC (last_rpo);
6341 for (i = 0; i < last_basic_block_for_fn (cfun); ++i)
6342 if (live[i])
6343 sbitmap_free (live[i]);
6344 XDELETEVEC (live);
6347 /* Create an ASSERT_EXPR for NAME and insert it in the location
6348 indicated by LOC. Return true if we made any edge insertions. */
6350 static bool
6351 process_assert_insertions_for (tree name, assert_locus *loc)
6353 /* Build the comparison expression NAME_i COMP_CODE VAL. */
6354 gimple *stmt;
6355 tree cond;
6356 gimple *assert_stmt;
6357 edge_iterator ei;
6358 edge e;
6360 /* If we have X <=> X do not insert an assert expr for that. */
6361 if (loc->expr == loc->val)
6362 return false;
6364 cond = build2 (loc->comp_code, boolean_type_node, loc->expr, loc->val);
6365 assert_stmt = build_assert_expr_for (cond, name);
6366 if (loc->e)
6368 /* We have been asked to insert the assertion on an edge. This
6369 is used only by COND_EXPR and SWITCH_EXPR assertions. */
6370 gcc_checking_assert (gimple_code (gsi_stmt (loc->si)) == GIMPLE_COND
6371 || (gimple_code (gsi_stmt (loc->si))
6372 == GIMPLE_SWITCH));
6374 gsi_insert_on_edge (loc->e, assert_stmt);
6375 return true;
6378 /* If the stmt iterator points at the end then this is an insertion
6379 at the beginning of a block. */
6380 if (gsi_end_p (loc->si))
6382 gimple_stmt_iterator si = gsi_after_labels (loc->bb);
6383 gsi_insert_before (&si, assert_stmt, GSI_SAME_STMT);
6384 return false;
6387 /* Otherwise, we can insert right after LOC->SI iff the
6388 statement must not be the last statement in the block. */
6389 stmt = gsi_stmt (loc->si);
6390 if (!stmt_ends_bb_p (stmt))
6392 gsi_insert_after (&loc->si, assert_stmt, GSI_SAME_STMT);
6393 return false;
6396 /* If STMT must be the last statement in BB, we can only insert new
6397 assertions on the non-abnormal edge out of BB. Note that since
6398 STMT is not control flow, there may only be one non-abnormal/eh edge
6399 out of BB. */
6400 FOR_EACH_EDGE (e, ei, loc->bb->succs)
6401 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
6403 gsi_insert_on_edge (e, assert_stmt);
6404 return true;
6407 gcc_unreachable ();
6410 /* Qsort helper for sorting assert locations. If stable is true, don't
6411 use iterative_hash_expr because it can be unstable for -fcompare-debug,
6412 on the other side some pointers might be NULL. */
6414 template <bool stable>
6415 static int
6416 compare_assert_loc (const void *pa, const void *pb)
6418 assert_locus * const a = *(assert_locus * const *)pa;
6419 assert_locus * const b = *(assert_locus * const *)pb;
6421 /* If stable, some asserts might be optimized away already, sort
6422 them last. */
6423 if (stable)
6425 if (a == NULL)
6426 return b != NULL;
6427 else if (b == NULL)
6428 return -1;
6431 if (a->e == NULL && b->e != NULL)
6432 return 1;
6433 else if (a->e != NULL && b->e == NULL)
6434 return -1;
6436 /* After the above checks, we know that (a->e == NULL) == (b->e == NULL),
6437 no need to test both a->e and b->e. */
6439 /* Sort after destination index. */
6440 if (a->e == NULL)
6442 else if (a->e->dest->index > b->e->dest->index)
6443 return 1;
6444 else if (a->e->dest->index < b->e->dest->index)
6445 return -1;
6447 /* Sort after comp_code. */
6448 if (a->comp_code > b->comp_code)
6449 return 1;
6450 else if (a->comp_code < b->comp_code)
6451 return -1;
6453 hashval_t ha, hb;
6455 /* E.g. if a->val is ADDR_EXPR of a VAR_DECL, iterative_hash_expr
6456 uses DECL_UID of the VAR_DECL, so sorting might differ between
6457 -g and -g0. When doing the removal of redundant assert exprs
6458 and commonization to successors, this does not matter, but for
6459 the final sort needs to be stable. */
6460 if (stable)
6462 ha = 0;
6463 hb = 0;
6465 else
6467 ha = iterative_hash_expr (a->expr, iterative_hash_expr (a->val, 0));
6468 hb = iterative_hash_expr (b->expr, iterative_hash_expr (b->val, 0));
6471 /* Break the tie using hashing and source/bb index. */
6472 if (ha == hb)
6473 return (a->e != NULL
6474 ? a->e->src->index - b->e->src->index
6475 : a->bb->index - b->bb->index);
6476 return ha > hb ? 1 : -1;
6479 /* Process all the insertions registered for every name N_i registered
6480 in NEED_ASSERT_FOR. The list of assertions to be inserted are
6481 found in ASSERTS_FOR[i]. */
6483 static void
6484 process_assert_insertions (void)
6486 unsigned i;
6487 bitmap_iterator bi;
6488 bool update_edges_p = false;
6489 int num_asserts = 0;
6491 if (dump_file && (dump_flags & TDF_DETAILS))
6492 dump_all_asserts (dump_file);
6494 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
6496 assert_locus *loc = asserts_for[i];
6497 gcc_assert (loc);
6499 auto_vec<assert_locus *, 16> asserts;
6500 for (; loc; loc = loc->next)
6501 asserts.safe_push (loc);
6502 asserts.qsort (compare_assert_loc<false>);
6504 /* Push down common asserts to successors and remove redundant ones. */
6505 unsigned ecnt = 0;
6506 assert_locus *common = NULL;
6507 unsigned commonj = 0;
6508 for (unsigned j = 0; j < asserts.length (); ++j)
6510 loc = asserts[j];
6511 if (! loc->e)
6512 common = NULL;
6513 else if (! common
6514 || loc->e->dest != common->e->dest
6515 || loc->comp_code != common->comp_code
6516 || ! operand_equal_p (loc->val, common->val, 0)
6517 || ! operand_equal_p (loc->expr, common->expr, 0))
6519 commonj = j;
6520 common = loc;
6521 ecnt = 1;
6523 else if (loc->e == asserts[j-1]->e)
6525 /* Remove duplicate asserts. */
6526 if (commonj == j - 1)
6528 commonj = j;
6529 common = loc;
6531 free (asserts[j-1]);
6532 asserts[j-1] = NULL;
6534 else
6536 ecnt++;
6537 if (EDGE_COUNT (common->e->dest->preds) == ecnt)
6539 /* We have the same assertion on all incoming edges of a BB.
6540 Insert it at the beginning of that block. */
6541 loc->bb = loc->e->dest;
6542 loc->e = NULL;
6543 loc->si = gsi_none ();
6544 common = NULL;
6545 /* Clear asserts commoned. */
6546 for (; commonj != j; ++commonj)
6547 if (asserts[commonj])
6549 free (asserts[commonj]);
6550 asserts[commonj] = NULL;
6556 /* The asserts vector sorting above might be unstable for
6557 -fcompare-debug, sort again to ensure a stable sort. */
6558 asserts.qsort (compare_assert_loc<true>);
6559 for (unsigned j = 0; j < asserts.length (); ++j)
6561 loc = asserts[j];
6562 if (! loc)
6563 break;
6564 update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
6565 num_asserts++;
6566 free (loc);
6570 if (update_edges_p)
6571 gsi_commit_edge_inserts ();
6573 statistics_counter_event (cfun, "Number of ASSERT_EXPR expressions inserted",
6574 num_asserts);
6578 /* Traverse the flowgraph looking for conditional jumps to insert range
6579 expressions. These range expressions are meant to provide information
6580 to optimizations that need to reason in terms of value ranges. They
6581 will not be expanded into RTL. For instance, given:
6583 x = ...
6584 y = ...
6585 if (x < y)
6586 y = x - 2;
6587 else
6588 x = y + 3;
6590 this pass will transform the code into:
6592 x = ...
6593 y = ...
6594 if (x < y)
6596 x = ASSERT_EXPR <x, x < y>
6597 y = x - 2
6599 else
6601 y = ASSERT_EXPR <y, x >= y>
6602 x = y + 3
6605 The idea is that once copy and constant propagation have run, other
6606 optimizations will be able to determine what ranges of values can 'x'
6607 take in different paths of the code, simply by checking the reaching
6608 definition of 'x'. */
6610 static void
6611 insert_range_assertions (void)
6613 need_assert_for = BITMAP_ALLOC (NULL);
6614 asserts_for = XCNEWVEC (assert_locus *, num_ssa_names);
6616 calculate_dominance_info (CDI_DOMINATORS);
6618 find_assert_locations ();
6619 if (!bitmap_empty_p (need_assert_for))
6621 process_assert_insertions ();
6622 update_ssa (TODO_update_ssa_no_phi);
6625 if (dump_file && (dump_flags & TDF_DETAILS))
6627 fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
6628 dump_function_to_file (current_function_decl, dump_file, dump_flags);
6631 free (asserts_for);
6632 BITMAP_FREE (need_assert_for);
6635 /* Checks one ARRAY_REF in REF, located at LOCUS. Ignores flexible arrays
6636 and "struct" hacks. If VRP can determine that the
6637 array subscript is a constant, check if it is outside valid
6638 range. If the array subscript is a RANGE, warn if it is
6639 non-overlapping with valid range.
6640 IGNORE_OFF_BY_ONE is true if the ARRAY_REF is inside a ADDR_EXPR. */
6642 static void
6643 check_array_ref (location_t location, tree ref, bool ignore_off_by_one)
6645 value_range *vr = NULL;
6646 tree low_sub, up_sub;
6647 tree low_bound, up_bound, up_bound_p1;
6649 if (TREE_NO_WARNING (ref))
6650 return;
6652 low_sub = up_sub = TREE_OPERAND (ref, 1);
6653 up_bound = array_ref_up_bound (ref);
6655 /* Can not check flexible arrays. */
6656 if (!up_bound
6657 || TREE_CODE (up_bound) != INTEGER_CST)
6658 return;
6660 /* Accesses to trailing arrays via pointers may access storage
6661 beyond the types array bounds. */
6662 if (warn_array_bounds < 2
6663 && array_at_struct_end_p (ref))
6664 return;
6666 low_bound = array_ref_low_bound (ref);
6667 up_bound_p1 = int_const_binop (PLUS_EXPR, up_bound,
6668 build_int_cst (TREE_TYPE (up_bound), 1));
6670 /* Empty array. */
6671 if (tree_int_cst_equal (low_bound, up_bound_p1))
6673 warning_at (location, OPT_Warray_bounds,
6674 "array subscript is above array bounds");
6675 TREE_NO_WARNING (ref) = 1;
6678 if (TREE_CODE (low_sub) == SSA_NAME)
6680 vr = get_value_range (low_sub);
6681 if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
6683 low_sub = vr->type == VR_RANGE ? vr->max : vr->min;
6684 up_sub = vr->type == VR_RANGE ? vr->min : vr->max;
6688 if (vr && vr->type == VR_ANTI_RANGE)
6690 if (TREE_CODE (up_sub) == INTEGER_CST
6691 && (ignore_off_by_one
6692 ? tree_int_cst_lt (up_bound, up_sub)
6693 : tree_int_cst_le (up_bound, up_sub))
6694 && TREE_CODE (low_sub) == INTEGER_CST
6695 && tree_int_cst_le (low_sub, low_bound))
6697 warning_at (location, OPT_Warray_bounds,
6698 "array subscript is outside array bounds");
6699 TREE_NO_WARNING (ref) = 1;
6702 else if (TREE_CODE (up_sub) == INTEGER_CST
6703 && (ignore_off_by_one
6704 ? !tree_int_cst_le (up_sub, up_bound_p1)
6705 : !tree_int_cst_le (up_sub, up_bound)))
6707 if (dump_file && (dump_flags & TDF_DETAILS))
6709 fprintf (dump_file, "Array bound warning for ");
6710 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
6711 fprintf (dump_file, "\n");
6713 warning_at (location, OPT_Warray_bounds,
6714 "array subscript is above array bounds");
6715 TREE_NO_WARNING (ref) = 1;
6717 else if (TREE_CODE (low_sub) == INTEGER_CST
6718 && tree_int_cst_lt (low_sub, low_bound))
6720 if (dump_file && (dump_flags & TDF_DETAILS))
6722 fprintf (dump_file, "Array bound warning for ");
6723 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
6724 fprintf (dump_file, "\n");
6726 warning_at (location, OPT_Warray_bounds,
6727 "array subscript is below array bounds");
6728 TREE_NO_WARNING (ref) = 1;
6732 /* Searches if the expr T, located at LOCATION computes
6733 address of an ARRAY_REF, and call check_array_ref on it. */
6735 static void
6736 search_for_addr_array (tree t, location_t location)
6738 /* Check each ARRAY_REFs in the reference chain. */
6741 if (TREE_CODE (t) == ARRAY_REF)
6742 check_array_ref (location, t, true /*ignore_off_by_one*/);
6744 t = TREE_OPERAND (t, 0);
6746 while (handled_component_p (t));
6748 if (TREE_CODE (t) == MEM_REF
6749 && TREE_CODE (TREE_OPERAND (t, 0)) == ADDR_EXPR
6750 && !TREE_NO_WARNING (t))
6752 tree tem = TREE_OPERAND (TREE_OPERAND (t, 0), 0);
6753 tree low_bound, up_bound, el_sz;
6754 offset_int idx;
6755 if (TREE_CODE (TREE_TYPE (tem)) != ARRAY_TYPE
6756 || TREE_CODE (TREE_TYPE (TREE_TYPE (tem))) == ARRAY_TYPE
6757 || !TYPE_DOMAIN (TREE_TYPE (tem)))
6758 return;
6760 low_bound = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
6761 up_bound = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
6762 el_sz = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (tem)));
6763 if (!low_bound
6764 || TREE_CODE (low_bound) != INTEGER_CST
6765 || !up_bound
6766 || TREE_CODE (up_bound) != INTEGER_CST
6767 || !el_sz
6768 || TREE_CODE (el_sz) != INTEGER_CST)
6769 return;
6771 idx = mem_ref_offset (t);
6772 idx = wi::sdiv_trunc (idx, wi::to_offset (el_sz));
6773 if (idx < 0)
6775 if (dump_file && (dump_flags & TDF_DETAILS))
6777 fprintf (dump_file, "Array bound warning for ");
6778 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
6779 fprintf (dump_file, "\n");
6781 warning_at (location, OPT_Warray_bounds,
6782 "array subscript is below array bounds");
6783 TREE_NO_WARNING (t) = 1;
6785 else if (idx > (wi::to_offset (up_bound)
6786 - wi::to_offset (low_bound) + 1))
6788 if (dump_file && (dump_flags & TDF_DETAILS))
6790 fprintf (dump_file, "Array bound warning for ");
6791 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
6792 fprintf (dump_file, "\n");
6794 warning_at (location, OPT_Warray_bounds,
6795 "array subscript is above array bounds");
6796 TREE_NO_WARNING (t) = 1;
6801 /* walk_tree() callback that checks if *TP is
6802 an ARRAY_REF inside an ADDR_EXPR (in which an array
6803 subscript one outside the valid range is allowed). Call
6804 check_array_ref for each ARRAY_REF found. The location is
6805 passed in DATA. */
6807 static tree
6808 check_array_bounds (tree *tp, int *walk_subtree, void *data)
6810 tree t = *tp;
6811 struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
6812 location_t location;
6814 if (EXPR_HAS_LOCATION (t))
6815 location = EXPR_LOCATION (t);
6816 else
6817 location = gimple_location (wi->stmt);
6819 *walk_subtree = TRUE;
6821 if (TREE_CODE (t) == ARRAY_REF)
6822 check_array_ref (location, t, false /*ignore_off_by_one*/);
6824 else if (TREE_CODE (t) == ADDR_EXPR)
6826 search_for_addr_array (t, location);
6827 *walk_subtree = FALSE;
6830 return NULL_TREE;
6833 /* Walk over all statements of all reachable BBs and call check_array_bounds
6834 on them. */
6836 static void
6837 check_all_array_refs (void)
6839 basic_block bb;
6840 gimple_stmt_iterator si;
6842 FOR_EACH_BB_FN (bb, cfun)
6844 edge_iterator ei;
6845 edge e;
6846 bool executable = false;
6848 /* Skip blocks that were found to be unreachable. */
6849 FOR_EACH_EDGE (e, ei, bb->preds)
6850 executable |= !!(e->flags & EDGE_EXECUTABLE);
6851 if (!executable)
6852 continue;
6854 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
6856 gimple *stmt = gsi_stmt (si);
6857 struct walk_stmt_info wi;
6858 if (!gimple_has_location (stmt)
6859 || is_gimple_debug (stmt))
6860 continue;
6862 memset (&wi, 0, sizeof (wi));
6864 walk_gimple_op (gsi_stmt (si),
6865 check_array_bounds,
6866 &wi);
6871 /* Return true if all imm uses of VAR are either in STMT, or
6872 feed (optionally through a chain of single imm uses) GIMPLE_COND
6873 in basic block COND_BB. */
6875 static bool
6876 all_imm_uses_in_stmt_or_feed_cond (tree var, gimple *stmt, basic_block cond_bb)
6878 use_operand_p use_p, use2_p;
6879 imm_use_iterator iter;
6881 FOR_EACH_IMM_USE_FAST (use_p, iter, var)
6882 if (USE_STMT (use_p) != stmt)
6884 gimple *use_stmt = USE_STMT (use_p), *use_stmt2;
6885 if (is_gimple_debug (use_stmt))
6886 continue;
6887 while (is_gimple_assign (use_stmt)
6888 && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
6889 && single_imm_use (gimple_assign_lhs (use_stmt),
6890 &use2_p, &use_stmt2))
6891 use_stmt = use_stmt2;
6892 if (gimple_code (use_stmt) != GIMPLE_COND
6893 || gimple_bb (use_stmt) != cond_bb)
6894 return false;
6896 return true;
6899 /* Handle
6900 _4 = x_3 & 31;
6901 if (_4 != 0)
6902 goto <bb 6>;
6903 else
6904 goto <bb 7>;
6905 <bb 6>:
6906 __builtin_unreachable ();
6907 <bb 7>:
6908 x_5 = ASSERT_EXPR <x_3, ...>;
6909 If x_3 has no other immediate uses (checked by caller),
6910 var is the x_3 var from ASSERT_EXPR, we can clear low 5 bits
6911 from the non-zero bitmask. */
6913 static void
6914 maybe_set_nonzero_bits (basic_block bb, tree var)
6916 edge e = single_pred_edge (bb);
6917 basic_block cond_bb = e->src;
6918 gimple *stmt = last_stmt (cond_bb);
6919 tree cst;
6921 if (stmt == NULL
6922 || gimple_code (stmt) != GIMPLE_COND
6923 || gimple_cond_code (stmt) != ((e->flags & EDGE_TRUE_VALUE)
6924 ? EQ_EXPR : NE_EXPR)
6925 || TREE_CODE (gimple_cond_lhs (stmt)) != SSA_NAME
6926 || !integer_zerop (gimple_cond_rhs (stmt)))
6927 return;
6929 stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt));
6930 if (!is_gimple_assign (stmt)
6931 || gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
6932 || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
6933 return;
6934 if (gimple_assign_rhs1 (stmt) != var)
6936 gimple *stmt2;
6938 if (TREE_CODE (gimple_assign_rhs1 (stmt)) != SSA_NAME)
6939 return;
6940 stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
6941 if (!gimple_assign_cast_p (stmt2)
6942 || gimple_assign_rhs1 (stmt2) != var
6943 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt2))
6944 || (TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (stmt)))
6945 != TYPE_PRECISION (TREE_TYPE (var))))
6946 return;
6948 cst = gimple_assign_rhs2 (stmt);
6949 set_nonzero_bits (var, wi::bit_and_not (get_nonzero_bits (var),
6950 wi::to_wide (cst)));
6953 /* Convert range assertion expressions into the implied copies and
6954 copy propagate away the copies. Doing the trivial copy propagation
6955 here avoids the need to run the full copy propagation pass after
6956 VRP.
6958 FIXME, this will eventually lead to copy propagation removing the
6959 names that had useful range information attached to them. For
6960 instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
6961 then N_i will have the range [3, +INF].
6963 However, by converting the assertion into the implied copy
6964 operation N_i = N_j, we will then copy-propagate N_j into the uses
6965 of N_i and lose the range information. We may want to hold on to
6966 ASSERT_EXPRs a little while longer as the ranges could be used in
6967 things like jump threading.
6969 The problem with keeping ASSERT_EXPRs around is that passes after
6970 VRP need to handle them appropriately.
6972 Another approach would be to make the range information a first
6973 class property of the SSA_NAME so that it can be queried from
6974 any pass. This is made somewhat more complex by the need for
6975 multiple ranges to be associated with one SSA_NAME. */
6977 static void
6978 remove_range_assertions (void)
6980 basic_block bb;
6981 gimple_stmt_iterator si;
6982 /* 1 if looking at ASSERT_EXPRs immediately at the beginning of
6983 a basic block preceeded by GIMPLE_COND branching to it and
6984 __builtin_trap, -1 if not yet checked, 0 otherwise. */
6985 int is_unreachable;
6987 /* Note that the BSI iterator bump happens at the bottom of the
6988 loop and no bump is necessary if we're removing the statement
6989 referenced by the current BSI. */
6990 FOR_EACH_BB_FN (bb, cfun)
6991 for (si = gsi_after_labels (bb), is_unreachable = -1; !gsi_end_p (si);)
6993 gimple *stmt = gsi_stmt (si);
6995 if (is_gimple_assign (stmt)
6996 && gimple_assign_rhs_code (stmt) == ASSERT_EXPR)
6998 tree lhs = gimple_assign_lhs (stmt);
6999 tree rhs = gimple_assign_rhs1 (stmt);
7000 tree var;
7002 var = ASSERT_EXPR_VAR (rhs);
7004 if (TREE_CODE (var) == SSA_NAME
7005 && !POINTER_TYPE_P (TREE_TYPE (lhs))
7006 && SSA_NAME_RANGE_INFO (lhs))
7008 if (is_unreachable == -1)
7010 is_unreachable = 0;
7011 if (single_pred_p (bb)
7012 && assert_unreachable_fallthru_edge_p
7013 (single_pred_edge (bb)))
7014 is_unreachable = 1;
7016 /* Handle
7017 if (x_7 >= 10 && x_7 < 20)
7018 __builtin_unreachable ();
7019 x_8 = ASSERT_EXPR <x_7, ...>;
7020 if the only uses of x_7 are in the ASSERT_EXPR and
7021 in the condition. In that case, we can copy the
7022 range info from x_8 computed in this pass also
7023 for x_7. */
7024 if (is_unreachable
7025 && all_imm_uses_in_stmt_or_feed_cond (var, stmt,
7026 single_pred (bb)))
7028 set_range_info (var, SSA_NAME_RANGE_TYPE (lhs),
7029 SSA_NAME_RANGE_INFO (lhs)->get_min (),
7030 SSA_NAME_RANGE_INFO (lhs)->get_max ());
7031 maybe_set_nonzero_bits (bb, var);
7035 /* Propagate the RHS into every use of the LHS. For SSA names
7036 also propagate abnormals as it merely restores the original
7037 IL in this case (an replace_uses_by would assert). */
7038 if (TREE_CODE (var) == SSA_NAME)
7040 imm_use_iterator iter;
7041 use_operand_p use_p;
7042 gimple *use_stmt;
7043 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
7044 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
7045 SET_USE (use_p, var);
7047 else
7048 replace_uses_by (lhs, var);
7050 /* And finally, remove the copy, it is not needed. */
7051 gsi_remove (&si, true);
7052 release_defs (stmt);
7054 else
7056 if (!is_gimple_debug (gsi_stmt (si)))
7057 is_unreachable = 0;
7058 gsi_next (&si);
7064 /* Return true if STMT is interesting for VRP. */
7066 static bool
7067 stmt_interesting_for_vrp (gimple *stmt)
7069 if (gimple_code (stmt) == GIMPLE_PHI)
7071 tree res = gimple_phi_result (stmt);
7072 return (!virtual_operand_p (res)
7073 && (INTEGRAL_TYPE_P (TREE_TYPE (res))
7074 || POINTER_TYPE_P (TREE_TYPE (res))));
7076 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
7078 tree lhs = gimple_get_lhs (stmt);
7080 /* In general, assignments with virtual operands are not useful
7081 for deriving ranges, with the obvious exception of calls to
7082 builtin functions. */
7083 if (lhs && TREE_CODE (lhs) == SSA_NAME
7084 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
7085 || POINTER_TYPE_P (TREE_TYPE (lhs)))
7086 && (is_gimple_call (stmt)
7087 || !gimple_vuse (stmt)))
7088 return true;
7089 else if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
7090 switch (gimple_call_internal_fn (stmt))
7092 case IFN_ADD_OVERFLOW:
7093 case IFN_SUB_OVERFLOW:
7094 case IFN_MUL_OVERFLOW:
7095 case IFN_ATOMIC_COMPARE_EXCHANGE:
7096 /* These internal calls return _Complex integer type,
7097 but are interesting to VRP nevertheless. */
7098 if (lhs && TREE_CODE (lhs) == SSA_NAME)
7099 return true;
7100 break;
7101 default:
7102 break;
7105 else if (gimple_code (stmt) == GIMPLE_COND
7106 || gimple_code (stmt) == GIMPLE_SWITCH)
7107 return true;
7109 return false;
7112 /* Initialize VRP lattice. */
7114 static void
7115 vrp_initialize_lattice ()
7117 values_propagated = false;
7118 num_vr_values = num_ssa_names;
7119 vr_value = XCNEWVEC (value_range *, num_vr_values);
7120 vr_phi_edge_counts = XCNEWVEC (int, num_ssa_names);
7121 bitmap_obstack_initialize (&vrp_equiv_obstack);
7124 /* Initialization required by ssa_propagate engine. */
7126 static void
7127 vrp_initialize ()
7129 basic_block bb;
7131 FOR_EACH_BB_FN (bb, cfun)
7133 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
7134 gsi_next (&si))
7136 gphi *phi = si.phi ();
7137 if (!stmt_interesting_for_vrp (phi))
7139 tree lhs = PHI_RESULT (phi);
7140 set_value_range_to_varying (get_value_range (lhs));
7141 prop_set_simulate_again (phi, false);
7143 else
7144 prop_set_simulate_again (phi, true);
7147 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
7148 gsi_next (&si))
7150 gimple *stmt = gsi_stmt (si);
7152 /* If the statement is a control insn, then we do not
7153 want to avoid simulating the statement once. Failure
7154 to do so means that those edges will never get added. */
7155 if (stmt_ends_bb_p (stmt))
7156 prop_set_simulate_again (stmt, true);
7157 else if (!stmt_interesting_for_vrp (stmt))
7159 set_defs_to_varying (stmt);
7160 prop_set_simulate_again (stmt, false);
7162 else
7163 prop_set_simulate_again (stmt, true);
7168 /* Return the singleton value-range for NAME or NAME. */
7170 static inline tree
7171 vrp_valueize (tree name)
7173 if (TREE_CODE (name) == SSA_NAME)
7175 value_range *vr = get_value_range (name);
7176 if (vr->type == VR_RANGE
7177 && (TREE_CODE (vr->min) == SSA_NAME
7178 || is_gimple_min_invariant (vr->min))
7179 && vrp_operand_equal_p (vr->min, vr->max))
7180 return vr->min;
7182 return name;
7185 /* Return the singleton value-range for NAME if that is a constant
7186 but signal to not follow SSA edges. */
7188 static inline tree
7189 vrp_valueize_1 (tree name)
7191 if (TREE_CODE (name) == SSA_NAME)
7193 /* If the definition may be simulated again we cannot follow
7194 this SSA edge as the SSA propagator does not necessarily
7195 re-visit the use. */
7196 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
7197 if (!gimple_nop_p (def_stmt)
7198 && prop_simulate_again_p (def_stmt))
7199 return NULL_TREE;
7200 value_range *vr = get_value_range (name);
7201 if (range_int_cst_singleton_p (vr))
7202 return vr->min;
7204 return name;
7207 /* Visit assignment STMT. If it produces an interesting range, record
7208 the range in VR and set LHS to OUTPUT_P. */
7210 static void
7211 vrp_visit_assignment_or_call (gimple *stmt, tree *output_p, value_range *vr)
7213 tree lhs;
7214 enum gimple_code code = gimple_code (stmt);
7215 lhs = gimple_get_lhs (stmt);
7216 *output_p = NULL_TREE;
7218 /* We only keep track of ranges in integral and pointer types. */
7219 if (TREE_CODE (lhs) == SSA_NAME
7220 && ((INTEGRAL_TYPE_P (TREE_TYPE (lhs))
7221 /* It is valid to have NULL MIN/MAX values on a type. See
7222 build_range_type. */
7223 && TYPE_MIN_VALUE (TREE_TYPE (lhs))
7224 && TYPE_MAX_VALUE (TREE_TYPE (lhs)))
7225 || POINTER_TYPE_P (TREE_TYPE (lhs))))
7227 *output_p = lhs;
7229 /* Try folding the statement to a constant first. */
7230 tree tem = gimple_fold_stmt_to_constant_1 (stmt, vrp_valueize,
7231 vrp_valueize_1);
7232 if (tem)
7234 if (TREE_CODE (tem) == SSA_NAME
7235 && (SSA_NAME_IS_DEFAULT_DEF (tem)
7236 || ! prop_simulate_again_p (SSA_NAME_DEF_STMT (tem))))
7238 extract_range_from_ssa_name (vr, tem);
7239 return;
7241 else if (is_gimple_min_invariant (tem))
7243 set_value_range_to_value (vr, tem, NULL);
7244 return;
7247 /* Then dispatch to value-range extracting functions. */
7248 if (code == GIMPLE_CALL)
7249 extract_range_basic (vr, stmt);
7250 else
7251 extract_range_from_assignment (vr, as_a <gassign *> (stmt));
7255 /* Helper that gets the value range of the SSA_NAME with version I
7256 or a symbolic range containing the SSA_NAME only if the value range
7257 is varying or undefined. */
7259 static inline value_range
7260 get_vr_for_comparison (int i)
7262 value_range vr = *get_value_range (ssa_name (i));
7264 /* If name N_i does not have a valid range, use N_i as its own
7265 range. This allows us to compare against names that may
7266 have N_i in their ranges. */
7267 if (vr.type == VR_VARYING || vr.type == VR_UNDEFINED)
7269 vr.type = VR_RANGE;
7270 vr.min = ssa_name (i);
7271 vr.max = ssa_name (i);
7274 return vr;
7277 /* Compare all the value ranges for names equivalent to VAR with VAL
7278 using comparison code COMP. Return the same value returned by
7279 compare_range_with_value, including the setting of
7280 *STRICT_OVERFLOW_P. */
7282 static tree
7283 compare_name_with_value (enum tree_code comp, tree var, tree val,
7284 bool *strict_overflow_p, bool use_equiv_p)
7286 bitmap_iterator bi;
7287 unsigned i;
7288 bitmap e;
7289 tree retval, t;
7290 int used_strict_overflow;
7291 bool sop;
7292 value_range equiv_vr;
7294 /* Get the set of equivalences for VAR. */
7295 e = get_value_range (var)->equiv;
7297 /* Start at -1. Set it to 0 if we do a comparison without relying
7298 on overflow, or 1 if all comparisons rely on overflow. */
7299 used_strict_overflow = -1;
7301 /* Compare vars' value range with val. */
7302 equiv_vr = get_vr_for_comparison (SSA_NAME_VERSION (var));
7303 sop = false;
7304 retval = compare_range_with_value (comp, &equiv_vr, val, &sop);
7305 if (retval)
7306 used_strict_overflow = sop ? 1 : 0;
7308 /* If the equiv set is empty we have done all work we need to do. */
7309 if (e == NULL)
7311 if (retval
7312 && used_strict_overflow > 0)
7313 *strict_overflow_p = true;
7314 return retval;
7317 EXECUTE_IF_SET_IN_BITMAP (e, 0, i, bi)
7319 tree name = ssa_name (i);
7320 if (! name)
7321 continue;
7323 if (! use_equiv_p
7324 && ! SSA_NAME_IS_DEFAULT_DEF (name)
7325 && prop_simulate_again_p (SSA_NAME_DEF_STMT (name)))
7326 continue;
7328 equiv_vr = get_vr_for_comparison (i);
7329 sop = false;
7330 t = compare_range_with_value (comp, &equiv_vr, val, &sop);
7331 if (t)
7333 /* If we get different answers from different members
7334 of the equivalence set this check must be in a dead
7335 code region. Folding it to a trap representation
7336 would be correct here. For now just return don't-know. */
7337 if (retval != NULL
7338 && t != retval)
7340 retval = NULL_TREE;
7341 break;
7343 retval = t;
7345 if (!sop)
7346 used_strict_overflow = 0;
7347 else if (used_strict_overflow < 0)
7348 used_strict_overflow = 1;
7352 if (retval
7353 && used_strict_overflow > 0)
7354 *strict_overflow_p = true;
7356 return retval;
7360 /* Given a comparison code COMP and names N1 and N2, compare all the
7361 ranges equivalent to N1 against all the ranges equivalent to N2
7362 to determine the value of N1 COMP N2. Return the same value
7363 returned by compare_ranges. Set *STRICT_OVERFLOW_P to indicate
7364 whether we relied on undefined signed overflow in the comparison. */
7367 static tree
7368 compare_names (enum tree_code comp, tree n1, tree n2,
7369 bool *strict_overflow_p)
7371 tree t, retval;
7372 bitmap e1, e2;
7373 bitmap_iterator bi1, bi2;
7374 unsigned i1, i2;
7375 int used_strict_overflow;
7376 static bitmap_obstack *s_obstack = NULL;
7377 static bitmap s_e1 = NULL, s_e2 = NULL;
7379 /* Compare the ranges of every name equivalent to N1 against the
7380 ranges of every name equivalent to N2. */
7381 e1 = get_value_range (n1)->equiv;
7382 e2 = get_value_range (n2)->equiv;
7384 /* Use the fake bitmaps if e1 or e2 are not available. */
7385 if (s_obstack == NULL)
7387 s_obstack = XNEW (bitmap_obstack);
7388 bitmap_obstack_initialize (s_obstack);
7389 s_e1 = BITMAP_ALLOC (s_obstack);
7390 s_e2 = BITMAP_ALLOC (s_obstack);
7392 if (e1 == NULL)
7393 e1 = s_e1;
7394 if (e2 == NULL)
7395 e2 = s_e2;
7397 /* Add N1 and N2 to their own set of equivalences to avoid
7398 duplicating the body of the loop just to check N1 and N2
7399 ranges. */
7400 bitmap_set_bit (e1, SSA_NAME_VERSION (n1));
7401 bitmap_set_bit (e2, SSA_NAME_VERSION (n2));
7403 /* If the equivalence sets have a common intersection, then the two
7404 names can be compared without checking their ranges. */
7405 if (bitmap_intersect_p (e1, e2))
7407 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7408 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7410 return (comp == EQ_EXPR || comp == GE_EXPR || comp == LE_EXPR)
7411 ? boolean_true_node
7412 : boolean_false_node;
7415 /* Start at -1. Set it to 0 if we do a comparison without relying
7416 on overflow, or 1 if all comparisons rely on overflow. */
7417 used_strict_overflow = -1;
7419 /* Otherwise, compare all the equivalent ranges. First, add N1 and
7420 N2 to their own set of equivalences to avoid duplicating the body
7421 of the loop just to check N1 and N2 ranges. */
7422 EXECUTE_IF_SET_IN_BITMAP (e1, 0, i1, bi1)
7424 if (! ssa_name (i1))
7425 continue;
7427 value_range vr1 = get_vr_for_comparison (i1);
7429 t = retval = NULL_TREE;
7430 EXECUTE_IF_SET_IN_BITMAP (e2, 0, i2, bi2)
7432 if (! ssa_name (i2))
7433 continue;
7435 bool sop = false;
7437 value_range vr2 = get_vr_for_comparison (i2);
7439 t = compare_ranges (comp, &vr1, &vr2, &sop);
7440 if (t)
7442 /* If we get different answers from different members
7443 of the equivalence set this check must be in a dead
7444 code region. Folding it to a trap representation
7445 would be correct here. For now just return don't-know. */
7446 if (retval != NULL
7447 && t != retval)
7449 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7450 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7451 return NULL_TREE;
7453 retval = t;
7455 if (!sop)
7456 used_strict_overflow = 0;
7457 else if (used_strict_overflow < 0)
7458 used_strict_overflow = 1;
7462 if (retval)
7464 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7465 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7466 if (used_strict_overflow > 0)
7467 *strict_overflow_p = true;
7468 return retval;
7472 /* None of the equivalent ranges are useful in computing this
7473 comparison. */
7474 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7475 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7476 return NULL_TREE;
7479 /* Helper function for vrp_evaluate_conditional_warnv & other
7480 optimizers. */
7482 static tree
7483 vrp_evaluate_conditional_warnv_with_ops_using_ranges (enum tree_code code,
7484 tree op0, tree op1,
7485 bool * strict_overflow_p)
7487 value_range *vr0, *vr1;
7489 vr0 = (TREE_CODE (op0) == SSA_NAME) ? get_value_range (op0) : NULL;
7490 vr1 = (TREE_CODE (op1) == SSA_NAME) ? get_value_range (op1) : NULL;
7492 tree res = NULL_TREE;
7493 if (vr0 && vr1)
7494 res = compare_ranges (code, vr0, vr1, strict_overflow_p);
7495 if (!res && vr0)
7496 res = compare_range_with_value (code, vr0, op1, strict_overflow_p);
7497 if (!res && vr1)
7498 res = (compare_range_with_value
7499 (swap_tree_comparison (code), vr1, op0, strict_overflow_p));
7500 return res;
7503 /* Helper function for vrp_evaluate_conditional_warnv. */
7505 static tree
7506 vrp_evaluate_conditional_warnv_with_ops (enum tree_code code, tree op0,
7507 tree op1, bool use_equiv_p,
7508 bool *strict_overflow_p, bool *only_ranges)
7510 tree ret;
7511 if (only_ranges)
7512 *only_ranges = true;
7514 /* We only deal with integral and pointer types. */
7515 if (!INTEGRAL_TYPE_P (TREE_TYPE (op0))
7516 && !POINTER_TYPE_P (TREE_TYPE (op0)))
7517 return NULL_TREE;
7519 /* If OP0 CODE OP1 is an overflow comparison, if it can be expressed
7520 as a simple equality test, then prefer that over its current form
7521 for evaluation.
7523 An overflow test which collapses to an equality test can always be
7524 expressed as a comparison of one argument against zero. Overflow
7525 occurs when the chosen argument is zero and does not occur if the
7526 chosen argument is not zero. */
7527 tree x;
7528 if (overflow_comparison_p (code, op0, op1, use_equiv_p, &x))
7530 wide_int max = wi::max_value (TYPE_PRECISION (TREE_TYPE (op0)), UNSIGNED);
7531 /* B = A - 1; if (A < B) -> B = A - 1; if (A == 0)
7532 B = A - 1; if (A > B) -> B = A - 1; if (A != 0)
7533 B = A + 1; if (B < A) -> B = A + 1; if (B == 0)
7534 B = A + 1; if (B > A) -> B = A + 1; if (B != 0) */
7535 if (integer_zerop (x))
7537 op1 = x;
7538 code = (code == LT_EXPR || code == LE_EXPR) ? EQ_EXPR : NE_EXPR;
7540 /* B = A + 1; if (A > B) -> B = A + 1; if (B == 0)
7541 B = A + 1; if (A < B) -> B = A + 1; if (B != 0)
7542 B = A - 1; if (B > A) -> B = A - 1; if (A == 0)
7543 B = A - 1; if (B < A) -> B = A - 1; if (A != 0) */
7544 else if (wi::to_wide (x) == max - 1)
7546 op0 = op1;
7547 op1 = wide_int_to_tree (TREE_TYPE (op0), 0);
7548 code = (code == GT_EXPR || code == GE_EXPR) ? EQ_EXPR : NE_EXPR;
7552 if ((ret = vrp_evaluate_conditional_warnv_with_ops_using_ranges
7553 (code, op0, op1, strict_overflow_p)))
7554 return ret;
7555 if (only_ranges)
7556 *only_ranges = false;
7557 /* Do not use compare_names during propagation, it's quadratic. */
7558 if (TREE_CODE (op0) == SSA_NAME && TREE_CODE (op1) == SSA_NAME
7559 && use_equiv_p)
7560 return compare_names (code, op0, op1, strict_overflow_p);
7561 else if (TREE_CODE (op0) == SSA_NAME)
7562 return compare_name_with_value (code, op0, op1,
7563 strict_overflow_p, use_equiv_p);
7564 else if (TREE_CODE (op1) == SSA_NAME)
7565 return compare_name_with_value (swap_tree_comparison (code), op1, op0,
7566 strict_overflow_p, use_equiv_p);
7567 return NULL_TREE;
7570 /* Given (CODE OP0 OP1) within STMT, try to simplify it based on value range
7571 information. Return NULL if the conditional can not be evaluated.
7572 The ranges of all the names equivalent with the operands in COND
7573 will be used when trying to compute the value. If the result is
7574 based on undefined signed overflow, issue a warning if
7575 appropriate. */
7577 static tree
7578 vrp_evaluate_conditional (tree_code code, tree op0, tree op1, gimple *stmt)
7580 bool sop;
7581 tree ret;
7582 bool only_ranges;
7584 /* Some passes and foldings leak constants with overflow flag set
7585 into the IL. Avoid doing wrong things with these and bail out. */
7586 if ((TREE_CODE (op0) == INTEGER_CST
7587 && TREE_OVERFLOW (op0))
7588 || (TREE_CODE (op1) == INTEGER_CST
7589 && TREE_OVERFLOW (op1)))
7590 return NULL_TREE;
7592 sop = false;
7593 ret = vrp_evaluate_conditional_warnv_with_ops (code, op0, op1, true, &sop,
7594 &only_ranges);
7596 if (ret && sop)
7598 enum warn_strict_overflow_code wc;
7599 const char* warnmsg;
7601 if (is_gimple_min_invariant (ret))
7603 wc = WARN_STRICT_OVERFLOW_CONDITIONAL;
7604 warnmsg = G_("assuming signed overflow does not occur when "
7605 "simplifying conditional to constant");
7607 else
7609 wc = WARN_STRICT_OVERFLOW_COMPARISON;
7610 warnmsg = G_("assuming signed overflow does not occur when "
7611 "simplifying conditional");
7614 if (issue_strict_overflow_warning (wc))
7616 location_t location;
7618 if (!gimple_has_location (stmt))
7619 location = input_location;
7620 else
7621 location = gimple_location (stmt);
7622 warning_at (location, OPT_Wstrict_overflow, "%s", warnmsg);
7626 if (warn_type_limits
7627 && ret && only_ranges
7628 && TREE_CODE_CLASS (code) == tcc_comparison
7629 && TREE_CODE (op0) == SSA_NAME)
7631 /* If the comparison is being folded and the operand on the LHS
7632 is being compared against a constant value that is outside of
7633 the natural range of OP0's type, then the predicate will
7634 always fold regardless of the value of OP0. If -Wtype-limits
7635 was specified, emit a warning. */
7636 tree type = TREE_TYPE (op0);
7637 value_range *vr0 = get_value_range (op0);
7639 if (vr0->type == VR_RANGE
7640 && INTEGRAL_TYPE_P (type)
7641 && vrp_val_is_min (vr0->min)
7642 && vrp_val_is_max (vr0->max)
7643 && is_gimple_min_invariant (op1))
7645 location_t location;
7647 if (!gimple_has_location (stmt))
7648 location = input_location;
7649 else
7650 location = gimple_location (stmt);
7652 warning_at (location, OPT_Wtype_limits,
7653 integer_zerop (ret)
7654 ? G_("comparison always false "
7655 "due to limited range of data type")
7656 : G_("comparison always true "
7657 "due to limited range of data type"));
7661 return ret;
7665 /* Visit conditional statement STMT. If we can determine which edge
7666 will be taken out of STMT's basic block, record it in
7667 *TAKEN_EDGE_P. Otherwise, set *TAKEN_EDGE_P to NULL. */
7669 static void
7670 vrp_visit_cond_stmt (gcond *stmt, edge *taken_edge_p)
7672 tree val;
7674 *taken_edge_p = NULL;
7676 if (dump_file && (dump_flags & TDF_DETAILS))
7678 tree use;
7679 ssa_op_iter i;
7681 fprintf (dump_file, "\nVisiting conditional with predicate: ");
7682 print_gimple_stmt (dump_file, stmt, 0);
7683 fprintf (dump_file, "\nWith known ranges\n");
7685 FOR_EACH_SSA_TREE_OPERAND (use, stmt, i, SSA_OP_USE)
7687 fprintf (dump_file, "\t");
7688 print_generic_expr (dump_file, use);
7689 fprintf (dump_file, ": ");
7690 dump_value_range (dump_file, vr_value[SSA_NAME_VERSION (use)]);
7693 fprintf (dump_file, "\n");
7696 /* Compute the value of the predicate COND by checking the known
7697 ranges of each of its operands.
7699 Note that we cannot evaluate all the equivalent ranges here
7700 because those ranges may not yet be final and with the current
7701 propagation strategy, we cannot determine when the value ranges
7702 of the names in the equivalence set have changed.
7704 For instance, given the following code fragment
7706 i_5 = PHI <8, i_13>
7708 i_14 = ASSERT_EXPR <i_5, i_5 != 0>
7709 if (i_14 == 1)
7712 Assume that on the first visit to i_14, i_5 has the temporary
7713 range [8, 8] because the second argument to the PHI function is
7714 not yet executable. We derive the range ~[0, 0] for i_14 and the
7715 equivalence set { i_5 }. So, when we visit 'if (i_14 == 1)' for
7716 the first time, since i_14 is equivalent to the range [8, 8], we
7717 determine that the predicate is always false.
7719 On the next round of propagation, i_13 is determined to be
7720 VARYING, which causes i_5 to drop down to VARYING. So, another
7721 visit to i_14 is scheduled. In this second visit, we compute the
7722 exact same range and equivalence set for i_14, namely ~[0, 0] and
7723 { i_5 }. But we did not have the previous range for i_5
7724 registered, so vrp_visit_assignment thinks that the range for
7725 i_14 has not changed. Therefore, the predicate 'if (i_14 == 1)'
7726 is not visited again, which stops propagation from visiting
7727 statements in the THEN clause of that if().
7729 To properly fix this we would need to keep the previous range
7730 value for the names in the equivalence set. This way we would've
7731 discovered that from one visit to the other i_5 changed from
7732 range [8, 8] to VR_VARYING.
7734 However, fixing this apparent limitation may not be worth the
7735 additional checking. Testing on several code bases (GCC, DLV,
7736 MICO, TRAMP3D and SPEC2000) showed that doing this results in
7737 4 more predicates folded in SPEC. */
7739 bool sop;
7740 val = vrp_evaluate_conditional_warnv_with_ops (gimple_cond_code (stmt),
7741 gimple_cond_lhs (stmt),
7742 gimple_cond_rhs (stmt),
7743 false, &sop, NULL);
7744 if (val)
7745 *taken_edge_p = find_taken_edge (gimple_bb (stmt), val);
7747 if (dump_file && (dump_flags & TDF_DETAILS))
7749 fprintf (dump_file, "\nPredicate evaluates to: ");
7750 if (val == NULL_TREE)
7751 fprintf (dump_file, "DON'T KNOW\n");
7752 else
7753 print_generic_stmt (dump_file, val);
7757 /* Searches the case label vector VEC for the index *IDX of the CASE_LABEL
7758 that includes the value VAL. The search is restricted to the range
7759 [START_IDX, n - 1] where n is the size of VEC.
7761 If there is a CASE_LABEL for VAL, its index is placed in IDX and true is
7762 returned.
7764 If there is no CASE_LABEL for VAL and there is one that is larger than VAL,
7765 it is placed in IDX and false is returned.
7767 If VAL is larger than any CASE_LABEL, n is placed on IDX and false is
7768 returned. */
7770 static bool
7771 find_case_label_index (gswitch *stmt, size_t start_idx, tree val, size_t *idx)
7773 size_t n = gimple_switch_num_labels (stmt);
7774 size_t low, high;
7776 /* Find case label for minimum of the value range or the next one.
7777 At each iteration we are searching in [low, high - 1]. */
7779 for (low = start_idx, high = n; high != low; )
7781 tree t;
7782 int cmp;
7783 /* Note that i != high, so we never ask for n. */
7784 size_t i = (high + low) / 2;
7785 t = gimple_switch_label (stmt, i);
7787 /* Cache the result of comparing CASE_LOW and val. */
7788 cmp = tree_int_cst_compare (CASE_LOW (t), val);
7790 if (cmp == 0)
7792 /* Ranges cannot be empty. */
7793 *idx = i;
7794 return true;
7796 else if (cmp > 0)
7797 high = i;
7798 else
7800 low = i + 1;
7801 if (CASE_HIGH (t) != NULL
7802 && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
7804 *idx = i;
7805 return true;
7810 *idx = high;
7811 return false;
7814 /* Searches the case label vector VEC for the range of CASE_LABELs that is used
7815 for values between MIN and MAX. The first index is placed in MIN_IDX. The
7816 last index is placed in MAX_IDX. If the range of CASE_LABELs is empty
7817 then MAX_IDX < MIN_IDX.
7818 Returns true if the default label is not needed. */
7820 static bool
7821 find_case_label_range (gswitch *stmt, tree min, tree max, size_t *min_idx,
7822 size_t *max_idx)
7824 size_t i, j;
7825 bool min_take_default = !find_case_label_index (stmt, 1, min, &i);
7826 bool max_take_default = !find_case_label_index (stmt, i, max, &j);
7828 if (i == j
7829 && min_take_default
7830 && max_take_default)
7832 /* Only the default case label reached.
7833 Return an empty range. */
7834 *min_idx = 1;
7835 *max_idx = 0;
7836 return false;
7838 else
7840 bool take_default = min_take_default || max_take_default;
7841 tree low, high;
7842 size_t k;
7844 if (max_take_default)
7845 j--;
7847 /* If the case label range is continuous, we do not need
7848 the default case label. Verify that. */
7849 high = CASE_LOW (gimple_switch_label (stmt, i));
7850 if (CASE_HIGH (gimple_switch_label (stmt, i)))
7851 high = CASE_HIGH (gimple_switch_label (stmt, i));
7852 for (k = i + 1; k <= j; ++k)
7854 low = CASE_LOW (gimple_switch_label (stmt, k));
7855 if (!integer_onep (int_const_binop (MINUS_EXPR, low, high)))
7857 take_default = true;
7858 break;
7860 high = low;
7861 if (CASE_HIGH (gimple_switch_label (stmt, k)))
7862 high = CASE_HIGH (gimple_switch_label (stmt, k));
7865 *min_idx = i;
7866 *max_idx = j;
7867 return !take_default;
7871 /* Searches the case label vector VEC for the ranges of CASE_LABELs that are
7872 used in range VR. The indices are placed in MIN_IDX1, MAX_IDX, MIN_IDX2 and
7873 MAX_IDX2. If the ranges of CASE_LABELs are empty then MAX_IDX1 < MIN_IDX1.
7874 Returns true if the default label is not needed. */
7876 static bool
7877 find_case_label_ranges (gswitch *stmt, value_range *vr, size_t *min_idx1,
7878 size_t *max_idx1, size_t *min_idx2,
7879 size_t *max_idx2)
7881 size_t i, j, k, l;
7882 unsigned int n = gimple_switch_num_labels (stmt);
7883 bool take_default;
7884 tree case_low, case_high;
7885 tree min = vr->min, max = vr->max;
7887 gcc_checking_assert (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE);
7889 take_default = !find_case_label_range (stmt, min, max, &i, &j);
7891 /* Set second range to emtpy. */
7892 *min_idx2 = 1;
7893 *max_idx2 = 0;
7895 if (vr->type == VR_RANGE)
7897 *min_idx1 = i;
7898 *max_idx1 = j;
7899 return !take_default;
7902 /* Set first range to all case labels. */
7903 *min_idx1 = 1;
7904 *max_idx1 = n - 1;
7906 if (i > j)
7907 return false;
7909 /* Make sure all the values of case labels [i , j] are contained in
7910 range [MIN, MAX]. */
7911 case_low = CASE_LOW (gimple_switch_label (stmt, i));
7912 case_high = CASE_HIGH (gimple_switch_label (stmt, j));
7913 if (tree_int_cst_compare (case_low, min) < 0)
7914 i += 1;
7915 if (case_high != NULL_TREE
7916 && tree_int_cst_compare (max, case_high) < 0)
7917 j -= 1;
7919 if (i > j)
7920 return false;
7922 /* If the range spans case labels [i, j], the corresponding anti-range spans
7923 the labels [1, i - 1] and [j + 1, n - 1]. */
7924 k = j + 1;
7925 l = n - 1;
7926 if (k > l)
7928 k = 1;
7929 l = 0;
7932 j = i - 1;
7933 i = 1;
7934 if (i > j)
7936 i = k;
7937 j = l;
7938 k = 1;
7939 l = 0;
7942 *min_idx1 = i;
7943 *max_idx1 = j;
7944 *min_idx2 = k;
7945 *max_idx2 = l;
7946 return false;
7949 /* Visit switch statement STMT. If we can determine which edge
7950 will be taken out of STMT's basic block, record it in
7951 *TAKEN_EDGE_P. Otherwise, *TAKEN_EDGE_P set to NULL. */
7953 static void
7954 vrp_visit_switch_stmt (gswitch *stmt, edge *taken_edge_p)
7956 tree op, val;
7957 value_range *vr;
7958 size_t i = 0, j = 0, k, l;
7959 bool take_default;
7961 *taken_edge_p = NULL;
7962 op = gimple_switch_index (stmt);
7963 if (TREE_CODE (op) != SSA_NAME)
7964 return;
7966 vr = get_value_range (op);
7967 if (dump_file && (dump_flags & TDF_DETAILS))
7969 fprintf (dump_file, "\nVisiting switch expression with operand ");
7970 print_generic_expr (dump_file, op);
7971 fprintf (dump_file, " with known range ");
7972 dump_value_range (dump_file, vr);
7973 fprintf (dump_file, "\n");
7976 if ((vr->type != VR_RANGE
7977 && vr->type != VR_ANTI_RANGE)
7978 || symbolic_range_p (vr))
7979 return;
7981 /* Find the single edge that is taken from the switch expression. */
7982 take_default = !find_case_label_ranges (stmt, vr, &i, &j, &k, &l);
7984 /* Check if the range spans no CASE_LABEL. If so, we only reach the default
7985 label */
7986 if (j < i)
7988 gcc_assert (take_default);
7989 val = gimple_switch_default_label (stmt);
7991 else
7993 /* Check if labels with index i to j and maybe the default label
7994 are all reaching the same label. */
7996 val = gimple_switch_label (stmt, i);
7997 if (take_default
7998 && CASE_LABEL (gimple_switch_default_label (stmt))
7999 != CASE_LABEL (val))
8001 if (dump_file && (dump_flags & TDF_DETAILS))
8002 fprintf (dump_file, " not a single destination for this "
8003 "range\n");
8004 return;
8006 for (++i; i <= j; ++i)
8008 if (CASE_LABEL (gimple_switch_label (stmt, i)) != CASE_LABEL (val))
8010 if (dump_file && (dump_flags & TDF_DETAILS))
8011 fprintf (dump_file, " not a single destination for this "
8012 "range\n");
8013 return;
8016 for (; k <= l; ++k)
8018 if (CASE_LABEL (gimple_switch_label (stmt, k)) != CASE_LABEL (val))
8020 if (dump_file && (dump_flags & TDF_DETAILS))
8021 fprintf (dump_file, " not a single destination for this "
8022 "range\n");
8023 return;
8028 *taken_edge_p = find_edge (gimple_bb (stmt),
8029 label_to_block (CASE_LABEL (val)));
8031 if (dump_file && (dump_flags & TDF_DETAILS))
8033 fprintf (dump_file, " will take edge to ");
8034 print_generic_stmt (dump_file, CASE_LABEL (val));
8039 /* Evaluate statement STMT. If the statement produces a useful range,
8040 set VR and corepsponding OUTPUT_P.
8042 If STMT is a conditional branch and we can determine its truth
8043 value, the taken edge is recorded in *TAKEN_EDGE_P. */
8045 static void
8046 extract_range_from_stmt (gimple *stmt, edge *taken_edge_p,
8047 tree *output_p, value_range *vr)
8050 if (dump_file && (dump_flags & TDF_DETAILS))
8052 fprintf (dump_file, "\nVisiting statement:\n");
8053 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
8056 if (!stmt_interesting_for_vrp (stmt))
8057 gcc_assert (stmt_ends_bb_p (stmt));
8058 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
8059 vrp_visit_assignment_or_call (stmt, output_p, vr);
8060 else if (gimple_code (stmt) == GIMPLE_COND)
8061 vrp_visit_cond_stmt (as_a <gcond *> (stmt), taken_edge_p);
8062 else if (gimple_code (stmt) == GIMPLE_SWITCH)
8063 vrp_visit_switch_stmt (as_a <gswitch *> (stmt), taken_edge_p);
8066 class vrp_prop : public ssa_propagation_engine
8068 public:
8069 enum ssa_prop_result visit_stmt (gimple *, edge *, tree *) FINAL OVERRIDE;
8070 enum ssa_prop_result visit_phi (gphi *) FINAL OVERRIDE;
8073 /* Evaluate statement STMT. If the statement produces a useful range,
8074 return SSA_PROP_INTERESTING and record the SSA name with the
8075 interesting range into *OUTPUT_P.
8077 If STMT is a conditional branch and we can determine its truth
8078 value, the taken edge is recorded in *TAKEN_EDGE_P.
8080 If STMT produces a varying value, return SSA_PROP_VARYING. */
8082 enum ssa_prop_result
8083 vrp_prop::visit_stmt (gimple *stmt, edge *taken_edge_p, tree *output_p)
8085 value_range vr = VR_INITIALIZER;
8086 tree lhs = gimple_get_lhs (stmt);
8087 extract_range_from_stmt (stmt, taken_edge_p, output_p, &vr);
8089 if (*output_p)
8091 if (update_value_range (*output_p, &vr))
8093 if (dump_file && (dump_flags & TDF_DETAILS))
8095 fprintf (dump_file, "Found new range for ");
8096 print_generic_expr (dump_file, *output_p);
8097 fprintf (dump_file, ": ");
8098 dump_value_range (dump_file, &vr);
8099 fprintf (dump_file, "\n");
8102 if (vr.type == VR_VARYING)
8103 return SSA_PROP_VARYING;
8105 return SSA_PROP_INTERESTING;
8107 return SSA_PROP_NOT_INTERESTING;
8110 if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
8111 switch (gimple_call_internal_fn (stmt))
8113 case IFN_ADD_OVERFLOW:
8114 case IFN_SUB_OVERFLOW:
8115 case IFN_MUL_OVERFLOW:
8116 case IFN_ATOMIC_COMPARE_EXCHANGE:
8117 /* These internal calls return _Complex integer type,
8118 which VRP does not track, but the immediate uses
8119 thereof might be interesting. */
8120 if (lhs && TREE_CODE (lhs) == SSA_NAME)
8122 imm_use_iterator iter;
8123 use_operand_p use_p;
8124 enum ssa_prop_result res = SSA_PROP_VARYING;
8126 set_value_range_to_varying (get_value_range (lhs));
8128 FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
8130 gimple *use_stmt = USE_STMT (use_p);
8131 if (!is_gimple_assign (use_stmt))
8132 continue;
8133 enum tree_code rhs_code = gimple_assign_rhs_code (use_stmt);
8134 if (rhs_code != REALPART_EXPR && rhs_code != IMAGPART_EXPR)
8135 continue;
8136 tree rhs1 = gimple_assign_rhs1 (use_stmt);
8137 tree use_lhs = gimple_assign_lhs (use_stmt);
8138 if (TREE_CODE (rhs1) != rhs_code
8139 || TREE_OPERAND (rhs1, 0) != lhs
8140 || TREE_CODE (use_lhs) != SSA_NAME
8141 || !stmt_interesting_for_vrp (use_stmt)
8142 || (!INTEGRAL_TYPE_P (TREE_TYPE (use_lhs))
8143 || !TYPE_MIN_VALUE (TREE_TYPE (use_lhs))
8144 || !TYPE_MAX_VALUE (TREE_TYPE (use_lhs))))
8145 continue;
8147 /* If there is a change in the value range for any of the
8148 REALPART_EXPR/IMAGPART_EXPR immediate uses, return
8149 SSA_PROP_INTERESTING. If there are any REALPART_EXPR
8150 or IMAGPART_EXPR immediate uses, but none of them have
8151 a change in their value ranges, return
8152 SSA_PROP_NOT_INTERESTING. If there are no
8153 {REAL,IMAG}PART_EXPR uses at all,
8154 return SSA_PROP_VARYING. */
8155 value_range new_vr = VR_INITIALIZER;
8156 extract_range_basic (&new_vr, use_stmt);
8157 value_range *old_vr = get_value_range (use_lhs);
8158 if (old_vr->type != new_vr.type
8159 || !vrp_operand_equal_p (old_vr->min, new_vr.min)
8160 || !vrp_operand_equal_p (old_vr->max, new_vr.max)
8161 || !vrp_bitmap_equal_p (old_vr->equiv, new_vr.equiv))
8162 res = SSA_PROP_INTERESTING;
8163 else
8164 res = SSA_PROP_NOT_INTERESTING;
8165 BITMAP_FREE (new_vr.equiv);
8166 if (res == SSA_PROP_INTERESTING)
8168 *output_p = lhs;
8169 return res;
8173 return res;
8175 break;
8176 default:
8177 break;
8180 /* All other statements produce nothing of interest for VRP, so mark
8181 their outputs varying and prevent further simulation. */
8182 set_defs_to_varying (stmt);
8184 return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
8187 /* Union the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
8188 { VR1TYPE, VR0MIN, VR0MAX } and store the result
8189 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
8190 possible such range. The resulting range is not canonicalized. */
8192 static void
8193 union_ranges (enum value_range_type *vr0type,
8194 tree *vr0min, tree *vr0max,
8195 enum value_range_type vr1type,
8196 tree vr1min, tree vr1max)
8198 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
8199 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
8201 /* [] is vr0, () is vr1 in the following classification comments. */
8202 if (mineq && maxeq)
8204 /* [( )] */
8205 if (*vr0type == vr1type)
8206 /* Nothing to do for equal ranges. */
8208 else if ((*vr0type == VR_RANGE
8209 && vr1type == VR_ANTI_RANGE)
8210 || (*vr0type == VR_ANTI_RANGE
8211 && vr1type == VR_RANGE))
8213 /* For anti-range with range union the result is varying. */
8214 goto give_up;
8216 else
8217 gcc_unreachable ();
8219 else if (operand_less_p (*vr0max, vr1min) == 1
8220 || operand_less_p (vr1max, *vr0min) == 1)
8222 /* [ ] ( ) or ( ) [ ]
8223 If the ranges have an empty intersection, result of the union
8224 operation is the anti-range or if both are anti-ranges
8225 it covers all. */
8226 if (*vr0type == VR_ANTI_RANGE
8227 && vr1type == VR_ANTI_RANGE)
8228 goto give_up;
8229 else if (*vr0type == VR_ANTI_RANGE
8230 && vr1type == VR_RANGE)
8232 else if (*vr0type == VR_RANGE
8233 && vr1type == VR_ANTI_RANGE)
8235 *vr0type = vr1type;
8236 *vr0min = vr1min;
8237 *vr0max = vr1max;
8239 else if (*vr0type == VR_RANGE
8240 && vr1type == VR_RANGE)
8242 /* The result is the convex hull of both ranges. */
8243 if (operand_less_p (*vr0max, vr1min) == 1)
8245 /* If the result can be an anti-range, create one. */
8246 if (TREE_CODE (*vr0max) == INTEGER_CST
8247 && TREE_CODE (vr1min) == INTEGER_CST
8248 && vrp_val_is_min (*vr0min)
8249 && vrp_val_is_max (vr1max))
8251 tree min = int_const_binop (PLUS_EXPR,
8252 *vr0max,
8253 build_int_cst (TREE_TYPE (*vr0max), 1));
8254 tree max = int_const_binop (MINUS_EXPR,
8255 vr1min,
8256 build_int_cst (TREE_TYPE (vr1min), 1));
8257 if (!operand_less_p (max, min))
8259 *vr0type = VR_ANTI_RANGE;
8260 *vr0min = min;
8261 *vr0max = max;
8263 else
8264 *vr0max = vr1max;
8266 else
8267 *vr0max = vr1max;
8269 else
8271 /* If the result can be an anti-range, create one. */
8272 if (TREE_CODE (vr1max) == INTEGER_CST
8273 && TREE_CODE (*vr0min) == INTEGER_CST
8274 && vrp_val_is_min (vr1min)
8275 && vrp_val_is_max (*vr0max))
8277 tree min = int_const_binop (PLUS_EXPR,
8278 vr1max,
8279 build_int_cst (TREE_TYPE (vr1max), 1));
8280 tree max = int_const_binop (MINUS_EXPR,
8281 *vr0min,
8282 build_int_cst (TREE_TYPE (*vr0min), 1));
8283 if (!operand_less_p (max, min))
8285 *vr0type = VR_ANTI_RANGE;
8286 *vr0min = min;
8287 *vr0max = max;
8289 else
8290 *vr0min = vr1min;
8292 else
8293 *vr0min = vr1min;
8296 else
8297 gcc_unreachable ();
8299 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
8300 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
8302 /* [ ( ) ] or [( ) ] or [ ( )] */
8303 if (*vr0type == VR_RANGE
8304 && vr1type == VR_RANGE)
8306 else if (*vr0type == VR_ANTI_RANGE
8307 && vr1type == VR_ANTI_RANGE)
8309 *vr0type = vr1type;
8310 *vr0min = vr1min;
8311 *vr0max = vr1max;
8313 else if (*vr0type == VR_ANTI_RANGE
8314 && vr1type == VR_RANGE)
8316 /* Arbitrarily choose the right or left gap. */
8317 if (!mineq && TREE_CODE (vr1min) == INTEGER_CST)
8318 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8319 build_int_cst (TREE_TYPE (vr1min), 1));
8320 else if (!maxeq && TREE_CODE (vr1max) == INTEGER_CST)
8321 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
8322 build_int_cst (TREE_TYPE (vr1max), 1));
8323 else
8324 goto give_up;
8326 else if (*vr0type == VR_RANGE
8327 && vr1type == VR_ANTI_RANGE)
8328 /* The result covers everything. */
8329 goto give_up;
8330 else
8331 gcc_unreachable ();
8333 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
8334 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
8336 /* ( [ ] ) or ([ ] ) or ( [ ]) */
8337 if (*vr0type == VR_RANGE
8338 && vr1type == VR_RANGE)
8340 *vr0type = vr1type;
8341 *vr0min = vr1min;
8342 *vr0max = vr1max;
8344 else if (*vr0type == VR_ANTI_RANGE
8345 && vr1type == VR_ANTI_RANGE)
8347 else if (*vr0type == VR_RANGE
8348 && vr1type == VR_ANTI_RANGE)
8350 *vr0type = VR_ANTI_RANGE;
8351 if (!mineq && TREE_CODE (*vr0min) == INTEGER_CST)
8353 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
8354 build_int_cst (TREE_TYPE (*vr0min), 1));
8355 *vr0min = vr1min;
8357 else if (!maxeq && TREE_CODE (*vr0max) == INTEGER_CST)
8359 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8360 build_int_cst (TREE_TYPE (*vr0max), 1));
8361 *vr0max = vr1max;
8363 else
8364 goto give_up;
8366 else if (*vr0type == VR_ANTI_RANGE
8367 && vr1type == VR_RANGE)
8368 /* The result covers everything. */
8369 goto give_up;
8370 else
8371 gcc_unreachable ();
8373 else if ((operand_less_p (vr1min, *vr0max) == 1
8374 || operand_equal_p (vr1min, *vr0max, 0))
8375 && operand_less_p (*vr0min, vr1min) == 1
8376 && operand_less_p (*vr0max, vr1max) == 1)
8378 /* [ ( ] ) or [ ]( ) */
8379 if (*vr0type == VR_RANGE
8380 && vr1type == VR_RANGE)
8381 *vr0max = vr1max;
8382 else if (*vr0type == VR_ANTI_RANGE
8383 && vr1type == VR_ANTI_RANGE)
8384 *vr0min = vr1min;
8385 else if (*vr0type == VR_ANTI_RANGE
8386 && vr1type == VR_RANGE)
8388 if (TREE_CODE (vr1min) == INTEGER_CST)
8389 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8390 build_int_cst (TREE_TYPE (vr1min), 1));
8391 else
8392 goto give_up;
8394 else if (*vr0type == VR_RANGE
8395 && vr1type == VR_ANTI_RANGE)
8397 if (TREE_CODE (*vr0max) == INTEGER_CST)
8399 *vr0type = vr1type;
8400 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8401 build_int_cst (TREE_TYPE (*vr0max), 1));
8402 *vr0max = vr1max;
8404 else
8405 goto give_up;
8407 else
8408 gcc_unreachable ();
8410 else if ((operand_less_p (*vr0min, vr1max) == 1
8411 || operand_equal_p (*vr0min, vr1max, 0))
8412 && operand_less_p (vr1min, *vr0min) == 1
8413 && operand_less_p (vr1max, *vr0max) == 1)
8415 /* ( [ ) ] or ( )[ ] */
8416 if (*vr0type == VR_RANGE
8417 && vr1type == VR_RANGE)
8418 *vr0min = vr1min;
8419 else if (*vr0type == VR_ANTI_RANGE
8420 && vr1type == VR_ANTI_RANGE)
8421 *vr0max = vr1max;
8422 else if (*vr0type == VR_ANTI_RANGE
8423 && vr1type == VR_RANGE)
8425 if (TREE_CODE (vr1max) == INTEGER_CST)
8426 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
8427 build_int_cst (TREE_TYPE (vr1max), 1));
8428 else
8429 goto give_up;
8431 else if (*vr0type == VR_RANGE
8432 && vr1type == VR_ANTI_RANGE)
8434 if (TREE_CODE (*vr0min) == INTEGER_CST)
8436 *vr0type = vr1type;
8437 *vr0min = vr1min;
8438 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
8439 build_int_cst (TREE_TYPE (*vr0min), 1));
8441 else
8442 goto give_up;
8444 else
8445 gcc_unreachable ();
8447 else
8448 goto give_up;
8450 return;
8452 give_up:
8453 *vr0type = VR_VARYING;
8454 *vr0min = NULL_TREE;
8455 *vr0max = NULL_TREE;
8458 /* Intersect the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
8459 { VR1TYPE, VR0MIN, VR0MAX } and store the result
8460 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
8461 possible such range. The resulting range is not canonicalized. */
8463 static void
8464 intersect_ranges (enum value_range_type *vr0type,
8465 tree *vr0min, tree *vr0max,
8466 enum value_range_type vr1type,
8467 tree vr1min, tree vr1max)
8469 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
8470 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
8472 /* [] is vr0, () is vr1 in the following classification comments. */
8473 if (mineq && maxeq)
8475 /* [( )] */
8476 if (*vr0type == vr1type)
8477 /* Nothing to do for equal ranges. */
8479 else if ((*vr0type == VR_RANGE
8480 && vr1type == VR_ANTI_RANGE)
8481 || (*vr0type == VR_ANTI_RANGE
8482 && vr1type == VR_RANGE))
8484 /* For anti-range with range intersection the result is empty. */
8485 *vr0type = VR_UNDEFINED;
8486 *vr0min = NULL_TREE;
8487 *vr0max = NULL_TREE;
8489 else
8490 gcc_unreachable ();
8492 else if (operand_less_p (*vr0max, vr1min) == 1
8493 || operand_less_p (vr1max, *vr0min) == 1)
8495 /* [ ] ( ) or ( ) [ ]
8496 If the ranges have an empty intersection, the result of the
8497 intersect operation is the range for intersecting an
8498 anti-range with a range or empty when intersecting two ranges. */
8499 if (*vr0type == VR_RANGE
8500 && vr1type == VR_ANTI_RANGE)
8502 else if (*vr0type == VR_ANTI_RANGE
8503 && vr1type == VR_RANGE)
8505 *vr0type = vr1type;
8506 *vr0min = vr1min;
8507 *vr0max = vr1max;
8509 else if (*vr0type == VR_RANGE
8510 && vr1type == VR_RANGE)
8512 *vr0type = VR_UNDEFINED;
8513 *vr0min = NULL_TREE;
8514 *vr0max = NULL_TREE;
8516 else if (*vr0type == VR_ANTI_RANGE
8517 && vr1type == VR_ANTI_RANGE)
8519 /* If the anti-ranges are adjacent to each other merge them. */
8520 if (TREE_CODE (*vr0max) == INTEGER_CST
8521 && TREE_CODE (vr1min) == INTEGER_CST
8522 && operand_less_p (*vr0max, vr1min) == 1
8523 && integer_onep (int_const_binop (MINUS_EXPR,
8524 vr1min, *vr0max)))
8525 *vr0max = vr1max;
8526 else if (TREE_CODE (vr1max) == INTEGER_CST
8527 && TREE_CODE (*vr0min) == INTEGER_CST
8528 && operand_less_p (vr1max, *vr0min) == 1
8529 && integer_onep (int_const_binop (MINUS_EXPR,
8530 *vr0min, vr1max)))
8531 *vr0min = vr1min;
8532 /* Else arbitrarily take VR0. */
8535 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
8536 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
8538 /* [ ( ) ] or [( ) ] or [ ( )] */
8539 if (*vr0type == VR_RANGE
8540 && vr1type == VR_RANGE)
8542 /* If both are ranges the result is the inner one. */
8543 *vr0type = vr1type;
8544 *vr0min = vr1min;
8545 *vr0max = vr1max;
8547 else if (*vr0type == VR_RANGE
8548 && vr1type == VR_ANTI_RANGE)
8550 /* Choose the right gap if the left one is empty. */
8551 if (mineq)
8553 if (TREE_CODE (vr1max) != INTEGER_CST)
8554 *vr0min = vr1max;
8555 else if (TYPE_PRECISION (TREE_TYPE (vr1max)) == 1
8556 && !TYPE_UNSIGNED (TREE_TYPE (vr1max)))
8557 *vr0min
8558 = int_const_binop (MINUS_EXPR, vr1max,
8559 build_int_cst (TREE_TYPE (vr1max), -1));
8560 else
8561 *vr0min
8562 = int_const_binop (PLUS_EXPR, vr1max,
8563 build_int_cst (TREE_TYPE (vr1max), 1));
8565 /* Choose the left gap if the right one is empty. */
8566 else if (maxeq)
8568 if (TREE_CODE (vr1min) != INTEGER_CST)
8569 *vr0max = vr1min;
8570 else if (TYPE_PRECISION (TREE_TYPE (vr1min)) == 1
8571 && !TYPE_UNSIGNED (TREE_TYPE (vr1min)))
8572 *vr0max
8573 = int_const_binop (PLUS_EXPR, vr1min,
8574 build_int_cst (TREE_TYPE (vr1min), -1));
8575 else
8576 *vr0max
8577 = int_const_binop (MINUS_EXPR, vr1min,
8578 build_int_cst (TREE_TYPE (vr1min), 1));
8580 /* Choose the anti-range if the range is effectively varying. */
8581 else if (vrp_val_is_min (*vr0min)
8582 && vrp_val_is_max (*vr0max))
8584 *vr0type = vr1type;
8585 *vr0min = vr1min;
8586 *vr0max = vr1max;
8588 /* Else choose the range. */
8590 else if (*vr0type == VR_ANTI_RANGE
8591 && vr1type == VR_ANTI_RANGE)
8592 /* If both are anti-ranges the result is the outer one. */
8594 else if (*vr0type == VR_ANTI_RANGE
8595 && vr1type == VR_RANGE)
8597 /* The intersection is empty. */
8598 *vr0type = VR_UNDEFINED;
8599 *vr0min = NULL_TREE;
8600 *vr0max = NULL_TREE;
8602 else
8603 gcc_unreachable ();
8605 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
8606 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
8608 /* ( [ ] ) or ([ ] ) or ( [ ]) */
8609 if (*vr0type == VR_RANGE
8610 && vr1type == VR_RANGE)
8611 /* Choose the inner range. */
8613 else if (*vr0type == VR_ANTI_RANGE
8614 && vr1type == VR_RANGE)
8616 /* Choose the right gap if the left is empty. */
8617 if (mineq)
8619 *vr0type = VR_RANGE;
8620 if (TREE_CODE (*vr0max) != INTEGER_CST)
8621 *vr0min = *vr0max;
8622 else if (TYPE_PRECISION (TREE_TYPE (*vr0max)) == 1
8623 && !TYPE_UNSIGNED (TREE_TYPE (*vr0max)))
8624 *vr0min
8625 = int_const_binop (MINUS_EXPR, *vr0max,
8626 build_int_cst (TREE_TYPE (*vr0max), -1));
8627 else
8628 *vr0min
8629 = int_const_binop (PLUS_EXPR, *vr0max,
8630 build_int_cst (TREE_TYPE (*vr0max), 1));
8631 *vr0max = vr1max;
8633 /* Choose the left gap if the right is empty. */
8634 else if (maxeq)
8636 *vr0type = VR_RANGE;
8637 if (TREE_CODE (*vr0min) != INTEGER_CST)
8638 *vr0max = *vr0min;
8639 else if (TYPE_PRECISION (TREE_TYPE (*vr0min)) == 1
8640 && !TYPE_UNSIGNED (TREE_TYPE (*vr0min)))
8641 *vr0max
8642 = int_const_binop (PLUS_EXPR, *vr0min,
8643 build_int_cst (TREE_TYPE (*vr0min), -1));
8644 else
8645 *vr0max
8646 = int_const_binop (MINUS_EXPR, *vr0min,
8647 build_int_cst (TREE_TYPE (*vr0min), 1));
8648 *vr0min = vr1min;
8650 /* Choose the anti-range if the range is effectively varying. */
8651 else if (vrp_val_is_min (vr1min)
8652 && vrp_val_is_max (vr1max))
8654 /* Choose the anti-range if it is ~[0,0], that range is special
8655 enough to special case when vr1's range is relatively wide. */
8656 else if (*vr0min == *vr0max
8657 && integer_zerop (*vr0min)
8658 && (TYPE_PRECISION (TREE_TYPE (*vr0min))
8659 == TYPE_PRECISION (ptr_type_node))
8660 && TREE_CODE (vr1max) == INTEGER_CST
8661 && TREE_CODE (vr1min) == INTEGER_CST
8662 && (wi::clz (wi::to_wide (vr1max) - wi::to_wide (vr1min))
8663 < TYPE_PRECISION (TREE_TYPE (*vr0min)) / 2))
8665 /* Else choose the range. */
8666 else
8668 *vr0type = vr1type;
8669 *vr0min = vr1min;
8670 *vr0max = vr1max;
8673 else if (*vr0type == VR_ANTI_RANGE
8674 && vr1type == VR_ANTI_RANGE)
8676 /* If both are anti-ranges the result is the outer one. */
8677 *vr0type = vr1type;
8678 *vr0min = vr1min;
8679 *vr0max = vr1max;
8681 else if (vr1type == VR_ANTI_RANGE
8682 && *vr0type == VR_RANGE)
8684 /* The intersection is empty. */
8685 *vr0type = VR_UNDEFINED;
8686 *vr0min = NULL_TREE;
8687 *vr0max = NULL_TREE;
8689 else
8690 gcc_unreachable ();
8692 else if ((operand_less_p (vr1min, *vr0max) == 1
8693 || operand_equal_p (vr1min, *vr0max, 0))
8694 && operand_less_p (*vr0min, vr1min) == 1)
8696 /* [ ( ] ) or [ ]( ) */
8697 if (*vr0type == VR_ANTI_RANGE
8698 && vr1type == VR_ANTI_RANGE)
8699 *vr0max = vr1max;
8700 else if (*vr0type == VR_RANGE
8701 && vr1type == VR_RANGE)
8702 *vr0min = vr1min;
8703 else if (*vr0type == VR_RANGE
8704 && vr1type == VR_ANTI_RANGE)
8706 if (TREE_CODE (vr1min) == INTEGER_CST)
8707 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8708 build_int_cst (TREE_TYPE (vr1min), 1));
8709 else
8710 *vr0max = vr1min;
8712 else if (*vr0type == VR_ANTI_RANGE
8713 && vr1type == VR_RANGE)
8715 *vr0type = VR_RANGE;
8716 if (TREE_CODE (*vr0max) == INTEGER_CST)
8717 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8718 build_int_cst (TREE_TYPE (*vr0max), 1));
8719 else
8720 *vr0min = *vr0max;
8721 *vr0max = vr1max;
8723 else
8724 gcc_unreachable ();
8726 else if ((operand_less_p (*vr0min, vr1max) == 1
8727 || operand_equal_p (*vr0min, vr1max, 0))
8728 && operand_less_p (vr1min, *vr0min) == 1)
8730 /* ( [ ) ] or ( )[ ] */
8731 if (*vr0type == VR_ANTI_RANGE
8732 && vr1type == VR_ANTI_RANGE)
8733 *vr0min = vr1min;
8734 else if (*vr0type == VR_RANGE
8735 && vr1type == VR_RANGE)
8736 *vr0max = vr1max;
8737 else if (*vr0type == VR_RANGE
8738 && vr1type == VR_ANTI_RANGE)
8740 if (TREE_CODE (vr1max) == INTEGER_CST)
8741 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
8742 build_int_cst (TREE_TYPE (vr1max), 1));
8743 else
8744 *vr0min = vr1max;
8746 else if (*vr0type == VR_ANTI_RANGE
8747 && vr1type == VR_RANGE)
8749 *vr0type = VR_RANGE;
8750 if (TREE_CODE (*vr0min) == INTEGER_CST)
8751 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
8752 build_int_cst (TREE_TYPE (*vr0min), 1));
8753 else
8754 *vr0max = *vr0min;
8755 *vr0min = vr1min;
8757 else
8758 gcc_unreachable ();
8761 /* As a fallback simply use { *VRTYPE, *VR0MIN, *VR0MAX } as
8762 result for the intersection. That's always a conservative
8763 correct estimate unless VR1 is a constant singleton range
8764 in which case we choose that. */
8765 if (vr1type == VR_RANGE
8766 && is_gimple_min_invariant (vr1min)
8767 && vrp_operand_equal_p (vr1min, vr1max))
8769 *vr0type = vr1type;
8770 *vr0min = vr1min;
8771 *vr0max = vr1max;
8774 return;
8778 /* Intersect the two value-ranges *VR0 and *VR1 and store the result
8779 in *VR0. This may not be the smallest possible such range. */
8781 static void
8782 vrp_intersect_ranges_1 (value_range *vr0, value_range *vr1)
8784 value_range saved;
8786 /* If either range is VR_VARYING the other one wins. */
8787 if (vr1->type == VR_VARYING)
8788 return;
8789 if (vr0->type == VR_VARYING)
8791 copy_value_range (vr0, vr1);
8792 return;
8795 /* When either range is VR_UNDEFINED the resulting range is
8796 VR_UNDEFINED, too. */
8797 if (vr0->type == VR_UNDEFINED)
8798 return;
8799 if (vr1->type == VR_UNDEFINED)
8801 set_value_range_to_undefined (vr0);
8802 return;
8805 /* Save the original vr0 so we can return it as conservative intersection
8806 result when our worker turns things to varying. */
8807 saved = *vr0;
8808 intersect_ranges (&vr0->type, &vr0->min, &vr0->max,
8809 vr1->type, vr1->min, vr1->max);
8810 /* Make sure to canonicalize the result though as the inversion of a
8811 VR_RANGE can still be a VR_RANGE. */
8812 set_and_canonicalize_value_range (vr0, vr0->type,
8813 vr0->min, vr0->max, vr0->equiv);
8814 /* If that failed, use the saved original VR0. */
8815 if (vr0->type == VR_VARYING)
8817 *vr0 = saved;
8818 return;
8820 /* If the result is VR_UNDEFINED there is no need to mess with
8821 the equivalencies. */
8822 if (vr0->type == VR_UNDEFINED)
8823 return;
8825 /* The resulting set of equivalences for range intersection is the union of
8826 the two sets. */
8827 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
8828 bitmap_ior_into (vr0->equiv, vr1->equiv);
8829 else if (vr1->equiv && !vr0->equiv)
8831 vr0->equiv = BITMAP_ALLOC (&vrp_equiv_obstack);
8832 bitmap_copy (vr0->equiv, vr1->equiv);
8836 void
8837 vrp_intersect_ranges (value_range *vr0, value_range *vr1)
8839 if (dump_file && (dump_flags & TDF_DETAILS))
8841 fprintf (dump_file, "Intersecting\n ");
8842 dump_value_range (dump_file, vr0);
8843 fprintf (dump_file, "\nand\n ");
8844 dump_value_range (dump_file, vr1);
8845 fprintf (dump_file, "\n");
8847 vrp_intersect_ranges_1 (vr0, vr1);
8848 if (dump_file && (dump_flags & TDF_DETAILS))
8850 fprintf (dump_file, "to\n ");
8851 dump_value_range (dump_file, vr0);
8852 fprintf (dump_file, "\n");
8856 /* Meet operation for value ranges. Given two value ranges VR0 and
8857 VR1, store in VR0 a range that contains both VR0 and VR1. This
8858 may not be the smallest possible such range. */
8860 static void
8861 vrp_meet_1 (value_range *vr0, const value_range *vr1)
8863 value_range saved;
8865 if (vr0->type == VR_UNDEFINED)
8867 set_value_range (vr0, vr1->type, vr1->min, vr1->max, vr1->equiv);
8868 return;
8871 if (vr1->type == VR_UNDEFINED)
8873 /* VR0 already has the resulting range. */
8874 return;
8877 if (vr0->type == VR_VARYING)
8879 /* Nothing to do. VR0 already has the resulting range. */
8880 return;
8883 if (vr1->type == VR_VARYING)
8885 set_value_range_to_varying (vr0);
8886 return;
8889 saved = *vr0;
8890 union_ranges (&vr0->type, &vr0->min, &vr0->max,
8891 vr1->type, vr1->min, vr1->max);
8892 if (vr0->type == VR_VARYING)
8894 /* Failed to find an efficient meet. Before giving up and setting
8895 the result to VARYING, see if we can at least derive a useful
8896 anti-range. FIXME, all this nonsense about distinguishing
8897 anti-ranges from ranges is necessary because of the odd
8898 semantics of range_includes_zero_p and friends. */
8899 if (((saved.type == VR_RANGE
8900 && range_includes_zero_p (saved.min, saved.max) == 0)
8901 || (saved.type == VR_ANTI_RANGE
8902 && range_includes_zero_p (saved.min, saved.max) == 1))
8903 && ((vr1->type == VR_RANGE
8904 && range_includes_zero_p (vr1->min, vr1->max) == 0)
8905 || (vr1->type == VR_ANTI_RANGE
8906 && range_includes_zero_p (vr1->min, vr1->max) == 1)))
8908 set_value_range_to_nonnull (vr0, TREE_TYPE (saved.min));
8910 /* Since this meet operation did not result from the meeting of
8911 two equivalent names, VR0 cannot have any equivalences. */
8912 if (vr0->equiv)
8913 bitmap_clear (vr0->equiv);
8914 return;
8917 set_value_range_to_varying (vr0);
8918 return;
8920 set_and_canonicalize_value_range (vr0, vr0->type, vr0->min, vr0->max,
8921 vr0->equiv);
8922 if (vr0->type == VR_VARYING)
8923 return;
8925 /* The resulting set of equivalences is always the intersection of
8926 the two sets. */
8927 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
8928 bitmap_and_into (vr0->equiv, vr1->equiv);
8929 else if (vr0->equiv && !vr1->equiv)
8930 bitmap_clear (vr0->equiv);
8933 void
8934 vrp_meet (value_range *vr0, const value_range *vr1)
8936 if (dump_file && (dump_flags & TDF_DETAILS))
8938 fprintf (dump_file, "Meeting\n ");
8939 dump_value_range (dump_file, vr0);
8940 fprintf (dump_file, "\nand\n ");
8941 dump_value_range (dump_file, vr1);
8942 fprintf (dump_file, "\n");
8944 vrp_meet_1 (vr0, vr1);
8945 if (dump_file && (dump_flags & TDF_DETAILS))
8947 fprintf (dump_file, "to\n ");
8948 dump_value_range (dump_file, vr0);
8949 fprintf (dump_file, "\n");
8954 /* Visit all arguments for PHI node PHI that flow through executable
8955 edges. If a valid value range can be derived from all the incoming
8956 value ranges, set a new range in VR_RESULT. */
8958 static void
8959 extract_range_from_phi_node (gphi *phi, value_range *vr_result)
8961 size_t i;
8962 tree lhs = PHI_RESULT (phi);
8963 value_range *lhs_vr = get_value_range (lhs);
8964 bool first = true;
8965 int edges, old_edges;
8966 struct loop *l;
8968 if (dump_file && (dump_flags & TDF_DETAILS))
8970 fprintf (dump_file, "\nVisiting PHI node: ");
8971 print_gimple_stmt (dump_file, phi, 0, dump_flags);
8974 bool may_simulate_backedge_again = false;
8975 edges = 0;
8976 for (i = 0; i < gimple_phi_num_args (phi); i++)
8978 edge e = gimple_phi_arg_edge (phi, i);
8980 if (dump_file && (dump_flags & TDF_DETAILS))
8982 fprintf (dump_file,
8983 " Argument #%d (%d -> %d %sexecutable)\n",
8984 (int) i, e->src->index, e->dest->index,
8985 (e->flags & EDGE_EXECUTABLE) ? "" : "not ");
8988 if (e->flags & EDGE_EXECUTABLE)
8990 tree arg = PHI_ARG_DEF (phi, i);
8991 value_range vr_arg;
8993 ++edges;
8995 if (TREE_CODE (arg) == SSA_NAME)
8997 /* See if we are eventually going to change one of the args. */
8998 gimple *def_stmt = SSA_NAME_DEF_STMT (arg);
8999 if (! gimple_nop_p (def_stmt)
9000 && prop_simulate_again_p (def_stmt)
9001 && e->flags & EDGE_DFS_BACK)
9002 may_simulate_backedge_again = true;
9004 vr_arg = *(get_value_range (arg));
9005 /* Do not allow equivalences or symbolic ranges to leak in from
9006 backedges. That creates invalid equivalencies.
9007 See PR53465 and PR54767. */
9008 if (e->flags & EDGE_DFS_BACK)
9010 if (vr_arg.type == VR_RANGE
9011 || vr_arg.type == VR_ANTI_RANGE)
9013 vr_arg.equiv = NULL;
9014 if (symbolic_range_p (&vr_arg))
9016 vr_arg.type = VR_VARYING;
9017 vr_arg.min = NULL_TREE;
9018 vr_arg.max = NULL_TREE;
9022 else
9024 /* If the non-backedge arguments range is VR_VARYING then
9025 we can still try recording a simple equivalence. */
9026 if (vr_arg.type == VR_VARYING)
9028 vr_arg.type = VR_RANGE;
9029 vr_arg.min = arg;
9030 vr_arg.max = arg;
9031 vr_arg.equiv = NULL;
9035 else
9037 if (TREE_OVERFLOW_P (arg))
9038 arg = drop_tree_overflow (arg);
9040 vr_arg.type = VR_RANGE;
9041 vr_arg.min = arg;
9042 vr_arg.max = arg;
9043 vr_arg.equiv = NULL;
9046 if (dump_file && (dump_flags & TDF_DETAILS))
9048 fprintf (dump_file, "\t");
9049 print_generic_expr (dump_file, arg, dump_flags);
9050 fprintf (dump_file, ": ");
9051 dump_value_range (dump_file, &vr_arg);
9052 fprintf (dump_file, "\n");
9055 if (first)
9056 copy_value_range (vr_result, &vr_arg);
9057 else
9058 vrp_meet (vr_result, &vr_arg);
9059 first = false;
9061 if (vr_result->type == VR_VARYING)
9062 break;
9066 if (vr_result->type == VR_VARYING)
9067 goto varying;
9068 else if (vr_result->type == VR_UNDEFINED)
9069 goto update_range;
9071 old_edges = vr_phi_edge_counts[SSA_NAME_VERSION (lhs)];
9072 vr_phi_edge_counts[SSA_NAME_VERSION (lhs)] = edges;
9074 /* To prevent infinite iterations in the algorithm, derive ranges
9075 when the new value is slightly bigger or smaller than the
9076 previous one. We don't do this if we have seen a new executable
9077 edge; this helps us avoid an infinity for conditionals
9078 which are not in a loop. If the old value-range was VR_UNDEFINED
9079 use the updated range and iterate one more time. If we will not
9080 simulate this PHI again via the backedge allow us to iterate. */
9081 if (edges > 0
9082 && gimple_phi_num_args (phi) > 1
9083 && edges == old_edges
9084 && lhs_vr->type != VR_UNDEFINED
9085 && may_simulate_backedge_again)
9087 /* Compare old and new ranges, fall back to varying if the
9088 values are not comparable. */
9089 int cmp_min = compare_values (lhs_vr->min, vr_result->min);
9090 if (cmp_min == -2)
9091 goto varying;
9092 int cmp_max = compare_values (lhs_vr->max, vr_result->max);
9093 if (cmp_max == -2)
9094 goto varying;
9096 /* For non VR_RANGE or for pointers fall back to varying if
9097 the range changed. */
9098 if ((lhs_vr->type != VR_RANGE || vr_result->type != VR_RANGE
9099 || POINTER_TYPE_P (TREE_TYPE (lhs)))
9100 && (cmp_min != 0 || cmp_max != 0))
9101 goto varying;
9103 /* If the new minimum is larger than the previous one
9104 retain the old value. If the new minimum value is smaller
9105 than the previous one and not -INF go all the way to -INF + 1.
9106 In the first case, to avoid infinite bouncing between different
9107 minimums, and in the other case to avoid iterating millions of
9108 times to reach -INF. Going to -INF + 1 also lets the following
9109 iteration compute whether there will be any overflow, at the
9110 expense of one additional iteration. */
9111 if (cmp_min < 0)
9112 vr_result->min = lhs_vr->min;
9113 else if (cmp_min > 0
9114 && !vrp_val_is_min (vr_result->min))
9115 vr_result->min
9116 = int_const_binop (PLUS_EXPR,
9117 vrp_val_min (TREE_TYPE (vr_result->min)),
9118 build_int_cst (TREE_TYPE (vr_result->min), 1));
9120 /* Similarly for the maximum value. */
9121 if (cmp_max > 0)
9122 vr_result->max = lhs_vr->max;
9123 else if (cmp_max < 0
9124 && !vrp_val_is_max (vr_result->max))
9125 vr_result->max
9126 = int_const_binop (MINUS_EXPR,
9127 vrp_val_max (TREE_TYPE (vr_result->min)),
9128 build_int_cst (TREE_TYPE (vr_result->min), 1));
9130 /* If we dropped either bound to +-INF then if this is a loop
9131 PHI node SCEV may known more about its value-range. */
9132 if (cmp_min > 0 || cmp_min < 0
9133 || cmp_max < 0 || cmp_max > 0)
9134 goto scev_check;
9136 goto infinite_check;
9139 goto update_range;
9141 varying:
9142 set_value_range_to_varying (vr_result);
9144 scev_check:
9145 /* If this is a loop PHI node SCEV may known more about its value-range.
9146 scev_check can be reached from two paths, one is a fall through from above
9147 "varying" label, the other is direct goto from code block which tries to
9148 avoid infinite simulation. */
9149 if ((l = loop_containing_stmt (phi))
9150 && l->header == gimple_bb (phi))
9151 adjust_range_with_scev (vr_result, l, phi, lhs);
9153 infinite_check:
9154 /* If we will end up with a (-INF, +INF) range, set it to
9155 VARYING. Same if the previous max value was invalid for
9156 the type and we end up with vr_result.min > vr_result.max. */
9157 if ((vr_result->type == VR_RANGE || vr_result->type == VR_ANTI_RANGE)
9158 && !((vrp_val_is_max (vr_result->max) && vrp_val_is_min (vr_result->min))
9159 || compare_values (vr_result->min, vr_result->max) > 0))
9161 else
9162 set_value_range_to_varying (vr_result);
9164 /* If the new range is different than the previous value, keep
9165 iterating. */
9166 update_range:
9167 return;
9170 /* Visit all arguments for PHI node PHI that flow through executable
9171 edges. If a valid value range can be derived from all the incoming
9172 value ranges, set a new range for the LHS of PHI. */
9174 enum ssa_prop_result
9175 vrp_prop::visit_phi (gphi *phi)
9177 tree lhs = PHI_RESULT (phi);
9178 value_range vr_result = VR_INITIALIZER;
9179 extract_range_from_phi_node (phi, &vr_result);
9180 if (update_value_range (lhs, &vr_result))
9182 if (dump_file && (dump_flags & TDF_DETAILS))
9184 fprintf (dump_file, "Found new range for ");
9185 print_generic_expr (dump_file, lhs);
9186 fprintf (dump_file, ": ");
9187 dump_value_range (dump_file, &vr_result);
9188 fprintf (dump_file, "\n");
9191 if (vr_result.type == VR_VARYING)
9192 return SSA_PROP_VARYING;
9194 return SSA_PROP_INTERESTING;
9197 /* Nothing changed, don't add outgoing edges. */
9198 return SSA_PROP_NOT_INTERESTING;
9201 /* Simplify boolean operations if the source is known
9202 to be already a boolean. */
9203 static bool
9204 simplify_truth_ops_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9206 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
9207 tree lhs, op0, op1;
9208 bool need_conversion;
9210 /* We handle only !=/== case here. */
9211 gcc_assert (rhs_code == EQ_EXPR || rhs_code == NE_EXPR);
9213 op0 = gimple_assign_rhs1 (stmt);
9214 if (!op_with_boolean_value_range_p (op0))
9215 return false;
9217 op1 = gimple_assign_rhs2 (stmt);
9218 if (!op_with_boolean_value_range_p (op1))
9219 return false;
9221 /* Reduce number of cases to handle to NE_EXPR. As there is no
9222 BIT_XNOR_EXPR we cannot replace A == B with a single statement. */
9223 if (rhs_code == EQ_EXPR)
9225 if (TREE_CODE (op1) == INTEGER_CST)
9226 op1 = int_const_binop (BIT_XOR_EXPR, op1,
9227 build_int_cst (TREE_TYPE (op1), 1));
9228 else
9229 return false;
9232 lhs = gimple_assign_lhs (stmt);
9233 need_conversion
9234 = !useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (op0));
9236 /* Make sure to not sign-extend a 1-bit 1 when converting the result. */
9237 if (need_conversion
9238 && !TYPE_UNSIGNED (TREE_TYPE (op0))
9239 && TYPE_PRECISION (TREE_TYPE (op0)) == 1
9240 && TYPE_PRECISION (TREE_TYPE (lhs)) > 1)
9241 return false;
9243 /* For A != 0 we can substitute A itself. */
9244 if (integer_zerop (op1))
9245 gimple_assign_set_rhs_with_ops (gsi,
9246 need_conversion
9247 ? NOP_EXPR : TREE_CODE (op0), op0);
9248 /* For A != B we substitute A ^ B. Either with conversion. */
9249 else if (need_conversion)
9251 tree tem = make_ssa_name (TREE_TYPE (op0));
9252 gassign *newop
9253 = gimple_build_assign (tem, BIT_XOR_EXPR, op0, op1);
9254 gsi_insert_before (gsi, newop, GSI_SAME_STMT);
9255 if (INTEGRAL_TYPE_P (TREE_TYPE (tem))
9256 && TYPE_PRECISION (TREE_TYPE (tem)) > 1)
9257 set_range_info (tem, VR_RANGE,
9258 wi::zero (TYPE_PRECISION (TREE_TYPE (tem))),
9259 wi::one (TYPE_PRECISION (TREE_TYPE (tem))));
9260 gimple_assign_set_rhs_with_ops (gsi, NOP_EXPR, tem);
9262 /* Or without. */
9263 else
9264 gimple_assign_set_rhs_with_ops (gsi, BIT_XOR_EXPR, op0, op1);
9265 update_stmt (gsi_stmt (*gsi));
9266 fold_stmt (gsi, follow_single_use_edges);
9268 return true;
9271 /* Simplify a division or modulo operator to a right shift or bitwise and
9272 if the first operand is unsigned or is greater than zero and the second
9273 operand is an exact power of two. For TRUNC_MOD_EXPR op0 % op1 with
9274 constant op1 (op1min = op1) or with op1 in [op1min, op1max] range,
9275 optimize it into just op0 if op0's range is known to be a subset of
9276 [-op1min + 1, op1min - 1] for signed and [0, op1min - 1] for unsigned
9277 modulo. */
9279 static bool
9280 simplify_div_or_mod_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9282 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
9283 tree val = NULL;
9284 tree op0 = gimple_assign_rhs1 (stmt);
9285 tree op1 = gimple_assign_rhs2 (stmt);
9286 tree op0min = NULL_TREE, op0max = NULL_TREE;
9287 tree op1min = op1;
9288 value_range *vr = NULL;
9290 if (TREE_CODE (op0) == INTEGER_CST)
9292 op0min = op0;
9293 op0max = op0;
9295 else
9297 vr = get_value_range (op0);
9298 if (range_int_cst_p (vr))
9300 op0min = vr->min;
9301 op0max = vr->max;
9305 if (rhs_code == TRUNC_MOD_EXPR
9306 && TREE_CODE (op1) == SSA_NAME)
9308 value_range *vr1 = get_value_range (op1);
9309 if (range_int_cst_p (vr1))
9310 op1min = vr1->min;
9312 if (rhs_code == TRUNC_MOD_EXPR
9313 && TREE_CODE (op1min) == INTEGER_CST
9314 && tree_int_cst_sgn (op1min) == 1
9315 && op0max
9316 && tree_int_cst_lt (op0max, op1min))
9318 if (TYPE_UNSIGNED (TREE_TYPE (op0))
9319 || tree_int_cst_sgn (op0min) >= 0
9320 || tree_int_cst_lt (fold_unary (NEGATE_EXPR, TREE_TYPE (op1min), op1min),
9321 op0min))
9323 /* If op0 already has the range op0 % op1 has,
9324 then TRUNC_MOD_EXPR won't change anything. */
9325 gimple_assign_set_rhs_from_tree (gsi, op0);
9326 return true;
9330 if (TREE_CODE (op0) != SSA_NAME)
9331 return false;
9333 if (!integer_pow2p (op1))
9335 /* X % -Y can be only optimized into X % Y either if
9336 X is not INT_MIN, or Y is not -1. Fold it now, as after
9337 remove_range_assertions the range info might be not available
9338 anymore. */
9339 if (rhs_code == TRUNC_MOD_EXPR
9340 && fold_stmt (gsi, follow_single_use_edges))
9341 return true;
9342 return false;
9345 if (TYPE_UNSIGNED (TREE_TYPE (op0)))
9346 val = integer_one_node;
9347 else
9349 bool sop = false;
9351 val = compare_range_with_value (GE_EXPR, vr, integer_zero_node, &sop);
9353 if (val
9354 && sop
9355 && integer_onep (val)
9356 && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
9358 location_t location;
9360 if (!gimple_has_location (stmt))
9361 location = input_location;
9362 else
9363 location = gimple_location (stmt);
9364 warning_at (location, OPT_Wstrict_overflow,
9365 "assuming signed overflow does not occur when "
9366 "simplifying %</%> or %<%%%> to %<>>%> or %<&%>");
9370 if (val && integer_onep (val))
9372 tree t;
9374 if (rhs_code == TRUNC_DIV_EXPR)
9376 t = build_int_cst (integer_type_node, tree_log2 (op1));
9377 gimple_assign_set_rhs_code (stmt, RSHIFT_EXPR);
9378 gimple_assign_set_rhs1 (stmt, op0);
9379 gimple_assign_set_rhs2 (stmt, t);
9381 else
9383 t = build_int_cst (TREE_TYPE (op1), 1);
9384 t = int_const_binop (MINUS_EXPR, op1, t);
9385 t = fold_convert (TREE_TYPE (op0), t);
9387 gimple_assign_set_rhs_code (stmt, BIT_AND_EXPR);
9388 gimple_assign_set_rhs1 (stmt, op0);
9389 gimple_assign_set_rhs2 (stmt, t);
9392 update_stmt (stmt);
9393 fold_stmt (gsi, follow_single_use_edges);
9394 return true;
9397 return false;
9400 /* Simplify a min or max if the ranges of the two operands are
9401 disjoint. Return true if we do simplify. */
9403 static bool
9404 simplify_min_or_max_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9406 tree op0 = gimple_assign_rhs1 (stmt);
9407 tree op1 = gimple_assign_rhs2 (stmt);
9408 bool sop = false;
9409 tree val;
9411 val = (vrp_evaluate_conditional_warnv_with_ops_using_ranges
9412 (LE_EXPR, op0, op1, &sop));
9413 if (!val)
9415 sop = false;
9416 val = (vrp_evaluate_conditional_warnv_with_ops_using_ranges
9417 (LT_EXPR, op0, op1, &sop));
9420 if (val)
9422 if (sop && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
9424 location_t location;
9426 if (!gimple_has_location (stmt))
9427 location = input_location;
9428 else
9429 location = gimple_location (stmt);
9430 warning_at (location, OPT_Wstrict_overflow,
9431 "assuming signed overflow does not occur when "
9432 "simplifying %<min/max (X,Y)%> to %<X%> or %<Y%>");
9435 /* VAL == TRUE -> OP0 < or <= op1
9436 VAL == FALSE -> OP0 > or >= op1. */
9437 tree res = ((gimple_assign_rhs_code (stmt) == MAX_EXPR)
9438 == integer_zerop (val)) ? op0 : op1;
9439 gimple_assign_set_rhs_from_tree (gsi, res);
9440 return true;
9443 return false;
9446 /* If the operand to an ABS_EXPR is >= 0, then eliminate the
9447 ABS_EXPR. If the operand is <= 0, then simplify the
9448 ABS_EXPR into a NEGATE_EXPR. */
9450 static bool
9451 simplify_abs_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9453 tree op = gimple_assign_rhs1 (stmt);
9454 value_range *vr = get_value_range (op);
9456 if (vr)
9458 tree val = NULL;
9459 bool sop = false;
9461 val = compare_range_with_value (LE_EXPR, vr, integer_zero_node, &sop);
9462 if (!val)
9464 /* The range is neither <= 0 nor > 0. Now see if it is
9465 either < 0 or >= 0. */
9466 sop = false;
9467 val = compare_range_with_value (LT_EXPR, vr, integer_zero_node,
9468 &sop);
9471 if (val)
9473 if (sop && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
9475 location_t location;
9477 if (!gimple_has_location (stmt))
9478 location = input_location;
9479 else
9480 location = gimple_location (stmt);
9481 warning_at (location, OPT_Wstrict_overflow,
9482 "assuming signed overflow does not occur when "
9483 "simplifying %<abs (X)%> to %<X%> or %<-X%>");
9486 gimple_assign_set_rhs1 (stmt, op);
9487 if (integer_zerop (val))
9488 gimple_assign_set_rhs_code (stmt, SSA_NAME);
9489 else
9490 gimple_assign_set_rhs_code (stmt, NEGATE_EXPR);
9491 update_stmt (stmt);
9492 fold_stmt (gsi, follow_single_use_edges);
9493 return true;
9497 return false;
9500 /* Optimize away redundant BIT_AND_EXPR and BIT_IOR_EXPR.
9501 If all the bits that are being cleared by & are already
9502 known to be zero from VR, or all the bits that are being
9503 set by | are already known to be one from VR, the bit
9504 operation is redundant. */
9506 static bool
9507 simplify_bit_ops_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9509 tree op0 = gimple_assign_rhs1 (stmt);
9510 tree op1 = gimple_assign_rhs2 (stmt);
9511 tree op = NULL_TREE;
9512 value_range vr0 = VR_INITIALIZER;
9513 value_range vr1 = VR_INITIALIZER;
9514 wide_int may_be_nonzero0, may_be_nonzero1;
9515 wide_int must_be_nonzero0, must_be_nonzero1;
9516 wide_int mask;
9518 if (TREE_CODE (op0) == SSA_NAME)
9519 vr0 = *(get_value_range (op0));
9520 else if (is_gimple_min_invariant (op0))
9521 set_value_range_to_value (&vr0, op0, NULL);
9522 else
9523 return false;
9525 if (TREE_CODE (op1) == SSA_NAME)
9526 vr1 = *(get_value_range (op1));
9527 else if (is_gimple_min_invariant (op1))
9528 set_value_range_to_value (&vr1, op1, NULL);
9529 else
9530 return false;
9532 if (!zero_nonzero_bits_from_vr (TREE_TYPE (op0), &vr0, &may_be_nonzero0,
9533 &must_be_nonzero0))
9534 return false;
9535 if (!zero_nonzero_bits_from_vr (TREE_TYPE (op1), &vr1, &may_be_nonzero1,
9536 &must_be_nonzero1))
9537 return false;
9539 switch (gimple_assign_rhs_code (stmt))
9541 case BIT_AND_EXPR:
9542 mask = wi::bit_and_not (may_be_nonzero0, must_be_nonzero1);
9543 if (mask == 0)
9545 op = op0;
9546 break;
9548 mask = wi::bit_and_not (may_be_nonzero1, must_be_nonzero0);
9549 if (mask == 0)
9551 op = op1;
9552 break;
9554 break;
9555 case BIT_IOR_EXPR:
9556 mask = wi::bit_and_not (may_be_nonzero0, must_be_nonzero1);
9557 if (mask == 0)
9559 op = op1;
9560 break;
9562 mask = wi::bit_and_not (may_be_nonzero1, must_be_nonzero0);
9563 if (mask == 0)
9565 op = op0;
9566 break;
9568 break;
9569 default:
9570 gcc_unreachable ();
9573 if (op == NULL_TREE)
9574 return false;
9576 gimple_assign_set_rhs_with_ops (gsi, TREE_CODE (op), op);
9577 update_stmt (gsi_stmt (*gsi));
9578 return true;
9581 /* We are comparing trees OP0 and OP1 using COND_CODE. OP0 has
9582 a known value range VR.
9584 If there is one and only one value which will satisfy the
9585 conditional, then return that value. Else return NULL.
9587 If signed overflow must be undefined for the value to satisfy
9588 the conditional, then set *STRICT_OVERFLOW_P to true. */
9590 static tree
9591 test_for_singularity (enum tree_code cond_code, tree op0,
9592 tree op1, value_range *vr)
9594 tree min = NULL;
9595 tree max = NULL;
9597 /* Extract minimum/maximum values which satisfy the conditional as it was
9598 written. */
9599 if (cond_code == LE_EXPR || cond_code == LT_EXPR)
9601 min = TYPE_MIN_VALUE (TREE_TYPE (op0));
9603 max = op1;
9604 if (cond_code == LT_EXPR)
9606 tree one = build_int_cst (TREE_TYPE (op0), 1);
9607 max = fold_build2 (MINUS_EXPR, TREE_TYPE (op0), max, one);
9608 /* Signal to compare_values_warnv this expr doesn't overflow. */
9609 if (EXPR_P (max))
9610 TREE_NO_WARNING (max) = 1;
9613 else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
9615 max = TYPE_MAX_VALUE (TREE_TYPE (op0));
9617 min = op1;
9618 if (cond_code == GT_EXPR)
9620 tree one = build_int_cst (TREE_TYPE (op0), 1);
9621 min = fold_build2 (PLUS_EXPR, TREE_TYPE (op0), min, one);
9622 /* Signal to compare_values_warnv this expr doesn't overflow. */
9623 if (EXPR_P (min))
9624 TREE_NO_WARNING (min) = 1;
9628 /* Now refine the minimum and maximum values using any
9629 value range information we have for op0. */
9630 if (min && max)
9632 if (compare_values (vr->min, min) == 1)
9633 min = vr->min;
9634 if (compare_values (vr->max, max) == -1)
9635 max = vr->max;
9637 /* If the new min/max values have converged to a single value,
9638 then there is only one value which can satisfy the condition,
9639 return that value. */
9640 if (operand_equal_p (min, max, 0) && is_gimple_min_invariant (min))
9641 return min;
9643 return NULL;
9646 /* Return whether the value range *VR fits in an integer type specified
9647 by PRECISION and UNSIGNED_P. */
9649 static bool
9650 range_fits_type_p (value_range *vr, unsigned dest_precision, signop dest_sgn)
9652 tree src_type;
9653 unsigned src_precision;
9654 widest_int tem;
9655 signop src_sgn;
9657 /* We can only handle integral and pointer types. */
9658 src_type = TREE_TYPE (vr->min);
9659 if (!INTEGRAL_TYPE_P (src_type)
9660 && !POINTER_TYPE_P (src_type))
9661 return false;
9663 /* An extension is fine unless VR is SIGNED and dest_sgn is UNSIGNED,
9664 and so is an identity transform. */
9665 src_precision = TYPE_PRECISION (TREE_TYPE (vr->min));
9666 src_sgn = TYPE_SIGN (src_type);
9667 if ((src_precision < dest_precision
9668 && !(dest_sgn == UNSIGNED && src_sgn == SIGNED))
9669 || (src_precision == dest_precision && src_sgn == dest_sgn))
9670 return true;
9672 /* Now we can only handle ranges with constant bounds. */
9673 if (vr->type != VR_RANGE
9674 || TREE_CODE (vr->min) != INTEGER_CST
9675 || TREE_CODE (vr->max) != INTEGER_CST)
9676 return false;
9678 /* For sign changes, the MSB of the wide_int has to be clear.
9679 An unsigned value with its MSB set cannot be represented by
9680 a signed wide_int, while a negative value cannot be represented
9681 by an unsigned wide_int. */
9682 if (src_sgn != dest_sgn
9683 && (wi::lts_p (wi::to_wide (vr->min), 0)
9684 || wi::lts_p (wi::to_wide (vr->max), 0)))
9685 return false;
9687 /* Then we can perform the conversion on both ends and compare
9688 the result for equality. */
9689 tem = wi::ext (wi::to_widest (vr->min), dest_precision, dest_sgn);
9690 if (tem != wi::to_widest (vr->min))
9691 return false;
9692 tem = wi::ext (wi::to_widest (vr->max), dest_precision, dest_sgn);
9693 if (tem != wi::to_widest (vr->max))
9694 return false;
9696 return true;
9699 /* Simplify a conditional using a relational operator to an equality
9700 test if the range information indicates only one value can satisfy
9701 the original conditional. */
9703 static bool
9704 simplify_cond_using_ranges_1 (gcond *stmt)
9706 tree op0 = gimple_cond_lhs (stmt);
9707 tree op1 = gimple_cond_rhs (stmt);
9708 enum tree_code cond_code = gimple_cond_code (stmt);
9710 if (cond_code != NE_EXPR
9711 && cond_code != EQ_EXPR
9712 && TREE_CODE (op0) == SSA_NAME
9713 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
9714 && is_gimple_min_invariant (op1))
9716 value_range *vr = get_value_range (op0);
9718 /* If we have range information for OP0, then we might be
9719 able to simplify this conditional. */
9720 if (vr->type == VR_RANGE)
9722 tree new_tree = test_for_singularity (cond_code, op0, op1, vr);
9723 if (new_tree)
9725 if (dump_file)
9727 fprintf (dump_file, "Simplified relational ");
9728 print_gimple_stmt (dump_file, stmt, 0);
9729 fprintf (dump_file, " into ");
9732 gimple_cond_set_code (stmt, EQ_EXPR);
9733 gimple_cond_set_lhs (stmt, op0);
9734 gimple_cond_set_rhs (stmt, new_tree);
9736 update_stmt (stmt);
9738 if (dump_file)
9740 print_gimple_stmt (dump_file, stmt, 0);
9741 fprintf (dump_file, "\n");
9744 return true;
9747 /* Try again after inverting the condition. We only deal
9748 with integral types here, so no need to worry about
9749 issues with inverting FP comparisons. */
9750 new_tree = test_for_singularity
9751 (invert_tree_comparison (cond_code, false),
9752 op0, op1, vr);
9753 if (new_tree)
9755 if (dump_file)
9757 fprintf (dump_file, "Simplified relational ");
9758 print_gimple_stmt (dump_file, stmt, 0);
9759 fprintf (dump_file, " into ");
9762 gimple_cond_set_code (stmt, NE_EXPR);
9763 gimple_cond_set_lhs (stmt, op0);
9764 gimple_cond_set_rhs (stmt, new_tree);
9766 update_stmt (stmt);
9768 if (dump_file)
9770 print_gimple_stmt (dump_file, stmt, 0);
9771 fprintf (dump_file, "\n");
9774 return true;
9778 return false;
9781 /* STMT is a conditional at the end of a basic block.
9783 If the conditional is of the form SSA_NAME op constant and the SSA_NAME
9784 was set via a type conversion, try to replace the SSA_NAME with the RHS
9785 of the type conversion. Doing so makes the conversion dead which helps
9786 subsequent passes. */
9788 static void
9789 simplify_cond_using_ranges_2 (gcond *stmt)
9791 tree op0 = gimple_cond_lhs (stmt);
9792 tree op1 = gimple_cond_rhs (stmt);
9794 /* If we have a comparison of an SSA_NAME (OP0) against a constant,
9795 see if OP0 was set by a type conversion where the source of
9796 the conversion is another SSA_NAME with a range that fits
9797 into the range of OP0's type.
9799 If so, the conversion is redundant as the earlier SSA_NAME can be
9800 used for the comparison directly if we just massage the constant in the
9801 comparison. */
9802 if (TREE_CODE (op0) == SSA_NAME
9803 && TREE_CODE (op1) == INTEGER_CST)
9805 gimple *def_stmt = SSA_NAME_DEF_STMT (op0);
9806 tree innerop;
9808 if (!is_gimple_assign (def_stmt)
9809 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)))
9810 return;
9812 innerop = gimple_assign_rhs1 (def_stmt);
9814 if (TREE_CODE (innerop) == SSA_NAME
9815 && !POINTER_TYPE_P (TREE_TYPE (innerop))
9816 && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (innerop)
9817 && desired_pro_or_demotion_p (TREE_TYPE (innerop), TREE_TYPE (op0)))
9819 value_range *vr = get_value_range (innerop);
9821 if (range_int_cst_p (vr)
9822 && range_fits_type_p (vr,
9823 TYPE_PRECISION (TREE_TYPE (op0)),
9824 TYPE_SIGN (TREE_TYPE (op0)))
9825 && int_fits_type_p (op1, TREE_TYPE (innerop)))
9827 tree newconst = fold_convert (TREE_TYPE (innerop), op1);
9828 gimple_cond_set_lhs (stmt, innerop);
9829 gimple_cond_set_rhs (stmt, newconst);
9830 update_stmt (stmt);
9831 if (dump_file && (dump_flags & TDF_DETAILS))
9833 fprintf (dump_file, "Folded into: ");
9834 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
9835 fprintf (dump_file, "\n");
9842 /* Simplify a switch statement using the value range of the switch
9843 argument. */
9845 static bool
9846 simplify_switch_using_ranges (gswitch *stmt)
9848 tree op = gimple_switch_index (stmt);
9849 value_range *vr = NULL;
9850 bool take_default;
9851 edge e;
9852 edge_iterator ei;
9853 size_t i = 0, j = 0, n, n2;
9854 tree vec2;
9855 switch_update su;
9856 size_t k = 1, l = 0;
9858 if (TREE_CODE (op) == SSA_NAME)
9860 vr = get_value_range (op);
9862 /* We can only handle integer ranges. */
9863 if ((vr->type != VR_RANGE
9864 && vr->type != VR_ANTI_RANGE)
9865 || symbolic_range_p (vr))
9866 return false;
9868 /* Find case label for min/max of the value range. */
9869 take_default = !find_case_label_ranges (stmt, vr, &i, &j, &k, &l);
9871 else if (TREE_CODE (op) == INTEGER_CST)
9873 take_default = !find_case_label_index (stmt, 1, op, &i);
9874 if (take_default)
9876 i = 1;
9877 j = 0;
9879 else
9881 j = i;
9884 else
9885 return false;
9887 n = gimple_switch_num_labels (stmt);
9889 /* We can truncate the case label ranges that partially overlap with OP's
9890 value range. */
9891 size_t min_idx = 1, max_idx = 0;
9892 if (vr != NULL)
9893 find_case_label_range (stmt, vr->min, vr->max, &min_idx, &max_idx);
9894 if (min_idx <= max_idx)
9896 tree min_label = gimple_switch_label (stmt, min_idx);
9897 tree max_label = gimple_switch_label (stmt, max_idx);
9899 /* Avoid changing the type of the case labels when truncating. */
9900 tree case_label_type = TREE_TYPE (CASE_LOW (min_label));
9901 tree vr_min = fold_convert (case_label_type, vr->min);
9902 tree vr_max = fold_convert (case_label_type, vr->max);
9904 if (vr->type == VR_RANGE)
9906 /* If OP's value range is [2,8] and the low label range is
9907 0 ... 3, truncate the label's range to 2 .. 3. */
9908 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
9909 && CASE_HIGH (min_label) != NULL_TREE
9910 && tree_int_cst_compare (CASE_HIGH (min_label), vr_min) >= 0)
9911 CASE_LOW (min_label) = vr_min;
9913 /* If OP's value range is [2,8] and the high label range is
9914 7 ... 10, truncate the label's range to 7 .. 8. */
9915 if (tree_int_cst_compare (CASE_LOW (max_label), vr_max) <= 0
9916 && CASE_HIGH (max_label) != NULL_TREE
9917 && tree_int_cst_compare (CASE_HIGH (max_label), vr_max) > 0)
9918 CASE_HIGH (max_label) = vr_max;
9920 else if (vr->type == VR_ANTI_RANGE)
9922 tree one_cst = build_one_cst (case_label_type);
9924 if (min_label == max_label)
9926 /* If OP's value range is ~[7,8] and the label's range is
9927 7 ... 10, truncate the label's range to 9 ... 10. */
9928 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) == 0
9929 && CASE_HIGH (min_label) != NULL_TREE
9930 && tree_int_cst_compare (CASE_HIGH (min_label), vr_max) > 0)
9931 CASE_LOW (min_label)
9932 = int_const_binop (PLUS_EXPR, vr_max, one_cst);
9934 /* If OP's value range is ~[7,8] and the label's range is
9935 5 ... 8, truncate the label's range to 5 ... 6. */
9936 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
9937 && CASE_HIGH (min_label) != NULL_TREE
9938 && tree_int_cst_compare (CASE_HIGH (min_label), vr_max) == 0)
9939 CASE_HIGH (min_label)
9940 = int_const_binop (MINUS_EXPR, vr_min, one_cst);
9942 else
9944 /* If OP's value range is ~[2,8] and the low label range is
9945 0 ... 3, truncate the label's range to 0 ... 1. */
9946 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
9947 && CASE_HIGH (min_label) != NULL_TREE
9948 && tree_int_cst_compare (CASE_HIGH (min_label), vr_min) >= 0)
9949 CASE_HIGH (min_label)
9950 = int_const_binop (MINUS_EXPR, vr_min, one_cst);
9952 /* If OP's value range is ~[2,8] and the high label range is
9953 7 ... 10, truncate the label's range to 9 ... 10. */
9954 if (tree_int_cst_compare (CASE_LOW (max_label), vr_max) <= 0
9955 && CASE_HIGH (max_label) != NULL_TREE
9956 && tree_int_cst_compare (CASE_HIGH (max_label), vr_max) > 0)
9957 CASE_LOW (max_label)
9958 = int_const_binop (PLUS_EXPR, vr_max, one_cst);
9962 /* Canonicalize singleton case ranges. */
9963 if (tree_int_cst_equal (CASE_LOW (min_label), CASE_HIGH (min_label)))
9964 CASE_HIGH (min_label) = NULL_TREE;
9965 if (tree_int_cst_equal (CASE_LOW (max_label), CASE_HIGH (max_label)))
9966 CASE_HIGH (max_label) = NULL_TREE;
9969 /* We can also eliminate case labels that lie completely outside OP's value
9970 range. */
9972 /* Bail out if this is just all edges taken. */
9973 if (i == 1
9974 && j == n - 1
9975 && take_default)
9976 return false;
9978 /* Build a new vector of taken case labels. */
9979 vec2 = make_tree_vec (j - i + 1 + l - k + 1 + (int)take_default);
9980 n2 = 0;
9982 /* Add the default edge, if necessary. */
9983 if (take_default)
9984 TREE_VEC_ELT (vec2, n2++) = gimple_switch_default_label (stmt);
9986 for (; i <= j; ++i, ++n2)
9987 TREE_VEC_ELT (vec2, n2) = gimple_switch_label (stmt, i);
9989 for (; k <= l; ++k, ++n2)
9990 TREE_VEC_ELT (vec2, n2) = gimple_switch_label (stmt, k);
9992 /* Mark needed edges. */
9993 for (i = 0; i < n2; ++i)
9995 e = find_edge (gimple_bb (stmt),
9996 label_to_block (CASE_LABEL (TREE_VEC_ELT (vec2, i))));
9997 e->aux = (void *)-1;
10000 /* Queue not needed edges for later removal. */
10001 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
10003 if (e->aux == (void *)-1)
10005 e->aux = NULL;
10006 continue;
10009 if (dump_file && (dump_flags & TDF_DETAILS))
10011 fprintf (dump_file, "removing unreachable case label\n");
10013 to_remove_edges.safe_push (e);
10014 e->flags &= ~EDGE_EXECUTABLE;
10017 /* And queue an update for the stmt. */
10018 su.stmt = stmt;
10019 su.vec = vec2;
10020 to_update_switch_stmts.safe_push (su);
10021 return false;
10024 /* Simplify an integral conversion from an SSA name in STMT. */
10026 static bool
10027 simplify_conversion_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
10029 tree innerop, middleop, finaltype;
10030 gimple *def_stmt;
10031 signop inner_sgn, middle_sgn, final_sgn;
10032 unsigned inner_prec, middle_prec, final_prec;
10033 widest_int innermin, innermed, innermax, middlemin, middlemed, middlemax;
10035 finaltype = TREE_TYPE (gimple_assign_lhs (stmt));
10036 if (!INTEGRAL_TYPE_P (finaltype))
10037 return false;
10038 middleop = gimple_assign_rhs1 (stmt);
10039 def_stmt = SSA_NAME_DEF_STMT (middleop);
10040 if (!is_gimple_assign (def_stmt)
10041 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)))
10042 return false;
10043 innerop = gimple_assign_rhs1 (def_stmt);
10044 if (TREE_CODE (innerop) != SSA_NAME
10045 || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (innerop))
10046 return false;
10048 /* Get the value-range of the inner operand. Use get_range_info in
10049 case innerop was created during substitute-and-fold. */
10050 wide_int imin, imax;
10051 if (!INTEGRAL_TYPE_P (TREE_TYPE (innerop))
10052 || get_range_info (innerop, &imin, &imax) != VR_RANGE)
10053 return false;
10054 innermin = widest_int::from (imin, TYPE_SIGN (TREE_TYPE (innerop)));
10055 innermax = widest_int::from (imax, TYPE_SIGN (TREE_TYPE (innerop)));
10057 /* Simulate the conversion chain to check if the result is equal if
10058 the middle conversion is removed. */
10059 inner_prec = TYPE_PRECISION (TREE_TYPE (innerop));
10060 middle_prec = TYPE_PRECISION (TREE_TYPE (middleop));
10061 final_prec = TYPE_PRECISION (finaltype);
10063 /* If the first conversion is not injective, the second must not
10064 be widening. */
10065 if (wi::gtu_p (innermax - innermin,
10066 wi::mask <widest_int> (middle_prec, false))
10067 && middle_prec < final_prec)
10068 return false;
10069 /* We also want a medium value so that we can track the effect that
10070 narrowing conversions with sign change have. */
10071 inner_sgn = TYPE_SIGN (TREE_TYPE (innerop));
10072 if (inner_sgn == UNSIGNED)
10073 innermed = wi::shifted_mask <widest_int> (1, inner_prec - 1, false);
10074 else
10075 innermed = 0;
10076 if (wi::cmp (innermin, innermed, inner_sgn) >= 0
10077 || wi::cmp (innermed, innermax, inner_sgn) >= 0)
10078 innermed = innermin;
10080 middle_sgn = TYPE_SIGN (TREE_TYPE (middleop));
10081 middlemin = wi::ext (innermin, middle_prec, middle_sgn);
10082 middlemed = wi::ext (innermed, middle_prec, middle_sgn);
10083 middlemax = wi::ext (innermax, middle_prec, middle_sgn);
10085 /* Require that the final conversion applied to both the original
10086 and the intermediate range produces the same result. */
10087 final_sgn = TYPE_SIGN (finaltype);
10088 if (wi::ext (middlemin, final_prec, final_sgn)
10089 != wi::ext (innermin, final_prec, final_sgn)
10090 || wi::ext (middlemed, final_prec, final_sgn)
10091 != wi::ext (innermed, final_prec, final_sgn)
10092 || wi::ext (middlemax, final_prec, final_sgn)
10093 != wi::ext (innermax, final_prec, final_sgn))
10094 return false;
10096 gimple_assign_set_rhs1 (stmt, innerop);
10097 fold_stmt (gsi, follow_single_use_edges);
10098 return true;
10101 /* Simplify a conversion from integral SSA name to float in STMT. */
10103 static bool
10104 simplify_float_conversion_using_ranges (gimple_stmt_iterator *gsi,
10105 gimple *stmt)
10107 tree rhs1 = gimple_assign_rhs1 (stmt);
10108 value_range *vr = get_value_range (rhs1);
10109 scalar_float_mode fltmode
10110 = SCALAR_FLOAT_TYPE_MODE (TREE_TYPE (gimple_assign_lhs (stmt)));
10111 scalar_int_mode mode;
10112 tree tem;
10113 gassign *conv;
10115 /* We can only handle constant ranges. */
10116 if (vr->type != VR_RANGE
10117 || TREE_CODE (vr->min) != INTEGER_CST
10118 || TREE_CODE (vr->max) != INTEGER_CST)
10119 return false;
10121 /* First check if we can use a signed type in place of an unsigned. */
10122 scalar_int_mode rhs_mode = SCALAR_INT_TYPE_MODE (TREE_TYPE (rhs1));
10123 if (TYPE_UNSIGNED (TREE_TYPE (rhs1))
10124 && can_float_p (fltmode, rhs_mode, 0) != CODE_FOR_nothing
10125 && range_fits_type_p (vr, TYPE_PRECISION (TREE_TYPE (rhs1)), SIGNED))
10126 mode = rhs_mode;
10127 /* If we can do the conversion in the current input mode do nothing. */
10128 else if (can_float_p (fltmode, rhs_mode,
10129 TYPE_UNSIGNED (TREE_TYPE (rhs1))) != CODE_FOR_nothing)
10130 return false;
10131 /* Otherwise search for a mode we can use, starting from the narrowest
10132 integer mode available. */
10133 else
10135 mode = NARROWEST_INT_MODE;
10136 for (;;)
10138 /* If we cannot do a signed conversion to float from mode
10139 or if the value-range does not fit in the signed type
10140 try with a wider mode. */
10141 if (can_float_p (fltmode, mode, 0) != CODE_FOR_nothing
10142 && range_fits_type_p (vr, GET_MODE_PRECISION (mode), SIGNED))
10143 break;
10145 /* But do not widen the input. Instead leave that to the
10146 optabs expansion code. */
10147 if (!GET_MODE_WIDER_MODE (mode).exists (&mode)
10148 || GET_MODE_PRECISION (mode) > TYPE_PRECISION (TREE_TYPE (rhs1)))
10149 return false;
10153 /* It works, insert a truncation or sign-change before the
10154 float conversion. */
10155 tem = make_ssa_name (build_nonstandard_integer_type
10156 (GET_MODE_PRECISION (mode), 0));
10157 conv = gimple_build_assign (tem, NOP_EXPR, rhs1);
10158 gsi_insert_before (gsi, conv, GSI_SAME_STMT);
10159 gimple_assign_set_rhs1 (stmt, tem);
10160 fold_stmt (gsi, follow_single_use_edges);
10162 return true;
10165 /* Simplify an internal fn call using ranges if possible. */
10167 static bool
10168 simplify_internal_call_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
10170 enum tree_code subcode;
10171 bool is_ubsan = false;
10172 bool ovf = false;
10173 switch (gimple_call_internal_fn (stmt))
10175 case IFN_UBSAN_CHECK_ADD:
10176 subcode = PLUS_EXPR;
10177 is_ubsan = true;
10178 break;
10179 case IFN_UBSAN_CHECK_SUB:
10180 subcode = MINUS_EXPR;
10181 is_ubsan = true;
10182 break;
10183 case IFN_UBSAN_CHECK_MUL:
10184 subcode = MULT_EXPR;
10185 is_ubsan = true;
10186 break;
10187 case IFN_ADD_OVERFLOW:
10188 subcode = PLUS_EXPR;
10189 break;
10190 case IFN_SUB_OVERFLOW:
10191 subcode = MINUS_EXPR;
10192 break;
10193 case IFN_MUL_OVERFLOW:
10194 subcode = MULT_EXPR;
10195 break;
10196 default:
10197 return false;
10200 tree op0 = gimple_call_arg (stmt, 0);
10201 tree op1 = gimple_call_arg (stmt, 1);
10202 tree type;
10203 if (is_ubsan)
10205 type = TREE_TYPE (op0);
10206 if (VECTOR_TYPE_P (type))
10207 return false;
10209 else if (gimple_call_lhs (stmt) == NULL_TREE)
10210 return false;
10211 else
10212 type = TREE_TYPE (TREE_TYPE (gimple_call_lhs (stmt)));
10213 if (!check_for_binary_op_overflow (subcode, type, op0, op1, &ovf)
10214 || (is_ubsan && ovf))
10215 return false;
10217 gimple *g;
10218 location_t loc = gimple_location (stmt);
10219 if (is_ubsan)
10220 g = gimple_build_assign (gimple_call_lhs (stmt), subcode, op0, op1);
10221 else
10223 int prec = TYPE_PRECISION (type);
10224 tree utype = type;
10225 if (ovf
10226 || !useless_type_conversion_p (type, TREE_TYPE (op0))
10227 || !useless_type_conversion_p (type, TREE_TYPE (op1)))
10228 utype = build_nonstandard_integer_type (prec, 1);
10229 if (TREE_CODE (op0) == INTEGER_CST)
10230 op0 = fold_convert (utype, op0);
10231 else if (!useless_type_conversion_p (utype, TREE_TYPE (op0)))
10233 g = gimple_build_assign (make_ssa_name (utype), NOP_EXPR, op0);
10234 gimple_set_location (g, loc);
10235 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10236 op0 = gimple_assign_lhs (g);
10238 if (TREE_CODE (op1) == INTEGER_CST)
10239 op1 = fold_convert (utype, op1);
10240 else if (!useless_type_conversion_p (utype, TREE_TYPE (op1)))
10242 g = gimple_build_assign (make_ssa_name (utype), NOP_EXPR, op1);
10243 gimple_set_location (g, loc);
10244 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10245 op1 = gimple_assign_lhs (g);
10247 g = gimple_build_assign (make_ssa_name (utype), subcode, op0, op1);
10248 gimple_set_location (g, loc);
10249 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10250 if (utype != type)
10252 g = gimple_build_assign (make_ssa_name (type), NOP_EXPR,
10253 gimple_assign_lhs (g));
10254 gimple_set_location (g, loc);
10255 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10257 g = gimple_build_assign (gimple_call_lhs (stmt), COMPLEX_EXPR,
10258 gimple_assign_lhs (g),
10259 build_int_cst (type, ovf));
10261 gimple_set_location (g, loc);
10262 gsi_replace (gsi, g, false);
10263 return true;
10266 /* Return true if VAR is a two-valued variable. Set a and b with the
10267 two-values when it is true. Return false otherwise. */
10269 static bool
10270 two_valued_val_range_p (tree var, tree *a, tree *b)
10272 value_range *vr = get_value_range (var);
10273 if ((vr->type != VR_RANGE
10274 && vr->type != VR_ANTI_RANGE)
10275 || TREE_CODE (vr->min) != INTEGER_CST
10276 || TREE_CODE (vr->max) != INTEGER_CST)
10277 return false;
10279 if (vr->type == VR_RANGE
10280 && wi::to_wide (vr->max) - wi::to_wide (vr->min) == 1)
10282 *a = vr->min;
10283 *b = vr->max;
10284 return true;
10287 /* ~[TYPE_MIN + 1, TYPE_MAX - 1] */
10288 if (vr->type == VR_ANTI_RANGE
10289 && (wi::to_wide (vr->min)
10290 - wi::to_wide (vrp_val_min (TREE_TYPE (var)))) == 1
10291 && (wi::to_wide (vrp_val_max (TREE_TYPE (var)))
10292 - wi::to_wide (vr->max)) == 1)
10294 *a = vrp_val_min (TREE_TYPE (var));
10295 *b = vrp_val_max (TREE_TYPE (var));
10296 return true;
10299 return false;
10302 /* Simplify STMT using ranges if possible. */
10304 static bool
10305 simplify_stmt_using_ranges (gimple_stmt_iterator *gsi)
10307 gimple *stmt = gsi_stmt (*gsi);
10308 if (is_gimple_assign (stmt))
10310 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
10311 tree rhs1 = gimple_assign_rhs1 (stmt);
10312 tree rhs2 = gimple_assign_rhs2 (stmt);
10313 tree lhs = gimple_assign_lhs (stmt);
10314 tree val1 = NULL_TREE, val2 = NULL_TREE;
10315 use_operand_p use_p;
10316 gimple *use_stmt;
10318 /* Convert:
10319 LHS = CST BINOP VAR
10320 Where VAR is two-valued and LHS is used in GIMPLE_COND only
10322 LHS = VAR == VAL1 ? (CST BINOP VAL1) : (CST BINOP VAL2)
10324 Also handles:
10325 LHS = VAR BINOP CST
10326 Where VAR is two-valued and LHS is used in GIMPLE_COND only
10328 LHS = VAR == VAL1 ? (VAL1 BINOP CST) : (VAL2 BINOP CST) */
10330 if (TREE_CODE_CLASS (rhs_code) == tcc_binary
10331 && INTEGRAL_TYPE_P (TREE_TYPE (lhs))
10332 && ((TREE_CODE (rhs1) == INTEGER_CST
10333 && TREE_CODE (rhs2) == SSA_NAME)
10334 || (TREE_CODE (rhs2) == INTEGER_CST
10335 && TREE_CODE (rhs1) == SSA_NAME))
10336 && single_imm_use (lhs, &use_p, &use_stmt)
10337 && gimple_code (use_stmt) == GIMPLE_COND)
10340 tree new_rhs1 = NULL_TREE;
10341 tree new_rhs2 = NULL_TREE;
10342 tree cmp_var = NULL_TREE;
10344 if (TREE_CODE (rhs2) == SSA_NAME
10345 && two_valued_val_range_p (rhs2, &val1, &val2))
10347 /* Optimize RHS1 OP [VAL1, VAL2]. */
10348 new_rhs1 = int_const_binop (rhs_code, rhs1, val1);
10349 new_rhs2 = int_const_binop (rhs_code, rhs1, val2);
10350 cmp_var = rhs2;
10352 else if (TREE_CODE (rhs1) == SSA_NAME
10353 && two_valued_val_range_p (rhs1, &val1, &val2))
10355 /* Optimize [VAL1, VAL2] OP RHS2. */
10356 new_rhs1 = int_const_binop (rhs_code, val1, rhs2);
10357 new_rhs2 = int_const_binop (rhs_code, val2, rhs2);
10358 cmp_var = rhs1;
10361 /* If we could not find two-vals or the optimzation is invalid as
10362 in divide by zero, new_rhs1 / new_rhs will be NULL_TREE. */
10363 if (new_rhs1 && new_rhs2)
10365 tree cond = build2 (EQ_EXPR, boolean_type_node, cmp_var, val1);
10366 gimple_assign_set_rhs_with_ops (gsi,
10367 COND_EXPR, cond,
10368 new_rhs1,
10369 new_rhs2);
10370 update_stmt (gsi_stmt (*gsi));
10371 fold_stmt (gsi, follow_single_use_edges);
10372 return true;
10376 switch (rhs_code)
10378 case EQ_EXPR:
10379 case NE_EXPR:
10380 /* Transform EQ_EXPR, NE_EXPR into BIT_XOR_EXPR or identity
10381 if the RHS is zero or one, and the LHS are known to be boolean
10382 values. */
10383 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10384 return simplify_truth_ops_using_ranges (gsi, stmt);
10385 break;
10387 /* Transform TRUNC_DIV_EXPR and TRUNC_MOD_EXPR into RSHIFT_EXPR
10388 and BIT_AND_EXPR respectively if the first operand is greater
10389 than zero and the second operand is an exact power of two.
10390 Also optimize TRUNC_MOD_EXPR away if the second operand is
10391 constant and the first operand already has the right value
10392 range. */
10393 case TRUNC_DIV_EXPR:
10394 case TRUNC_MOD_EXPR:
10395 if ((TREE_CODE (rhs1) == SSA_NAME
10396 || TREE_CODE (rhs1) == INTEGER_CST)
10397 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10398 return simplify_div_or_mod_using_ranges (gsi, stmt);
10399 break;
10401 /* Transform ABS (X) into X or -X as appropriate. */
10402 case ABS_EXPR:
10403 if (TREE_CODE (rhs1) == SSA_NAME
10404 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10405 return simplify_abs_using_ranges (gsi, stmt);
10406 break;
10408 case BIT_AND_EXPR:
10409 case BIT_IOR_EXPR:
10410 /* Optimize away BIT_AND_EXPR and BIT_IOR_EXPR
10411 if all the bits being cleared are already cleared or
10412 all the bits being set are already set. */
10413 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10414 return simplify_bit_ops_using_ranges (gsi, stmt);
10415 break;
10417 CASE_CONVERT:
10418 if (TREE_CODE (rhs1) == SSA_NAME
10419 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10420 return simplify_conversion_using_ranges (gsi, stmt);
10421 break;
10423 case FLOAT_EXPR:
10424 if (TREE_CODE (rhs1) == SSA_NAME
10425 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10426 return simplify_float_conversion_using_ranges (gsi, stmt);
10427 break;
10429 case MIN_EXPR:
10430 case MAX_EXPR:
10431 return simplify_min_or_max_using_ranges (gsi, stmt);
10433 default:
10434 break;
10437 else if (gimple_code (stmt) == GIMPLE_COND)
10438 return simplify_cond_using_ranges_1 (as_a <gcond *> (stmt));
10439 else if (gimple_code (stmt) == GIMPLE_SWITCH)
10440 return simplify_switch_using_ranges (as_a <gswitch *> (stmt));
10441 else if (is_gimple_call (stmt)
10442 && gimple_call_internal_p (stmt))
10443 return simplify_internal_call_using_ranges (gsi, stmt);
10445 return false;
10448 /* If the statement pointed by SI has a predicate whose value can be
10449 computed using the value range information computed by VRP, compute
10450 its value and return true. Otherwise, return false. */
10452 static bool
10453 fold_predicate_in (gimple_stmt_iterator *si)
10455 bool assignment_p = false;
10456 tree val;
10457 gimple *stmt = gsi_stmt (*si);
10459 if (is_gimple_assign (stmt)
10460 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
10462 assignment_p = true;
10463 val = vrp_evaluate_conditional (gimple_assign_rhs_code (stmt),
10464 gimple_assign_rhs1 (stmt),
10465 gimple_assign_rhs2 (stmt),
10466 stmt);
10468 else if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
10469 val = vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
10470 gimple_cond_lhs (cond_stmt),
10471 gimple_cond_rhs (cond_stmt),
10472 stmt);
10473 else
10474 return false;
10476 if (val)
10478 if (assignment_p)
10479 val = fold_convert (gimple_expr_type (stmt), val);
10481 if (dump_file)
10483 fprintf (dump_file, "Folding predicate ");
10484 print_gimple_expr (dump_file, stmt, 0);
10485 fprintf (dump_file, " to ");
10486 print_generic_expr (dump_file, val);
10487 fprintf (dump_file, "\n");
10490 if (is_gimple_assign (stmt))
10491 gimple_assign_set_rhs_from_tree (si, val);
10492 else
10494 gcc_assert (gimple_code (stmt) == GIMPLE_COND);
10495 gcond *cond_stmt = as_a <gcond *> (stmt);
10496 if (integer_zerop (val))
10497 gimple_cond_make_false (cond_stmt);
10498 else if (integer_onep (val))
10499 gimple_cond_make_true (cond_stmt);
10500 else
10501 gcc_unreachable ();
10504 return true;
10507 return false;
10510 class vrp_folder : public substitute_and_fold_engine
10512 public:
10513 tree get_value (tree) FINAL OVERRIDE;
10514 bool fold_stmt (gimple_stmt_iterator *) FINAL OVERRIDE;
10517 /* Callback for substitute_and_fold folding the stmt at *SI. */
10519 bool
10520 vrp_folder::fold_stmt (gimple_stmt_iterator *si)
10522 if (fold_predicate_in (si))
10523 return true;
10525 return simplify_stmt_using_ranges (si);
10528 /* If OP has a value range with a single constant value return that,
10529 otherwise return NULL_TREE. This returns OP itself if OP is a
10530 constant.
10532 Implemented as a pure wrapper right now, but this will change. */
10534 tree
10535 vrp_folder::get_value (tree op)
10537 return op_with_constant_singleton_value_range (op);
10540 /* Return the LHS of any ASSERT_EXPR where OP appears as the first
10541 argument to the ASSERT_EXPR and in which the ASSERT_EXPR dominates
10542 BB. If no such ASSERT_EXPR is found, return OP. */
10544 static tree
10545 lhs_of_dominating_assert (tree op, basic_block bb, gimple *stmt)
10547 imm_use_iterator imm_iter;
10548 gimple *use_stmt;
10549 use_operand_p use_p;
10551 if (TREE_CODE (op) == SSA_NAME)
10553 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, op)
10555 use_stmt = USE_STMT (use_p);
10556 if (use_stmt != stmt
10557 && gimple_assign_single_p (use_stmt)
10558 && TREE_CODE (gimple_assign_rhs1 (use_stmt)) == ASSERT_EXPR
10559 && TREE_OPERAND (gimple_assign_rhs1 (use_stmt), 0) == op
10560 && dominated_by_p (CDI_DOMINATORS, bb, gimple_bb (use_stmt)))
10561 return gimple_assign_lhs (use_stmt);
10564 return op;
10567 /* A trivial wrapper so that we can present the generic jump threading
10568 code with a simple API for simplifying statements. STMT is the
10569 statement we want to simplify, WITHIN_STMT provides the location
10570 for any overflow warnings. */
10572 static tree
10573 simplify_stmt_for_jump_threading (gimple *stmt, gimple *within_stmt,
10574 class avail_exprs_stack *avail_exprs_stack ATTRIBUTE_UNUSED,
10575 basic_block bb)
10577 /* First see if the conditional is in the hash table. */
10578 tree cached_lhs = avail_exprs_stack->lookup_avail_expr (stmt, false, true);
10579 if (cached_lhs && is_gimple_min_invariant (cached_lhs))
10580 return cached_lhs;
10582 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
10584 tree op0 = gimple_cond_lhs (cond_stmt);
10585 op0 = lhs_of_dominating_assert (op0, bb, stmt);
10587 tree op1 = gimple_cond_rhs (cond_stmt);
10588 op1 = lhs_of_dominating_assert (op1, bb, stmt);
10590 return vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
10591 op0, op1, within_stmt);
10594 /* We simplify a switch statement by trying to determine which case label
10595 will be taken. If we are successful then we return the corresponding
10596 CASE_LABEL_EXPR. */
10597 if (gswitch *switch_stmt = dyn_cast <gswitch *> (stmt))
10599 tree op = gimple_switch_index (switch_stmt);
10600 if (TREE_CODE (op) != SSA_NAME)
10601 return NULL_TREE;
10603 op = lhs_of_dominating_assert (op, bb, stmt);
10605 value_range *vr = get_value_range (op);
10606 if ((vr->type != VR_RANGE && vr->type != VR_ANTI_RANGE)
10607 || symbolic_range_p (vr))
10608 return NULL_TREE;
10610 if (vr->type == VR_RANGE)
10612 size_t i, j;
10613 /* Get the range of labels that contain a part of the operand's
10614 value range. */
10615 find_case_label_range (switch_stmt, vr->min, vr->max, &i, &j);
10617 /* Is there only one such label? */
10618 if (i == j)
10620 tree label = gimple_switch_label (switch_stmt, i);
10622 /* The i'th label will be taken only if the value range of the
10623 operand is entirely within the bounds of this label. */
10624 if (CASE_HIGH (label) != NULL_TREE
10625 ? (tree_int_cst_compare (CASE_LOW (label), vr->min) <= 0
10626 && tree_int_cst_compare (CASE_HIGH (label), vr->max) >= 0)
10627 : (tree_int_cst_equal (CASE_LOW (label), vr->min)
10628 && tree_int_cst_equal (vr->min, vr->max)))
10629 return label;
10632 /* If there are no such labels then the default label will be
10633 taken. */
10634 if (i > j)
10635 return gimple_switch_label (switch_stmt, 0);
10638 if (vr->type == VR_ANTI_RANGE)
10640 unsigned n = gimple_switch_num_labels (switch_stmt);
10641 tree min_label = gimple_switch_label (switch_stmt, 1);
10642 tree max_label = gimple_switch_label (switch_stmt, n - 1);
10644 /* The default label will be taken only if the anti-range of the
10645 operand is entirely outside the bounds of all the (non-default)
10646 case labels. */
10647 if (tree_int_cst_compare (vr->min, CASE_LOW (min_label)) <= 0
10648 && (CASE_HIGH (max_label) != NULL_TREE
10649 ? tree_int_cst_compare (vr->max, CASE_HIGH (max_label)) >= 0
10650 : tree_int_cst_compare (vr->max, CASE_LOW (max_label)) >= 0))
10651 return gimple_switch_label (switch_stmt, 0);
10654 return NULL_TREE;
10657 if (gassign *assign_stmt = dyn_cast <gassign *> (stmt))
10659 value_range new_vr = VR_INITIALIZER;
10660 tree lhs = gimple_assign_lhs (assign_stmt);
10662 if (TREE_CODE (lhs) == SSA_NAME
10663 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
10664 || POINTER_TYPE_P (TREE_TYPE (lhs))))
10666 extract_range_from_assignment (&new_vr, assign_stmt);
10667 if (range_int_cst_singleton_p (&new_vr))
10668 return new_vr.min;
10672 return NULL_TREE;
10675 class vrp_dom_walker : public dom_walker
10677 public:
10678 vrp_dom_walker (cdi_direction direction,
10679 class const_and_copies *const_and_copies,
10680 class avail_exprs_stack *avail_exprs_stack)
10681 : dom_walker (direction, true),
10682 m_const_and_copies (const_and_copies),
10683 m_avail_exprs_stack (avail_exprs_stack),
10684 m_dummy_cond (NULL) {}
10686 virtual edge before_dom_children (basic_block);
10687 virtual void after_dom_children (basic_block);
10689 private:
10690 class const_and_copies *m_const_and_copies;
10691 class avail_exprs_stack *m_avail_exprs_stack;
10693 gcond *m_dummy_cond;
10696 /* Called before processing dominator children of BB. We want to look
10697 at ASSERT_EXPRs and record information from them in the appropriate
10698 tables.
10700 We could look at other statements here. It's not seen as likely
10701 to significantly increase the jump threads we discover. */
10703 edge
10704 vrp_dom_walker::before_dom_children (basic_block bb)
10706 gimple_stmt_iterator gsi;
10708 m_avail_exprs_stack->push_marker ();
10709 m_const_and_copies->push_marker ();
10710 for (gsi = gsi_start_nondebug_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
10712 gimple *stmt = gsi_stmt (gsi);
10713 if (gimple_assign_single_p (stmt)
10714 && TREE_CODE (gimple_assign_rhs1 (stmt)) == ASSERT_EXPR)
10716 tree rhs1 = gimple_assign_rhs1 (stmt);
10717 tree cond = TREE_OPERAND (rhs1, 1);
10718 tree inverted = invert_truthvalue (cond);
10719 vec<cond_equivalence> p;
10720 p.create (3);
10721 record_conditions (&p, cond, inverted);
10722 for (unsigned int i = 0; i < p.length (); i++)
10723 m_avail_exprs_stack->record_cond (&p[i]);
10725 tree lhs = gimple_assign_lhs (stmt);
10726 m_const_and_copies->record_const_or_copy (lhs,
10727 TREE_OPERAND (rhs1, 0));
10728 p.release ();
10729 continue;
10731 break;
10733 return NULL;
10736 /* Called after processing dominator children of BB. This is where we
10737 actually call into the threader. */
10738 void
10739 vrp_dom_walker::after_dom_children (basic_block bb)
10741 if (!m_dummy_cond)
10742 m_dummy_cond = gimple_build_cond (NE_EXPR,
10743 integer_zero_node, integer_zero_node,
10744 NULL, NULL);
10746 thread_outgoing_edges (bb, m_dummy_cond, m_const_and_copies,
10747 m_avail_exprs_stack,
10748 simplify_stmt_for_jump_threading);
10750 m_avail_exprs_stack->pop_to_marker ();
10751 m_const_and_copies->pop_to_marker ();
10754 /* Blocks which have more than one predecessor and more than
10755 one successor present jump threading opportunities, i.e.,
10756 when the block is reached from a specific predecessor, we
10757 may be able to determine which of the outgoing edges will
10758 be traversed. When this optimization applies, we are able
10759 to avoid conditionals at runtime and we may expose secondary
10760 optimization opportunities.
10762 This routine is effectively a driver for the generic jump
10763 threading code. It basically just presents the generic code
10764 with edges that may be suitable for jump threading.
10766 Unlike DOM, we do not iterate VRP if jump threading was successful.
10767 While iterating may expose new opportunities for VRP, it is expected
10768 those opportunities would be very limited and the compile time cost
10769 to expose those opportunities would be significant.
10771 As jump threading opportunities are discovered, they are registered
10772 for later realization. */
10774 static void
10775 identify_jump_threads (void)
10777 int i;
10778 edge e;
10780 /* Ugh. When substituting values earlier in this pass we can
10781 wipe the dominance information. So rebuild the dominator
10782 information as we need it within the jump threading code. */
10783 calculate_dominance_info (CDI_DOMINATORS);
10785 /* We do not allow VRP information to be used for jump threading
10786 across a back edge in the CFG. Otherwise it becomes too
10787 difficult to avoid eliminating loop exit tests. Of course
10788 EDGE_DFS_BACK is not accurate at this time so we have to
10789 recompute it. */
10790 mark_dfs_back_edges ();
10792 /* Do not thread across edges we are about to remove. Just marking
10793 them as EDGE_IGNORE will do. */
10794 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
10795 e->flags |= EDGE_IGNORE;
10797 /* Allocate our unwinder stack to unwind any temporary equivalences
10798 that might be recorded. */
10799 const_and_copies *equiv_stack = new const_and_copies ();
10801 hash_table<expr_elt_hasher> *avail_exprs
10802 = new hash_table<expr_elt_hasher> (1024);
10803 avail_exprs_stack *avail_exprs_stack
10804 = new class avail_exprs_stack (avail_exprs);
10806 vrp_dom_walker walker (CDI_DOMINATORS, equiv_stack, avail_exprs_stack);
10807 walker.walk (cfun->cfg->x_entry_block_ptr);
10809 /* Clear EDGE_IGNORE. */
10810 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
10811 e->flags &= ~EDGE_IGNORE;
10813 /* We do not actually update the CFG or SSA graphs at this point as
10814 ASSERT_EXPRs are still in the IL and cfg cleanup code does not yet
10815 handle ASSERT_EXPRs gracefully. */
10816 delete equiv_stack;
10817 delete avail_exprs;
10818 delete avail_exprs_stack;
10821 /* Free VRP lattice. */
10823 static void
10824 vrp_free_lattice ()
10826 /* Free allocated memory. */
10827 free (vr_value);
10828 free (vr_phi_edge_counts);
10829 bitmap_obstack_release (&vrp_equiv_obstack);
10830 vrp_value_range_pool.release ();
10832 /* So that we can distinguish between VRP data being available
10833 and not available. */
10834 vr_value = NULL;
10835 vr_phi_edge_counts = NULL;
10838 /* Traverse all the blocks folding conditionals with known ranges. */
10840 static void
10841 vrp_finalize (bool warn_array_bounds_p)
10843 size_t i;
10845 values_propagated = true;
10847 if (dump_file)
10849 fprintf (dump_file, "\nValue ranges after VRP:\n\n");
10850 dump_all_value_ranges (dump_file);
10851 fprintf (dump_file, "\n");
10854 /* Set value range to non pointer SSA_NAMEs. */
10855 for (i = 0; i < num_vr_values; i++)
10856 if (vr_value[i])
10858 tree name = ssa_name (i);
10860 if (!name
10861 || (vr_value[i]->type == VR_VARYING)
10862 || (vr_value[i]->type == VR_UNDEFINED)
10863 || (TREE_CODE (vr_value[i]->min) != INTEGER_CST)
10864 || (TREE_CODE (vr_value[i]->max) != INTEGER_CST))
10865 continue;
10867 if (POINTER_TYPE_P (TREE_TYPE (name))
10868 && ((vr_value[i]->type == VR_RANGE
10869 && range_includes_zero_p (vr_value[i]->min,
10870 vr_value[i]->max) == 0)
10871 || (vr_value[i]->type == VR_ANTI_RANGE
10872 && range_includes_zero_p (vr_value[i]->min,
10873 vr_value[i]->max) == 1)))
10874 set_ptr_nonnull (name);
10875 else if (!POINTER_TYPE_P (TREE_TYPE (name)))
10876 set_range_info (name, vr_value[i]->type,
10877 wi::to_wide (vr_value[i]->min),
10878 wi::to_wide (vr_value[i]->max));
10881 class vrp_folder vrp_folder;
10882 vrp_folder.substitute_and_fold ();
10884 if (warn_array_bounds && warn_array_bounds_p)
10885 check_all_array_refs ();
10888 /* evrp_dom_walker visits the basic blocks in the dominance order and set
10889 the Value Ranges (VR) for SSA_NAMEs in the scope. Use this VR to
10890 discover more VRs. */
10892 class evrp_dom_walker : public dom_walker
10894 public:
10895 evrp_dom_walker ()
10896 : dom_walker (CDI_DOMINATORS), stack (10)
10898 need_eh_cleanup = BITMAP_ALLOC (NULL);
10900 ~evrp_dom_walker ()
10902 BITMAP_FREE (need_eh_cleanup);
10904 virtual edge before_dom_children (basic_block);
10905 virtual void after_dom_children (basic_block);
10906 void push_value_range (tree var, value_range *vr);
10907 value_range *pop_value_range (tree var);
10908 value_range *try_find_new_range (tree, tree op, tree_code code, tree limit);
10910 /* Cond_stack holds the old VR. */
10911 auto_vec<std::pair <tree, value_range*> > stack;
10912 bitmap need_eh_cleanup;
10913 auto_vec<gimple *> stmts_to_fixup;
10914 auto_vec<gimple *> stmts_to_remove;
10917 /* Find new range for NAME such that (OP CODE LIMIT) is true. */
10919 value_range *
10920 evrp_dom_walker::try_find_new_range (tree name,
10921 tree op, tree_code code, tree limit)
10923 value_range vr = VR_INITIALIZER;
10924 value_range *old_vr = get_value_range (name);
10926 /* Discover VR when condition is true. */
10927 extract_range_for_var_from_comparison_expr (name, code, op,
10928 limit, &vr);
10929 /* If we found any usable VR, set the VR to ssa_name and create a
10930 PUSH old value in the stack with the old VR. */
10931 if (vr.type == VR_RANGE || vr.type == VR_ANTI_RANGE)
10933 if (old_vr->type == vr.type
10934 && vrp_operand_equal_p (old_vr->min, vr.min)
10935 && vrp_operand_equal_p (old_vr->max, vr.max))
10936 return NULL;
10937 value_range *new_vr = vrp_value_range_pool.allocate ();
10938 *new_vr = vr;
10939 return new_vr;
10941 return NULL;
10944 /* See if there is any new scope is entered with new VR and set that VR to
10945 ssa_name before visiting the statements in the scope. */
10947 edge
10948 evrp_dom_walker::before_dom_children (basic_block bb)
10950 if (dump_file && (dump_flags & TDF_DETAILS))
10951 fprintf (dump_file, "Visiting BB%d\n", bb->index);
10953 stack.safe_push (std::make_pair (NULL_TREE, (value_range *)NULL));
10955 edge pred_e = single_pred_edge_ignoring_loop_edges (bb, false);
10956 if (pred_e)
10958 gimple *stmt = last_stmt (pred_e->src);
10959 tree op0 = NULL_TREE;
10961 if (stmt
10962 && gimple_code (stmt) == GIMPLE_COND
10963 && (op0 = gimple_cond_lhs (stmt))
10964 && TREE_CODE (op0) == SSA_NAME
10965 && (INTEGRAL_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)))
10966 || POINTER_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)))))
10968 if (dump_file && (dump_flags & TDF_DETAILS))
10970 fprintf (dump_file, "Visiting controlling predicate ");
10971 print_gimple_stmt (dump_file, stmt, 0);
10973 /* Entering a new scope. Try to see if we can find a VR
10974 here. */
10975 tree op1 = gimple_cond_rhs (stmt);
10976 if (TREE_OVERFLOW_P (op1))
10977 op1 = drop_tree_overflow (op1);
10978 tree_code code = gimple_cond_code (stmt);
10980 auto_vec<assert_info, 8> asserts;
10981 register_edge_assert_for (op0, pred_e, code, op0, op1, asserts);
10982 if (TREE_CODE (op1) == SSA_NAME)
10983 register_edge_assert_for (op1, pred_e, code, op0, op1, asserts);
10985 auto_vec<std::pair<tree, value_range *>, 8> vrs;
10986 for (unsigned i = 0; i < asserts.length (); ++i)
10988 value_range *vr = try_find_new_range (asserts[i].name,
10989 asserts[i].expr,
10990 asserts[i].comp_code,
10991 asserts[i].val);
10992 if (vr)
10993 vrs.safe_push (std::make_pair (asserts[i].name, vr));
10995 /* Push updated ranges only after finding all of them to avoid
10996 ordering issues that can lead to worse ranges. */
10997 for (unsigned i = 0; i < vrs.length (); ++i)
10998 push_value_range (vrs[i].first, vrs[i].second);
11002 /* Visit PHI stmts and discover any new VRs possible. */
11003 bool has_unvisited_preds = false;
11004 edge_iterator ei;
11005 edge e;
11006 FOR_EACH_EDGE (e, ei, bb->preds)
11007 if (e->flags & EDGE_EXECUTABLE
11008 && !(e->src->flags & BB_VISITED))
11010 has_unvisited_preds = true;
11011 break;
11014 for (gphi_iterator gpi = gsi_start_phis (bb);
11015 !gsi_end_p (gpi); gsi_next (&gpi))
11017 gphi *phi = gpi.phi ();
11018 tree lhs = PHI_RESULT (phi);
11019 if (virtual_operand_p (lhs))
11020 continue;
11021 value_range vr_result = VR_INITIALIZER;
11022 bool interesting = stmt_interesting_for_vrp (phi);
11023 if (interesting && dump_file && (dump_flags & TDF_DETAILS))
11025 fprintf (dump_file, "Visiting PHI node ");
11026 print_gimple_stmt (dump_file, phi, 0);
11028 if (!has_unvisited_preds
11029 && interesting)
11030 extract_range_from_phi_node (phi, &vr_result);
11031 else
11033 set_value_range_to_varying (&vr_result);
11034 /* When we have an unvisited executable predecessor we can't
11035 use PHI arg ranges which may be still UNDEFINED but have
11036 to use VARYING for them. But we can still resort to
11037 SCEV for loop header PHIs. */
11038 struct loop *l;
11039 if (interesting
11040 && (l = loop_containing_stmt (phi))
11041 && l->header == gimple_bb (phi))
11042 adjust_range_with_scev (&vr_result, l, phi, lhs);
11044 update_value_range (lhs, &vr_result);
11046 /* Mark PHIs whose lhs we fully propagate for removal. */
11047 tree val = op_with_constant_singleton_value_range (lhs);
11048 if (val && may_propagate_copy (lhs, val))
11050 stmts_to_remove.safe_push (phi);
11051 continue;
11054 /* Set the SSA with the value range. */
11055 if (INTEGRAL_TYPE_P (TREE_TYPE (lhs)))
11057 if ((vr_result.type == VR_RANGE
11058 || vr_result.type == VR_ANTI_RANGE)
11059 && (TREE_CODE (vr_result.min) == INTEGER_CST)
11060 && (TREE_CODE (vr_result.max) == INTEGER_CST))
11061 set_range_info (lhs, vr_result.type,
11062 wi::to_wide (vr_result.min),
11063 wi::to_wide (vr_result.max));
11065 else if (POINTER_TYPE_P (TREE_TYPE (lhs))
11066 && ((vr_result.type == VR_RANGE
11067 && range_includes_zero_p (vr_result.min,
11068 vr_result.max) == 0)
11069 || (vr_result.type == VR_ANTI_RANGE
11070 && range_includes_zero_p (vr_result.min,
11071 vr_result.max) == 1)))
11072 set_ptr_nonnull (lhs);
11075 edge taken_edge = NULL;
11077 /* Visit all other stmts and discover any new VRs possible. */
11078 for (gimple_stmt_iterator gsi = gsi_start_bb (bb);
11079 !gsi_end_p (gsi); gsi_next (&gsi))
11081 gimple *stmt = gsi_stmt (gsi);
11082 tree output = NULL_TREE;
11083 gimple *old_stmt = stmt;
11084 bool was_noreturn = (is_gimple_call (stmt)
11085 && gimple_call_noreturn_p (stmt));
11087 if (dump_file && (dump_flags & TDF_DETAILS))
11089 fprintf (dump_file, "Visiting stmt ");
11090 print_gimple_stmt (dump_file, stmt, 0);
11093 if (gcond *cond = dyn_cast <gcond *> (stmt))
11095 vrp_visit_cond_stmt (cond, &taken_edge);
11096 if (taken_edge)
11098 if (taken_edge->flags & EDGE_TRUE_VALUE)
11099 gimple_cond_make_true (cond);
11100 else if (taken_edge->flags & EDGE_FALSE_VALUE)
11101 gimple_cond_make_false (cond);
11102 else
11103 gcc_unreachable ();
11104 update_stmt (stmt);
11107 else if (stmt_interesting_for_vrp (stmt))
11109 edge taken_edge;
11110 value_range vr = VR_INITIALIZER;
11111 extract_range_from_stmt (stmt, &taken_edge, &output, &vr);
11112 if (output
11113 && (vr.type == VR_RANGE || vr.type == VR_ANTI_RANGE))
11115 update_value_range (output, &vr);
11116 vr = *get_value_range (output);
11118 /* Mark stmts whose output we fully propagate for removal. */
11119 tree val;
11120 if ((val = op_with_constant_singleton_value_range (output))
11121 && may_propagate_copy (output, val)
11122 && !stmt_could_throw_p (stmt)
11123 && !gimple_has_side_effects (stmt))
11125 stmts_to_remove.safe_push (stmt);
11126 continue;
11129 /* Set the SSA with the value range. */
11130 if (INTEGRAL_TYPE_P (TREE_TYPE (output)))
11132 if ((vr.type == VR_RANGE
11133 || vr.type == VR_ANTI_RANGE)
11134 && (TREE_CODE (vr.min) == INTEGER_CST)
11135 && (TREE_CODE (vr.max) == INTEGER_CST))
11136 set_range_info (output, vr.type,
11137 wi::to_wide (vr.min),
11138 wi::to_wide (vr.max));
11140 else if (POINTER_TYPE_P (TREE_TYPE (output))
11141 && ((vr.type == VR_RANGE
11142 && range_includes_zero_p (vr.min,
11143 vr.max) == 0)
11144 || (vr.type == VR_ANTI_RANGE
11145 && range_includes_zero_p (vr.min,
11146 vr.max) == 1)))
11147 set_ptr_nonnull (output);
11149 else
11150 set_defs_to_varying (stmt);
11152 else
11153 set_defs_to_varying (stmt);
11155 /* See if we can derive a range for any of STMT's operands. */
11156 tree op;
11157 ssa_op_iter i;
11158 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
11160 tree value;
11161 enum tree_code comp_code;
11163 /* If OP is used in such a way that we can infer a value
11164 range for it, and we don't find a previous assertion for
11165 it, create a new assertion location node for OP. */
11166 if (infer_value_range (stmt, op, &comp_code, &value))
11168 /* If we are able to infer a nonzero value range for OP,
11169 then walk backwards through the use-def chain to see if OP
11170 was set via a typecast.
11171 If so, then we can also infer a nonzero value range
11172 for the operand of the NOP_EXPR. */
11173 if (comp_code == NE_EXPR && integer_zerop (value))
11175 tree t = op;
11176 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
11177 while (is_gimple_assign (def_stmt)
11178 && CONVERT_EXPR_CODE_P
11179 (gimple_assign_rhs_code (def_stmt))
11180 && TREE_CODE
11181 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
11182 && POINTER_TYPE_P
11183 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
11185 t = gimple_assign_rhs1 (def_stmt);
11186 def_stmt = SSA_NAME_DEF_STMT (t);
11188 /* Add VR when (T COMP_CODE value) condition is
11189 true. */
11190 value_range *op_range
11191 = try_find_new_range (t, t, comp_code, value);
11192 if (op_range)
11193 push_value_range (t, op_range);
11196 /* Add VR when (OP COMP_CODE value) condition is true. */
11197 value_range *op_range = try_find_new_range (op, op,
11198 comp_code, value);
11199 if (op_range)
11200 push_value_range (op, op_range);
11204 /* Try folding stmts with the VR discovered. */
11205 class vrp_folder vrp_folder;
11206 bool did_replace = vrp_folder.replace_uses_in (stmt);
11207 if (fold_stmt (&gsi, follow_single_use_edges)
11208 || did_replace)
11210 stmt = gsi_stmt (gsi);
11211 update_stmt (stmt);
11212 did_replace = true;
11215 if (did_replace)
11217 /* If we cleaned up EH information from the statement,
11218 remove EH edges. */
11219 if (maybe_clean_or_replace_eh_stmt (old_stmt, stmt))
11220 bitmap_set_bit (need_eh_cleanup, bb->index);
11222 /* If we turned a not noreturn call into a noreturn one
11223 schedule it for fixup. */
11224 if (!was_noreturn
11225 && is_gimple_call (stmt)
11226 && gimple_call_noreturn_p (stmt))
11227 stmts_to_fixup.safe_push (stmt);
11229 if (gimple_assign_single_p (stmt))
11231 tree rhs = gimple_assign_rhs1 (stmt);
11232 if (TREE_CODE (rhs) == ADDR_EXPR)
11233 recompute_tree_invariant_for_addr_expr (rhs);
11238 /* Visit BB successor PHI nodes and replace PHI args. */
11239 FOR_EACH_EDGE (e, ei, bb->succs)
11241 for (gphi_iterator gpi = gsi_start_phis (e->dest);
11242 !gsi_end_p (gpi); gsi_next (&gpi))
11244 gphi *phi = gpi.phi ();
11245 use_operand_p use_p = PHI_ARG_DEF_PTR_FROM_EDGE (phi, e);
11246 tree arg = USE_FROM_PTR (use_p);
11247 if (TREE_CODE (arg) != SSA_NAME
11248 || virtual_operand_p (arg))
11249 continue;
11250 tree val = op_with_constant_singleton_value_range (arg);
11251 if (val && may_propagate_copy (arg, val))
11252 propagate_value (use_p, val);
11256 bb->flags |= BB_VISITED;
11258 return taken_edge;
11261 /* Restore/pop VRs valid only for BB when we leave BB. */
11263 void
11264 evrp_dom_walker::after_dom_children (basic_block bb ATTRIBUTE_UNUSED)
11266 gcc_checking_assert (!stack.is_empty ());
11267 while (stack.last ().first != NULL_TREE)
11268 pop_value_range (stack.last ().first);
11269 stack.pop ();
11272 /* Push the Value Range of VAR to the stack and update it with new VR. */
11274 void
11275 evrp_dom_walker::push_value_range (tree var, value_range *vr)
11277 if (SSA_NAME_VERSION (var) >= num_vr_values)
11278 return;
11279 if (dump_file && (dump_flags & TDF_DETAILS))
11281 fprintf (dump_file, "pushing new range for ");
11282 print_generic_expr (dump_file, var);
11283 fprintf (dump_file, ": ");
11284 dump_value_range (dump_file, vr);
11285 fprintf (dump_file, "\n");
11287 stack.safe_push (std::make_pair (var, get_value_range (var)));
11288 vr_value[SSA_NAME_VERSION (var)] = vr;
11291 /* Pop the Value Range from the vrp_stack and update VAR with it. */
11293 value_range *
11294 evrp_dom_walker::pop_value_range (tree var)
11296 value_range *vr = stack.last ().second;
11297 gcc_checking_assert (var == stack.last ().first);
11298 if (dump_file && (dump_flags & TDF_DETAILS))
11300 fprintf (dump_file, "popping range for ");
11301 print_generic_expr (dump_file, var);
11302 fprintf (dump_file, ", restoring ");
11303 dump_value_range (dump_file, vr);
11304 fprintf (dump_file, "\n");
11306 vr_value[SSA_NAME_VERSION (var)] = vr;
11307 stack.pop ();
11308 return vr;
11312 /* Main entry point for the early vrp pass which is a simplified non-iterative
11313 version of vrp where basic blocks are visited in dominance order. Value
11314 ranges discovered in early vrp will also be used by ipa-vrp. */
11316 static unsigned int
11317 execute_early_vrp ()
11319 edge e;
11320 edge_iterator ei;
11321 basic_block bb;
11323 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
11324 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
11325 scev_initialize ();
11326 calculate_dominance_info (CDI_DOMINATORS);
11327 FOR_EACH_BB_FN (bb, cfun)
11329 bb->flags &= ~BB_VISITED;
11330 FOR_EACH_EDGE (e, ei, bb->preds)
11331 e->flags |= EDGE_EXECUTABLE;
11333 vrp_initialize_lattice ();
11335 /* Walk stmts in dominance order and propagate VRP. */
11336 evrp_dom_walker walker;
11337 walker.walk (ENTRY_BLOCK_PTR_FOR_FN (cfun));
11339 if (dump_file)
11341 fprintf (dump_file, "\nValue ranges after Early VRP:\n\n");
11342 dump_all_value_ranges (dump_file);
11343 fprintf (dump_file, "\n");
11346 /* Remove stmts in reverse order to make debug stmt creation possible. */
11347 while (! walker.stmts_to_remove.is_empty ())
11349 gimple *stmt = walker.stmts_to_remove.pop ();
11350 if (dump_file && dump_flags & TDF_DETAILS)
11352 fprintf (dump_file, "Removing dead stmt ");
11353 print_gimple_stmt (dump_file, stmt, 0);
11354 fprintf (dump_file, "\n");
11356 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
11357 if (gimple_code (stmt) == GIMPLE_PHI)
11358 remove_phi_node (&gsi, true);
11359 else
11361 unlink_stmt_vdef (stmt);
11362 gsi_remove (&gsi, true);
11363 release_defs (stmt);
11367 if (!bitmap_empty_p (walker.need_eh_cleanup))
11368 gimple_purge_all_dead_eh_edges (walker.need_eh_cleanup);
11370 /* Fixup stmts that became noreturn calls. This may require splitting
11371 blocks and thus isn't possible during the dominator walk. Do this
11372 in reverse order so we don't inadvertedly remove a stmt we want to
11373 fixup by visiting a dominating now noreturn call first. */
11374 while (!walker.stmts_to_fixup.is_empty ())
11376 gimple *stmt = walker.stmts_to_fixup.pop ();
11377 fixup_noreturn_call (stmt);
11380 vrp_free_lattice ();
11381 scev_finalize ();
11382 loop_optimizer_finalize ();
11383 return 0;
11387 /* Main entry point to VRP (Value Range Propagation). This pass is
11388 loosely based on J. R. C. Patterson, ``Accurate Static Branch
11389 Prediction by Value Range Propagation,'' in SIGPLAN Conference on
11390 Programming Language Design and Implementation, pp. 67-78, 1995.
11391 Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
11393 This is essentially an SSA-CCP pass modified to deal with ranges
11394 instead of constants.
11396 While propagating ranges, we may find that two or more SSA name
11397 have equivalent, though distinct ranges. For instance,
11399 1 x_9 = p_3->a;
11400 2 p_4 = ASSERT_EXPR <p_3, p_3 != 0>
11401 3 if (p_4 == q_2)
11402 4 p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
11403 5 endif
11404 6 if (q_2)
11406 In the code above, pointer p_5 has range [q_2, q_2], but from the
11407 code we can also determine that p_5 cannot be NULL and, if q_2 had
11408 a non-varying range, p_5's range should also be compatible with it.
11410 These equivalences are created by two expressions: ASSERT_EXPR and
11411 copy operations. Since p_5 is an assertion on p_4, and p_4 was the
11412 result of another assertion, then we can use the fact that p_5 and
11413 p_4 are equivalent when evaluating p_5's range.
11415 Together with value ranges, we also propagate these equivalences
11416 between names so that we can take advantage of information from
11417 multiple ranges when doing final replacement. Note that this
11418 equivalency relation is transitive but not symmetric.
11420 In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
11421 cannot assert that q_2 is equivalent to p_5 because q_2 may be used
11422 in contexts where that assertion does not hold (e.g., in line 6).
11424 TODO, the main difference between this pass and Patterson's is that
11425 we do not propagate edge probabilities. We only compute whether
11426 edges can be taken or not. That is, instead of having a spectrum
11427 of jump probabilities between 0 and 1, we only deal with 0, 1 and
11428 DON'T KNOW. In the future, it may be worthwhile to propagate
11429 probabilities to aid branch prediction. */
11431 static unsigned int
11432 execute_vrp (bool warn_array_bounds_p)
11434 int i;
11435 edge e;
11436 switch_update *su;
11438 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
11439 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
11440 scev_initialize ();
11442 /* ??? This ends up using stale EDGE_DFS_BACK for liveness computation.
11443 Inserting assertions may split edges which will invalidate
11444 EDGE_DFS_BACK. */
11445 insert_range_assertions ();
11447 to_remove_edges.create (10);
11448 to_update_switch_stmts.create (5);
11449 threadedge_initialize_values ();
11451 /* For visiting PHI nodes we need EDGE_DFS_BACK computed. */
11452 mark_dfs_back_edges ();
11454 vrp_initialize_lattice ();
11455 vrp_initialize ();
11456 class vrp_prop vrp_prop;
11457 vrp_prop.ssa_propagate ();
11458 vrp_finalize (warn_array_bounds_p);
11460 /* We must identify jump threading opportunities before we release
11461 the datastructures built by VRP. */
11462 identify_jump_threads ();
11464 /* A comparison of an SSA_NAME against a constant where the SSA_NAME
11465 was set by a type conversion can often be rewritten to use the
11466 RHS of the type conversion.
11468 However, doing so inhibits jump threading through the comparison.
11469 So that transformation is not performed until after jump threading
11470 is complete. */
11471 basic_block bb;
11472 FOR_EACH_BB_FN (bb, cfun)
11474 gimple *last = last_stmt (bb);
11475 if (last && gimple_code (last) == GIMPLE_COND)
11476 simplify_cond_using_ranges_2 (as_a <gcond *> (last));
11479 vrp_free_lattice ();
11481 free_numbers_of_iterations_estimates (cfun);
11483 /* ASSERT_EXPRs must be removed before finalizing jump threads
11484 as finalizing jump threads calls the CFG cleanup code which
11485 does not properly handle ASSERT_EXPRs. */
11486 remove_range_assertions ();
11488 /* If we exposed any new variables, go ahead and put them into
11489 SSA form now, before we handle jump threading. This simplifies
11490 interactions between rewriting of _DECL nodes into SSA form
11491 and rewriting SSA_NAME nodes into SSA form after block
11492 duplication and CFG manipulation. */
11493 update_ssa (TODO_update_ssa);
11495 /* We identified all the jump threading opportunities earlier, but could
11496 not transform the CFG at that time. This routine transforms the
11497 CFG and arranges for the dominator tree to be rebuilt if necessary.
11499 Note the SSA graph update will occur during the normal TODO
11500 processing by the pass manager. */
11501 thread_through_all_blocks (false);
11503 /* Remove dead edges from SWITCH_EXPR optimization. This leaves the
11504 CFG in a broken state and requires a cfg_cleanup run. */
11505 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
11506 remove_edge (e);
11507 /* Update SWITCH_EXPR case label vector. */
11508 FOR_EACH_VEC_ELT (to_update_switch_stmts, i, su)
11510 size_t j;
11511 size_t n = TREE_VEC_LENGTH (su->vec);
11512 tree label;
11513 gimple_switch_set_num_labels (su->stmt, n);
11514 for (j = 0; j < n; j++)
11515 gimple_switch_set_label (su->stmt, j, TREE_VEC_ELT (su->vec, j));
11516 /* As we may have replaced the default label with a regular one
11517 make sure to make it a real default label again. This ensures
11518 optimal expansion. */
11519 label = gimple_switch_label (su->stmt, 0);
11520 CASE_LOW (label) = NULL_TREE;
11521 CASE_HIGH (label) = NULL_TREE;
11524 if (to_remove_edges.length () > 0)
11526 free_dominance_info (CDI_DOMINATORS);
11527 loops_state_set (LOOPS_NEED_FIXUP);
11530 to_remove_edges.release ();
11531 to_update_switch_stmts.release ();
11532 threadedge_finalize_values ();
11534 scev_finalize ();
11535 loop_optimizer_finalize ();
11536 return 0;
11539 namespace {
11541 const pass_data pass_data_vrp =
11543 GIMPLE_PASS, /* type */
11544 "vrp", /* name */
11545 OPTGROUP_NONE, /* optinfo_flags */
11546 TV_TREE_VRP, /* tv_id */
11547 PROP_ssa, /* properties_required */
11548 0, /* properties_provided */
11549 0, /* properties_destroyed */
11550 0, /* todo_flags_start */
11551 ( TODO_cleanup_cfg | TODO_update_ssa ), /* todo_flags_finish */
11554 class pass_vrp : public gimple_opt_pass
11556 public:
11557 pass_vrp (gcc::context *ctxt)
11558 : gimple_opt_pass (pass_data_vrp, ctxt), warn_array_bounds_p (false)
11561 /* opt_pass methods: */
11562 opt_pass * clone () { return new pass_vrp (m_ctxt); }
11563 void set_pass_param (unsigned int n, bool param)
11565 gcc_assert (n == 0);
11566 warn_array_bounds_p = param;
11568 virtual bool gate (function *) { return flag_tree_vrp != 0; }
11569 virtual unsigned int execute (function *)
11570 { return execute_vrp (warn_array_bounds_p); }
11572 private:
11573 bool warn_array_bounds_p;
11574 }; // class pass_vrp
11576 } // anon namespace
11578 gimple_opt_pass *
11579 make_pass_vrp (gcc::context *ctxt)
11581 return new pass_vrp (ctxt);
11584 namespace {
11586 const pass_data pass_data_early_vrp =
11588 GIMPLE_PASS, /* type */
11589 "evrp", /* name */
11590 OPTGROUP_NONE, /* optinfo_flags */
11591 TV_TREE_EARLY_VRP, /* tv_id */
11592 PROP_ssa, /* properties_required */
11593 0, /* properties_provided */
11594 0, /* properties_destroyed */
11595 0, /* todo_flags_start */
11596 ( TODO_cleanup_cfg | TODO_update_ssa | TODO_verify_all ),
11599 class pass_early_vrp : public gimple_opt_pass
11601 public:
11602 pass_early_vrp (gcc::context *ctxt)
11603 : gimple_opt_pass (pass_data_early_vrp, ctxt)
11606 /* opt_pass methods: */
11607 opt_pass * clone () { return new pass_early_vrp (m_ctxt); }
11608 virtual bool gate (function *)
11610 return flag_tree_vrp != 0;
11612 virtual unsigned int execute (function *)
11613 { return execute_early_vrp (); }
11615 }; // class pass_vrp
11616 } // anon namespace
11618 gimple_opt_pass *
11619 make_pass_early_vrp (gcc::context *ctxt)
11621 return new pass_early_vrp (ctxt);