2017-09-21 Paul Thomas <pault@gcc.gnu.org>
[official-gcc.git] / gcc / tree-vrp.c
blobaef20f4e8a5a71336c39d5186848904dff9c8623
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 (inv1, inv2, TYPE_SIGN (TREE_TYPE (val1)));
1078 const bool cst1 = is_gimple_min_invariant (val1);
1079 const bool cst2 = is_gimple_min_invariant (val2);
1081 /* If one is of the form '[-]NAME + CST' and the other is constant, then
1082 it might be possible to say something depending on the constants. */
1083 if ((sym1 && inv1 && cst2) || (sym2 && inv2 && cst1))
1085 if (!overflow_undefined)
1086 return -2;
1088 if (strict_overflow_p != NULL
1089 /* Symbolic range building sets TREE_NO_WARNING to declare
1090 that overflow doesn't happen. */
1091 && (!sym1 || !TREE_NO_WARNING (val1))
1092 && (!sym2 || !TREE_NO_WARNING (val2)))
1093 *strict_overflow_p = true;
1095 const signop sgn = TYPE_SIGN (TREE_TYPE (val1));
1096 tree cst = cst1 ? val1 : val2;
1097 tree inv = cst1 ? inv2 : inv1;
1099 /* Compute the difference between the constants. If it overflows or
1100 underflows, this means that we can trivially compare the NAME with
1101 it and, consequently, the two values with each other. */
1102 wide_int diff = wi::sub (cst, inv);
1103 if (wi::cmp (0, inv, sgn) != wi::cmp (diff, cst, sgn))
1105 const int res = wi::cmp (cst, inv, sgn);
1106 return cst1 ? res : -res;
1109 return -2;
1112 /* We cannot say anything more for non-constants. */
1113 if (!cst1 || !cst2)
1114 return -2;
1116 if (!POINTER_TYPE_P (TREE_TYPE (val1)))
1118 /* We cannot compare overflowed values. */
1119 if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
1120 return -2;
1122 return tree_int_cst_compare (val1, val2);
1124 else
1126 tree t;
1128 /* First see if VAL1 and VAL2 are not the same. */
1129 if (val1 == val2 || operand_equal_p (val1, val2, 0))
1130 return 0;
1132 /* If VAL1 is a lower address than VAL2, return -1. */
1133 if (operand_less_p (val1, val2) == 1)
1134 return -1;
1136 /* If VAL1 is a higher address than VAL2, return +1. */
1137 if (operand_less_p (val2, val1) == 1)
1138 return 1;
1140 /* If VAL1 is different than VAL2, return +2.
1141 For integer constants we either have already returned -1 or 1
1142 or they are equivalent. We still might succeed in proving
1143 something about non-trivial operands. */
1144 if (TREE_CODE (val1) != INTEGER_CST
1145 || TREE_CODE (val2) != INTEGER_CST)
1147 t = fold_binary_to_constant (NE_EXPR, boolean_type_node, val1, val2);
1148 if (t && integer_onep (t))
1149 return 2;
1152 return -2;
1156 /* Compare values like compare_values_warnv. */
1158 static int
1159 compare_values (tree val1, tree val2)
1161 bool sop;
1162 return compare_values_warnv (val1, val2, &sop);
1166 /* Return 1 if VAL is inside value range MIN <= VAL <= MAX,
1167 0 if VAL is not inside [MIN, MAX],
1168 -2 if we cannot tell either way.
1170 Benchmark compile/20001226-1.c compilation time after changing this
1171 function. */
1173 static inline int
1174 value_inside_range (tree val, tree min, tree max)
1176 int cmp1, cmp2;
1178 cmp1 = operand_less_p (val, min);
1179 if (cmp1 == -2)
1180 return -2;
1181 if (cmp1 == 1)
1182 return 0;
1184 cmp2 = operand_less_p (max, val);
1185 if (cmp2 == -2)
1186 return -2;
1188 return !cmp2;
1192 /* Return true if value ranges VR0 and VR1 have a non-empty
1193 intersection.
1195 Benchmark compile/20001226-1.c compilation time after changing this
1196 function.
1199 static inline bool
1200 value_ranges_intersect_p (value_range *vr0, value_range *vr1)
1202 /* The value ranges do not intersect if the maximum of the first range is
1203 less than the minimum of the second range or vice versa.
1204 When those relations are unknown, we can't do any better. */
1205 if (operand_less_p (vr0->max, vr1->min) != 0)
1206 return false;
1207 if (operand_less_p (vr1->max, vr0->min) != 0)
1208 return false;
1209 return true;
1213 /* Return 1 if [MIN, MAX] includes the value zero, 0 if it does not
1214 include the value zero, -2 if we cannot tell. */
1216 static inline int
1217 range_includes_zero_p (tree min, tree max)
1219 tree zero = build_int_cst (TREE_TYPE (min), 0);
1220 return value_inside_range (zero, min, max);
1223 /* Return true if *VR is know to only contain nonnegative values. */
1225 static inline bool
1226 value_range_nonnegative_p (value_range *vr)
1228 /* Testing for VR_ANTI_RANGE is not useful here as any anti-range
1229 which would return a useful value should be encoded as a
1230 VR_RANGE. */
1231 if (vr->type == VR_RANGE)
1233 int result = compare_values (vr->min, integer_zero_node);
1234 return (result == 0 || result == 1);
1237 return false;
1240 /* If *VR has a value rante that is a single constant value return that,
1241 otherwise return NULL_TREE. */
1243 static tree
1244 value_range_constant_singleton (value_range *vr)
1246 if (vr->type == VR_RANGE
1247 && vrp_operand_equal_p (vr->min, vr->max)
1248 && is_gimple_min_invariant (vr->min))
1249 return vr->min;
1251 return NULL_TREE;
1254 /* If OP has a value range with a single constant value return that,
1255 otherwise return NULL_TREE. This returns OP itself if OP is a
1256 constant. */
1258 static tree
1259 op_with_constant_singleton_value_range (tree op)
1261 if (is_gimple_min_invariant (op))
1262 return op;
1264 if (TREE_CODE (op) != SSA_NAME)
1265 return NULL_TREE;
1267 return value_range_constant_singleton (get_value_range (op));
1270 /* Return true if op is in a boolean [0, 1] value-range. */
1272 static bool
1273 op_with_boolean_value_range_p (tree op)
1275 value_range *vr;
1277 if (TYPE_PRECISION (TREE_TYPE (op)) == 1)
1278 return true;
1280 if (integer_zerop (op)
1281 || integer_onep (op))
1282 return true;
1284 if (TREE_CODE (op) != SSA_NAME)
1285 return false;
1287 vr = get_value_range (op);
1288 return (vr->type == VR_RANGE
1289 && integer_zerop (vr->min)
1290 && integer_onep (vr->max));
1293 /* Extract value range information for VAR when (OP COND_CODE LIMIT) is
1294 true and store it in *VR_P. */
1296 static void
1297 extract_range_for_var_from_comparison_expr (tree var, enum tree_code cond_code,
1298 tree op, tree limit,
1299 value_range *vr_p)
1301 tree min, max, type;
1302 value_range *limit_vr;
1303 type = TREE_TYPE (var);
1304 gcc_assert (limit != var);
1306 /* For pointer arithmetic, we only keep track of pointer equality
1307 and inequality. */
1308 if (POINTER_TYPE_P (type) && cond_code != NE_EXPR && cond_code != EQ_EXPR)
1310 set_value_range_to_varying (vr_p);
1311 return;
1314 /* If LIMIT is another SSA name and LIMIT has a range of its own,
1315 try to use LIMIT's range to avoid creating symbolic ranges
1316 unnecessarily. */
1317 limit_vr = (TREE_CODE (limit) == SSA_NAME) ? get_value_range (limit) : NULL;
1319 /* LIMIT's range is only interesting if it has any useful information. */
1320 if (! limit_vr
1321 || limit_vr->type == VR_UNDEFINED
1322 || limit_vr->type == VR_VARYING
1323 || (symbolic_range_p (limit_vr)
1324 && ! (limit_vr->type == VR_RANGE
1325 && (limit_vr->min == limit_vr->max
1326 || operand_equal_p (limit_vr->min, limit_vr->max, 0)))))
1327 limit_vr = NULL;
1329 /* Initially, the new range has the same set of equivalences of
1330 VAR's range. This will be revised before returning the final
1331 value. Since assertions may be chained via mutually exclusive
1332 predicates, we will need to trim the set of equivalences before
1333 we are done. */
1334 gcc_assert (vr_p->equiv == NULL);
1335 add_equivalence (&vr_p->equiv, var);
1337 /* Extract a new range based on the asserted comparison for VAR and
1338 LIMIT's value range. Notice that if LIMIT has an anti-range, we
1339 will only use it for equality comparisons (EQ_EXPR). For any
1340 other kind of assertion, we cannot derive a range from LIMIT's
1341 anti-range that can be used to describe the new range. For
1342 instance, ASSERT_EXPR <x_2, x_2 <= b_4>. If b_4 is ~[2, 10],
1343 then b_4 takes on the ranges [-INF, 1] and [11, +INF]. There is
1344 no single range for x_2 that could describe LE_EXPR, so we might
1345 as well build the range [b_4, +INF] for it.
1346 One special case we handle is extracting a range from a
1347 range test encoded as (unsigned)var + CST <= limit. */
1348 if (TREE_CODE (op) == NOP_EXPR
1349 || TREE_CODE (op) == PLUS_EXPR)
1351 if (TREE_CODE (op) == PLUS_EXPR)
1353 min = fold_build1 (NEGATE_EXPR, TREE_TYPE (TREE_OPERAND (op, 1)),
1354 TREE_OPERAND (op, 1));
1355 max = int_const_binop (PLUS_EXPR, limit, min);
1356 op = TREE_OPERAND (op, 0);
1358 else
1360 min = build_int_cst (TREE_TYPE (var), 0);
1361 max = limit;
1364 /* Make sure to not set TREE_OVERFLOW on the final type
1365 conversion. We are willingly interpreting large positive
1366 unsigned values as negative signed values here. */
1367 min = force_fit_type (TREE_TYPE (var), wi::to_widest (min), 0, false);
1368 max = force_fit_type (TREE_TYPE (var), wi::to_widest (max), 0, false);
1370 /* We can transform a max, min range to an anti-range or
1371 vice-versa. Use set_and_canonicalize_value_range which does
1372 this for us. */
1373 if (cond_code == LE_EXPR)
1374 set_and_canonicalize_value_range (vr_p, VR_RANGE,
1375 min, max, vr_p->equiv);
1376 else if (cond_code == GT_EXPR)
1377 set_and_canonicalize_value_range (vr_p, VR_ANTI_RANGE,
1378 min, max, vr_p->equiv);
1379 else
1380 gcc_unreachable ();
1382 else if (cond_code == EQ_EXPR)
1384 enum value_range_type range_type;
1386 if (limit_vr)
1388 range_type = limit_vr->type;
1389 min = limit_vr->min;
1390 max = limit_vr->max;
1392 else
1394 range_type = VR_RANGE;
1395 min = limit;
1396 max = limit;
1399 set_value_range (vr_p, range_type, min, max, vr_p->equiv);
1401 /* When asserting the equality VAR == LIMIT and LIMIT is another
1402 SSA name, the new range will also inherit the equivalence set
1403 from LIMIT. */
1404 if (TREE_CODE (limit) == SSA_NAME)
1405 add_equivalence (&vr_p->equiv, limit);
1407 else if (cond_code == NE_EXPR)
1409 /* As described above, when LIMIT's range is an anti-range and
1410 this assertion is an inequality (NE_EXPR), then we cannot
1411 derive anything from the anti-range. For instance, if
1412 LIMIT's range was ~[0, 0], the assertion 'VAR != LIMIT' does
1413 not imply that VAR's range is [0, 0]. So, in the case of
1414 anti-ranges, we just assert the inequality using LIMIT and
1415 not its anti-range.
1417 If LIMIT_VR is a range, we can only use it to build a new
1418 anti-range if LIMIT_VR is a single-valued range. For
1419 instance, if LIMIT_VR is [0, 1], the predicate
1420 VAR != [0, 1] does not mean that VAR's range is ~[0, 1].
1421 Rather, it means that for value 0 VAR should be ~[0, 0]
1422 and for value 1, VAR should be ~[1, 1]. We cannot
1423 represent these ranges.
1425 The only situation in which we can build a valid
1426 anti-range is when LIMIT_VR is a single-valued range
1427 (i.e., LIMIT_VR->MIN == LIMIT_VR->MAX). In that case,
1428 build the anti-range ~[LIMIT_VR->MIN, LIMIT_VR->MAX]. */
1429 if (limit_vr
1430 && limit_vr->type == VR_RANGE
1431 && compare_values (limit_vr->min, limit_vr->max) == 0)
1433 min = limit_vr->min;
1434 max = limit_vr->max;
1436 else
1438 /* In any other case, we cannot use LIMIT's range to build a
1439 valid anti-range. */
1440 min = max = limit;
1443 /* If MIN and MAX cover the whole range for their type, then
1444 just use the original LIMIT. */
1445 if (INTEGRAL_TYPE_P (type)
1446 && vrp_val_is_min (min)
1447 && vrp_val_is_max (max))
1448 min = max = limit;
1450 set_and_canonicalize_value_range (vr_p, VR_ANTI_RANGE,
1451 min, max, vr_p->equiv);
1453 else if (cond_code == LE_EXPR || cond_code == LT_EXPR)
1455 min = TYPE_MIN_VALUE (type);
1457 if (limit_vr == NULL || limit_vr->type == VR_ANTI_RANGE)
1458 max = limit;
1459 else
1461 /* If LIMIT_VR is of the form [N1, N2], we need to build the
1462 range [MIN, N2] for LE_EXPR and [MIN, N2 - 1] for
1463 LT_EXPR. */
1464 max = limit_vr->max;
1467 /* If the maximum value forces us to be out of bounds, simply punt.
1468 It would be pointless to try and do anything more since this
1469 all should be optimized away above us. */
1470 if (cond_code == LT_EXPR
1471 && compare_values (max, min) == 0)
1472 set_value_range_to_varying (vr_p);
1473 else
1475 /* For LT_EXPR, we create the range [MIN, MAX - 1]. */
1476 if (cond_code == LT_EXPR)
1478 if (TYPE_PRECISION (TREE_TYPE (max)) == 1
1479 && !TYPE_UNSIGNED (TREE_TYPE (max)))
1480 max = fold_build2 (PLUS_EXPR, TREE_TYPE (max), max,
1481 build_int_cst (TREE_TYPE (max), -1));
1482 else
1483 max = fold_build2 (MINUS_EXPR, TREE_TYPE (max), max,
1484 build_int_cst (TREE_TYPE (max), 1));
1485 /* Signal to compare_values_warnv this expr doesn't overflow. */
1486 if (EXPR_P (max))
1487 TREE_NO_WARNING (max) = 1;
1490 set_value_range (vr_p, VR_RANGE, min, max, vr_p->equiv);
1493 else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
1495 max = TYPE_MAX_VALUE (type);
1497 if (limit_vr == NULL || limit_vr->type == VR_ANTI_RANGE)
1498 min = limit;
1499 else
1501 /* If LIMIT_VR is of the form [N1, N2], we need to build the
1502 range [N1, MAX] for GE_EXPR and [N1 + 1, MAX] for
1503 GT_EXPR. */
1504 min = limit_vr->min;
1507 /* If the minimum value forces us to be out of bounds, simply punt.
1508 It would be pointless to try and do anything more since this
1509 all should be optimized away above us. */
1510 if (cond_code == GT_EXPR
1511 && compare_values (min, max) == 0)
1512 set_value_range_to_varying (vr_p);
1513 else
1515 /* For GT_EXPR, we create the range [MIN + 1, MAX]. */
1516 if (cond_code == GT_EXPR)
1518 if (TYPE_PRECISION (TREE_TYPE (min)) == 1
1519 && !TYPE_UNSIGNED (TREE_TYPE (min)))
1520 min = fold_build2 (MINUS_EXPR, TREE_TYPE (min), min,
1521 build_int_cst (TREE_TYPE (min), -1));
1522 else
1523 min = fold_build2 (PLUS_EXPR, TREE_TYPE (min), min,
1524 build_int_cst (TREE_TYPE (min), 1));
1525 /* Signal to compare_values_warnv this expr doesn't overflow. */
1526 if (EXPR_P (min))
1527 TREE_NO_WARNING (min) = 1;
1530 set_value_range (vr_p, VR_RANGE, min, max, vr_p->equiv);
1533 else
1534 gcc_unreachable ();
1536 /* Finally intersect the new range with what we already know about var. */
1537 vrp_intersect_ranges (vr_p, get_value_range (var));
1540 /* Extract value range information from an ASSERT_EXPR EXPR and store
1541 it in *VR_P. */
1543 static void
1544 extract_range_from_assert (value_range *vr_p, tree expr)
1546 tree var = ASSERT_EXPR_VAR (expr);
1547 tree cond = ASSERT_EXPR_COND (expr);
1548 tree limit, op;
1549 enum tree_code cond_code;
1550 gcc_assert (COMPARISON_CLASS_P (cond));
1552 /* Find VAR in the ASSERT_EXPR conditional. */
1553 if (var == TREE_OPERAND (cond, 0)
1554 || TREE_CODE (TREE_OPERAND (cond, 0)) == PLUS_EXPR
1555 || TREE_CODE (TREE_OPERAND (cond, 0)) == NOP_EXPR)
1557 /* If the predicate is of the form VAR COMP LIMIT, then we just
1558 take LIMIT from the RHS and use the same comparison code. */
1559 cond_code = TREE_CODE (cond);
1560 limit = TREE_OPERAND (cond, 1);
1561 op = TREE_OPERAND (cond, 0);
1563 else
1565 /* If the predicate is of the form LIMIT COMP VAR, then we need
1566 to flip around the comparison code to create the proper range
1567 for VAR. */
1568 cond_code = swap_tree_comparison (TREE_CODE (cond));
1569 limit = TREE_OPERAND (cond, 0);
1570 op = TREE_OPERAND (cond, 1);
1572 extract_range_for_var_from_comparison_expr (var, cond_code, op,
1573 limit, vr_p);
1576 /* Extract range information from SSA name VAR and store it in VR. If
1577 VAR has an interesting range, use it. Otherwise, create the
1578 range [VAR, VAR] and return it. This is useful in situations where
1579 we may have conditionals testing values of VARYING names. For
1580 instance,
1582 x_3 = y_5;
1583 if (x_3 > y_5)
1586 Even if y_5 is deemed VARYING, we can determine that x_3 > y_5 is
1587 always false. */
1589 static void
1590 extract_range_from_ssa_name (value_range *vr, tree var)
1592 value_range *var_vr = get_value_range (var);
1594 if (var_vr->type != VR_VARYING)
1595 copy_value_range (vr, var_vr);
1596 else
1597 set_value_range (vr, VR_RANGE, var, var, NULL);
1599 add_equivalence (&vr->equiv, var);
1603 /* Wrapper around int_const_binop. If the operation overflows and
1604 overflow is undefined, then adjust the result to be
1605 -INF or +INF depending on CODE, VAL1 and VAL2. Sets *OVERFLOW_P
1606 to whether the operation overflowed. For division by zero
1607 the result is indeterminate but *OVERFLOW_P is set. */
1609 static wide_int
1610 vrp_int_const_binop (enum tree_code code, tree val1, tree val2,
1611 bool *overflow_p)
1613 bool overflow = false;
1614 signop sign = TYPE_SIGN (TREE_TYPE (val1));
1615 wide_int res;
1617 *overflow_p = false;
1619 switch (code)
1621 case RSHIFT_EXPR:
1622 case LSHIFT_EXPR:
1624 wide_int wval2 = wi::to_wide (val2, TYPE_PRECISION (TREE_TYPE (val1)));
1625 if (wi::neg_p (wval2))
1627 wval2 = -wval2;
1628 if (code == RSHIFT_EXPR)
1629 code = LSHIFT_EXPR;
1630 else
1631 code = RSHIFT_EXPR;
1634 if (code == RSHIFT_EXPR)
1635 /* It's unclear from the C standard whether shifts can overflow.
1636 The following code ignores overflow; perhaps a C standard
1637 interpretation ruling is needed. */
1638 res = wi::rshift (val1, wval2, sign);
1639 else
1640 res = wi::lshift (val1, wval2);
1641 break;
1644 case MULT_EXPR:
1645 res = wi::mul (val1, val2, sign, &overflow);
1646 break;
1648 case TRUNC_DIV_EXPR:
1649 case EXACT_DIV_EXPR:
1650 if (val2 == 0)
1652 *overflow_p = true;
1653 return res;
1655 else
1656 res = wi::div_trunc (val1, val2, sign, &overflow);
1657 break;
1659 case FLOOR_DIV_EXPR:
1660 if (val2 == 0)
1662 *overflow_p = true;
1663 return res;
1665 res = wi::div_floor (val1, val2, sign, &overflow);
1666 break;
1668 case CEIL_DIV_EXPR:
1669 if (val2 == 0)
1671 *overflow_p = true;
1672 return res;
1674 res = wi::div_ceil (val1, val2, sign, &overflow);
1675 break;
1677 case ROUND_DIV_EXPR:
1678 if (val2 == 0)
1680 *overflow_p = 0;
1681 return res;
1683 res = wi::div_round (val1, val2, sign, &overflow);
1684 break;
1686 default:
1687 gcc_unreachable ();
1690 if (overflow
1691 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1)))
1693 /* If the operation overflowed return -INF or +INF depending
1694 on the operation and the combination of signs of the operands. */
1695 int sgn1 = tree_int_cst_sgn (val1);
1696 int sgn2 = tree_int_cst_sgn (val2);
1698 /* Notice that we only need to handle the restricted set of
1699 operations handled by extract_range_from_binary_expr.
1700 Among them, only multiplication, addition and subtraction
1701 can yield overflow without overflown operands because we
1702 are working with integral types only... except in the
1703 case VAL1 = -INF and VAL2 = -1 which overflows to +INF
1704 for division too. */
1706 /* For multiplication, the sign of the overflow is given
1707 by the comparison of the signs of the operands. */
1708 if ((code == MULT_EXPR && sgn1 == sgn2)
1709 /* For addition, the operands must be of the same sign
1710 to yield an overflow. Its sign is therefore that
1711 of one of the operands, for example the first. */
1712 || (code == PLUS_EXPR && sgn1 >= 0)
1713 /* For subtraction, operands must be of
1714 different signs to yield an overflow. Its sign is
1715 therefore that of the first operand or the opposite of
1716 that of the second operand. A first operand of 0 counts
1717 as positive here, for the corner case 0 - (-INF), which
1718 overflows, but must yield +INF. */
1719 || (code == MINUS_EXPR && sgn1 >= 0)
1720 /* For division, the only case is -INF / -1 = +INF. */
1721 || code == TRUNC_DIV_EXPR
1722 || code == FLOOR_DIV_EXPR
1723 || code == CEIL_DIV_EXPR
1724 || code == EXACT_DIV_EXPR
1725 || code == ROUND_DIV_EXPR)
1726 return wi::max_value (TYPE_PRECISION (TREE_TYPE (val1)),
1727 TYPE_SIGN (TREE_TYPE (val1)));
1728 else
1729 return wi::min_value (TYPE_PRECISION (TREE_TYPE (val1)),
1730 TYPE_SIGN (TREE_TYPE (val1)));
1733 *overflow_p = overflow;
1735 return res;
1739 /* For range VR compute two wide_int bitmasks. In *MAY_BE_NONZERO
1740 bitmask if some bit is unset, it means for all numbers in the range
1741 the bit is 0, otherwise it might be 0 or 1. In *MUST_BE_NONZERO
1742 bitmask if some bit is set, it means for all numbers in the range
1743 the bit is 1, otherwise it might be 0 or 1. */
1745 static bool
1746 zero_nonzero_bits_from_vr (const tree expr_type,
1747 value_range *vr,
1748 wide_int *may_be_nonzero,
1749 wide_int *must_be_nonzero)
1751 *may_be_nonzero = wi::minus_one (TYPE_PRECISION (expr_type));
1752 *must_be_nonzero = wi::zero (TYPE_PRECISION (expr_type));
1753 if (!range_int_cst_p (vr))
1754 return false;
1756 if (range_int_cst_singleton_p (vr))
1758 *may_be_nonzero = vr->min;
1759 *must_be_nonzero = *may_be_nonzero;
1761 else if (tree_int_cst_sgn (vr->min) >= 0
1762 || tree_int_cst_sgn (vr->max) < 0)
1764 wide_int xor_mask = wi::bit_xor (vr->min, vr->max);
1765 *may_be_nonzero = wi::bit_or (vr->min, vr->max);
1766 *must_be_nonzero = wi::bit_and (vr->min, vr->max);
1767 if (xor_mask != 0)
1769 wide_int mask = wi::mask (wi::floor_log2 (xor_mask), false,
1770 may_be_nonzero->get_precision ());
1771 *may_be_nonzero = *may_be_nonzero | mask;
1772 *must_be_nonzero = must_be_nonzero->and_not (mask);
1776 return true;
1779 /* Create two value-ranges in *VR0 and *VR1 from the anti-range *AR
1780 so that *VR0 U *VR1 == *AR. Returns true if that is possible,
1781 false otherwise. If *AR can be represented with a single range
1782 *VR1 will be VR_UNDEFINED. */
1784 static bool
1785 ranges_from_anti_range (value_range *ar,
1786 value_range *vr0, value_range *vr1)
1788 tree type = TREE_TYPE (ar->min);
1790 vr0->type = VR_UNDEFINED;
1791 vr1->type = VR_UNDEFINED;
1793 if (ar->type != VR_ANTI_RANGE
1794 || TREE_CODE (ar->min) != INTEGER_CST
1795 || TREE_CODE (ar->max) != INTEGER_CST
1796 || !vrp_val_min (type)
1797 || !vrp_val_max (type))
1798 return false;
1800 if (!vrp_val_is_min (ar->min))
1802 vr0->type = VR_RANGE;
1803 vr0->min = vrp_val_min (type);
1804 vr0->max = wide_int_to_tree (type, wi::sub (ar->min, 1));
1806 if (!vrp_val_is_max (ar->max))
1808 vr1->type = VR_RANGE;
1809 vr1->min = wide_int_to_tree (type, wi::add (ar->max, 1));
1810 vr1->max = vrp_val_max (type);
1812 if (vr0->type == VR_UNDEFINED)
1814 *vr0 = *vr1;
1815 vr1->type = VR_UNDEFINED;
1818 return vr0->type != VR_UNDEFINED;
1821 /* Helper to extract a value-range *VR for a multiplicative operation
1822 *VR0 CODE *VR1. */
1824 static void
1825 extract_range_from_multiplicative_op_1 (value_range *vr,
1826 enum tree_code code,
1827 value_range *vr0, value_range *vr1)
1829 enum value_range_type rtype;
1830 wide_int val, min, max;
1831 bool sop;
1832 tree type;
1834 /* Multiplications, divisions and shifts are a bit tricky to handle,
1835 depending on the mix of signs we have in the two ranges, we
1836 need to operate on different values to get the minimum and
1837 maximum values for the new range. One approach is to figure
1838 out all the variations of range combinations and do the
1839 operations.
1841 However, this involves several calls to compare_values and it
1842 is pretty convoluted. It's simpler to do the 4 operations
1843 (MIN0 OP MIN1, MIN0 OP MAX1, MAX0 OP MIN1 and MAX0 OP MAX0 OP
1844 MAX1) and then figure the smallest and largest values to form
1845 the new range. */
1846 gcc_assert (code == MULT_EXPR
1847 || code == TRUNC_DIV_EXPR
1848 || code == FLOOR_DIV_EXPR
1849 || code == CEIL_DIV_EXPR
1850 || code == EXACT_DIV_EXPR
1851 || code == ROUND_DIV_EXPR
1852 || code == RSHIFT_EXPR
1853 || code == LSHIFT_EXPR);
1854 gcc_assert ((vr0->type == VR_RANGE
1855 || (code == MULT_EXPR && vr0->type == VR_ANTI_RANGE))
1856 && vr0->type == vr1->type);
1858 rtype = vr0->type;
1859 type = TREE_TYPE (vr0->min);
1860 signop sgn = TYPE_SIGN (type);
1862 /* Compute the 4 cross operations and their minimum and maximum value. */
1863 sop = false;
1864 val = vrp_int_const_binop (code, vr0->min, vr1->min, &sop);
1865 if (! sop)
1866 min = max = val;
1868 if (vr1->max == vr1->min)
1870 else if (! sop)
1872 val = vrp_int_const_binop (code, vr0->min, vr1->max, &sop);
1873 if (! sop)
1875 if (wi::lt_p (val, min, sgn))
1876 min = val;
1877 else if (wi::gt_p (val, max, sgn))
1878 max = val;
1882 if (vr0->max == vr0->min)
1884 else if (! sop)
1886 val = vrp_int_const_binop (code, vr0->max, vr1->min, &sop);
1887 if (! sop)
1889 if (wi::lt_p (val, min, sgn))
1890 min = val;
1891 else if (wi::gt_p (val, max, sgn))
1892 max = val;
1896 if (vr0->min == vr0->max || vr1->min == vr1->max)
1898 else if (! sop)
1900 val = vrp_int_const_binop (code, vr0->max, vr1->max, &sop);
1901 if (! sop)
1903 if (wi::lt_p (val, min, sgn))
1904 min = val;
1905 else if (wi::gt_p (val, max, sgn))
1906 max = val;
1910 /* If either operation overflowed, drop to VARYING. */
1911 if (sop)
1913 set_value_range_to_varying (vr);
1914 return;
1917 /* If the new range has its limits swapped around (MIN > MAX),
1918 then the operation caused one of them to wrap around, mark
1919 the new range VARYING. */
1920 if (wi::gt_p (min, max, sgn))
1922 set_value_range_to_varying (vr);
1923 return;
1926 /* We punt for [-INF, +INF].
1927 We learn nothing when we have INF on both sides.
1928 Note that we do accept [-INF, -INF] and [+INF, +INF]. */
1929 if (wi::eq_p (min, wi::min_value (TYPE_PRECISION (type), sgn))
1930 && wi::eq_p (max, wi::max_value (TYPE_PRECISION (type), sgn)))
1932 set_value_range_to_varying (vr);
1933 return;
1936 set_value_range (vr, rtype,
1937 wide_int_to_tree (type, min),
1938 wide_int_to_tree (type, max), NULL);
1941 /* Extract range information from a binary operation CODE based on
1942 the ranges of each of its operands *VR0 and *VR1 with resulting
1943 type EXPR_TYPE. The resulting range is stored in *VR. */
1945 static void
1946 extract_range_from_binary_expr_1 (value_range *vr,
1947 enum tree_code code, tree expr_type,
1948 value_range *vr0_, value_range *vr1_)
1950 value_range vr0 = *vr0_, vr1 = *vr1_;
1951 value_range vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
1952 enum value_range_type type;
1953 tree min = NULL_TREE, max = NULL_TREE;
1954 int cmp;
1956 if (!INTEGRAL_TYPE_P (expr_type)
1957 && !POINTER_TYPE_P (expr_type))
1959 set_value_range_to_varying (vr);
1960 return;
1963 /* Not all binary expressions can be applied to ranges in a
1964 meaningful way. Handle only arithmetic operations. */
1965 if (code != PLUS_EXPR
1966 && code != MINUS_EXPR
1967 && code != POINTER_PLUS_EXPR
1968 && code != MULT_EXPR
1969 && code != TRUNC_DIV_EXPR
1970 && code != FLOOR_DIV_EXPR
1971 && code != CEIL_DIV_EXPR
1972 && code != EXACT_DIV_EXPR
1973 && code != ROUND_DIV_EXPR
1974 && code != TRUNC_MOD_EXPR
1975 && code != RSHIFT_EXPR
1976 && code != LSHIFT_EXPR
1977 && code != MIN_EXPR
1978 && code != MAX_EXPR
1979 && code != BIT_AND_EXPR
1980 && code != BIT_IOR_EXPR
1981 && code != BIT_XOR_EXPR)
1983 set_value_range_to_varying (vr);
1984 return;
1987 /* If both ranges are UNDEFINED, so is the result. */
1988 if (vr0.type == VR_UNDEFINED && vr1.type == VR_UNDEFINED)
1990 set_value_range_to_undefined (vr);
1991 return;
1993 /* If one of the ranges is UNDEFINED drop it to VARYING for the following
1994 code. At some point we may want to special-case operations that
1995 have UNDEFINED result for all or some value-ranges of the not UNDEFINED
1996 operand. */
1997 else if (vr0.type == VR_UNDEFINED)
1998 set_value_range_to_varying (&vr0);
1999 else if (vr1.type == VR_UNDEFINED)
2000 set_value_range_to_varying (&vr1);
2002 /* We get imprecise results from ranges_from_anti_range when
2003 code is EXACT_DIV_EXPR. We could mask out bits in the resulting
2004 range, but then we also need to hack up vrp_meet. It's just
2005 easier to special case when vr0 is ~[0,0] for EXACT_DIV_EXPR. */
2006 if (code == EXACT_DIV_EXPR
2007 && vr0.type == VR_ANTI_RANGE
2008 && vr0.min == vr0.max
2009 && integer_zerop (vr0.min))
2011 set_value_range_to_nonnull (vr, expr_type);
2012 return;
2015 /* Now canonicalize anti-ranges to ranges when they are not symbolic
2016 and express ~[] op X as ([]' op X) U ([]'' op X). */
2017 if (vr0.type == VR_ANTI_RANGE
2018 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
2020 extract_range_from_binary_expr_1 (vr, code, expr_type, &vrtem0, vr1_);
2021 if (vrtem1.type != VR_UNDEFINED)
2023 value_range vrres = VR_INITIALIZER;
2024 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
2025 &vrtem1, vr1_);
2026 vrp_meet (vr, &vrres);
2028 return;
2030 /* Likewise for X op ~[]. */
2031 if (vr1.type == VR_ANTI_RANGE
2032 && ranges_from_anti_range (&vr1, &vrtem0, &vrtem1))
2034 extract_range_from_binary_expr_1 (vr, code, expr_type, vr0_, &vrtem0);
2035 if (vrtem1.type != VR_UNDEFINED)
2037 value_range vrres = VR_INITIALIZER;
2038 extract_range_from_binary_expr_1 (&vrres, code, expr_type,
2039 vr0_, &vrtem1);
2040 vrp_meet (vr, &vrres);
2042 return;
2045 /* The type of the resulting value range defaults to VR0.TYPE. */
2046 type = vr0.type;
2048 /* Refuse to operate on VARYING ranges, ranges of different kinds
2049 and symbolic ranges. As an exception, we allow BIT_{AND,IOR}
2050 because we may be able to derive a useful range even if one of
2051 the operands is VR_VARYING or symbolic range. Similarly for
2052 divisions, MIN/MAX and PLUS/MINUS.
2054 TODO, we may be able to derive anti-ranges in some cases. */
2055 if (code != BIT_AND_EXPR
2056 && code != BIT_IOR_EXPR
2057 && code != TRUNC_DIV_EXPR
2058 && code != FLOOR_DIV_EXPR
2059 && code != CEIL_DIV_EXPR
2060 && code != EXACT_DIV_EXPR
2061 && code != ROUND_DIV_EXPR
2062 && code != TRUNC_MOD_EXPR
2063 && code != MIN_EXPR
2064 && code != MAX_EXPR
2065 && code != PLUS_EXPR
2066 && code != MINUS_EXPR
2067 && code != RSHIFT_EXPR
2068 && (vr0.type == VR_VARYING
2069 || vr1.type == VR_VARYING
2070 || vr0.type != vr1.type
2071 || symbolic_range_p (&vr0)
2072 || symbolic_range_p (&vr1)))
2074 set_value_range_to_varying (vr);
2075 return;
2078 /* Now evaluate the expression to determine the new range. */
2079 if (POINTER_TYPE_P (expr_type))
2081 if (code == MIN_EXPR || code == MAX_EXPR)
2083 /* For MIN/MAX expressions with pointers, we only care about
2084 nullness, if both are non null, then the result is nonnull.
2085 If both are null, then the result is null. Otherwise they
2086 are varying. */
2087 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
2088 set_value_range_to_nonnull (vr, expr_type);
2089 else if (range_is_null (&vr0) && range_is_null (&vr1))
2090 set_value_range_to_null (vr, expr_type);
2091 else
2092 set_value_range_to_varying (vr);
2094 else if (code == POINTER_PLUS_EXPR)
2096 /* For pointer types, we are really only interested in asserting
2097 whether the expression evaluates to non-NULL. */
2098 if (range_is_nonnull (&vr0) || range_is_nonnull (&vr1))
2099 set_value_range_to_nonnull (vr, expr_type);
2100 else if (range_is_null (&vr0) && range_is_null (&vr1))
2101 set_value_range_to_null (vr, expr_type);
2102 else
2103 set_value_range_to_varying (vr);
2105 else if (code == BIT_AND_EXPR)
2107 /* For pointer types, we are really only interested in asserting
2108 whether the expression evaluates to non-NULL. */
2109 if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
2110 set_value_range_to_nonnull (vr, expr_type);
2111 else if (range_is_null (&vr0) || range_is_null (&vr1))
2112 set_value_range_to_null (vr, expr_type);
2113 else
2114 set_value_range_to_varying (vr);
2116 else
2117 set_value_range_to_varying (vr);
2119 return;
2122 /* For integer ranges, apply the operation to each end of the
2123 range and see what we end up with. */
2124 if (code == PLUS_EXPR || code == MINUS_EXPR)
2126 const bool minus_p = (code == MINUS_EXPR);
2127 tree min_op0 = vr0.min;
2128 tree min_op1 = minus_p ? vr1.max : vr1.min;
2129 tree max_op0 = vr0.max;
2130 tree max_op1 = minus_p ? vr1.min : vr1.max;
2131 tree sym_min_op0 = NULL_TREE;
2132 tree sym_min_op1 = NULL_TREE;
2133 tree sym_max_op0 = NULL_TREE;
2134 tree sym_max_op1 = NULL_TREE;
2135 bool neg_min_op0, neg_min_op1, neg_max_op0, neg_max_op1;
2137 /* If we have a PLUS or MINUS with two VR_RANGEs, either constant or
2138 single-symbolic ranges, try to compute the precise resulting range,
2139 but only if we know that this resulting range will also be constant
2140 or single-symbolic. */
2141 if (vr0.type == VR_RANGE && vr1.type == VR_RANGE
2142 && (TREE_CODE (min_op0) == INTEGER_CST
2143 || (sym_min_op0
2144 = get_single_symbol (min_op0, &neg_min_op0, &min_op0)))
2145 && (TREE_CODE (min_op1) == INTEGER_CST
2146 || (sym_min_op1
2147 = get_single_symbol (min_op1, &neg_min_op1, &min_op1)))
2148 && (!(sym_min_op0 && sym_min_op1)
2149 || (sym_min_op0 == sym_min_op1
2150 && neg_min_op0 == (minus_p ? neg_min_op1 : !neg_min_op1)))
2151 && (TREE_CODE (max_op0) == INTEGER_CST
2152 || (sym_max_op0
2153 = get_single_symbol (max_op0, &neg_max_op0, &max_op0)))
2154 && (TREE_CODE (max_op1) == INTEGER_CST
2155 || (sym_max_op1
2156 = get_single_symbol (max_op1, &neg_max_op1, &max_op1)))
2157 && (!(sym_max_op0 && sym_max_op1)
2158 || (sym_max_op0 == sym_max_op1
2159 && neg_max_op0 == (minus_p ? neg_max_op1 : !neg_max_op1))))
2161 const signop sgn = TYPE_SIGN (expr_type);
2162 const unsigned int prec = TYPE_PRECISION (expr_type);
2163 wide_int type_min, type_max, wmin, wmax;
2164 int min_ovf = 0;
2165 int max_ovf = 0;
2167 /* Get the lower and upper bounds of the type. */
2168 if (TYPE_OVERFLOW_WRAPS (expr_type))
2170 type_min = wi::min_value (prec, sgn);
2171 type_max = wi::max_value (prec, sgn);
2173 else
2175 type_min = vrp_val_min (expr_type);
2176 type_max = vrp_val_max (expr_type);
2179 /* Combine the lower bounds, if any. */
2180 if (min_op0 && min_op1)
2182 if (minus_p)
2184 wmin = wi::sub (min_op0, min_op1);
2186 /* Check for overflow. */
2187 if (wi::cmp (0, min_op1, sgn)
2188 != wi::cmp (wmin, min_op0, sgn))
2189 min_ovf = wi::cmp (min_op0, min_op1, sgn);
2191 else
2193 wmin = wi::add (min_op0, min_op1);
2195 /* Check for overflow. */
2196 if (wi::cmp (min_op1, 0, sgn)
2197 != wi::cmp (wmin, min_op0, sgn))
2198 min_ovf = wi::cmp (min_op0, wmin, sgn);
2201 else if (min_op0)
2202 wmin = min_op0;
2203 else if (min_op1)
2205 if (minus_p)
2207 wmin = wi::neg (min_op1);
2209 /* Check for overflow. */
2210 if (sgn == SIGNED && wi::neg_p (min_op1) && wi::neg_p (wmin))
2211 min_ovf = 1;
2212 else if (sgn == UNSIGNED && wi::ne_p (min_op1, 0))
2213 min_ovf = -1;
2215 else
2216 wmin = min_op1;
2218 else
2219 wmin = wi::shwi (0, prec);
2221 /* Combine the upper bounds, if any. */
2222 if (max_op0 && max_op1)
2224 if (minus_p)
2226 wmax = wi::sub (max_op0, max_op1);
2228 /* Check for overflow. */
2229 if (wi::cmp (0, max_op1, sgn)
2230 != wi::cmp (wmax, max_op0, sgn))
2231 max_ovf = wi::cmp (max_op0, max_op1, sgn);
2233 else
2235 wmax = wi::add (max_op0, max_op1);
2237 if (wi::cmp (max_op1, 0, sgn)
2238 != wi::cmp (wmax, max_op0, sgn))
2239 max_ovf = wi::cmp (max_op0, wmax, sgn);
2242 else if (max_op0)
2243 wmax = max_op0;
2244 else if (max_op1)
2246 if (minus_p)
2248 wmax = wi::neg (max_op1);
2250 /* Check for overflow. */
2251 if (sgn == SIGNED && wi::neg_p (max_op1) && wi::neg_p (wmax))
2252 max_ovf = 1;
2253 else if (sgn == UNSIGNED && wi::ne_p (max_op1, 0))
2254 max_ovf = -1;
2256 else
2257 wmax = max_op1;
2259 else
2260 wmax = wi::shwi (0, prec);
2262 /* Check for type overflow. */
2263 if (min_ovf == 0)
2265 if (wi::cmp (wmin, type_min, sgn) == -1)
2266 min_ovf = -1;
2267 else if (wi::cmp (wmin, type_max, sgn) == 1)
2268 min_ovf = 1;
2270 if (max_ovf == 0)
2272 if (wi::cmp (wmax, type_min, sgn) == -1)
2273 max_ovf = -1;
2274 else if (wi::cmp (wmax, type_max, sgn) == 1)
2275 max_ovf = 1;
2278 /* If we have overflow for the constant part and the resulting
2279 range will be symbolic, drop to VR_VARYING. */
2280 if ((min_ovf && sym_min_op0 != sym_min_op1)
2281 || (max_ovf && sym_max_op0 != sym_max_op1))
2283 set_value_range_to_varying (vr);
2284 return;
2287 if (TYPE_OVERFLOW_WRAPS (expr_type))
2289 /* If overflow wraps, truncate the values and adjust the
2290 range kind and bounds appropriately. */
2291 wide_int tmin = wide_int::from (wmin, prec, sgn);
2292 wide_int tmax = wide_int::from (wmax, prec, sgn);
2293 if (min_ovf == max_ovf)
2295 /* No overflow or both overflow or underflow. The
2296 range kind stays VR_RANGE. */
2297 min = wide_int_to_tree (expr_type, tmin);
2298 max = wide_int_to_tree (expr_type, tmax);
2300 else if ((min_ovf == -1 && max_ovf == 0)
2301 || (max_ovf == 1 && min_ovf == 0))
2303 /* Min underflow or max overflow. The range kind
2304 changes to VR_ANTI_RANGE. */
2305 bool covers = false;
2306 wide_int tem = tmin;
2307 type = VR_ANTI_RANGE;
2308 tmin = tmax + 1;
2309 if (wi::cmp (tmin, tmax, sgn) < 0)
2310 covers = true;
2311 tmax = tem - 1;
2312 if (wi::cmp (tmax, tem, sgn) > 0)
2313 covers = true;
2314 /* If the anti-range would cover nothing, drop to varying.
2315 Likewise if the anti-range bounds are outside of the
2316 types values. */
2317 if (covers || wi::cmp (tmin, tmax, sgn) > 0)
2319 set_value_range_to_varying (vr);
2320 return;
2322 min = wide_int_to_tree (expr_type, tmin);
2323 max = wide_int_to_tree (expr_type, tmax);
2325 else
2327 /* Other underflow and/or overflow, drop to VR_VARYING. */
2328 set_value_range_to_varying (vr);
2329 return;
2332 else
2334 /* If overflow does not wrap, saturate to the types min/max
2335 value. */
2336 if (min_ovf == -1)
2337 min = wide_int_to_tree (expr_type, type_min);
2338 else if (min_ovf == 1)
2339 min = wide_int_to_tree (expr_type, type_max);
2340 else
2341 min = wide_int_to_tree (expr_type, wmin);
2343 if (max_ovf == -1)
2344 max = wide_int_to_tree (expr_type, type_min);
2345 else if (max_ovf == 1)
2346 max = wide_int_to_tree (expr_type, type_max);
2347 else
2348 max = wide_int_to_tree (expr_type, wmax);
2351 /* If the result lower bound is constant, we're done;
2352 otherwise, build the symbolic lower bound. */
2353 if (sym_min_op0 == sym_min_op1)
2355 else if (sym_min_op0)
2356 min = build_symbolic_expr (expr_type, sym_min_op0,
2357 neg_min_op0, min);
2358 else if (sym_min_op1)
2360 /* We may not negate if that might introduce
2361 undefined overflow. */
2362 if (! minus_p
2363 || neg_min_op1
2364 || TYPE_OVERFLOW_WRAPS (expr_type))
2365 min = build_symbolic_expr (expr_type, sym_min_op1,
2366 neg_min_op1 ^ minus_p, min);
2367 else
2368 min = NULL_TREE;
2371 /* Likewise for the upper bound. */
2372 if (sym_max_op0 == sym_max_op1)
2374 else if (sym_max_op0)
2375 max = build_symbolic_expr (expr_type, sym_max_op0,
2376 neg_max_op0, max);
2377 else if (sym_max_op1)
2379 /* We may not negate if that might introduce
2380 undefined overflow. */
2381 if (! minus_p
2382 || neg_max_op1
2383 || TYPE_OVERFLOW_WRAPS (expr_type))
2384 max = build_symbolic_expr (expr_type, sym_max_op1,
2385 neg_max_op1 ^ minus_p, max);
2386 else
2387 max = NULL_TREE;
2390 else
2392 /* For other cases, for example if we have a PLUS_EXPR with two
2393 VR_ANTI_RANGEs, drop to VR_VARYING. It would take more effort
2394 to compute a precise range for such a case.
2395 ??? General even mixed range kind operations can be expressed
2396 by for example transforming ~[3, 5] + [1, 2] to range-only
2397 operations and a union primitive:
2398 [-INF, 2] + [1, 2] U [5, +INF] + [1, 2]
2399 [-INF+1, 4] U [6, +INF(OVF)]
2400 though usually the union is not exactly representable with
2401 a single range or anti-range as the above is
2402 [-INF+1, +INF(OVF)] intersected with ~[5, 5]
2403 but one could use a scheme similar to equivalences for this. */
2404 set_value_range_to_varying (vr);
2405 return;
2408 else if (code == MIN_EXPR
2409 || code == MAX_EXPR)
2411 if (vr0.type == VR_RANGE
2412 && !symbolic_range_p (&vr0))
2414 type = VR_RANGE;
2415 if (vr1.type == VR_RANGE
2416 && !symbolic_range_p (&vr1))
2418 /* For operations that make the resulting range directly
2419 proportional to the original ranges, apply the operation to
2420 the same end of each range. */
2421 min = int_const_binop (code, vr0.min, vr1.min);
2422 max = int_const_binop (code, vr0.max, vr1.max);
2424 else if (code == MIN_EXPR)
2426 min = vrp_val_min (expr_type);
2427 max = vr0.max;
2429 else if (code == MAX_EXPR)
2431 min = vr0.min;
2432 max = vrp_val_max (expr_type);
2435 else if (vr1.type == VR_RANGE
2436 && !symbolic_range_p (&vr1))
2438 type = VR_RANGE;
2439 if (code == MIN_EXPR)
2441 min = vrp_val_min (expr_type);
2442 max = vr1.max;
2444 else if (code == MAX_EXPR)
2446 min = vr1.min;
2447 max = vrp_val_max (expr_type);
2450 else
2452 set_value_range_to_varying (vr);
2453 return;
2456 else if (code == MULT_EXPR)
2458 /* Fancy code so that with unsigned, [-3,-1]*[-3,-1] does not
2459 drop to varying. This test requires 2*prec bits if both
2460 operands are signed and 2*prec + 2 bits if either is not. */
2462 signop sign = TYPE_SIGN (expr_type);
2463 unsigned int prec = TYPE_PRECISION (expr_type);
2465 if (range_int_cst_p (&vr0)
2466 && range_int_cst_p (&vr1)
2467 && TYPE_OVERFLOW_WRAPS (expr_type))
2469 typedef FIXED_WIDE_INT (WIDE_INT_MAX_PRECISION * 2) vrp_int;
2470 typedef generic_wide_int
2471 <wi::extended_tree <WIDE_INT_MAX_PRECISION * 2> > vrp_int_cst;
2472 vrp_int sizem1 = wi::mask <vrp_int> (prec, false);
2473 vrp_int size = sizem1 + 1;
2475 /* Extend the values using the sign of the result to PREC2.
2476 From here on out, everthing is just signed math no matter
2477 what the input types were. */
2478 vrp_int min0 = vrp_int_cst (vr0.min);
2479 vrp_int max0 = vrp_int_cst (vr0.max);
2480 vrp_int min1 = vrp_int_cst (vr1.min);
2481 vrp_int max1 = vrp_int_cst (vr1.max);
2482 /* Canonicalize the intervals. */
2483 if (sign == UNSIGNED)
2485 if (wi::ltu_p (size, min0 + max0))
2487 min0 -= size;
2488 max0 -= size;
2491 if (wi::ltu_p (size, min1 + max1))
2493 min1 -= size;
2494 max1 -= size;
2498 vrp_int prod0 = min0 * min1;
2499 vrp_int prod1 = min0 * max1;
2500 vrp_int prod2 = max0 * min1;
2501 vrp_int prod3 = max0 * max1;
2503 /* Sort the 4 products so that min is in prod0 and max is in
2504 prod3. */
2505 /* min0min1 > max0max1 */
2506 if (prod0 > prod3)
2507 std::swap (prod0, prod3);
2509 /* min0max1 > max0min1 */
2510 if (prod1 > prod2)
2511 std::swap (prod1, prod2);
2513 if (prod0 > prod1)
2514 std::swap (prod0, prod1);
2516 if (prod2 > prod3)
2517 std::swap (prod2, prod3);
2519 /* diff = max - min. */
2520 prod2 = prod3 - prod0;
2521 if (wi::geu_p (prod2, sizem1))
2523 /* the range covers all values. */
2524 set_value_range_to_varying (vr);
2525 return;
2528 /* The following should handle the wrapping and selecting
2529 VR_ANTI_RANGE for us. */
2530 min = wide_int_to_tree (expr_type, prod0);
2531 max = wide_int_to_tree (expr_type, prod3);
2532 set_and_canonicalize_value_range (vr, VR_RANGE, min, max, NULL);
2533 return;
2536 /* If we have an unsigned MULT_EXPR with two VR_ANTI_RANGEs,
2537 drop to VR_VARYING. It would take more effort to compute a
2538 precise range for such a case. For example, if we have
2539 op0 == 65536 and op1 == 65536 with their ranges both being
2540 ~[0,0] on a 32-bit machine, we would have op0 * op1 == 0, so
2541 we cannot claim that the product is in ~[0,0]. Note that we
2542 are guaranteed to have vr0.type == vr1.type at this
2543 point. */
2544 if (vr0.type == VR_ANTI_RANGE
2545 && !TYPE_OVERFLOW_UNDEFINED (expr_type))
2547 set_value_range_to_varying (vr);
2548 return;
2551 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2552 return;
2554 else if (code == RSHIFT_EXPR
2555 || code == LSHIFT_EXPR)
2557 /* If we have a RSHIFT_EXPR with any shift values outside [0..prec-1],
2558 then drop to VR_VARYING. Outside of this range we get undefined
2559 behavior from the shift operation. We cannot even trust
2560 SHIFT_COUNT_TRUNCATED at this stage, because that applies to rtl
2561 shifts, and the operation at the tree level may be widened. */
2562 if (range_int_cst_p (&vr1)
2563 && compare_tree_int (vr1.min, 0) >= 0
2564 && compare_tree_int (vr1.max, TYPE_PRECISION (expr_type)) == -1)
2566 if (code == RSHIFT_EXPR)
2568 /* Even if vr0 is VARYING or otherwise not usable, we can derive
2569 useful ranges just from the shift count. E.g.
2570 x >> 63 for signed 64-bit x is always [-1, 0]. */
2571 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
2573 vr0.type = type = VR_RANGE;
2574 vr0.min = vrp_val_min (expr_type);
2575 vr0.max = vrp_val_max (expr_type);
2577 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2578 return;
2580 /* We can map lshifts by constants to MULT_EXPR handling. */
2581 else if (code == LSHIFT_EXPR
2582 && range_int_cst_singleton_p (&vr1))
2584 bool saved_flag_wrapv;
2585 value_range vr1p = VR_INITIALIZER;
2586 vr1p.type = VR_RANGE;
2587 vr1p.min = (wide_int_to_tree
2588 (expr_type,
2589 wi::set_bit_in_zero (tree_to_shwi (vr1.min),
2590 TYPE_PRECISION (expr_type))));
2591 vr1p.max = vr1p.min;
2592 /* We have to use a wrapping multiply though as signed overflow
2593 on lshifts is implementation defined in C89. */
2594 saved_flag_wrapv = flag_wrapv;
2595 flag_wrapv = 1;
2596 extract_range_from_binary_expr_1 (vr, MULT_EXPR, expr_type,
2597 &vr0, &vr1p);
2598 flag_wrapv = saved_flag_wrapv;
2599 return;
2601 else if (code == LSHIFT_EXPR
2602 && range_int_cst_p (&vr0))
2604 int prec = TYPE_PRECISION (expr_type);
2605 int overflow_pos = prec;
2606 int bound_shift;
2607 wide_int low_bound, high_bound;
2608 bool uns = TYPE_UNSIGNED (expr_type);
2609 bool in_bounds = false;
2611 if (!uns)
2612 overflow_pos -= 1;
2614 bound_shift = overflow_pos - tree_to_shwi (vr1.max);
2615 /* If bound_shift == HOST_BITS_PER_WIDE_INT, the llshift can
2616 overflow. However, for that to happen, vr1.max needs to be
2617 zero, which means vr1 is a singleton range of zero, which
2618 means it should be handled by the previous LSHIFT_EXPR
2619 if-clause. */
2620 wide_int bound = wi::set_bit_in_zero (bound_shift, prec);
2621 wide_int complement = ~(bound - 1);
2623 if (uns)
2625 low_bound = bound;
2626 high_bound = complement;
2627 if (wi::ltu_p (vr0.max, low_bound))
2629 /* [5, 6] << [1, 2] == [10, 24]. */
2630 /* We're shifting out only zeroes, the value increases
2631 monotonically. */
2632 in_bounds = true;
2634 else if (wi::ltu_p (high_bound, vr0.min))
2636 /* [0xffffff00, 0xffffffff] << [1, 2]
2637 == [0xfffffc00, 0xfffffffe]. */
2638 /* We're shifting out only ones, the value decreases
2639 monotonically. */
2640 in_bounds = true;
2643 else
2645 /* [-1, 1] << [1, 2] == [-4, 4]. */
2646 low_bound = complement;
2647 high_bound = bound;
2648 if (wi::lts_p (vr0.max, high_bound)
2649 && wi::lts_p (low_bound, vr0.min))
2651 /* For non-negative numbers, we're shifting out only
2652 zeroes, the value increases monotonically.
2653 For negative numbers, we're shifting out only ones, the
2654 value decreases monotomically. */
2655 in_bounds = true;
2659 if (in_bounds)
2661 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2662 return;
2666 set_value_range_to_varying (vr);
2667 return;
2669 else if (code == TRUNC_DIV_EXPR
2670 || code == FLOOR_DIV_EXPR
2671 || code == CEIL_DIV_EXPR
2672 || code == EXACT_DIV_EXPR
2673 || code == ROUND_DIV_EXPR)
2675 if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
2677 /* For division, if op1 has VR_RANGE but op0 does not, something
2678 can be deduced just from that range. Say [min, max] / [4, max]
2679 gives [min / 4, max / 4] range. */
2680 if (vr1.type == VR_RANGE
2681 && !symbolic_range_p (&vr1)
2682 && range_includes_zero_p (vr1.min, vr1.max) == 0)
2684 vr0.type = type = VR_RANGE;
2685 vr0.min = vrp_val_min (expr_type);
2686 vr0.max = vrp_val_max (expr_type);
2688 else
2690 set_value_range_to_varying (vr);
2691 return;
2695 /* For divisions, if flag_non_call_exceptions is true, we must
2696 not eliminate a division by zero. */
2697 if (cfun->can_throw_non_call_exceptions
2698 && (vr1.type != VR_RANGE
2699 || range_includes_zero_p (vr1.min, vr1.max) != 0))
2701 set_value_range_to_varying (vr);
2702 return;
2705 /* For divisions, if op0 is VR_RANGE, we can deduce a range
2706 even if op1 is VR_VARYING, VR_ANTI_RANGE, symbolic or can
2707 include 0. */
2708 if (vr0.type == VR_RANGE
2709 && (vr1.type != VR_RANGE
2710 || range_includes_zero_p (vr1.min, vr1.max) != 0))
2712 tree zero = build_int_cst (TREE_TYPE (vr0.min), 0);
2713 int cmp;
2715 min = NULL_TREE;
2716 max = NULL_TREE;
2717 if (TYPE_UNSIGNED (expr_type)
2718 || value_range_nonnegative_p (&vr1))
2720 /* For unsigned division or when divisor is known
2721 to be non-negative, the range has to cover
2722 all numbers from 0 to max for positive max
2723 and all numbers from min to 0 for negative min. */
2724 cmp = compare_values (vr0.max, zero);
2725 if (cmp == -1)
2727 /* When vr0.max < 0, vr1.min != 0 and value
2728 ranges for dividend and divisor are available. */
2729 if (vr1.type == VR_RANGE
2730 && !symbolic_range_p (&vr0)
2731 && !symbolic_range_p (&vr1)
2732 && compare_values (vr1.min, zero) != 0)
2733 max = int_const_binop (code, vr0.max, vr1.min);
2734 else
2735 max = zero;
2737 else if (cmp == 0 || cmp == 1)
2738 max = vr0.max;
2739 else
2740 type = VR_VARYING;
2741 cmp = compare_values (vr0.min, zero);
2742 if (cmp == 1)
2744 /* For unsigned division when value ranges for dividend
2745 and divisor are available. */
2746 if (vr1.type == VR_RANGE
2747 && !symbolic_range_p (&vr0)
2748 && !symbolic_range_p (&vr1)
2749 && compare_values (vr1.max, zero) != 0)
2750 min = int_const_binop (code, vr0.min, vr1.max);
2751 else
2752 min = zero;
2754 else if (cmp == 0 || cmp == -1)
2755 min = vr0.min;
2756 else
2757 type = VR_VARYING;
2759 else
2761 /* Otherwise the range is -max .. max or min .. -min
2762 depending on which bound is bigger in absolute value,
2763 as the division can change the sign. */
2764 abs_extent_range (vr, vr0.min, vr0.max);
2765 return;
2767 if (type == VR_VARYING)
2769 set_value_range_to_varying (vr);
2770 return;
2773 else if (!symbolic_range_p (&vr0) && !symbolic_range_p (&vr1))
2775 extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2776 return;
2779 else if (code == TRUNC_MOD_EXPR)
2781 if (range_is_null (&vr1))
2783 set_value_range_to_undefined (vr);
2784 return;
2786 /* ABS (A % B) < ABS (B) and either
2787 0 <= A % B <= A or A <= A % B <= 0. */
2788 type = VR_RANGE;
2789 signop sgn = TYPE_SIGN (expr_type);
2790 unsigned int prec = TYPE_PRECISION (expr_type);
2791 wide_int wmin, wmax, tmp;
2792 wide_int zero = wi::zero (prec);
2793 wide_int one = wi::one (prec);
2794 if (vr1.type == VR_RANGE && !symbolic_range_p (&vr1))
2796 wmax = wi::sub (vr1.max, one);
2797 if (sgn == SIGNED)
2799 tmp = wi::sub (wi::minus_one (prec), vr1.min);
2800 wmax = wi::smax (wmax, tmp);
2803 else
2805 wmax = wi::max_value (prec, sgn);
2806 /* X % INT_MIN may be INT_MAX. */
2807 if (sgn == UNSIGNED)
2808 wmax = wmax - one;
2811 if (sgn == UNSIGNED)
2812 wmin = zero;
2813 else
2815 wmin = -wmax;
2816 if (vr0.type == VR_RANGE && TREE_CODE (vr0.min) == INTEGER_CST)
2818 tmp = vr0.min;
2819 if (wi::gts_p (tmp, zero))
2820 tmp = zero;
2821 wmin = wi::smax (wmin, tmp);
2825 if (vr0.type == VR_RANGE && TREE_CODE (vr0.max) == INTEGER_CST)
2827 tmp = vr0.max;
2828 if (sgn == SIGNED && wi::neg_p (tmp))
2829 tmp = zero;
2830 wmax = wi::min (wmax, tmp, sgn);
2833 min = wide_int_to_tree (expr_type, wmin);
2834 max = wide_int_to_tree (expr_type, wmax);
2836 else if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR || code == BIT_XOR_EXPR)
2838 bool int_cst_range0, int_cst_range1;
2839 wide_int may_be_nonzero0, may_be_nonzero1;
2840 wide_int must_be_nonzero0, must_be_nonzero1;
2842 int_cst_range0 = zero_nonzero_bits_from_vr (expr_type, &vr0,
2843 &may_be_nonzero0,
2844 &must_be_nonzero0);
2845 int_cst_range1 = zero_nonzero_bits_from_vr (expr_type, &vr1,
2846 &may_be_nonzero1,
2847 &must_be_nonzero1);
2849 if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR)
2851 value_range *vr0p = NULL, *vr1p = NULL;
2852 if (range_int_cst_singleton_p (&vr1))
2854 vr0p = &vr0;
2855 vr1p = &vr1;
2857 else if (range_int_cst_singleton_p (&vr0))
2859 vr0p = &vr1;
2860 vr1p = &vr0;
2862 /* For op & or | attempt to optimize:
2863 [x, y] op z into [x op z, y op z]
2864 if z is a constant which (for op | its bitwise not) has n
2865 consecutive least significant bits cleared followed by m 1
2866 consecutive bits set immediately above it and either
2867 m + n == precision, or (x >> (m + n)) == (y >> (m + n)).
2868 The least significant n bits of all the values in the range are
2869 cleared or set, the m bits above it are preserved and any bits
2870 above these are required to be the same for all values in the
2871 range. */
2872 if (vr0p && range_int_cst_p (vr0p))
2874 wide_int w = vr1p->min;
2875 int m = 0, n = 0;
2876 if (code == BIT_IOR_EXPR)
2877 w = ~w;
2878 if (wi::eq_p (w, 0))
2879 n = TYPE_PRECISION (expr_type);
2880 else
2882 n = wi::ctz (w);
2883 w = ~(w | wi::mask (n, false, w.get_precision ()));
2884 if (wi::eq_p (w, 0))
2885 m = TYPE_PRECISION (expr_type) - n;
2886 else
2887 m = wi::ctz (w) - n;
2889 wide_int mask = wi::mask (m + n, true, w.get_precision ());
2890 if (wi::eq_p (mask & vr0p->min, mask & vr0p->max))
2892 min = int_const_binop (code, vr0p->min, vr1p->min);
2893 max = int_const_binop (code, vr0p->max, vr1p->min);
2898 type = VR_RANGE;
2899 if (min && max)
2900 /* Optimized above already. */;
2901 else if (code == BIT_AND_EXPR)
2903 min = wide_int_to_tree (expr_type,
2904 must_be_nonzero0 & must_be_nonzero1);
2905 wide_int wmax = may_be_nonzero0 & may_be_nonzero1;
2906 /* If both input ranges contain only negative values we can
2907 truncate the result range maximum to the minimum of the
2908 input range maxima. */
2909 if (int_cst_range0 && int_cst_range1
2910 && tree_int_cst_sgn (vr0.max) < 0
2911 && tree_int_cst_sgn (vr1.max) < 0)
2913 wmax = wi::min (wmax, vr0.max, TYPE_SIGN (expr_type));
2914 wmax = wi::min (wmax, vr1.max, TYPE_SIGN (expr_type));
2916 /* If either input range contains only non-negative values
2917 we can truncate the result range maximum to the respective
2918 maximum of the input range. */
2919 if (int_cst_range0 && tree_int_cst_sgn (vr0.min) >= 0)
2920 wmax = wi::min (wmax, vr0.max, TYPE_SIGN (expr_type));
2921 if (int_cst_range1 && tree_int_cst_sgn (vr1.min) >= 0)
2922 wmax = wi::min (wmax, vr1.max, TYPE_SIGN (expr_type));
2923 max = wide_int_to_tree (expr_type, wmax);
2924 cmp = compare_values (min, max);
2925 /* PR68217: In case of signed & sign-bit-CST should
2926 result in [-INF, 0] instead of [-INF, INF]. */
2927 if (cmp == -2 || cmp == 1)
2929 wide_int sign_bit
2930 = wi::set_bit_in_zero (TYPE_PRECISION (expr_type) - 1,
2931 TYPE_PRECISION (expr_type));
2932 if (!TYPE_UNSIGNED (expr_type)
2933 && ((int_cst_range0
2934 && value_range_constant_singleton (&vr0)
2935 && !wi::cmps (vr0.min, sign_bit))
2936 || (int_cst_range1
2937 && value_range_constant_singleton (&vr1)
2938 && !wi::cmps (vr1.min, sign_bit))))
2940 min = TYPE_MIN_VALUE (expr_type);
2941 max = build_int_cst (expr_type, 0);
2945 else if (code == BIT_IOR_EXPR)
2947 max = wide_int_to_tree (expr_type,
2948 may_be_nonzero0 | may_be_nonzero1);
2949 wide_int wmin = must_be_nonzero0 | must_be_nonzero1;
2950 /* If the input ranges contain only positive values we can
2951 truncate the minimum of the result range to the maximum
2952 of the input range minima. */
2953 if (int_cst_range0 && int_cst_range1
2954 && tree_int_cst_sgn (vr0.min) >= 0
2955 && tree_int_cst_sgn (vr1.min) >= 0)
2957 wmin = wi::max (wmin, vr0.min, TYPE_SIGN (expr_type));
2958 wmin = wi::max (wmin, vr1.min, TYPE_SIGN (expr_type));
2960 /* If either input range contains only negative values
2961 we can truncate the minimum of the result range to the
2962 respective minimum range. */
2963 if (int_cst_range0 && tree_int_cst_sgn (vr0.max) < 0)
2964 wmin = wi::max (wmin, vr0.min, TYPE_SIGN (expr_type));
2965 if (int_cst_range1 && tree_int_cst_sgn (vr1.max) < 0)
2966 wmin = wi::max (wmin, vr1.min, TYPE_SIGN (expr_type));
2967 min = wide_int_to_tree (expr_type, wmin);
2969 else if (code == BIT_XOR_EXPR)
2971 wide_int result_zero_bits = ((must_be_nonzero0 & must_be_nonzero1)
2972 | ~(may_be_nonzero0 | may_be_nonzero1));
2973 wide_int result_one_bits
2974 = (must_be_nonzero0.and_not (may_be_nonzero1)
2975 | must_be_nonzero1.and_not (may_be_nonzero0));
2976 max = wide_int_to_tree (expr_type, ~result_zero_bits);
2977 min = wide_int_to_tree (expr_type, result_one_bits);
2978 /* If the range has all positive or all negative values the
2979 result is better than VARYING. */
2980 if (tree_int_cst_sgn (min) < 0
2981 || tree_int_cst_sgn (max) >= 0)
2983 else
2984 max = min = NULL_TREE;
2987 else
2988 gcc_unreachable ();
2990 /* If either MIN or MAX overflowed, then set the resulting range to
2991 VARYING. */
2992 if (min == NULL_TREE
2993 || TREE_OVERFLOW_P (min)
2994 || max == NULL_TREE
2995 || TREE_OVERFLOW_P (max))
2997 set_value_range_to_varying (vr);
2998 return;
3001 /* We punt for [-INF, +INF].
3002 We learn nothing when we have INF on both sides.
3003 Note that we do accept [-INF, -INF] and [+INF, +INF]. */
3004 if (vrp_val_is_min (min) && vrp_val_is_max (max))
3006 set_value_range_to_varying (vr);
3007 return;
3010 cmp = compare_values (min, max);
3011 if (cmp == -2 || cmp == 1)
3013 /* If the new range has its limits swapped around (MIN > MAX),
3014 then the operation caused one of them to wrap around, mark
3015 the new range VARYING. */
3016 set_value_range_to_varying (vr);
3018 else
3019 set_value_range (vr, type, min, max, NULL);
3022 /* Extract range information from a binary expression OP0 CODE OP1 based on
3023 the ranges of each of its operands with resulting type EXPR_TYPE.
3024 The resulting range is stored in *VR. */
3026 static void
3027 extract_range_from_binary_expr (value_range *vr,
3028 enum tree_code code,
3029 tree expr_type, tree op0, tree op1)
3031 value_range vr0 = VR_INITIALIZER;
3032 value_range vr1 = VR_INITIALIZER;
3034 /* Get value ranges for each operand. For constant operands, create
3035 a new value range with the operand to simplify processing. */
3036 if (TREE_CODE (op0) == SSA_NAME)
3037 vr0 = *(get_value_range (op0));
3038 else if (is_gimple_min_invariant (op0))
3039 set_value_range_to_value (&vr0, op0, NULL);
3040 else
3041 set_value_range_to_varying (&vr0);
3043 if (TREE_CODE (op1) == SSA_NAME)
3044 vr1 = *(get_value_range (op1));
3045 else if (is_gimple_min_invariant (op1))
3046 set_value_range_to_value (&vr1, op1, NULL);
3047 else
3048 set_value_range_to_varying (&vr1);
3050 extract_range_from_binary_expr_1 (vr, code, expr_type, &vr0, &vr1);
3052 /* Try harder for PLUS and MINUS if the range of one operand is symbolic
3053 and based on the other operand, for example if it was deduced from a
3054 symbolic comparison. When a bound of the range of the first operand
3055 is invariant, we set the corresponding bound of the new range to INF
3056 in order to avoid recursing on the range of the second operand. */
3057 if (vr->type == VR_VARYING
3058 && (code == PLUS_EXPR || code == MINUS_EXPR)
3059 && TREE_CODE (op1) == SSA_NAME
3060 && vr0.type == VR_RANGE
3061 && symbolic_range_based_on_p (&vr0, op1))
3063 const bool minus_p = (code == MINUS_EXPR);
3064 value_range n_vr1 = VR_INITIALIZER;
3066 /* Try with VR0 and [-INF, OP1]. */
3067 if (is_gimple_min_invariant (minus_p ? vr0.max : vr0.min))
3068 set_value_range (&n_vr1, VR_RANGE, vrp_val_min (expr_type), op1, NULL);
3070 /* Try with VR0 and [OP1, +INF]. */
3071 else if (is_gimple_min_invariant (minus_p ? vr0.min : vr0.max))
3072 set_value_range (&n_vr1, VR_RANGE, op1, vrp_val_max (expr_type), NULL);
3074 /* Try with VR0 and [OP1, OP1]. */
3075 else
3076 set_value_range (&n_vr1, VR_RANGE, op1, op1, NULL);
3078 extract_range_from_binary_expr_1 (vr, code, expr_type, &vr0, &n_vr1);
3081 if (vr->type == VR_VARYING
3082 && (code == PLUS_EXPR || code == MINUS_EXPR)
3083 && TREE_CODE (op0) == SSA_NAME
3084 && vr1.type == VR_RANGE
3085 && symbolic_range_based_on_p (&vr1, op0))
3087 const bool minus_p = (code == MINUS_EXPR);
3088 value_range n_vr0 = VR_INITIALIZER;
3090 /* Try with [-INF, OP0] and VR1. */
3091 if (is_gimple_min_invariant (minus_p ? vr1.max : vr1.min))
3092 set_value_range (&n_vr0, VR_RANGE, vrp_val_min (expr_type), op0, NULL);
3094 /* Try with [OP0, +INF] and VR1. */
3095 else if (is_gimple_min_invariant (minus_p ? vr1.min : vr1.max))
3096 set_value_range (&n_vr0, VR_RANGE, op0, vrp_val_max (expr_type), NULL);
3098 /* Try with [OP0, OP0] and VR1. */
3099 else
3100 set_value_range (&n_vr0, VR_RANGE, op0, op0, NULL);
3102 extract_range_from_binary_expr_1 (vr, code, expr_type, &n_vr0, &vr1);
3105 /* If we didn't derive a range for MINUS_EXPR, and
3106 op1's range is ~[op0,op0] or vice-versa, then we
3107 can derive a non-null range. This happens often for
3108 pointer subtraction. */
3109 if (vr->type == VR_VARYING
3110 && code == MINUS_EXPR
3111 && TREE_CODE (op0) == SSA_NAME
3112 && ((vr0.type == VR_ANTI_RANGE
3113 && vr0.min == op1
3114 && vr0.min == vr0.max)
3115 || (vr1.type == VR_ANTI_RANGE
3116 && vr1.min == op0
3117 && vr1.min == vr1.max)))
3118 set_value_range_to_nonnull (vr, TREE_TYPE (op0));
3121 /* Extract range information from a unary operation CODE based on
3122 the range of its operand *VR0 with type OP0_TYPE with resulting type TYPE.
3123 The resulting range is stored in *VR. */
3125 void
3126 extract_range_from_unary_expr (value_range *vr,
3127 enum tree_code code, tree type,
3128 value_range *vr0_, tree op0_type)
3130 value_range vr0 = *vr0_, vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
3132 /* VRP only operates on integral and pointer types. */
3133 if (!(INTEGRAL_TYPE_P (op0_type)
3134 || POINTER_TYPE_P (op0_type))
3135 || !(INTEGRAL_TYPE_P (type)
3136 || POINTER_TYPE_P (type)))
3138 set_value_range_to_varying (vr);
3139 return;
3142 /* If VR0 is UNDEFINED, so is the result. */
3143 if (vr0.type == VR_UNDEFINED)
3145 set_value_range_to_undefined (vr);
3146 return;
3149 /* Handle operations that we express in terms of others. */
3150 if (code == PAREN_EXPR || code == OBJ_TYPE_REF)
3152 /* PAREN_EXPR and OBJ_TYPE_REF are simple copies. */
3153 copy_value_range (vr, &vr0);
3154 return;
3156 else if (code == NEGATE_EXPR)
3158 /* -X is simply 0 - X, so re-use existing code that also handles
3159 anti-ranges fine. */
3160 value_range zero = VR_INITIALIZER;
3161 set_value_range_to_value (&zero, build_int_cst (type, 0), NULL);
3162 extract_range_from_binary_expr_1 (vr, MINUS_EXPR, type, &zero, &vr0);
3163 return;
3165 else if (code == BIT_NOT_EXPR)
3167 /* ~X is simply -1 - X, so re-use existing code that also handles
3168 anti-ranges fine. */
3169 value_range minusone = VR_INITIALIZER;
3170 set_value_range_to_value (&minusone, build_int_cst (type, -1), NULL);
3171 extract_range_from_binary_expr_1 (vr, MINUS_EXPR,
3172 type, &minusone, &vr0);
3173 return;
3176 /* Now canonicalize anti-ranges to ranges when they are not symbolic
3177 and express op ~[] as (op []') U (op []''). */
3178 if (vr0.type == VR_ANTI_RANGE
3179 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
3181 extract_range_from_unary_expr (vr, code, type, &vrtem0, op0_type);
3182 if (vrtem1.type != VR_UNDEFINED)
3184 value_range vrres = VR_INITIALIZER;
3185 extract_range_from_unary_expr (&vrres, code, type,
3186 &vrtem1, op0_type);
3187 vrp_meet (vr, &vrres);
3189 return;
3192 if (CONVERT_EXPR_CODE_P (code))
3194 tree inner_type = op0_type;
3195 tree outer_type = type;
3197 /* If the expression evaluates to a pointer, we are only interested in
3198 determining if it evaluates to NULL [0, 0] or non-NULL (~[0, 0]). */
3199 if (POINTER_TYPE_P (type))
3201 if (range_is_nonnull (&vr0))
3202 set_value_range_to_nonnull (vr, type);
3203 else if (range_is_null (&vr0))
3204 set_value_range_to_null (vr, type);
3205 else
3206 set_value_range_to_varying (vr);
3207 return;
3210 /* If VR0 is varying and we increase the type precision, assume
3211 a full range for the following transformation. */
3212 if (vr0.type == VR_VARYING
3213 && INTEGRAL_TYPE_P (inner_type)
3214 && TYPE_PRECISION (inner_type) < TYPE_PRECISION (outer_type))
3216 vr0.type = VR_RANGE;
3217 vr0.min = TYPE_MIN_VALUE (inner_type);
3218 vr0.max = TYPE_MAX_VALUE (inner_type);
3221 /* If VR0 is a constant range or anti-range and the conversion is
3222 not truncating we can convert the min and max values and
3223 canonicalize the resulting range. Otherwise we can do the
3224 conversion if the size of the range is less than what the
3225 precision of the target type can represent and the range is
3226 not an anti-range. */
3227 if ((vr0.type == VR_RANGE
3228 || vr0.type == VR_ANTI_RANGE)
3229 && TREE_CODE (vr0.min) == INTEGER_CST
3230 && TREE_CODE (vr0.max) == INTEGER_CST
3231 && (TYPE_PRECISION (outer_type) >= TYPE_PRECISION (inner_type)
3232 || (vr0.type == VR_RANGE
3233 && integer_zerop (int_const_binop (RSHIFT_EXPR,
3234 int_const_binop (MINUS_EXPR, vr0.max, vr0.min),
3235 size_int (TYPE_PRECISION (outer_type)))))))
3237 tree new_min, new_max;
3238 new_min = force_fit_type (outer_type, wi::to_widest (vr0.min),
3239 0, false);
3240 new_max = force_fit_type (outer_type, wi::to_widest (vr0.max),
3241 0, false);
3242 set_and_canonicalize_value_range (vr, vr0.type,
3243 new_min, new_max, NULL);
3244 return;
3247 set_value_range_to_varying (vr);
3248 return;
3250 else if (code == ABS_EXPR)
3252 tree min, max;
3253 int cmp;
3255 /* Pass through vr0 in the easy cases. */
3256 if (TYPE_UNSIGNED (type)
3257 || value_range_nonnegative_p (&vr0))
3259 copy_value_range (vr, &vr0);
3260 return;
3263 /* For the remaining varying or symbolic ranges we can't do anything
3264 useful. */
3265 if (vr0.type == VR_VARYING
3266 || symbolic_range_p (&vr0))
3268 set_value_range_to_varying (vr);
3269 return;
3272 /* -TYPE_MIN_VALUE = TYPE_MIN_VALUE with flag_wrapv so we can't get a
3273 useful range. */
3274 if (!TYPE_OVERFLOW_UNDEFINED (type)
3275 && ((vr0.type == VR_RANGE
3276 && vrp_val_is_min (vr0.min))
3277 || (vr0.type == VR_ANTI_RANGE
3278 && !vrp_val_is_min (vr0.min))))
3280 set_value_range_to_varying (vr);
3281 return;
3284 /* ABS_EXPR may flip the range around, if the original range
3285 included negative values. */
3286 if (!vrp_val_is_min (vr0.min))
3287 min = fold_unary_to_constant (code, type, vr0.min);
3288 else
3289 min = TYPE_MAX_VALUE (type);
3291 if (!vrp_val_is_min (vr0.max))
3292 max = fold_unary_to_constant (code, type, vr0.max);
3293 else
3294 max = TYPE_MAX_VALUE (type);
3296 cmp = compare_values (min, max);
3298 /* If a VR_ANTI_RANGEs contains zero, then we have
3299 ~[-INF, min(MIN, MAX)]. */
3300 if (vr0.type == VR_ANTI_RANGE)
3302 if (range_includes_zero_p (vr0.min, vr0.max) == 1)
3304 /* Take the lower of the two values. */
3305 if (cmp != 1)
3306 max = min;
3308 /* Create ~[-INF, min (abs(MIN), abs(MAX))]
3309 or ~[-INF + 1, min (abs(MIN), abs(MAX))] when
3310 flag_wrapv is set and the original anti-range doesn't include
3311 TYPE_MIN_VALUE, remember -TYPE_MIN_VALUE = TYPE_MIN_VALUE. */
3312 if (TYPE_OVERFLOW_WRAPS (type))
3314 tree type_min_value = TYPE_MIN_VALUE (type);
3316 min = (vr0.min != type_min_value
3317 ? int_const_binop (PLUS_EXPR, type_min_value,
3318 build_int_cst (TREE_TYPE (type_min_value), 1))
3319 : type_min_value);
3321 else
3322 min = TYPE_MIN_VALUE (type);
3324 else
3326 /* All else has failed, so create the range [0, INF], even for
3327 flag_wrapv since TYPE_MIN_VALUE is in the original
3328 anti-range. */
3329 vr0.type = VR_RANGE;
3330 min = build_int_cst (type, 0);
3331 max = TYPE_MAX_VALUE (type);
3335 /* If the range contains zero then we know that the minimum value in the
3336 range will be zero. */
3337 else if (range_includes_zero_p (vr0.min, vr0.max) == 1)
3339 if (cmp == 1)
3340 max = min;
3341 min = build_int_cst (type, 0);
3343 else
3345 /* If the range was reversed, swap MIN and MAX. */
3346 if (cmp == 1)
3347 std::swap (min, max);
3350 cmp = compare_values (min, max);
3351 if (cmp == -2 || cmp == 1)
3353 /* If the new range has its limits swapped around (MIN > MAX),
3354 then the operation caused one of them to wrap around, mark
3355 the new range VARYING. */
3356 set_value_range_to_varying (vr);
3358 else
3359 set_value_range (vr, vr0.type, min, max, NULL);
3360 return;
3363 /* For unhandled operations fall back to varying. */
3364 set_value_range_to_varying (vr);
3365 return;
3369 /* Extract range information from a unary expression CODE OP0 based on
3370 the range of its operand with resulting type TYPE.
3371 The resulting range is stored in *VR. */
3373 static void
3374 extract_range_from_unary_expr (value_range *vr, enum tree_code code,
3375 tree type, tree op0)
3377 value_range vr0 = VR_INITIALIZER;
3379 /* Get value ranges for the operand. For constant operands, create
3380 a new value range with the operand to simplify processing. */
3381 if (TREE_CODE (op0) == SSA_NAME)
3382 vr0 = *(get_value_range (op0));
3383 else if (is_gimple_min_invariant (op0))
3384 set_value_range_to_value (&vr0, op0, NULL);
3385 else
3386 set_value_range_to_varying (&vr0);
3388 extract_range_from_unary_expr (vr, code, type, &vr0, TREE_TYPE (op0));
3392 /* Extract range information from a conditional expression STMT based on
3393 the ranges of each of its operands and the expression code. */
3395 static void
3396 extract_range_from_cond_expr (value_range *vr, gassign *stmt)
3398 tree op0, op1;
3399 value_range vr0 = VR_INITIALIZER;
3400 value_range vr1 = VR_INITIALIZER;
3402 /* Get value ranges for each operand. For constant operands, create
3403 a new value range with the operand to simplify processing. */
3404 op0 = gimple_assign_rhs2 (stmt);
3405 if (TREE_CODE (op0) == SSA_NAME)
3406 vr0 = *(get_value_range (op0));
3407 else if (is_gimple_min_invariant (op0))
3408 set_value_range_to_value (&vr0, op0, NULL);
3409 else
3410 set_value_range_to_varying (&vr0);
3412 op1 = gimple_assign_rhs3 (stmt);
3413 if (TREE_CODE (op1) == SSA_NAME)
3414 vr1 = *(get_value_range (op1));
3415 else if (is_gimple_min_invariant (op1))
3416 set_value_range_to_value (&vr1, op1, NULL);
3417 else
3418 set_value_range_to_varying (&vr1);
3420 /* The resulting value range is the union of the operand ranges */
3421 copy_value_range (vr, &vr0);
3422 vrp_meet (vr, &vr1);
3426 /* Extract range information from a comparison expression EXPR based
3427 on the range of its operand and the expression code. */
3429 static void
3430 extract_range_from_comparison (value_range *vr, enum tree_code code,
3431 tree type, tree op0, tree op1)
3433 bool sop;
3434 tree val;
3436 val = vrp_evaluate_conditional_warnv_with_ops (code, op0, op1, false, &sop,
3437 NULL);
3438 if (val)
3440 /* Since this expression was found on the RHS of an assignment,
3441 its type may be different from _Bool. Convert VAL to EXPR's
3442 type. */
3443 val = fold_convert (type, val);
3444 if (is_gimple_min_invariant (val))
3445 set_value_range_to_value (vr, val, vr->equiv);
3446 else
3447 set_value_range (vr, VR_RANGE, val, val, vr->equiv);
3449 else
3450 /* The result of a comparison is always true or false. */
3451 set_value_range_to_truthvalue (vr, type);
3454 /* Helper function for simplify_internal_call_using_ranges and
3455 extract_range_basic. Return true if OP0 SUBCODE OP1 for
3456 SUBCODE {PLUS,MINUS,MULT}_EXPR is known to never overflow or
3457 always overflow. Set *OVF to true if it is known to always
3458 overflow. */
3460 static bool
3461 check_for_binary_op_overflow (enum tree_code subcode, tree type,
3462 tree op0, tree op1, bool *ovf)
3464 value_range vr0 = VR_INITIALIZER;
3465 value_range vr1 = VR_INITIALIZER;
3466 if (TREE_CODE (op0) == SSA_NAME)
3467 vr0 = *get_value_range (op0);
3468 else if (TREE_CODE (op0) == INTEGER_CST)
3469 set_value_range_to_value (&vr0, op0, NULL);
3470 else
3471 set_value_range_to_varying (&vr0);
3473 if (TREE_CODE (op1) == SSA_NAME)
3474 vr1 = *get_value_range (op1);
3475 else if (TREE_CODE (op1) == INTEGER_CST)
3476 set_value_range_to_value (&vr1, op1, NULL);
3477 else
3478 set_value_range_to_varying (&vr1);
3480 if (!range_int_cst_p (&vr0)
3481 || TREE_OVERFLOW (vr0.min)
3482 || TREE_OVERFLOW (vr0.max))
3484 vr0.min = vrp_val_min (TREE_TYPE (op0));
3485 vr0.max = vrp_val_max (TREE_TYPE (op0));
3487 if (!range_int_cst_p (&vr1)
3488 || TREE_OVERFLOW (vr1.min)
3489 || TREE_OVERFLOW (vr1.max))
3491 vr1.min = vrp_val_min (TREE_TYPE (op1));
3492 vr1.max = vrp_val_max (TREE_TYPE (op1));
3494 *ovf = arith_overflowed_p (subcode, type, vr0.min,
3495 subcode == MINUS_EXPR ? vr1.max : vr1.min);
3496 if (arith_overflowed_p (subcode, type, vr0.max,
3497 subcode == MINUS_EXPR ? vr1.min : vr1.max) != *ovf)
3498 return false;
3499 if (subcode == MULT_EXPR)
3501 if (arith_overflowed_p (subcode, type, vr0.min, vr1.max) != *ovf
3502 || arith_overflowed_p (subcode, type, vr0.max, vr1.min) != *ovf)
3503 return false;
3505 if (*ovf)
3507 /* So far we found that there is an overflow on the boundaries.
3508 That doesn't prove that there is an overflow even for all values
3509 in between the boundaries. For that compute widest_int range
3510 of the result and see if it doesn't overlap the range of
3511 type. */
3512 widest_int wmin, wmax;
3513 widest_int w[4];
3514 int i;
3515 w[0] = wi::to_widest (vr0.min);
3516 w[1] = wi::to_widest (vr0.max);
3517 w[2] = wi::to_widest (vr1.min);
3518 w[3] = wi::to_widest (vr1.max);
3519 for (i = 0; i < 4; i++)
3521 widest_int wt;
3522 switch (subcode)
3524 case PLUS_EXPR:
3525 wt = wi::add (w[i & 1], w[2 + (i & 2) / 2]);
3526 break;
3527 case MINUS_EXPR:
3528 wt = wi::sub (w[i & 1], w[2 + (i & 2) / 2]);
3529 break;
3530 case MULT_EXPR:
3531 wt = wi::mul (w[i & 1], w[2 + (i & 2) / 2]);
3532 break;
3533 default:
3534 gcc_unreachable ();
3536 if (i == 0)
3538 wmin = wt;
3539 wmax = wt;
3541 else
3543 wmin = wi::smin (wmin, wt);
3544 wmax = wi::smax (wmax, wt);
3547 /* The result of op0 CODE op1 is known to be in range
3548 [wmin, wmax]. */
3549 widest_int wtmin = wi::to_widest (vrp_val_min (type));
3550 widest_int wtmax = wi::to_widest (vrp_val_max (type));
3551 /* If all values in [wmin, wmax] are smaller than
3552 [wtmin, wtmax] or all are larger than [wtmin, wtmax],
3553 the arithmetic operation will always overflow. */
3554 if (wmax < wtmin || wmin > wtmax)
3555 return true;
3556 return false;
3558 return true;
3561 /* Try to derive a nonnegative or nonzero range out of STMT relying
3562 primarily on generic routines in fold in conjunction with range data.
3563 Store the result in *VR */
3565 static void
3566 extract_range_basic (value_range *vr, gimple *stmt)
3568 bool sop;
3569 tree type = gimple_expr_type (stmt);
3571 if (is_gimple_call (stmt))
3573 tree arg;
3574 int mini, maxi, zerov = 0, prec;
3575 enum tree_code subcode = ERROR_MARK;
3576 combined_fn cfn = gimple_call_combined_fn (stmt);
3577 scalar_int_mode mode;
3579 switch (cfn)
3581 case CFN_BUILT_IN_CONSTANT_P:
3582 /* If the call is __builtin_constant_p and the argument is a
3583 function parameter resolve it to false. This avoids bogus
3584 array bound warnings.
3585 ??? We could do this as early as inlining is finished. */
3586 arg = gimple_call_arg (stmt, 0);
3587 if (TREE_CODE (arg) == SSA_NAME
3588 && SSA_NAME_IS_DEFAULT_DEF (arg)
3589 && TREE_CODE (SSA_NAME_VAR (arg)) == PARM_DECL
3590 && cfun->after_inlining)
3592 set_value_range_to_null (vr, type);
3593 return;
3595 break;
3596 /* Both __builtin_ffs* and __builtin_popcount return
3597 [0, prec]. */
3598 CASE_CFN_FFS:
3599 CASE_CFN_POPCOUNT:
3600 arg = gimple_call_arg (stmt, 0);
3601 prec = TYPE_PRECISION (TREE_TYPE (arg));
3602 mini = 0;
3603 maxi = prec;
3604 if (TREE_CODE (arg) == SSA_NAME)
3606 value_range *vr0 = get_value_range (arg);
3607 /* If arg is non-zero, then ffs or popcount
3608 are non-zero. */
3609 if ((vr0->type == VR_RANGE
3610 && range_includes_zero_p (vr0->min, vr0->max) == 0)
3611 || (vr0->type == VR_ANTI_RANGE
3612 && range_includes_zero_p (vr0->min, vr0->max) == 1))
3613 mini = 1;
3614 /* If some high bits are known to be zero,
3615 we can decrease the maximum. */
3616 if (vr0->type == VR_RANGE
3617 && TREE_CODE (vr0->max) == INTEGER_CST
3618 && !operand_less_p (vr0->min,
3619 build_zero_cst (TREE_TYPE (vr0->min))))
3620 maxi = tree_floor_log2 (vr0->max) + 1;
3622 goto bitop_builtin;
3623 /* __builtin_parity* returns [0, 1]. */
3624 CASE_CFN_PARITY:
3625 mini = 0;
3626 maxi = 1;
3627 goto bitop_builtin;
3628 /* __builtin_c[lt]z* return [0, prec-1], except for
3629 when the argument is 0, but that is undefined behavior.
3630 On many targets where the CLZ RTL or optab value is defined
3631 for 0 the value is prec, so include that in the range
3632 by default. */
3633 CASE_CFN_CLZ:
3634 arg = gimple_call_arg (stmt, 0);
3635 prec = TYPE_PRECISION (TREE_TYPE (arg));
3636 mini = 0;
3637 maxi = prec;
3638 mode = SCALAR_INT_TYPE_MODE (TREE_TYPE (arg));
3639 if (optab_handler (clz_optab, mode) != CODE_FOR_nothing
3640 && CLZ_DEFINED_VALUE_AT_ZERO (mode, zerov)
3641 /* Handle only the single common value. */
3642 && zerov != prec)
3643 /* Magic value to give up, unless vr0 proves
3644 arg is non-zero. */
3645 mini = -2;
3646 if (TREE_CODE (arg) == SSA_NAME)
3648 value_range *vr0 = get_value_range (arg);
3649 /* From clz of VR_RANGE minimum we can compute
3650 result maximum. */
3651 if (vr0->type == VR_RANGE
3652 && TREE_CODE (vr0->min) == INTEGER_CST)
3654 maxi = prec - 1 - tree_floor_log2 (vr0->min);
3655 if (maxi != prec)
3656 mini = 0;
3658 else if (vr0->type == VR_ANTI_RANGE
3659 && integer_zerop (vr0->min))
3661 maxi = prec - 1;
3662 mini = 0;
3664 if (mini == -2)
3665 break;
3666 /* From clz of VR_RANGE maximum we can compute
3667 result minimum. */
3668 if (vr0->type == VR_RANGE
3669 && TREE_CODE (vr0->max) == INTEGER_CST)
3671 mini = prec - 1 - tree_floor_log2 (vr0->max);
3672 if (mini == prec)
3673 break;
3676 if (mini == -2)
3677 break;
3678 goto bitop_builtin;
3679 /* __builtin_ctz* return [0, prec-1], except for
3680 when the argument is 0, but that is undefined behavior.
3681 If there is a ctz optab for this mode and
3682 CTZ_DEFINED_VALUE_AT_ZERO, include that in the range,
3683 otherwise just assume 0 won't be seen. */
3684 CASE_CFN_CTZ:
3685 arg = gimple_call_arg (stmt, 0);
3686 prec = TYPE_PRECISION (TREE_TYPE (arg));
3687 mini = 0;
3688 maxi = prec - 1;
3689 mode = SCALAR_INT_TYPE_MODE (TREE_TYPE (arg));
3690 if (optab_handler (ctz_optab, mode) != CODE_FOR_nothing
3691 && CTZ_DEFINED_VALUE_AT_ZERO (mode, zerov))
3693 /* Handle only the two common values. */
3694 if (zerov == -1)
3695 mini = -1;
3696 else if (zerov == prec)
3697 maxi = prec;
3698 else
3699 /* Magic value to give up, unless vr0 proves
3700 arg is non-zero. */
3701 mini = -2;
3703 if (TREE_CODE (arg) == SSA_NAME)
3705 value_range *vr0 = get_value_range (arg);
3706 /* If arg is non-zero, then use [0, prec - 1]. */
3707 if ((vr0->type == VR_RANGE
3708 && integer_nonzerop (vr0->min))
3709 || (vr0->type == VR_ANTI_RANGE
3710 && integer_zerop (vr0->min)))
3712 mini = 0;
3713 maxi = prec - 1;
3715 /* If some high bits are known to be zero,
3716 we can decrease the result maximum. */
3717 if (vr0->type == VR_RANGE
3718 && TREE_CODE (vr0->max) == INTEGER_CST)
3720 maxi = tree_floor_log2 (vr0->max);
3721 /* For vr0 [0, 0] give up. */
3722 if (maxi == -1)
3723 break;
3726 if (mini == -2)
3727 break;
3728 goto bitop_builtin;
3729 /* __builtin_clrsb* returns [0, prec-1]. */
3730 CASE_CFN_CLRSB:
3731 arg = gimple_call_arg (stmt, 0);
3732 prec = TYPE_PRECISION (TREE_TYPE (arg));
3733 mini = 0;
3734 maxi = prec - 1;
3735 goto bitop_builtin;
3736 bitop_builtin:
3737 set_value_range (vr, VR_RANGE, build_int_cst (type, mini),
3738 build_int_cst (type, maxi), NULL);
3739 return;
3740 case CFN_UBSAN_CHECK_ADD:
3741 subcode = PLUS_EXPR;
3742 break;
3743 case CFN_UBSAN_CHECK_SUB:
3744 subcode = MINUS_EXPR;
3745 break;
3746 case CFN_UBSAN_CHECK_MUL:
3747 subcode = MULT_EXPR;
3748 break;
3749 case CFN_GOACC_DIM_SIZE:
3750 case CFN_GOACC_DIM_POS:
3751 /* Optimizing these two internal functions helps the loop
3752 optimizer eliminate outer comparisons. Size is [1,N]
3753 and pos is [0,N-1]. */
3755 bool is_pos = cfn == CFN_GOACC_DIM_POS;
3756 int axis = oacc_get_ifn_dim_arg (stmt);
3757 int size = oacc_get_fn_dim_size (current_function_decl, axis);
3759 if (!size)
3760 /* If it's dynamic, the backend might know a hardware
3761 limitation. */
3762 size = targetm.goacc.dim_limit (axis);
3764 tree type = TREE_TYPE (gimple_call_lhs (stmt));
3765 set_value_range (vr, VR_RANGE,
3766 build_int_cst (type, is_pos ? 0 : 1),
3767 size ? build_int_cst (type, size - is_pos)
3768 : vrp_val_max (type), NULL);
3770 return;
3771 case CFN_BUILT_IN_STRLEN:
3772 if (tree lhs = gimple_call_lhs (stmt))
3773 if (ptrdiff_type_node
3774 && (TYPE_PRECISION (ptrdiff_type_node)
3775 == TYPE_PRECISION (TREE_TYPE (lhs))))
3777 tree type = TREE_TYPE (lhs);
3778 tree max = vrp_val_max (ptrdiff_type_node);
3779 wide_int wmax = wi::to_wide (max, TYPE_PRECISION (TREE_TYPE (max)));
3780 tree range_min = build_zero_cst (type);
3781 tree range_max = wide_int_to_tree (type, wmax - 1);
3782 set_value_range (vr, VR_RANGE, range_min, range_max, NULL);
3783 return;
3785 break;
3786 default:
3787 break;
3789 if (subcode != ERROR_MARK)
3791 bool saved_flag_wrapv = flag_wrapv;
3792 /* Pretend the arithmetics is wrapping. If there is
3793 any overflow, we'll complain, but will actually do
3794 wrapping operation. */
3795 flag_wrapv = 1;
3796 extract_range_from_binary_expr (vr, subcode, type,
3797 gimple_call_arg (stmt, 0),
3798 gimple_call_arg (stmt, 1));
3799 flag_wrapv = saved_flag_wrapv;
3801 /* If for both arguments vrp_valueize returned non-NULL,
3802 this should have been already folded and if not, it
3803 wasn't folded because of overflow. Avoid removing the
3804 UBSAN_CHECK_* calls in that case. */
3805 if (vr->type == VR_RANGE
3806 && (vr->min == vr->max
3807 || operand_equal_p (vr->min, vr->max, 0)))
3808 set_value_range_to_varying (vr);
3809 return;
3812 /* Handle extraction of the two results (result of arithmetics and
3813 a flag whether arithmetics overflowed) from {ADD,SUB,MUL}_OVERFLOW
3814 internal function. Similarly from ATOMIC_COMPARE_EXCHANGE. */
3815 else if (is_gimple_assign (stmt)
3816 && (gimple_assign_rhs_code (stmt) == REALPART_EXPR
3817 || gimple_assign_rhs_code (stmt) == IMAGPART_EXPR)
3818 && INTEGRAL_TYPE_P (type))
3820 enum tree_code code = gimple_assign_rhs_code (stmt);
3821 tree op = gimple_assign_rhs1 (stmt);
3822 if (TREE_CODE (op) == code && TREE_CODE (TREE_OPERAND (op, 0)) == SSA_NAME)
3824 gimple *g = SSA_NAME_DEF_STMT (TREE_OPERAND (op, 0));
3825 if (is_gimple_call (g) && gimple_call_internal_p (g))
3827 enum tree_code subcode = ERROR_MARK;
3828 switch (gimple_call_internal_fn (g))
3830 case IFN_ADD_OVERFLOW:
3831 subcode = PLUS_EXPR;
3832 break;
3833 case IFN_SUB_OVERFLOW:
3834 subcode = MINUS_EXPR;
3835 break;
3836 case IFN_MUL_OVERFLOW:
3837 subcode = MULT_EXPR;
3838 break;
3839 case IFN_ATOMIC_COMPARE_EXCHANGE:
3840 if (code == IMAGPART_EXPR)
3842 /* This is the boolean return value whether compare and
3843 exchange changed anything or not. */
3844 set_value_range (vr, VR_RANGE, build_int_cst (type, 0),
3845 build_int_cst (type, 1), NULL);
3846 return;
3848 break;
3849 default:
3850 break;
3852 if (subcode != ERROR_MARK)
3854 tree op0 = gimple_call_arg (g, 0);
3855 tree op1 = gimple_call_arg (g, 1);
3856 if (code == IMAGPART_EXPR)
3858 bool ovf = false;
3859 if (check_for_binary_op_overflow (subcode, type,
3860 op0, op1, &ovf))
3861 set_value_range_to_value (vr,
3862 build_int_cst (type, ovf),
3863 NULL);
3864 else if (TYPE_PRECISION (type) == 1
3865 && !TYPE_UNSIGNED (type))
3866 set_value_range_to_varying (vr);
3867 else
3868 set_value_range (vr, VR_RANGE, build_int_cst (type, 0),
3869 build_int_cst (type, 1), NULL);
3871 else if (types_compatible_p (type, TREE_TYPE (op0))
3872 && types_compatible_p (type, TREE_TYPE (op1)))
3874 bool saved_flag_wrapv = flag_wrapv;
3875 /* Pretend the arithmetics is wrapping. If there is
3876 any overflow, IMAGPART_EXPR will be set. */
3877 flag_wrapv = 1;
3878 extract_range_from_binary_expr (vr, subcode, type,
3879 op0, op1);
3880 flag_wrapv = saved_flag_wrapv;
3882 else
3884 value_range vr0 = VR_INITIALIZER;
3885 value_range vr1 = VR_INITIALIZER;
3886 bool saved_flag_wrapv = flag_wrapv;
3887 /* Pretend the arithmetics is wrapping. If there is
3888 any overflow, IMAGPART_EXPR will be set. */
3889 flag_wrapv = 1;
3890 extract_range_from_unary_expr (&vr0, NOP_EXPR,
3891 type, op0);
3892 extract_range_from_unary_expr (&vr1, NOP_EXPR,
3893 type, op1);
3894 extract_range_from_binary_expr_1 (vr, subcode, type,
3895 &vr0, &vr1);
3896 flag_wrapv = saved_flag_wrapv;
3898 return;
3903 if (INTEGRAL_TYPE_P (type)
3904 && gimple_stmt_nonnegative_warnv_p (stmt, &sop))
3905 set_value_range_to_nonnegative (vr, type);
3906 else if (vrp_stmt_computes_nonzero (stmt))
3907 set_value_range_to_nonnull (vr, type);
3908 else
3909 set_value_range_to_varying (vr);
3913 /* Try to compute a useful range out of assignment STMT and store it
3914 in *VR. */
3916 static void
3917 extract_range_from_assignment (value_range *vr, gassign *stmt)
3919 enum tree_code code = gimple_assign_rhs_code (stmt);
3921 if (code == ASSERT_EXPR)
3922 extract_range_from_assert (vr, gimple_assign_rhs1 (stmt));
3923 else if (code == SSA_NAME)
3924 extract_range_from_ssa_name (vr, gimple_assign_rhs1 (stmt));
3925 else if (TREE_CODE_CLASS (code) == tcc_binary)
3926 extract_range_from_binary_expr (vr, gimple_assign_rhs_code (stmt),
3927 gimple_expr_type (stmt),
3928 gimple_assign_rhs1 (stmt),
3929 gimple_assign_rhs2 (stmt));
3930 else if (TREE_CODE_CLASS (code) == tcc_unary)
3931 extract_range_from_unary_expr (vr, gimple_assign_rhs_code (stmt),
3932 gimple_expr_type (stmt),
3933 gimple_assign_rhs1 (stmt));
3934 else if (code == COND_EXPR)
3935 extract_range_from_cond_expr (vr, stmt);
3936 else if (TREE_CODE_CLASS (code) == tcc_comparison)
3937 extract_range_from_comparison (vr, gimple_assign_rhs_code (stmt),
3938 gimple_expr_type (stmt),
3939 gimple_assign_rhs1 (stmt),
3940 gimple_assign_rhs2 (stmt));
3941 else if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS
3942 && is_gimple_min_invariant (gimple_assign_rhs1 (stmt)))
3943 set_value_range_to_value (vr, gimple_assign_rhs1 (stmt), NULL);
3944 else
3945 set_value_range_to_varying (vr);
3947 if (vr->type == VR_VARYING)
3948 extract_range_basic (vr, stmt);
3951 /* Given a range VR, a LOOP and a variable VAR, determine whether it
3952 would be profitable to adjust VR using scalar evolution information
3953 for VAR. If so, update VR with the new limits. */
3955 static void
3956 adjust_range_with_scev (value_range *vr, struct loop *loop,
3957 gimple *stmt, tree var)
3959 tree init, step, chrec, tmin, tmax, min, max, type, tem;
3960 enum ev_direction dir;
3962 /* TODO. Don't adjust anti-ranges. An anti-range may provide
3963 better opportunities than a regular range, but I'm not sure. */
3964 if (vr->type == VR_ANTI_RANGE)
3965 return;
3967 chrec = instantiate_parameters (loop, analyze_scalar_evolution (loop, var));
3969 /* Like in PR19590, scev can return a constant function. */
3970 if (is_gimple_min_invariant (chrec))
3972 set_value_range_to_value (vr, chrec, vr->equiv);
3973 return;
3976 if (TREE_CODE (chrec) != POLYNOMIAL_CHREC)
3977 return;
3979 init = initial_condition_in_loop_num (chrec, loop->num);
3980 tem = op_with_constant_singleton_value_range (init);
3981 if (tem)
3982 init = tem;
3983 step = evolution_part_in_loop_num (chrec, loop->num);
3984 tem = op_with_constant_singleton_value_range (step);
3985 if (tem)
3986 step = tem;
3988 /* If STEP is symbolic, we can't know whether INIT will be the
3989 minimum or maximum value in the range. Also, unless INIT is
3990 a simple expression, compare_values and possibly other functions
3991 in tree-vrp won't be able to handle it. */
3992 if (step == NULL_TREE
3993 || !is_gimple_min_invariant (step)
3994 || !valid_value_p (init))
3995 return;
3997 dir = scev_direction (chrec);
3998 if (/* Do not adjust ranges if we do not know whether the iv increases
3999 or decreases, ... */
4000 dir == EV_DIR_UNKNOWN
4001 /* ... or if it may wrap. */
4002 || scev_probably_wraps_p (NULL_TREE, init, step, stmt,
4003 get_chrec_loop (chrec), true))
4004 return;
4006 type = TREE_TYPE (var);
4007 if (POINTER_TYPE_P (type) || !TYPE_MIN_VALUE (type))
4008 tmin = lower_bound_in_type (type, type);
4009 else
4010 tmin = TYPE_MIN_VALUE (type);
4011 if (POINTER_TYPE_P (type) || !TYPE_MAX_VALUE (type))
4012 tmax = upper_bound_in_type (type, type);
4013 else
4014 tmax = TYPE_MAX_VALUE (type);
4016 /* Try to use estimated number of iterations for the loop to constrain the
4017 final value in the evolution. */
4018 if (TREE_CODE (step) == INTEGER_CST
4019 && is_gimple_val (init)
4020 && (TREE_CODE (init) != SSA_NAME
4021 || get_value_range (init)->type == VR_RANGE))
4023 widest_int nit;
4025 /* We are only entering here for loop header PHI nodes, so using
4026 the number of latch executions is the correct thing to use. */
4027 if (max_loop_iterations (loop, &nit))
4029 value_range maxvr = VR_INITIALIZER;
4030 signop sgn = TYPE_SIGN (TREE_TYPE (step));
4031 bool overflow;
4033 widest_int wtmp = wi::mul (wi::to_widest (step), nit, sgn,
4034 &overflow);
4035 /* If the multiplication overflowed we can't do a meaningful
4036 adjustment. Likewise if the result doesn't fit in the type
4037 of the induction variable. For a signed type we have to
4038 check whether the result has the expected signedness which
4039 is that of the step as number of iterations is unsigned. */
4040 if (!overflow
4041 && wi::fits_to_tree_p (wtmp, TREE_TYPE (init))
4042 && (sgn == UNSIGNED
4043 || wi::gts_p (wtmp, 0) == wi::gts_p (step, 0)))
4045 tem = wide_int_to_tree (TREE_TYPE (init), wtmp);
4046 extract_range_from_binary_expr (&maxvr, PLUS_EXPR,
4047 TREE_TYPE (init), init, tem);
4048 /* Likewise if the addition did. */
4049 if (maxvr.type == VR_RANGE)
4051 value_range initvr = VR_INITIALIZER;
4053 if (TREE_CODE (init) == SSA_NAME)
4054 initvr = *(get_value_range (init));
4055 else if (is_gimple_min_invariant (init))
4056 set_value_range_to_value (&initvr, init, NULL);
4057 else
4058 return;
4060 /* Check if init + nit * step overflows. Though we checked
4061 scev {init, step}_loop doesn't wrap, it is not enough
4062 because the loop may exit immediately. Overflow could
4063 happen in the plus expression in this case. */
4064 if ((dir == EV_DIR_DECREASES
4065 && compare_values (maxvr.min, initvr.min) != -1)
4066 || (dir == EV_DIR_GROWS
4067 && compare_values (maxvr.max, initvr.max) != 1))
4068 return;
4070 tmin = maxvr.min;
4071 tmax = maxvr.max;
4077 if (vr->type == VR_VARYING || vr->type == VR_UNDEFINED)
4079 min = tmin;
4080 max = tmax;
4082 /* For VARYING or UNDEFINED ranges, just about anything we get
4083 from scalar evolutions should be better. */
4085 if (dir == EV_DIR_DECREASES)
4086 max = init;
4087 else
4088 min = init;
4090 else if (vr->type == VR_RANGE)
4092 min = vr->min;
4093 max = vr->max;
4095 if (dir == EV_DIR_DECREASES)
4097 /* INIT is the maximum value. If INIT is lower than VR->MAX
4098 but no smaller than VR->MIN, set VR->MAX to INIT. */
4099 if (compare_values (init, max) == -1)
4100 max = init;
4102 /* According to the loop information, the variable does not
4103 overflow. */
4104 if (compare_values (min, tmin) == -1)
4105 min = tmin;
4108 else
4110 /* If INIT is bigger than VR->MIN, set VR->MIN to INIT. */
4111 if (compare_values (init, min) == 1)
4112 min = init;
4114 if (compare_values (tmax, max) == -1)
4115 max = tmax;
4118 else
4119 return;
4121 /* If we just created an invalid range with the minimum
4122 greater than the maximum, we fail conservatively.
4123 This should happen only in unreachable
4124 parts of code, or for invalid programs. */
4125 if (compare_values (min, max) == 1)
4126 return;
4128 /* Even for valid range info, sometimes overflow flag will leak in.
4129 As GIMPLE IL should have no constants with TREE_OVERFLOW set, we
4130 drop them. */
4131 if (TREE_OVERFLOW_P (min))
4132 min = drop_tree_overflow (min);
4133 if (TREE_OVERFLOW_P (max))
4134 max = drop_tree_overflow (max);
4136 set_value_range (vr, VR_RANGE, min, max, vr->equiv);
4140 /* Given two numeric value ranges VR0, VR1 and a comparison code COMP:
4142 - Return BOOLEAN_TRUE_NODE if VR0 COMP VR1 always returns true for
4143 all the values in the ranges.
4145 - Return BOOLEAN_FALSE_NODE if the comparison always returns false.
4147 - Return NULL_TREE if it is not always possible to determine the
4148 value of the comparison.
4150 Also set *STRICT_OVERFLOW_P to indicate whether comparision evaluation
4151 assumed signed overflow is undefined. */
4154 static tree
4155 compare_ranges (enum tree_code comp, value_range *vr0, value_range *vr1,
4156 bool *strict_overflow_p)
4158 /* VARYING or UNDEFINED ranges cannot be compared. */
4159 if (vr0->type == VR_VARYING
4160 || vr0->type == VR_UNDEFINED
4161 || vr1->type == VR_VARYING
4162 || vr1->type == VR_UNDEFINED)
4163 return NULL_TREE;
4165 /* Anti-ranges need to be handled separately. */
4166 if (vr0->type == VR_ANTI_RANGE || vr1->type == VR_ANTI_RANGE)
4168 /* If both are anti-ranges, then we cannot compute any
4169 comparison. */
4170 if (vr0->type == VR_ANTI_RANGE && vr1->type == VR_ANTI_RANGE)
4171 return NULL_TREE;
4173 /* These comparisons are never statically computable. */
4174 if (comp == GT_EXPR
4175 || comp == GE_EXPR
4176 || comp == LT_EXPR
4177 || comp == LE_EXPR)
4178 return NULL_TREE;
4180 /* Equality can be computed only between a range and an
4181 anti-range. ~[VAL1, VAL2] == [VAL1, VAL2] is always false. */
4182 if (vr0->type == VR_RANGE)
4184 /* To simplify processing, make VR0 the anti-range. */
4185 value_range *tmp = vr0;
4186 vr0 = vr1;
4187 vr1 = tmp;
4190 gcc_assert (comp == NE_EXPR || comp == EQ_EXPR);
4192 if (compare_values_warnv (vr0->min, vr1->min, strict_overflow_p) == 0
4193 && compare_values_warnv (vr0->max, vr1->max, strict_overflow_p) == 0)
4194 return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
4196 return NULL_TREE;
4199 /* Simplify processing. If COMP is GT_EXPR or GE_EXPR, switch the
4200 operands around and change the comparison code. */
4201 if (comp == GT_EXPR || comp == GE_EXPR)
4203 comp = (comp == GT_EXPR) ? LT_EXPR : LE_EXPR;
4204 std::swap (vr0, vr1);
4207 if (comp == EQ_EXPR)
4209 /* Equality may only be computed if both ranges represent
4210 exactly one value. */
4211 if (compare_values_warnv (vr0->min, vr0->max, strict_overflow_p) == 0
4212 && compare_values_warnv (vr1->min, vr1->max, strict_overflow_p) == 0)
4214 int cmp_min = compare_values_warnv (vr0->min, vr1->min,
4215 strict_overflow_p);
4216 int cmp_max = compare_values_warnv (vr0->max, vr1->max,
4217 strict_overflow_p);
4218 if (cmp_min == 0 && cmp_max == 0)
4219 return boolean_true_node;
4220 else if (cmp_min != -2 && cmp_max != -2)
4221 return boolean_false_node;
4223 /* If [V0_MIN, V1_MAX] < [V1_MIN, V1_MAX] then V0 != V1. */
4224 else if (compare_values_warnv (vr0->min, vr1->max,
4225 strict_overflow_p) == 1
4226 || compare_values_warnv (vr1->min, vr0->max,
4227 strict_overflow_p) == 1)
4228 return boolean_false_node;
4230 return NULL_TREE;
4232 else if (comp == NE_EXPR)
4234 int cmp1, cmp2;
4236 /* If VR0 is completely to the left or completely to the right
4237 of VR1, they are always different. Notice that we need to
4238 make sure that both comparisons yield similar results to
4239 avoid comparing values that cannot be compared at
4240 compile-time. */
4241 cmp1 = compare_values_warnv (vr0->max, vr1->min, strict_overflow_p);
4242 cmp2 = compare_values_warnv (vr0->min, vr1->max, strict_overflow_p);
4243 if ((cmp1 == -1 && cmp2 == -1) || (cmp1 == 1 && cmp2 == 1))
4244 return boolean_true_node;
4246 /* If VR0 and VR1 represent a single value and are identical,
4247 return false. */
4248 else if (compare_values_warnv (vr0->min, vr0->max,
4249 strict_overflow_p) == 0
4250 && compare_values_warnv (vr1->min, vr1->max,
4251 strict_overflow_p) == 0
4252 && compare_values_warnv (vr0->min, vr1->min,
4253 strict_overflow_p) == 0
4254 && compare_values_warnv (vr0->max, vr1->max,
4255 strict_overflow_p) == 0)
4256 return boolean_false_node;
4258 /* Otherwise, they may or may not be different. */
4259 else
4260 return NULL_TREE;
4262 else if (comp == LT_EXPR || comp == LE_EXPR)
4264 int tst;
4266 /* If VR0 is to the left of VR1, return true. */
4267 tst = compare_values_warnv (vr0->max, vr1->min, strict_overflow_p);
4268 if ((comp == LT_EXPR && tst == -1)
4269 || (comp == LE_EXPR && (tst == -1 || tst == 0)))
4270 return boolean_true_node;
4272 /* If VR0 is to the right of VR1, return false. */
4273 tst = compare_values_warnv (vr0->min, vr1->max, strict_overflow_p);
4274 if ((comp == LT_EXPR && (tst == 0 || tst == 1))
4275 || (comp == LE_EXPR && tst == 1))
4276 return boolean_false_node;
4278 /* Otherwise, we don't know. */
4279 return NULL_TREE;
4282 gcc_unreachable ();
4286 /* Given a value range VR, a value VAL and a comparison code COMP, return
4287 BOOLEAN_TRUE_NODE if VR COMP VAL always returns true for all the
4288 values in VR. Return BOOLEAN_FALSE_NODE if the comparison
4289 always returns false. Return NULL_TREE if it is not always
4290 possible to determine the value of the comparison. Also set
4291 *STRICT_OVERFLOW_P to indicate whether comparision evaluation
4292 assumed signed overflow is undefined. */
4294 static tree
4295 compare_range_with_value (enum tree_code comp, value_range *vr, tree val,
4296 bool *strict_overflow_p)
4298 if (vr->type == VR_VARYING || vr->type == VR_UNDEFINED)
4299 return NULL_TREE;
4301 /* Anti-ranges need to be handled separately. */
4302 if (vr->type == VR_ANTI_RANGE)
4304 /* For anti-ranges, the only predicates that we can compute at
4305 compile time are equality and inequality. */
4306 if (comp == GT_EXPR
4307 || comp == GE_EXPR
4308 || comp == LT_EXPR
4309 || comp == LE_EXPR)
4310 return NULL_TREE;
4312 /* ~[VAL_1, VAL_2] OP VAL is known if VAL_1 <= VAL <= VAL_2. */
4313 if (value_inside_range (val, vr->min, vr->max) == 1)
4314 return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
4316 return NULL_TREE;
4319 if (comp == EQ_EXPR)
4321 /* EQ_EXPR may only be computed if VR represents exactly
4322 one value. */
4323 if (compare_values_warnv (vr->min, vr->max, strict_overflow_p) == 0)
4325 int cmp = compare_values_warnv (vr->min, val, strict_overflow_p);
4326 if (cmp == 0)
4327 return boolean_true_node;
4328 else if (cmp == -1 || cmp == 1 || cmp == 2)
4329 return boolean_false_node;
4331 else if (compare_values_warnv (val, vr->min, strict_overflow_p) == -1
4332 || compare_values_warnv (vr->max, val, strict_overflow_p) == -1)
4333 return boolean_false_node;
4335 return NULL_TREE;
4337 else if (comp == NE_EXPR)
4339 /* If VAL is not inside VR, then they are always different. */
4340 if (compare_values_warnv (vr->max, val, strict_overflow_p) == -1
4341 || compare_values_warnv (vr->min, val, strict_overflow_p) == 1)
4342 return boolean_true_node;
4344 /* If VR represents exactly one value equal to VAL, then return
4345 false. */
4346 if (compare_values_warnv (vr->min, vr->max, strict_overflow_p) == 0
4347 && compare_values_warnv (vr->min, val, strict_overflow_p) == 0)
4348 return boolean_false_node;
4350 /* Otherwise, they may or may not be different. */
4351 return NULL_TREE;
4353 else if (comp == LT_EXPR || comp == LE_EXPR)
4355 int tst;
4357 /* If VR is to the left of VAL, return true. */
4358 tst = compare_values_warnv (vr->max, val, strict_overflow_p);
4359 if ((comp == LT_EXPR && tst == -1)
4360 || (comp == LE_EXPR && (tst == -1 || tst == 0)))
4361 return boolean_true_node;
4363 /* If VR is to the right of VAL, return false. */
4364 tst = compare_values_warnv (vr->min, val, strict_overflow_p);
4365 if ((comp == LT_EXPR && (tst == 0 || tst == 1))
4366 || (comp == LE_EXPR && tst == 1))
4367 return boolean_false_node;
4369 /* Otherwise, we don't know. */
4370 return NULL_TREE;
4372 else if (comp == GT_EXPR || comp == GE_EXPR)
4374 int tst;
4376 /* If VR is to the right of VAL, return true. */
4377 tst = compare_values_warnv (vr->min, val, strict_overflow_p);
4378 if ((comp == GT_EXPR && tst == 1)
4379 || (comp == GE_EXPR && (tst == 0 || tst == 1)))
4380 return boolean_true_node;
4382 /* If VR is to the left of VAL, return false. */
4383 tst = compare_values_warnv (vr->max, val, strict_overflow_p);
4384 if ((comp == GT_EXPR && (tst == -1 || tst == 0))
4385 || (comp == GE_EXPR && tst == -1))
4386 return boolean_false_node;
4388 /* Otherwise, we don't know. */
4389 return NULL_TREE;
4392 gcc_unreachable ();
4396 /* Debugging dumps. */
4398 void dump_value_range (FILE *, const value_range *);
4399 void debug_value_range (value_range *);
4400 void dump_all_value_ranges (FILE *);
4401 void debug_all_value_ranges (void);
4402 void dump_vr_equiv (FILE *, bitmap);
4403 void debug_vr_equiv (bitmap);
4406 /* Dump value range VR to FILE. */
4408 void
4409 dump_value_range (FILE *file, const value_range *vr)
4411 if (vr == NULL)
4412 fprintf (file, "[]");
4413 else if (vr->type == VR_UNDEFINED)
4414 fprintf (file, "UNDEFINED");
4415 else if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
4417 tree type = TREE_TYPE (vr->min);
4419 fprintf (file, "%s[", (vr->type == VR_ANTI_RANGE) ? "~" : "");
4421 if (INTEGRAL_TYPE_P (type)
4422 && !TYPE_UNSIGNED (type)
4423 && vrp_val_is_min (vr->min))
4424 fprintf (file, "-INF");
4425 else
4426 print_generic_expr (file, vr->min);
4428 fprintf (file, ", ");
4430 if (INTEGRAL_TYPE_P (type)
4431 && vrp_val_is_max (vr->max))
4432 fprintf (file, "+INF");
4433 else
4434 print_generic_expr (file, vr->max);
4436 fprintf (file, "]");
4438 if (vr->equiv)
4440 bitmap_iterator bi;
4441 unsigned i, c = 0;
4443 fprintf (file, " EQUIVALENCES: { ");
4445 EXECUTE_IF_SET_IN_BITMAP (vr->equiv, 0, i, bi)
4447 print_generic_expr (file, ssa_name (i));
4448 fprintf (file, " ");
4449 c++;
4452 fprintf (file, "} (%u elements)", c);
4455 else if (vr->type == VR_VARYING)
4456 fprintf (file, "VARYING");
4457 else
4458 fprintf (file, "INVALID RANGE");
4462 /* Dump value range VR to stderr. */
4464 DEBUG_FUNCTION void
4465 debug_value_range (value_range *vr)
4467 dump_value_range (stderr, vr);
4468 fprintf (stderr, "\n");
4472 /* Dump value ranges of all SSA_NAMEs to FILE. */
4474 void
4475 dump_all_value_ranges (FILE *file)
4477 size_t i;
4479 for (i = 0; i < num_vr_values; i++)
4481 if (vr_value[i])
4483 print_generic_expr (file, ssa_name (i));
4484 fprintf (file, ": ");
4485 dump_value_range (file, vr_value[i]);
4486 fprintf (file, "\n");
4490 fprintf (file, "\n");
4494 /* Dump all value ranges to stderr. */
4496 DEBUG_FUNCTION void
4497 debug_all_value_ranges (void)
4499 dump_all_value_ranges (stderr);
4503 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
4504 create a new SSA name N and return the assertion assignment
4505 'N = ASSERT_EXPR <V, V OP W>'. */
4507 static gimple *
4508 build_assert_expr_for (tree cond, tree v)
4510 tree a;
4511 gassign *assertion;
4513 gcc_assert (TREE_CODE (v) == SSA_NAME
4514 && COMPARISON_CLASS_P (cond));
4516 a = build2 (ASSERT_EXPR, TREE_TYPE (v), v, cond);
4517 assertion = gimple_build_assign (NULL_TREE, a);
4519 /* The new ASSERT_EXPR, creates a new SSA name that replaces the
4520 operand of the ASSERT_EXPR. Create it so the new name and the old one
4521 are registered in the replacement table so that we can fix the SSA web
4522 after adding all the ASSERT_EXPRs. */
4523 tree new_def = create_new_def_for (v, assertion, NULL);
4524 /* Make sure we preserve abnormalness throughout an ASSERT_EXPR chain
4525 given we have to be able to fully propagate those out to re-create
4526 valid SSA when removing the asserts. */
4527 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (v))
4528 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_def) = 1;
4530 return assertion;
4534 /* Return false if EXPR is a predicate expression involving floating
4535 point values. */
4537 static inline bool
4538 fp_predicate (gimple *stmt)
4540 GIMPLE_CHECK (stmt, GIMPLE_COND);
4542 return FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)));
4545 /* If the range of values taken by OP can be inferred after STMT executes,
4546 return the comparison code (COMP_CODE_P) and value (VAL_P) that
4547 describes the inferred range. Return true if a range could be
4548 inferred. */
4550 static bool
4551 infer_value_range (gimple *stmt, tree op, tree_code *comp_code_p, tree *val_p)
4553 *val_p = NULL_TREE;
4554 *comp_code_p = ERROR_MARK;
4556 /* Do not attempt to infer anything in names that flow through
4557 abnormal edges. */
4558 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
4559 return false;
4561 /* If STMT is the last statement of a basic block with no normal
4562 successors, there is no point inferring anything about any of its
4563 operands. We would not be able to find a proper insertion point
4564 for the assertion, anyway. */
4565 if (stmt_ends_bb_p (stmt))
4567 edge_iterator ei;
4568 edge e;
4570 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
4571 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
4572 break;
4573 if (e == NULL)
4574 return false;
4577 if (infer_nonnull_range (stmt, op))
4579 *val_p = build_int_cst (TREE_TYPE (op), 0);
4580 *comp_code_p = NE_EXPR;
4581 return true;
4584 return false;
4588 void dump_asserts_for (FILE *, tree);
4589 void debug_asserts_for (tree);
4590 void dump_all_asserts (FILE *);
4591 void debug_all_asserts (void);
4593 /* Dump all the registered assertions for NAME to FILE. */
4595 void
4596 dump_asserts_for (FILE *file, tree name)
4598 assert_locus *loc;
4600 fprintf (file, "Assertions to be inserted for ");
4601 print_generic_expr (file, name);
4602 fprintf (file, "\n");
4604 loc = asserts_for[SSA_NAME_VERSION (name)];
4605 while (loc)
4607 fprintf (file, "\t");
4608 print_gimple_stmt (file, gsi_stmt (loc->si), 0);
4609 fprintf (file, "\n\tBB #%d", loc->bb->index);
4610 if (loc->e)
4612 fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
4613 loc->e->dest->index);
4614 dump_edge_info (file, loc->e, dump_flags, 0);
4616 fprintf (file, "\n\tPREDICATE: ");
4617 print_generic_expr (file, loc->expr);
4618 fprintf (file, " %s ", get_tree_code_name (loc->comp_code));
4619 print_generic_expr (file, loc->val);
4620 fprintf (file, "\n\n");
4621 loc = loc->next;
4624 fprintf (file, "\n");
4628 /* Dump all the registered assertions for NAME to stderr. */
4630 DEBUG_FUNCTION void
4631 debug_asserts_for (tree name)
4633 dump_asserts_for (stderr, name);
4637 /* Dump all the registered assertions for all the names to FILE. */
4639 void
4640 dump_all_asserts (FILE *file)
4642 unsigned i;
4643 bitmap_iterator bi;
4645 fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
4646 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
4647 dump_asserts_for (file, ssa_name (i));
4648 fprintf (file, "\n");
4652 /* Dump all the registered assertions for all the names to stderr. */
4654 DEBUG_FUNCTION void
4655 debug_all_asserts (void)
4657 dump_all_asserts (stderr);
4660 /* Push the assert info for NAME, EXPR, COMP_CODE and VAL to ASSERTS. */
4662 static void
4663 add_assert_info (vec<assert_info> &asserts,
4664 tree name, tree expr, enum tree_code comp_code, tree val)
4666 assert_info info;
4667 info.comp_code = comp_code;
4668 info.name = name;
4669 info.val = val;
4670 info.expr = expr;
4671 asserts.safe_push (info);
4674 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
4675 'EXPR COMP_CODE VAL' at a location that dominates block BB or
4676 E->DEST, then register this location as a possible insertion point
4677 for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
4679 BB, E and SI provide the exact insertion point for the new
4680 ASSERT_EXPR. If BB is NULL, then the ASSERT_EXPR is to be inserted
4681 on edge E. Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
4682 BB. If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
4683 must not be NULL. */
4685 static void
4686 register_new_assert_for (tree name, tree expr,
4687 enum tree_code comp_code,
4688 tree val,
4689 basic_block bb,
4690 edge e,
4691 gimple_stmt_iterator si)
4693 assert_locus *n, *loc, *last_loc;
4694 basic_block dest_bb;
4696 gcc_checking_assert (bb == NULL || e == NULL);
4698 if (e == NULL)
4699 gcc_checking_assert (gimple_code (gsi_stmt (si)) != GIMPLE_COND
4700 && gimple_code (gsi_stmt (si)) != GIMPLE_SWITCH);
4702 /* Never build an assert comparing against an integer constant with
4703 TREE_OVERFLOW set. This confuses our undefined overflow warning
4704 machinery. */
4705 if (TREE_OVERFLOW_P (val))
4706 val = drop_tree_overflow (val);
4708 /* The new assertion A will be inserted at BB or E. We need to
4709 determine if the new location is dominated by a previously
4710 registered location for A. If we are doing an edge insertion,
4711 assume that A will be inserted at E->DEST. Note that this is not
4712 necessarily true.
4714 If E is a critical edge, it will be split. But even if E is
4715 split, the new block will dominate the same set of blocks that
4716 E->DEST dominates.
4718 The reverse, however, is not true, blocks dominated by E->DEST
4719 will not be dominated by the new block created to split E. So,
4720 if the insertion location is on a critical edge, we will not use
4721 the new location to move another assertion previously registered
4722 at a block dominated by E->DEST. */
4723 dest_bb = (bb) ? bb : e->dest;
4725 /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
4726 VAL at a block dominating DEST_BB, then we don't need to insert a new
4727 one. Similarly, if the same assertion already exists at a block
4728 dominated by DEST_BB and the new location is not on a critical
4729 edge, then update the existing location for the assertion (i.e.,
4730 move the assertion up in the dominance tree).
4732 Note, this is implemented as a simple linked list because there
4733 should not be more than a handful of assertions registered per
4734 name. If this becomes a performance problem, a table hashed by
4735 COMP_CODE and VAL could be implemented. */
4736 loc = asserts_for[SSA_NAME_VERSION (name)];
4737 last_loc = loc;
4738 while (loc)
4740 if (loc->comp_code == comp_code
4741 && (loc->val == val
4742 || operand_equal_p (loc->val, val, 0))
4743 && (loc->expr == expr
4744 || operand_equal_p (loc->expr, expr, 0)))
4746 /* If E is not a critical edge and DEST_BB
4747 dominates the existing location for the assertion, move
4748 the assertion up in the dominance tree by updating its
4749 location information. */
4750 if ((e == NULL || !EDGE_CRITICAL_P (e))
4751 && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
4753 loc->bb = dest_bb;
4754 loc->e = e;
4755 loc->si = si;
4756 return;
4760 /* Update the last node of the list and move to the next one. */
4761 last_loc = loc;
4762 loc = loc->next;
4765 /* If we didn't find an assertion already registered for
4766 NAME COMP_CODE VAL, add a new one at the end of the list of
4767 assertions associated with NAME. */
4768 n = XNEW (struct assert_locus);
4769 n->bb = dest_bb;
4770 n->e = e;
4771 n->si = si;
4772 n->comp_code = comp_code;
4773 n->val = val;
4774 n->expr = expr;
4775 n->next = NULL;
4777 if (last_loc)
4778 last_loc->next = n;
4779 else
4780 asserts_for[SSA_NAME_VERSION (name)] = n;
4782 bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
4785 /* (COND_OP0 COND_CODE COND_OP1) is a predicate which uses NAME.
4786 Extract a suitable test code and value and store them into *CODE_P and
4787 *VAL_P so the predicate is normalized to NAME *CODE_P *VAL_P.
4789 If no extraction was possible, return FALSE, otherwise return TRUE.
4791 If INVERT is true, then we invert the result stored into *CODE_P. */
4793 static bool
4794 extract_code_and_val_from_cond_with_ops (tree name, enum tree_code cond_code,
4795 tree cond_op0, tree cond_op1,
4796 bool invert, enum tree_code *code_p,
4797 tree *val_p)
4799 enum tree_code comp_code;
4800 tree val;
4802 /* Otherwise, we have a comparison of the form NAME COMP VAL
4803 or VAL COMP NAME. */
4804 if (name == cond_op1)
4806 /* If the predicate is of the form VAL COMP NAME, flip
4807 COMP around because we need to register NAME as the
4808 first operand in the predicate. */
4809 comp_code = swap_tree_comparison (cond_code);
4810 val = cond_op0;
4812 else if (name == cond_op0)
4814 /* The comparison is of the form NAME COMP VAL, so the
4815 comparison code remains unchanged. */
4816 comp_code = cond_code;
4817 val = cond_op1;
4819 else
4820 gcc_unreachable ();
4822 /* Invert the comparison code as necessary. */
4823 if (invert)
4824 comp_code = invert_tree_comparison (comp_code, 0);
4826 /* VRP only handles integral and pointer types. */
4827 if (! INTEGRAL_TYPE_P (TREE_TYPE (val))
4828 && ! POINTER_TYPE_P (TREE_TYPE (val)))
4829 return false;
4831 /* Do not register always-false predicates.
4832 FIXME: this works around a limitation in fold() when dealing with
4833 enumerations. Given 'enum { N1, N2 } x;', fold will not
4834 fold 'if (x > N2)' to 'if (0)'. */
4835 if ((comp_code == GT_EXPR || comp_code == LT_EXPR)
4836 && INTEGRAL_TYPE_P (TREE_TYPE (val)))
4838 tree min = TYPE_MIN_VALUE (TREE_TYPE (val));
4839 tree max = TYPE_MAX_VALUE (TREE_TYPE (val));
4841 if (comp_code == GT_EXPR
4842 && (!max
4843 || compare_values (val, max) == 0))
4844 return false;
4846 if (comp_code == LT_EXPR
4847 && (!min
4848 || compare_values (val, min) == 0))
4849 return false;
4851 *code_p = comp_code;
4852 *val_p = val;
4853 return true;
4856 /* Find out smallest RES where RES > VAL && (RES & MASK) == RES, if any
4857 (otherwise return VAL). VAL and MASK must be zero-extended for
4858 precision PREC. If SGNBIT is non-zero, first xor VAL with SGNBIT
4859 (to transform signed values into unsigned) and at the end xor
4860 SGNBIT back. */
4862 static wide_int
4863 masked_increment (const wide_int &val_in, const wide_int &mask,
4864 const wide_int &sgnbit, unsigned int prec)
4866 wide_int bit = wi::one (prec), res;
4867 unsigned int i;
4869 wide_int val = val_in ^ sgnbit;
4870 for (i = 0; i < prec; i++, bit += bit)
4872 res = mask;
4873 if ((res & bit) == 0)
4874 continue;
4875 res = bit - 1;
4876 res = (val + bit).and_not (res);
4877 res &= mask;
4878 if (wi::gtu_p (res, val))
4879 return res ^ sgnbit;
4881 return val ^ sgnbit;
4884 /* Helper for overflow_comparison_p
4886 OP0 CODE OP1 is a comparison. Examine the comparison and potentially
4887 OP1's defining statement to see if it ultimately has the form
4888 OP0 CODE (OP0 PLUS INTEGER_CST)
4890 If so, return TRUE indicating this is an overflow test and store into
4891 *NEW_CST an updated constant that can be used in a narrowed range test.
4893 REVERSED indicates if the comparison was originally:
4895 OP1 CODE' OP0.
4897 This affects how we build the updated constant. */
4899 static bool
4900 overflow_comparison_p_1 (enum tree_code code, tree op0, tree op1,
4901 bool follow_assert_exprs, bool reversed, tree *new_cst)
4903 /* See if this is a relational operation between two SSA_NAMES with
4904 unsigned, overflow wrapping values. If so, check it more deeply. */
4905 if ((code == LT_EXPR || code == LE_EXPR
4906 || code == GE_EXPR || code == GT_EXPR)
4907 && TREE_CODE (op0) == SSA_NAME
4908 && TREE_CODE (op1) == SSA_NAME
4909 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
4910 && TYPE_UNSIGNED (TREE_TYPE (op0))
4911 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0)))
4913 gimple *op1_def = SSA_NAME_DEF_STMT (op1);
4915 /* If requested, follow any ASSERT_EXPRs backwards for OP1. */
4916 if (follow_assert_exprs)
4918 while (gimple_assign_single_p (op1_def)
4919 && TREE_CODE (gimple_assign_rhs1 (op1_def)) == ASSERT_EXPR)
4921 op1 = TREE_OPERAND (gimple_assign_rhs1 (op1_def), 0);
4922 if (TREE_CODE (op1) != SSA_NAME)
4923 break;
4924 op1_def = SSA_NAME_DEF_STMT (op1);
4928 /* Now look at the defining statement of OP1 to see if it adds
4929 or subtracts a nonzero constant from another operand. */
4930 if (op1_def
4931 && is_gimple_assign (op1_def)
4932 && gimple_assign_rhs_code (op1_def) == PLUS_EXPR
4933 && TREE_CODE (gimple_assign_rhs2 (op1_def)) == INTEGER_CST
4934 && !integer_zerop (gimple_assign_rhs2 (op1_def)))
4936 tree target = gimple_assign_rhs1 (op1_def);
4938 /* If requested, follow ASSERT_EXPRs backwards for op0 looking
4939 for one where TARGET appears on the RHS. */
4940 if (follow_assert_exprs)
4942 /* Now see if that "other operand" is op0, following the chain
4943 of ASSERT_EXPRs if necessary. */
4944 gimple *op0_def = SSA_NAME_DEF_STMT (op0);
4945 while (op0 != target
4946 && gimple_assign_single_p (op0_def)
4947 && TREE_CODE (gimple_assign_rhs1 (op0_def)) == ASSERT_EXPR)
4949 op0 = TREE_OPERAND (gimple_assign_rhs1 (op0_def), 0);
4950 if (TREE_CODE (op0) != SSA_NAME)
4951 break;
4952 op0_def = SSA_NAME_DEF_STMT (op0);
4956 /* If we did not find our target SSA_NAME, then this is not
4957 an overflow test. */
4958 if (op0 != target)
4959 return false;
4961 tree type = TREE_TYPE (op0);
4962 wide_int max = wi::max_value (TYPE_PRECISION (type), UNSIGNED);
4963 tree inc = gimple_assign_rhs2 (op1_def);
4964 if (reversed)
4965 *new_cst = wide_int_to_tree (type, max + inc);
4966 else
4967 *new_cst = wide_int_to_tree (type, max - inc);
4968 return true;
4971 return false;
4974 /* OP0 CODE OP1 is a comparison. Examine the comparison and potentially
4975 OP1's defining statement to see if it ultimately has the form
4976 OP0 CODE (OP0 PLUS INTEGER_CST)
4978 If so, return TRUE indicating this is an overflow test and store into
4979 *NEW_CST an updated constant that can be used in a narrowed range test.
4981 These statements are left as-is in the IL to facilitate discovery of
4982 {ADD,SUB}_OVERFLOW sequences later in the optimizer pipeline. But
4983 the alternate range representation is often useful within VRP. */
4985 static bool
4986 overflow_comparison_p (tree_code code, tree name, tree val,
4987 bool use_equiv_p, tree *new_cst)
4989 if (overflow_comparison_p_1 (code, name, val, use_equiv_p, false, new_cst))
4990 return true;
4991 return overflow_comparison_p_1 (swap_tree_comparison (code), val, name,
4992 use_equiv_p, true, new_cst);
4996 /* Try to register an edge assertion for SSA name NAME on edge E for
4997 the condition COND contributing to the conditional jump pointed to by BSI.
4998 Invert the condition COND if INVERT is true. */
5000 static void
5001 register_edge_assert_for_2 (tree name, edge e,
5002 enum tree_code cond_code,
5003 tree cond_op0, tree cond_op1, bool invert,
5004 vec<assert_info> &asserts)
5006 tree val;
5007 enum tree_code comp_code;
5009 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
5010 cond_op0,
5011 cond_op1,
5012 invert, &comp_code, &val))
5013 return;
5015 /* Queue the assert. */
5016 tree x;
5017 if (overflow_comparison_p (comp_code, name, val, false, &x))
5019 enum tree_code new_code = ((comp_code == GT_EXPR || comp_code == GE_EXPR)
5020 ? GT_EXPR : LE_EXPR);
5021 add_assert_info (asserts, name, name, new_code, x);
5023 add_assert_info (asserts, name, name, comp_code, val);
5025 /* In the case of NAME <= CST and NAME being defined as
5026 NAME = (unsigned) NAME2 + CST2 we can assert NAME2 >= -CST2
5027 and NAME2 <= CST - CST2. We can do the same for NAME > CST.
5028 This catches range and anti-range tests. */
5029 if ((comp_code == LE_EXPR
5030 || comp_code == GT_EXPR)
5031 && TREE_CODE (val) == INTEGER_CST
5032 && TYPE_UNSIGNED (TREE_TYPE (val)))
5034 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5035 tree cst2 = NULL_TREE, name2 = NULL_TREE, name3 = NULL_TREE;
5037 /* Extract CST2 from the (optional) addition. */
5038 if (is_gimple_assign (def_stmt)
5039 && gimple_assign_rhs_code (def_stmt) == PLUS_EXPR)
5041 name2 = gimple_assign_rhs1 (def_stmt);
5042 cst2 = gimple_assign_rhs2 (def_stmt);
5043 if (TREE_CODE (name2) == SSA_NAME
5044 && TREE_CODE (cst2) == INTEGER_CST)
5045 def_stmt = SSA_NAME_DEF_STMT (name2);
5048 /* Extract NAME2 from the (optional) sign-changing cast. */
5049 if (gimple_assign_cast_p (def_stmt))
5051 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt))
5052 && ! TYPE_UNSIGNED (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
5053 && (TYPE_PRECISION (gimple_expr_type (def_stmt))
5054 == TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))))
5055 name3 = gimple_assign_rhs1 (def_stmt);
5058 /* If name3 is used later, create an ASSERT_EXPR for it. */
5059 if (name3 != NULL_TREE
5060 && TREE_CODE (name3) == SSA_NAME
5061 && (cst2 == NULL_TREE
5062 || TREE_CODE (cst2) == INTEGER_CST)
5063 && INTEGRAL_TYPE_P (TREE_TYPE (name3)))
5065 tree tmp;
5067 /* Build an expression for the range test. */
5068 tmp = build1 (NOP_EXPR, TREE_TYPE (name), name3);
5069 if (cst2 != NULL_TREE)
5070 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
5072 if (dump_file)
5074 fprintf (dump_file, "Adding assert for ");
5075 print_generic_expr (dump_file, name3);
5076 fprintf (dump_file, " from ");
5077 print_generic_expr (dump_file, tmp);
5078 fprintf (dump_file, "\n");
5081 add_assert_info (asserts, name3, tmp, comp_code, val);
5084 /* If name2 is used later, create an ASSERT_EXPR for it. */
5085 if (name2 != NULL_TREE
5086 && TREE_CODE (name2) == SSA_NAME
5087 && TREE_CODE (cst2) == INTEGER_CST
5088 && INTEGRAL_TYPE_P (TREE_TYPE (name2)))
5090 tree tmp;
5092 /* Build an expression for the range test. */
5093 tmp = name2;
5094 if (TREE_TYPE (name) != TREE_TYPE (name2))
5095 tmp = build1 (NOP_EXPR, TREE_TYPE (name), tmp);
5096 if (cst2 != NULL_TREE)
5097 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
5099 if (dump_file)
5101 fprintf (dump_file, "Adding assert for ");
5102 print_generic_expr (dump_file, name2);
5103 fprintf (dump_file, " from ");
5104 print_generic_expr (dump_file, tmp);
5105 fprintf (dump_file, "\n");
5108 add_assert_info (asserts, name2, tmp, comp_code, val);
5112 /* In the case of post-in/decrement tests like if (i++) ... and uses
5113 of the in/decremented value on the edge the extra name we want to
5114 assert for is not on the def chain of the name compared. Instead
5115 it is in the set of use stmts.
5116 Similar cases happen for conversions that were simplified through
5117 fold_{sign_changed,widened}_comparison. */
5118 if ((comp_code == NE_EXPR
5119 || comp_code == EQ_EXPR)
5120 && TREE_CODE (val) == INTEGER_CST)
5122 imm_use_iterator ui;
5123 gimple *use_stmt;
5124 FOR_EACH_IMM_USE_STMT (use_stmt, ui, name)
5126 if (!is_gimple_assign (use_stmt))
5127 continue;
5129 /* Cut off to use-stmts that are dominating the predecessor. */
5130 if (!dominated_by_p (CDI_DOMINATORS, e->src, gimple_bb (use_stmt)))
5131 continue;
5133 tree name2 = gimple_assign_lhs (use_stmt);
5134 if (TREE_CODE (name2) != SSA_NAME)
5135 continue;
5137 enum tree_code code = gimple_assign_rhs_code (use_stmt);
5138 tree cst;
5139 if (code == PLUS_EXPR
5140 || code == MINUS_EXPR)
5142 cst = gimple_assign_rhs2 (use_stmt);
5143 if (TREE_CODE (cst) != INTEGER_CST)
5144 continue;
5145 cst = int_const_binop (code, val, cst);
5147 else if (CONVERT_EXPR_CODE_P (code))
5149 /* For truncating conversions we cannot record
5150 an inequality. */
5151 if (comp_code == NE_EXPR
5152 && (TYPE_PRECISION (TREE_TYPE (name2))
5153 < TYPE_PRECISION (TREE_TYPE (name))))
5154 continue;
5155 cst = fold_convert (TREE_TYPE (name2), val);
5157 else
5158 continue;
5160 if (TREE_OVERFLOW_P (cst))
5161 cst = drop_tree_overflow (cst);
5162 add_assert_info (asserts, name2, name2, comp_code, cst);
5166 if (TREE_CODE_CLASS (comp_code) == tcc_comparison
5167 && TREE_CODE (val) == INTEGER_CST)
5169 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5170 tree name2 = NULL_TREE, names[2], cst2 = NULL_TREE;
5171 tree val2 = NULL_TREE;
5172 unsigned int prec = TYPE_PRECISION (TREE_TYPE (val));
5173 wide_int mask = wi::zero (prec);
5174 unsigned int nprec = prec;
5175 enum tree_code rhs_code = ERROR_MARK;
5177 if (is_gimple_assign (def_stmt))
5178 rhs_code = gimple_assign_rhs_code (def_stmt);
5180 /* In the case of NAME != CST1 where NAME = A +- CST2 we can
5181 assert that A != CST1 -+ CST2. */
5182 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
5183 && (rhs_code == PLUS_EXPR || rhs_code == MINUS_EXPR))
5185 tree op0 = gimple_assign_rhs1 (def_stmt);
5186 tree op1 = gimple_assign_rhs2 (def_stmt);
5187 if (TREE_CODE (op0) == SSA_NAME
5188 && TREE_CODE (op1) == INTEGER_CST)
5190 enum tree_code reverse_op = (rhs_code == PLUS_EXPR
5191 ? MINUS_EXPR : PLUS_EXPR);
5192 op1 = int_const_binop (reverse_op, val, op1);
5193 if (TREE_OVERFLOW (op1))
5194 op1 = drop_tree_overflow (op1);
5195 add_assert_info (asserts, op0, op0, comp_code, op1);
5199 /* Add asserts for NAME cmp CST and NAME being defined
5200 as NAME = (int) NAME2. */
5201 if (!TYPE_UNSIGNED (TREE_TYPE (val))
5202 && (comp_code == LE_EXPR || comp_code == LT_EXPR
5203 || comp_code == GT_EXPR || comp_code == GE_EXPR)
5204 && gimple_assign_cast_p (def_stmt))
5206 name2 = gimple_assign_rhs1 (def_stmt);
5207 if (CONVERT_EXPR_CODE_P (rhs_code)
5208 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
5209 && TYPE_UNSIGNED (TREE_TYPE (name2))
5210 && prec == TYPE_PRECISION (TREE_TYPE (name2))
5211 && (comp_code == LE_EXPR || comp_code == GT_EXPR
5212 || !tree_int_cst_equal (val,
5213 TYPE_MIN_VALUE (TREE_TYPE (val)))))
5215 tree tmp, cst;
5216 enum tree_code new_comp_code = comp_code;
5218 cst = fold_convert (TREE_TYPE (name2),
5219 TYPE_MIN_VALUE (TREE_TYPE (val)));
5220 /* Build an expression for the range test. */
5221 tmp = build2 (PLUS_EXPR, TREE_TYPE (name2), name2, cst);
5222 cst = fold_build2 (PLUS_EXPR, TREE_TYPE (name2), cst,
5223 fold_convert (TREE_TYPE (name2), val));
5224 if (comp_code == LT_EXPR || comp_code == GE_EXPR)
5226 new_comp_code = comp_code == LT_EXPR ? LE_EXPR : GT_EXPR;
5227 cst = fold_build2 (MINUS_EXPR, TREE_TYPE (name2), cst,
5228 build_int_cst (TREE_TYPE (name2), 1));
5231 if (dump_file)
5233 fprintf (dump_file, "Adding assert for ");
5234 print_generic_expr (dump_file, name2);
5235 fprintf (dump_file, " from ");
5236 print_generic_expr (dump_file, tmp);
5237 fprintf (dump_file, "\n");
5240 add_assert_info (asserts, name2, tmp, new_comp_code, cst);
5244 /* Add asserts for NAME cmp CST and NAME being defined as
5245 NAME = NAME2 >> CST2.
5247 Extract CST2 from the right shift. */
5248 if (rhs_code == RSHIFT_EXPR)
5250 name2 = gimple_assign_rhs1 (def_stmt);
5251 cst2 = gimple_assign_rhs2 (def_stmt);
5252 if (TREE_CODE (name2) == SSA_NAME
5253 && tree_fits_uhwi_p (cst2)
5254 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
5255 && IN_RANGE (tree_to_uhwi (cst2), 1, prec - 1)
5256 && type_has_mode_precision_p (TREE_TYPE (val)))
5258 mask = wi::mask (tree_to_uhwi (cst2), false, prec);
5259 val2 = fold_binary (LSHIFT_EXPR, TREE_TYPE (val), val, cst2);
5262 if (val2 != NULL_TREE
5263 && TREE_CODE (val2) == INTEGER_CST
5264 && simple_cst_equal (fold_build2 (RSHIFT_EXPR,
5265 TREE_TYPE (val),
5266 val2, cst2), val))
5268 enum tree_code new_comp_code = comp_code;
5269 tree tmp, new_val;
5271 tmp = name2;
5272 if (comp_code == EQ_EXPR || comp_code == NE_EXPR)
5274 if (!TYPE_UNSIGNED (TREE_TYPE (val)))
5276 tree type = build_nonstandard_integer_type (prec, 1);
5277 tmp = build1 (NOP_EXPR, type, name2);
5278 val2 = fold_convert (type, val2);
5280 tmp = fold_build2 (MINUS_EXPR, TREE_TYPE (tmp), tmp, val2);
5281 new_val = wide_int_to_tree (TREE_TYPE (tmp), mask);
5282 new_comp_code = comp_code == EQ_EXPR ? LE_EXPR : GT_EXPR;
5284 else if (comp_code == LT_EXPR || comp_code == GE_EXPR)
5286 wide_int minval
5287 = wi::min_value (prec, TYPE_SIGN (TREE_TYPE (val)));
5288 new_val = val2;
5289 if (minval == new_val)
5290 new_val = NULL_TREE;
5292 else
5294 wide_int maxval
5295 = wi::max_value (prec, TYPE_SIGN (TREE_TYPE (val)));
5296 mask |= val2;
5297 if (mask == maxval)
5298 new_val = NULL_TREE;
5299 else
5300 new_val = wide_int_to_tree (TREE_TYPE (val2), mask);
5303 if (new_val)
5305 if (dump_file)
5307 fprintf (dump_file, "Adding assert for ");
5308 print_generic_expr (dump_file, name2);
5309 fprintf (dump_file, " from ");
5310 print_generic_expr (dump_file, tmp);
5311 fprintf (dump_file, "\n");
5314 add_assert_info (asserts, name2, tmp, new_comp_code, new_val);
5318 /* Add asserts for NAME cmp CST and NAME being defined as
5319 NAME = NAME2 & CST2.
5321 Extract CST2 from the and.
5323 Also handle
5324 NAME = (unsigned) NAME2;
5325 casts where NAME's type is unsigned and has smaller precision
5326 than NAME2's type as if it was NAME = NAME2 & MASK. */
5327 names[0] = NULL_TREE;
5328 names[1] = NULL_TREE;
5329 cst2 = NULL_TREE;
5330 if (rhs_code == BIT_AND_EXPR
5331 || (CONVERT_EXPR_CODE_P (rhs_code)
5332 && INTEGRAL_TYPE_P (TREE_TYPE (val))
5333 && TYPE_UNSIGNED (TREE_TYPE (val))
5334 && TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
5335 > prec))
5337 name2 = gimple_assign_rhs1 (def_stmt);
5338 if (rhs_code == BIT_AND_EXPR)
5339 cst2 = gimple_assign_rhs2 (def_stmt);
5340 else
5342 cst2 = TYPE_MAX_VALUE (TREE_TYPE (val));
5343 nprec = TYPE_PRECISION (TREE_TYPE (name2));
5345 if (TREE_CODE (name2) == SSA_NAME
5346 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
5347 && TREE_CODE (cst2) == INTEGER_CST
5348 && !integer_zerop (cst2)
5349 && (nprec > 1
5350 || TYPE_UNSIGNED (TREE_TYPE (val))))
5352 gimple *def_stmt2 = SSA_NAME_DEF_STMT (name2);
5353 if (gimple_assign_cast_p (def_stmt2))
5355 names[1] = gimple_assign_rhs1 (def_stmt2);
5356 if (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt2))
5357 || !INTEGRAL_TYPE_P (TREE_TYPE (names[1]))
5358 || (TYPE_PRECISION (TREE_TYPE (name2))
5359 != TYPE_PRECISION (TREE_TYPE (names[1]))))
5360 names[1] = NULL_TREE;
5362 names[0] = name2;
5365 if (names[0] || names[1])
5367 wide_int minv, maxv, valv, cst2v;
5368 wide_int tem, sgnbit;
5369 bool valid_p = false, valn, cst2n;
5370 enum tree_code ccode = comp_code;
5372 valv = wide_int::from (val, nprec, UNSIGNED);
5373 cst2v = wide_int::from (cst2, nprec, UNSIGNED);
5374 valn = wi::neg_p (valv, TYPE_SIGN (TREE_TYPE (val)));
5375 cst2n = wi::neg_p (cst2v, TYPE_SIGN (TREE_TYPE (val)));
5376 /* If CST2 doesn't have most significant bit set,
5377 but VAL is negative, we have comparison like
5378 if ((x & 0x123) > -4) (always true). Just give up. */
5379 if (!cst2n && valn)
5380 ccode = ERROR_MARK;
5381 if (cst2n)
5382 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
5383 else
5384 sgnbit = wi::zero (nprec);
5385 minv = valv & cst2v;
5386 switch (ccode)
5388 case EQ_EXPR:
5389 /* Minimum unsigned value for equality is VAL & CST2
5390 (should be equal to VAL, otherwise we probably should
5391 have folded the comparison into false) and
5392 maximum unsigned value is VAL | ~CST2. */
5393 maxv = valv | ~cst2v;
5394 valid_p = true;
5395 break;
5397 case NE_EXPR:
5398 tem = valv | ~cst2v;
5399 /* If VAL is 0, handle (X & CST2) != 0 as (X & CST2) > 0U. */
5400 if (valv == 0)
5402 cst2n = false;
5403 sgnbit = wi::zero (nprec);
5404 goto gt_expr;
5406 /* If (VAL | ~CST2) is all ones, handle it as
5407 (X & CST2) < VAL. */
5408 if (tem == -1)
5410 cst2n = false;
5411 valn = false;
5412 sgnbit = wi::zero (nprec);
5413 goto lt_expr;
5415 if (!cst2n && wi::neg_p (cst2v))
5416 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
5417 if (sgnbit != 0)
5419 if (valv == sgnbit)
5421 cst2n = true;
5422 valn = true;
5423 goto gt_expr;
5425 if (tem == wi::mask (nprec - 1, false, nprec))
5427 cst2n = true;
5428 goto lt_expr;
5430 if (!cst2n)
5431 sgnbit = wi::zero (nprec);
5433 break;
5435 case GE_EXPR:
5436 /* Minimum unsigned value for >= if (VAL & CST2) == VAL
5437 is VAL and maximum unsigned value is ~0. For signed
5438 comparison, if CST2 doesn't have most significant bit
5439 set, handle it similarly. If CST2 has MSB set,
5440 the minimum is the same, and maximum is ~0U/2. */
5441 if (minv != valv)
5443 /* If (VAL & CST2) != VAL, X & CST2 can't be equal to
5444 VAL. */
5445 minv = masked_increment (valv, cst2v, sgnbit, nprec);
5446 if (minv == valv)
5447 break;
5449 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
5450 valid_p = true;
5451 break;
5453 case GT_EXPR:
5454 gt_expr:
5455 /* Find out smallest MINV where MINV > VAL
5456 && (MINV & CST2) == MINV, if any. If VAL is signed and
5457 CST2 has MSB set, compute it biased by 1 << (nprec - 1). */
5458 minv = masked_increment (valv, cst2v, sgnbit, nprec);
5459 if (minv == valv)
5460 break;
5461 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
5462 valid_p = true;
5463 break;
5465 case LE_EXPR:
5466 /* Minimum unsigned value for <= is 0 and maximum
5467 unsigned value is VAL | ~CST2 if (VAL & CST2) == VAL.
5468 Otherwise, find smallest VAL2 where VAL2 > VAL
5469 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
5470 as maximum.
5471 For signed comparison, if CST2 doesn't have most
5472 significant bit set, handle it similarly. If CST2 has
5473 MSB set, the maximum is the same and minimum is INT_MIN. */
5474 if (minv == valv)
5475 maxv = valv;
5476 else
5478 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
5479 if (maxv == valv)
5480 break;
5481 maxv -= 1;
5483 maxv |= ~cst2v;
5484 minv = sgnbit;
5485 valid_p = true;
5486 break;
5488 case LT_EXPR:
5489 lt_expr:
5490 /* Minimum unsigned value for < is 0 and maximum
5491 unsigned value is (VAL-1) | ~CST2 if (VAL & CST2) == VAL.
5492 Otherwise, find smallest VAL2 where VAL2 > VAL
5493 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
5494 as maximum.
5495 For signed comparison, if CST2 doesn't have most
5496 significant bit set, handle it similarly. If CST2 has
5497 MSB set, the maximum is the same and minimum is INT_MIN. */
5498 if (minv == valv)
5500 if (valv == sgnbit)
5501 break;
5502 maxv = valv;
5504 else
5506 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
5507 if (maxv == valv)
5508 break;
5510 maxv -= 1;
5511 maxv |= ~cst2v;
5512 minv = sgnbit;
5513 valid_p = true;
5514 break;
5516 default:
5517 break;
5519 if (valid_p
5520 && (maxv - minv) != -1)
5522 tree tmp, new_val, type;
5523 int i;
5525 for (i = 0; i < 2; i++)
5526 if (names[i])
5528 wide_int maxv2 = maxv;
5529 tmp = names[i];
5530 type = TREE_TYPE (names[i]);
5531 if (!TYPE_UNSIGNED (type))
5533 type = build_nonstandard_integer_type (nprec, 1);
5534 tmp = build1 (NOP_EXPR, type, names[i]);
5536 if (minv != 0)
5538 tmp = build2 (PLUS_EXPR, type, tmp,
5539 wide_int_to_tree (type, -minv));
5540 maxv2 = maxv - minv;
5542 new_val = wide_int_to_tree (type, maxv2);
5544 if (dump_file)
5546 fprintf (dump_file, "Adding assert for ");
5547 print_generic_expr (dump_file, names[i]);
5548 fprintf (dump_file, " from ");
5549 print_generic_expr (dump_file, tmp);
5550 fprintf (dump_file, "\n");
5553 add_assert_info (asserts, names[i], tmp, LE_EXPR, new_val);
5560 /* OP is an operand of a truth value expression which is known to have
5561 a particular value. Register any asserts for OP and for any
5562 operands in OP's defining statement.
5564 If CODE is EQ_EXPR, then we want to register OP is zero (false),
5565 if CODE is NE_EXPR, then we want to register OP is nonzero (true). */
5567 static void
5568 register_edge_assert_for_1 (tree op, enum tree_code code,
5569 edge e, vec<assert_info> &asserts)
5571 gimple *op_def;
5572 tree val;
5573 enum tree_code rhs_code;
5575 /* We only care about SSA_NAMEs. */
5576 if (TREE_CODE (op) != SSA_NAME)
5577 return;
5579 /* We know that OP will have a zero or nonzero value. */
5580 val = build_int_cst (TREE_TYPE (op), 0);
5581 add_assert_info (asserts, op, op, code, val);
5583 /* Now look at how OP is set. If it's set from a comparison,
5584 a truth operation or some bit operations, then we may be able
5585 to register information about the operands of that assignment. */
5586 op_def = SSA_NAME_DEF_STMT (op);
5587 if (gimple_code (op_def) != GIMPLE_ASSIGN)
5588 return;
5590 rhs_code = gimple_assign_rhs_code (op_def);
5592 if (TREE_CODE_CLASS (rhs_code) == tcc_comparison)
5594 bool invert = (code == EQ_EXPR ? true : false);
5595 tree op0 = gimple_assign_rhs1 (op_def);
5596 tree op1 = gimple_assign_rhs2 (op_def);
5598 if (TREE_CODE (op0) == SSA_NAME)
5599 register_edge_assert_for_2 (op0, e, rhs_code, op0, op1, invert, asserts);
5600 if (TREE_CODE (op1) == SSA_NAME)
5601 register_edge_assert_for_2 (op1, e, rhs_code, op0, op1, invert, asserts);
5603 else if ((code == NE_EXPR
5604 && gimple_assign_rhs_code (op_def) == BIT_AND_EXPR)
5605 || (code == EQ_EXPR
5606 && gimple_assign_rhs_code (op_def) == BIT_IOR_EXPR))
5608 /* Recurse on each operand. */
5609 tree op0 = gimple_assign_rhs1 (op_def);
5610 tree op1 = gimple_assign_rhs2 (op_def);
5611 if (TREE_CODE (op0) == SSA_NAME
5612 && has_single_use (op0))
5613 register_edge_assert_for_1 (op0, code, e, asserts);
5614 if (TREE_CODE (op1) == SSA_NAME
5615 && has_single_use (op1))
5616 register_edge_assert_for_1 (op1, code, e, asserts);
5618 else if (gimple_assign_rhs_code (op_def) == BIT_NOT_EXPR
5619 && TYPE_PRECISION (TREE_TYPE (gimple_assign_lhs (op_def))) == 1)
5621 /* Recurse, flipping CODE. */
5622 code = invert_tree_comparison (code, false);
5623 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
5625 else if (gimple_assign_rhs_code (op_def) == SSA_NAME)
5627 /* Recurse through the copy. */
5628 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
5630 else if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (op_def)))
5632 /* Recurse through the type conversion, unless it is a narrowing
5633 conversion or conversion from non-integral type. */
5634 tree rhs = gimple_assign_rhs1 (op_def);
5635 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs))
5636 && (TYPE_PRECISION (TREE_TYPE (rhs))
5637 <= TYPE_PRECISION (TREE_TYPE (op))))
5638 register_edge_assert_for_1 (rhs, code, e, asserts);
5642 /* Check if comparison
5643 NAME COND_OP INTEGER_CST
5644 has a form of
5645 (X & 11...100..0) COND_OP XX...X00...0
5646 Such comparison can yield assertions like
5647 X >= XX...X00...0
5648 X <= XX...X11...1
5649 in case of COND_OP being NE_EXPR or
5650 X < XX...X00...0
5651 X > XX...X11...1
5652 in case of EQ_EXPR. */
5654 static bool
5655 is_masked_range_test (tree name, tree valt, enum tree_code cond_code,
5656 tree *new_name, tree *low, enum tree_code *low_code,
5657 tree *high, enum tree_code *high_code)
5659 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5661 if (!is_gimple_assign (def_stmt)
5662 || gimple_assign_rhs_code (def_stmt) != BIT_AND_EXPR)
5663 return false;
5665 tree t = gimple_assign_rhs1 (def_stmt);
5666 tree maskt = gimple_assign_rhs2 (def_stmt);
5667 if (TREE_CODE (t) != SSA_NAME || TREE_CODE (maskt) != INTEGER_CST)
5668 return false;
5670 wide_int mask = maskt;
5671 wide_int inv_mask = ~mask;
5672 wide_int val = valt; // Assume VALT is INTEGER_CST
5674 if ((inv_mask & (inv_mask + 1)) != 0
5675 || (val & mask) != val)
5676 return false;
5678 bool is_range = cond_code == EQ_EXPR;
5680 tree type = TREE_TYPE (t);
5681 wide_int min = wi::min_value (type),
5682 max = wi::max_value (type);
5684 if (is_range)
5686 *low_code = val == min ? ERROR_MARK : GE_EXPR;
5687 *high_code = val == max ? ERROR_MARK : LE_EXPR;
5689 else
5691 /* We can still generate assertion if one of alternatives
5692 is known to always be false. */
5693 if (val == min)
5695 *low_code = (enum tree_code) 0;
5696 *high_code = GT_EXPR;
5698 else if ((val | inv_mask) == max)
5700 *low_code = LT_EXPR;
5701 *high_code = (enum tree_code) 0;
5703 else
5704 return false;
5707 *new_name = t;
5708 *low = wide_int_to_tree (type, val);
5709 *high = wide_int_to_tree (type, val | inv_mask);
5711 if (wi::neg_p (val, TYPE_SIGN (type)))
5712 std::swap (*low, *high);
5714 return true;
5717 /* Try to register an edge assertion for SSA name NAME on edge E for
5718 the condition COND contributing to the conditional jump pointed to by
5719 SI. */
5721 static void
5722 register_edge_assert_for (tree name, edge e,
5723 enum tree_code cond_code, tree cond_op0,
5724 tree cond_op1, vec<assert_info> &asserts)
5726 tree val;
5727 enum tree_code comp_code;
5728 bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
5730 /* Do not attempt to infer anything in names that flow through
5731 abnormal edges. */
5732 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
5733 return;
5735 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
5736 cond_op0, cond_op1,
5737 is_else_edge,
5738 &comp_code, &val))
5739 return;
5741 /* Register ASSERT_EXPRs for name. */
5742 register_edge_assert_for_2 (name, e, cond_code, cond_op0,
5743 cond_op1, is_else_edge, asserts);
5746 /* If COND is effectively an equality test of an SSA_NAME against
5747 the value zero or one, then we may be able to assert values
5748 for SSA_NAMEs which flow into COND. */
5750 /* In the case of NAME == 1 or NAME != 0, for BIT_AND_EXPR defining
5751 statement of NAME we can assert both operands of the BIT_AND_EXPR
5752 have nonzero value. */
5753 if (((comp_code == EQ_EXPR && integer_onep (val))
5754 || (comp_code == NE_EXPR && integer_zerop (val))))
5756 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5758 if (is_gimple_assign (def_stmt)
5759 && gimple_assign_rhs_code (def_stmt) == BIT_AND_EXPR)
5761 tree op0 = gimple_assign_rhs1 (def_stmt);
5762 tree op1 = gimple_assign_rhs2 (def_stmt);
5763 register_edge_assert_for_1 (op0, NE_EXPR, e, asserts);
5764 register_edge_assert_for_1 (op1, NE_EXPR, e, asserts);
5768 /* In the case of NAME == 0 or NAME != 1, for BIT_IOR_EXPR defining
5769 statement of NAME we can assert both operands of the BIT_IOR_EXPR
5770 have zero value. */
5771 if (((comp_code == EQ_EXPR && integer_zerop (val))
5772 || (comp_code == NE_EXPR && integer_onep (val))))
5774 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
5776 /* For BIT_IOR_EXPR only if NAME == 0 both operands have
5777 necessarily zero value, or if type-precision is one. */
5778 if (is_gimple_assign (def_stmt)
5779 && (gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR
5780 && (TYPE_PRECISION (TREE_TYPE (name)) == 1
5781 || comp_code == EQ_EXPR)))
5783 tree op0 = gimple_assign_rhs1 (def_stmt);
5784 tree op1 = gimple_assign_rhs2 (def_stmt);
5785 register_edge_assert_for_1 (op0, EQ_EXPR, e, asserts);
5786 register_edge_assert_for_1 (op1, EQ_EXPR, e, asserts);
5790 /* Sometimes we can infer ranges from (NAME & MASK) == VALUE. */
5791 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
5792 && TREE_CODE (val) == INTEGER_CST)
5794 enum tree_code low_code, high_code;
5795 tree low, high;
5796 if (is_masked_range_test (name, val, comp_code, &name, &low,
5797 &low_code, &high, &high_code))
5799 if (low_code != ERROR_MARK)
5800 register_edge_assert_for_2 (name, e, low_code, name,
5801 low, /*invert*/false, asserts);
5802 if (high_code != ERROR_MARK)
5803 register_edge_assert_for_2 (name, e, high_code, name,
5804 high, /*invert*/false, asserts);
5809 /* Finish found ASSERTS for E and register them at GSI. */
5811 static void
5812 finish_register_edge_assert_for (edge e, gimple_stmt_iterator gsi,
5813 vec<assert_info> &asserts)
5815 for (unsigned i = 0; i < asserts.length (); ++i)
5816 /* Only register an ASSERT_EXPR if NAME was found in the sub-graph
5817 reachable from E. */
5818 if (live_on_edge (e, asserts[i].name))
5819 register_new_assert_for (asserts[i].name, asserts[i].expr,
5820 asserts[i].comp_code, asserts[i].val,
5821 NULL, e, gsi);
5826 /* Determine whether the outgoing edges of BB should receive an
5827 ASSERT_EXPR for each of the operands of BB's LAST statement.
5828 The last statement of BB must be a COND_EXPR.
5830 If any of the sub-graphs rooted at BB have an interesting use of
5831 the predicate operands, an assert location node is added to the
5832 list of assertions for the corresponding operands. */
5834 static void
5835 find_conditional_asserts (basic_block bb, gcond *last)
5837 gimple_stmt_iterator bsi;
5838 tree op;
5839 edge_iterator ei;
5840 edge e;
5841 ssa_op_iter iter;
5843 bsi = gsi_for_stmt (last);
5845 /* Look for uses of the operands in each of the sub-graphs
5846 rooted at BB. We need to check each of the outgoing edges
5847 separately, so that we know what kind of ASSERT_EXPR to
5848 insert. */
5849 FOR_EACH_EDGE (e, ei, bb->succs)
5851 if (e->dest == bb)
5852 continue;
5854 /* Register the necessary assertions for each operand in the
5855 conditional predicate. */
5856 auto_vec<assert_info, 8> asserts;
5857 FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
5858 register_edge_assert_for (op, e,
5859 gimple_cond_code (last),
5860 gimple_cond_lhs (last),
5861 gimple_cond_rhs (last), asserts);
5862 finish_register_edge_assert_for (e, bsi, asserts);
5866 struct case_info
5868 tree expr;
5869 basic_block bb;
5872 /* Compare two case labels sorting first by the destination bb index
5873 and then by the case value. */
5875 static int
5876 compare_case_labels (const void *p1, const void *p2)
5878 const struct case_info *ci1 = (const struct case_info *) p1;
5879 const struct case_info *ci2 = (const struct case_info *) p2;
5880 int idx1 = ci1->bb->index;
5881 int idx2 = ci2->bb->index;
5883 if (idx1 < idx2)
5884 return -1;
5885 else if (idx1 == idx2)
5887 /* Make sure the default label is first in a group. */
5888 if (!CASE_LOW (ci1->expr))
5889 return -1;
5890 else if (!CASE_LOW (ci2->expr))
5891 return 1;
5892 else
5893 return tree_int_cst_compare (CASE_LOW (ci1->expr),
5894 CASE_LOW (ci2->expr));
5896 else
5897 return 1;
5900 /* Determine whether the outgoing edges of BB should receive an
5901 ASSERT_EXPR for each of the operands of BB's LAST statement.
5902 The last statement of BB must be a SWITCH_EXPR.
5904 If any of the sub-graphs rooted at BB have an interesting use of
5905 the predicate operands, an assert location node is added to the
5906 list of assertions for the corresponding operands. */
5908 static void
5909 find_switch_asserts (basic_block bb, gswitch *last)
5911 gimple_stmt_iterator bsi;
5912 tree op;
5913 edge e;
5914 struct case_info *ci;
5915 size_t n = gimple_switch_num_labels (last);
5916 #if GCC_VERSION >= 4000
5917 unsigned int idx;
5918 #else
5919 /* Work around GCC 3.4 bug (PR 37086). */
5920 volatile unsigned int idx;
5921 #endif
5923 bsi = gsi_for_stmt (last);
5924 op = gimple_switch_index (last);
5925 if (TREE_CODE (op) != SSA_NAME)
5926 return;
5928 /* Build a vector of case labels sorted by destination label. */
5929 ci = XNEWVEC (struct case_info, n);
5930 for (idx = 0; idx < n; ++idx)
5932 ci[idx].expr = gimple_switch_label (last, idx);
5933 ci[idx].bb = label_to_block (CASE_LABEL (ci[idx].expr));
5935 edge default_edge = find_edge (bb, ci[0].bb);
5936 qsort (ci, n, sizeof (struct case_info), compare_case_labels);
5938 for (idx = 0; idx < n; ++idx)
5940 tree min, max;
5941 tree cl = ci[idx].expr;
5942 basic_block cbb = ci[idx].bb;
5944 min = CASE_LOW (cl);
5945 max = CASE_HIGH (cl);
5947 /* If there are multiple case labels with the same destination
5948 we need to combine them to a single value range for the edge. */
5949 if (idx + 1 < n && cbb == ci[idx + 1].bb)
5951 /* Skip labels until the last of the group. */
5952 do {
5953 ++idx;
5954 } while (idx < n && cbb == ci[idx].bb);
5955 --idx;
5957 /* Pick up the maximum of the case label range. */
5958 if (CASE_HIGH (ci[idx].expr))
5959 max = CASE_HIGH (ci[idx].expr);
5960 else
5961 max = CASE_LOW (ci[idx].expr);
5964 /* Can't extract a useful assertion out of a range that includes the
5965 default label. */
5966 if (min == NULL_TREE)
5967 continue;
5969 /* Find the edge to register the assert expr on. */
5970 e = find_edge (bb, cbb);
5972 /* Register the necessary assertions for the operand in the
5973 SWITCH_EXPR. */
5974 auto_vec<assert_info, 8> asserts;
5975 register_edge_assert_for (op, e,
5976 max ? GE_EXPR : EQ_EXPR,
5977 op, fold_convert (TREE_TYPE (op), min),
5978 asserts);
5979 if (max)
5980 register_edge_assert_for (op, e, LE_EXPR, op,
5981 fold_convert (TREE_TYPE (op), max),
5982 asserts);
5983 finish_register_edge_assert_for (e, bsi, asserts);
5986 XDELETEVEC (ci);
5988 if (!live_on_edge (default_edge, op))
5989 return;
5991 /* Now register along the default label assertions that correspond to the
5992 anti-range of each label. */
5993 int insertion_limit = PARAM_VALUE (PARAM_MAX_VRP_SWITCH_ASSERTIONS);
5994 if (insertion_limit == 0)
5995 return;
5997 /* We can't do this if the default case shares a label with another case. */
5998 tree default_cl = gimple_switch_default_label (last);
5999 for (idx = 1; idx < n; idx++)
6001 tree min, max;
6002 tree cl = gimple_switch_label (last, idx);
6003 if (CASE_LABEL (cl) == CASE_LABEL (default_cl))
6004 continue;
6006 min = CASE_LOW (cl);
6007 max = CASE_HIGH (cl);
6009 /* Combine contiguous case ranges to reduce the number of assertions
6010 to insert. */
6011 for (idx = idx + 1; idx < n; idx++)
6013 tree next_min, next_max;
6014 tree next_cl = gimple_switch_label (last, idx);
6015 if (CASE_LABEL (next_cl) == CASE_LABEL (default_cl))
6016 break;
6018 next_min = CASE_LOW (next_cl);
6019 next_max = CASE_HIGH (next_cl);
6021 wide_int difference = wi::sub (next_min, max ? max : min);
6022 if (wi::eq_p (difference, 1))
6023 max = next_max ? next_max : next_min;
6024 else
6025 break;
6027 idx--;
6029 if (max == NULL_TREE)
6031 /* Register the assertion OP != MIN. */
6032 auto_vec<assert_info, 8> asserts;
6033 min = fold_convert (TREE_TYPE (op), min);
6034 register_edge_assert_for (op, default_edge, NE_EXPR, op, min,
6035 asserts);
6036 finish_register_edge_assert_for (default_edge, bsi, asserts);
6038 else
6040 /* Register the assertion (unsigned)OP - MIN > (MAX - MIN),
6041 which will give OP the anti-range ~[MIN,MAX]. */
6042 tree uop = fold_convert (unsigned_type_for (TREE_TYPE (op)), op);
6043 min = fold_convert (TREE_TYPE (uop), min);
6044 max = fold_convert (TREE_TYPE (uop), max);
6046 tree lhs = fold_build2 (MINUS_EXPR, TREE_TYPE (uop), uop, min);
6047 tree rhs = int_const_binop (MINUS_EXPR, max, min);
6048 register_new_assert_for (op, lhs, GT_EXPR, rhs,
6049 NULL, default_edge, bsi);
6052 if (--insertion_limit == 0)
6053 break;
6058 /* Traverse all the statements in block BB looking for statements that
6059 may generate useful assertions for the SSA names in their operand.
6060 If a statement produces a useful assertion A for name N_i, then the
6061 list of assertions already generated for N_i is scanned to
6062 determine if A is actually needed.
6064 If N_i already had the assertion A at a location dominating the
6065 current location, then nothing needs to be done. Otherwise, the
6066 new location for A is recorded instead.
6068 1- For every statement S in BB, all the variables used by S are
6069 added to bitmap FOUND_IN_SUBGRAPH.
6071 2- If statement S uses an operand N in a way that exposes a known
6072 value range for N, then if N was not already generated by an
6073 ASSERT_EXPR, create a new assert location for N. For instance,
6074 if N is a pointer and the statement dereferences it, we can
6075 assume that N is not NULL.
6077 3- COND_EXPRs are a special case of #2. We can derive range
6078 information from the predicate but need to insert different
6079 ASSERT_EXPRs for each of the sub-graphs rooted at the
6080 conditional block. If the last statement of BB is a conditional
6081 expression of the form 'X op Y', then
6083 a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
6085 b) If the conditional is the only entry point to the sub-graph
6086 corresponding to the THEN_CLAUSE, recurse into it. On
6087 return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
6088 an ASSERT_EXPR is added for the corresponding variable.
6090 c) Repeat step (b) on the ELSE_CLAUSE.
6092 d) Mark X and Y in FOUND_IN_SUBGRAPH.
6094 For instance,
6096 if (a == 9)
6097 b = a;
6098 else
6099 b = c + 1;
6101 In this case, an assertion on the THEN clause is useful to
6102 determine that 'a' is always 9 on that edge. However, an assertion
6103 on the ELSE clause would be unnecessary.
6105 4- If BB does not end in a conditional expression, then we recurse
6106 into BB's dominator children.
6108 At the end of the recursive traversal, every SSA name will have a
6109 list of locations where ASSERT_EXPRs should be added. When a new
6110 location for name N is found, it is registered by calling
6111 register_new_assert_for. That function keeps track of all the
6112 registered assertions to prevent adding unnecessary assertions.
6113 For instance, if a pointer P_4 is dereferenced more than once in a
6114 dominator tree, only the location dominating all the dereference of
6115 P_4 will receive an ASSERT_EXPR. */
6117 static void
6118 find_assert_locations_1 (basic_block bb, sbitmap live)
6120 gimple *last;
6122 last = last_stmt (bb);
6124 /* If BB's last statement is a conditional statement involving integer
6125 operands, determine if we need to add ASSERT_EXPRs. */
6126 if (last
6127 && gimple_code (last) == GIMPLE_COND
6128 && !fp_predicate (last)
6129 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
6130 find_conditional_asserts (bb, as_a <gcond *> (last));
6132 /* If BB's last statement is a switch statement involving integer
6133 operands, determine if we need to add ASSERT_EXPRs. */
6134 if (last
6135 && gimple_code (last) == GIMPLE_SWITCH
6136 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
6137 find_switch_asserts (bb, as_a <gswitch *> (last));
6139 /* Traverse all the statements in BB marking used names and looking
6140 for statements that may infer assertions for their used operands. */
6141 for (gimple_stmt_iterator si = gsi_last_bb (bb); !gsi_end_p (si);
6142 gsi_prev (&si))
6144 gimple *stmt;
6145 tree op;
6146 ssa_op_iter i;
6148 stmt = gsi_stmt (si);
6150 if (is_gimple_debug (stmt))
6151 continue;
6153 /* See if we can derive an assertion for any of STMT's operands. */
6154 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
6156 tree value;
6157 enum tree_code comp_code;
6159 /* If op is not live beyond this stmt, do not bother to insert
6160 asserts for it. */
6161 if (!bitmap_bit_p (live, SSA_NAME_VERSION (op)))
6162 continue;
6164 /* If OP is used in such a way that we can infer a value
6165 range for it, and we don't find a previous assertion for
6166 it, create a new assertion location node for OP. */
6167 if (infer_value_range (stmt, op, &comp_code, &value))
6169 /* If we are able to infer a nonzero value range for OP,
6170 then walk backwards through the use-def chain to see if OP
6171 was set via a typecast.
6173 If so, then we can also infer a nonzero value range
6174 for the operand of the NOP_EXPR. */
6175 if (comp_code == NE_EXPR && integer_zerop (value))
6177 tree t = op;
6178 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
6180 while (is_gimple_assign (def_stmt)
6181 && CONVERT_EXPR_CODE_P
6182 (gimple_assign_rhs_code (def_stmt))
6183 && TREE_CODE
6184 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
6185 && POINTER_TYPE_P
6186 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
6188 t = gimple_assign_rhs1 (def_stmt);
6189 def_stmt = SSA_NAME_DEF_STMT (t);
6191 /* Note we want to register the assert for the
6192 operand of the NOP_EXPR after SI, not after the
6193 conversion. */
6194 if (bitmap_bit_p (live, SSA_NAME_VERSION (t)))
6195 register_new_assert_for (t, t, comp_code, value,
6196 bb, NULL, si);
6200 register_new_assert_for (op, op, comp_code, value, bb, NULL, si);
6204 /* Update live. */
6205 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
6206 bitmap_set_bit (live, SSA_NAME_VERSION (op));
6207 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_DEF)
6208 bitmap_clear_bit (live, SSA_NAME_VERSION (op));
6211 /* Traverse all PHI nodes in BB, updating live. */
6212 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
6213 gsi_next (&si))
6215 use_operand_p arg_p;
6216 ssa_op_iter i;
6217 gphi *phi = si.phi ();
6218 tree res = gimple_phi_result (phi);
6220 if (virtual_operand_p (res))
6221 continue;
6223 FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
6225 tree arg = USE_FROM_PTR (arg_p);
6226 if (TREE_CODE (arg) == SSA_NAME)
6227 bitmap_set_bit (live, SSA_NAME_VERSION (arg));
6230 bitmap_clear_bit (live, SSA_NAME_VERSION (res));
6234 /* Do an RPO walk over the function computing SSA name liveness
6235 on-the-fly and deciding on assert expressions to insert. */
6237 static void
6238 find_assert_locations (void)
6240 int *rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
6241 int *bb_rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
6242 int *last_rpo = XCNEWVEC (int, last_basic_block_for_fn (cfun));
6243 int rpo_cnt, i;
6245 live = XCNEWVEC (sbitmap, last_basic_block_for_fn (cfun));
6246 rpo_cnt = pre_and_rev_post_order_compute (NULL, rpo, false);
6247 for (i = 0; i < rpo_cnt; ++i)
6248 bb_rpo[rpo[i]] = i;
6250 /* Pre-seed loop latch liveness from loop header PHI nodes. Due to
6251 the order we compute liveness and insert asserts we otherwise
6252 fail to insert asserts into the loop latch. */
6253 loop_p loop;
6254 FOR_EACH_LOOP (loop, 0)
6256 i = loop->latch->index;
6257 unsigned int j = single_succ_edge (loop->latch)->dest_idx;
6258 for (gphi_iterator gsi = gsi_start_phis (loop->header);
6259 !gsi_end_p (gsi); gsi_next (&gsi))
6261 gphi *phi = gsi.phi ();
6262 if (virtual_operand_p (gimple_phi_result (phi)))
6263 continue;
6264 tree arg = gimple_phi_arg_def (phi, j);
6265 if (TREE_CODE (arg) == SSA_NAME)
6267 if (live[i] == NULL)
6269 live[i] = sbitmap_alloc (num_ssa_names);
6270 bitmap_clear (live[i]);
6272 bitmap_set_bit (live[i], SSA_NAME_VERSION (arg));
6277 for (i = rpo_cnt - 1; i >= 0; --i)
6279 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, rpo[i]);
6280 edge e;
6281 edge_iterator ei;
6283 if (!live[rpo[i]])
6285 live[rpo[i]] = sbitmap_alloc (num_ssa_names);
6286 bitmap_clear (live[rpo[i]]);
6289 /* Process BB and update the live information with uses in
6290 this block. */
6291 find_assert_locations_1 (bb, live[rpo[i]]);
6293 /* Merge liveness into the predecessor blocks and free it. */
6294 if (!bitmap_empty_p (live[rpo[i]]))
6296 int pred_rpo = i;
6297 FOR_EACH_EDGE (e, ei, bb->preds)
6299 int pred = e->src->index;
6300 if ((e->flags & EDGE_DFS_BACK) || pred == ENTRY_BLOCK)
6301 continue;
6303 if (!live[pred])
6305 live[pred] = sbitmap_alloc (num_ssa_names);
6306 bitmap_clear (live[pred]);
6308 bitmap_ior (live[pred], live[pred], live[rpo[i]]);
6310 if (bb_rpo[pred] < pred_rpo)
6311 pred_rpo = bb_rpo[pred];
6314 /* Record the RPO number of the last visited block that needs
6315 live information from this block. */
6316 last_rpo[rpo[i]] = pred_rpo;
6318 else
6320 sbitmap_free (live[rpo[i]]);
6321 live[rpo[i]] = NULL;
6324 /* We can free all successors live bitmaps if all their
6325 predecessors have been visited already. */
6326 FOR_EACH_EDGE (e, ei, bb->succs)
6327 if (last_rpo[e->dest->index] == i
6328 && live[e->dest->index])
6330 sbitmap_free (live[e->dest->index]);
6331 live[e->dest->index] = NULL;
6335 XDELETEVEC (rpo);
6336 XDELETEVEC (bb_rpo);
6337 XDELETEVEC (last_rpo);
6338 for (i = 0; i < last_basic_block_for_fn (cfun); ++i)
6339 if (live[i])
6340 sbitmap_free (live[i]);
6341 XDELETEVEC (live);
6344 /* Create an ASSERT_EXPR for NAME and insert it in the location
6345 indicated by LOC. Return true if we made any edge insertions. */
6347 static bool
6348 process_assert_insertions_for (tree name, assert_locus *loc)
6350 /* Build the comparison expression NAME_i COMP_CODE VAL. */
6351 gimple *stmt;
6352 tree cond;
6353 gimple *assert_stmt;
6354 edge_iterator ei;
6355 edge e;
6357 /* If we have X <=> X do not insert an assert expr for that. */
6358 if (loc->expr == loc->val)
6359 return false;
6361 cond = build2 (loc->comp_code, boolean_type_node, loc->expr, loc->val);
6362 assert_stmt = build_assert_expr_for (cond, name);
6363 if (loc->e)
6365 /* We have been asked to insert the assertion on an edge. This
6366 is used only by COND_EXPR and SWITCH_EXPR assertions. */
6367 gcc_checking_assert (gimple_code (gsi_stmt (loc->si)) == GIMPLE_COND
6368 || (gimple_code (gsi_stmt (loc->si))
6369 == GIMPLE_SWITCH));
6371 gsi_insert_on_edge (loc->e, assert_stmt);
6372 return true;
6375 /* If the stmt iterator points at the end then this is an insertion
6376 at the beginning of a block. */
6377 if (gsi_end_p (loc->si))
6379 gimple_stmt_iterator si = gsi_after_labels (loc->bb);
6380 gsi_insert_before (&si, assert_stmt, GSI_SAME_STMT);
6381 return false;
6384 /* Otherwise, we can insert right after LOC->SI iff the
6385 statement must not be the last statement in the block. */
6386 stmt = gsi_stmt (loc->si);
6387 if (!stmt_ends_bb_p (stmt))
6389 gsi_insert_after (&loc->si, assert_stmt, GSI_SAME_STMT);
6390 return false;
6393 /* If STMT must be the last statement in BB, we can only insert new
6394 assertions on the non-abnormal edge out of BB. Note that since
6395 STMT is not control flow, there may only be one non-abnormal/eh edge
6396 out of BB. */
6397 FOR_EACH_EDGE (e, ei, loc->bb->succs)
6398 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
6400 gsi_insert_on_edge (e, assert_stmt);
6401 return true;
6404 gcc_unreachable ();
6407 /* Qsort helper for sorting assert locations. If stable is true, don't
6408 use iterative_hash_expr because it can be unstable for -fcompare-debug,
6409 on the other side some pointers might be NULL. */
6411 template <bool stable>
6412 static int
6413 compare_assert_loc (const void *pa, const void *pb)
6415 assert_locus * const a = *(assert_locus * const *)pa;
6416 assert_locus * const b = *(assert_locus * const *)pb;
6418 /* If stable, some asserts might be optimized away already, sort
6419 them last. */
6420 if (stable)
6422 if (a == NULL)
6423 return b != NULL;
6424 else if (b == NULL)
6425 return -1;
6428 if (a->e == NULL && b->e != NULL)
6429 return 1;
6430 else if (a->e != NULL && b->e == NULL)
6431 return -1;
6433 /* After the above checks, we know that (a->e == NULL) == (b->e == NULL),
6434 no need to test both a->e and b->e. */
6436 /* Sort after destination index. */
6437 if (a->e == NULL)
6439 else if (a->e->dest->index > b->e->dest->index)
6440 return 1;
6441 else if (a->e->dest->index < b->e->dest->index)
6442 return -1;
6444 /* Sort after comp_code. */
6445 if (a->comp_code > b->comp_code)
6446 return 1;
6447 else if (a->comp_code < b->comp_code)
6448 return -1;
6450 hashval_t ha, hb;
6452 /* E.g. if a->val is ADDR_EXPR of a VAR_DECL, iterative_hash_expr
6453 uses DECL_UID of the VAR_DECL, so sorting might differ between
6454 -g and -g0. When doing the removal of redundant assert exprs
6455 and commonization to successors, this does not matter, but for
6456 the final sort needs to be stable. */
6457 if (stable)
6459 ha = 0;
6460 hb = 0;
6462 else
6464 ha = iterative_hash_expr (a->expr, iterative_hash_expr (a->val, 0));
6465 hb = iterative_hash_expr (b->expr, iterative_hash_expr (b->val, 0));
6468 /* Break the tie using hashing and source/bb index. */
6469 if (ha == hb)
6470 return (a->e != NULL
6471 ? a->e->src->index - b->e->src->index
6472 : a->bb->index - b->bb->index);
6473 return ha > hb ? 1 : -1;
6476 /* Process all the insertions registered for every name N_i registered
6477 in NEED_ASSERT_FOR. The list of assertions to be inserted are
6478 found in ASSERTS_FOR[i]. */
6480 static void
6481 process_assert_insertions (void)
6483 unsigned i;
6484 bitmap_iterator bi;
6485 bool update_edges_p = false;
6486 int num_asserts = 0;
6488 if (dump_file && (dump_flags & TDF_DETAILS))
6489 dump_all_asserts (dump_file);
6491 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
6493 assert_locus *loc = asserts_for[i];
6494 gcc_assert (loc);
6496 auto_vec<assert_locus *, 16> asserts;
6497 for (; loc; loc = loc->next)
6498 asserts.safe_push (loc);
6499 asserts.qsort (compare_assert_loc<false>);
6501 /* Push down common asserts to successors and remove redundant ones. */
6502 unsigned ecnt = 0;
6503 assert_locus *common = NULL;
6504 unsigned commonj = 0;
6505 for (unsigned j = 0; j < asserts.length (); ++j)
6507 loc = asserts[j];
6508 if (! loc->e)
6509 common = NULL;
6510 else if (! common
6511 || loc->e->dest != common->e->dest
6512 || loc->comp_code != common->comp_code
6513 || ! operand_equal_p (loc->val, common->val, 0)
6514 || ! operand_equal_p (loc->expr, common->expr, 0))
6516 commonj = j;
6517 common = loc;
6518 ecnt = 1;
6520 else if (loc->e == asserts[j-1]->e)
6522 /* Remove duplicate asserts. */
6523 if (commonj == j - 1)
6525 commonj = j;
6526 common = loc;
6528 free (asserts[j-1]);
6529 asserts[j-1] = NULL;
6531 else
6533 ecnt++;
6534 if (EDGE_COUNT (common->e->dest->preds) == ecnt)
6536 /* We have the same assertion on all incoming edges of a BB.
6537 Insert it at the beginning of that block. */
6538 loc->bb = loc->e->dest;
6539 loc->e = NULL;
6540 loc->si = gsi_none ();
6541 common = NULL;
6542 /* Clear asserts commoned. */
6543 for (; commonj != j; ++commonj)
6544 if (asserts[commonj])
6546 free (asserts[commonj]);
6547 asserts[commonj] = NULL;
6553 /* The asserts vector sorting above might be unstable for
6554 -fcompare-debug, sort again to ensure a stable sort. */
6555 asserts.qsort (compare_assert_loc<true>);
6556 for (unsigned j = 0; j < asserts.length (); ++j)
6558 loc = asserts[j];
6559 if (! loc)
6560 break;
6561 update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
6562 num_asserts++;
6563 free (loc);
6567 if (update_edges_p)
6568 gsi_commit_edge_inserts ();
6570 statistics_counter_event (cfun, "Number of ASSERT_EXPR expressions inserted",
6571 num_asserts);
6575 /* Traverse the flowgraph looking for conditional jumps to insert range
6576 expressions. These range expressions are meant to provide information
6577 to optimizations that need to reason in terms of value ranges. They
6578 will not be expanded into RTL. For instance, given:
6580 x = ...
6581 y = ...
6582 if (x < y)
6583 y = x - 2;
6584 else
6585 x = y + 3;
6587 this pass will transform the code into:
6589 x = ...
6590 y = ...
6591 if (x < y)
6593 x = ASSERT_EXPR <x, x < y>
6594 y = x - 2
6596 else
6598 y = ASSERT_EXPR <y, x >= y>
6599 x = y + 3
6602 The idea is that once copy and constant propagation have run, other
6603 optimizations will be able to determine what ranges of values can 'x'
6604 take in different paths of the code, simply by checking the reaching
6605 definition of 'x'. */
6607 static void
6608 insert_range_assertions (void)
6610 need_assert_for = BITMAP_ALLOC (NULL);
6611 asserts_for = XCNEWVEC (assert_locus *, num_ssa_names);
6613 calculate_dominance_info (CDI_DOMINATORS);
6615 find_assert_locations ();
6616 if (!bitmap_empty_p (need_assert_for))
6618 process_assert_insertions ();
6619 update_ssa (TODO_update_ssa_no_phi);
6622 if (dump_file && (dump_flags & TDF_DETAILS))
6624 fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
6625 dump_function_to_file (current_function_decl, dump_file, dump_flags);
6628 free (asserts_for);
6629 BITMAP_FREE (need_assert_for);
6632 /* Checks one ARRAY_REF in REF, located at LOCUS. Ignores flexible arrays
6633 and "struct" hacks. If VRP can determine that the
6634 array subscript is a constant, check if it is outside valid
6635 range. If the array subscript is a RANGE, warn if it is
6636 non-overlapping with valid range.
6637 IGNORE_OFF_BY_ONE is true if the ARRAY_REF is inside a ADDR_EXPR. */
6639 static void
6640 check_array_ref (location_t location, tree ref, bool ignore_off_by_one)
6642 value_range *vr = NULL;
6643 tree low_sub, up_sub;
6644 tree low_bound, up_bound, up_bound_p1;
6646 if (TREE_NO_WARNING (ref))
6647 return;
6649 low_sub = up_sub = TREE_OPERAND (ref, 1);
6650 up_bound = array_ref_up_bound (ref);
6652 /* Can not check flexible arrays. */
6653 if (!up_bound
6654 || TREE_CODE (up_bound) != INTEGER_CST)
6655 return;
6657 /* Accesses to trailing arrays via pointers may access storage
6658 beyond the types array bounds. */
6659 if (warn_array_bounds < 2
6660 && array_at_struct_end_p (ref))
6661 return;
6663 low_bound = array_ref_low_bound (ref);
6664 up_bound_p1 = int_const_binop (PLUS_EXPR, up_bound,
6665 build_int_cst (TREE_TYPE (up_bound), 1));
6667 /* Empty array. */
6668 if (tree_int_cst_equal (low_bound, up_bound_p1))
6670 warning_at (location, OPT_Warray_bounds,
6671 "array subscript is above array bounds");
6672 TREE_NO_WARNING (ref) = 1;
6675 if (TREE_CODE (low_sub) == SSA_NAME)
6677 vr = get_value_range (low_sub);
6678 if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
6680 low_sub = vr->type == VR_RANGE ? vr->max : vr->min;
6681 up_sub = vr->type == VR_RANGE ? vr->min : vr->max;
6685 if (vr && vr->type == VR_ANTI_RANGE)
6687 if (TREE_CODE (up_sub) == INTEGER_CST
6688 && (ignore_off_by_one
6689 ? tree_int_cst_lt (up_bound, up_sub)
6690 : tree_int_cst_le (up_bound, up_sub))
6691 && TREE_CODE (low_sub) == INTEGER_CST
6692 && tree_int_cst_le (low_sub, low_bound))
6694 warning_at (location, OPT_Warray_bounds,
6695 "array subscript is outside array bounds");
6696 TREE_NO_WARNING (ref) = 1;
6699 else if (TREE_CODE (up_sub) == INTEGER_CST
6700 && (ignore_off_by_one
6701 ? !tree_int_cst_le (up_sub, up_bound_p1)
6702 : !tree_int_cst_le (up_sub, up_bound)))
6704 if (dump_file && (dump_flags & TDF_DETAILS))
6706 fprintf (dump_file, "Array bound warning for ");
6707 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
6708 fprintf (dump_file, "\n");
6710 warning_at (location, OPT_Warray_bounds,
6711 "array subscript is above array bounds");
6712 TREE_NO_WARNING (ref) = 1;
6714 else if (TREE_CODE (low_sub) == INTEGER_CST
6715 && tree_int_cst_lt (low_sub, low_bound))
6717 if (dump_file && (dump_flags & TDF_DETAILS))
6719 fprintf (dump_file, "Array bound warning for ");
6720 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
6721 fprintf (dump_file, "\n");
6723 warning_at (location, OPT_Warray_bounds,
6724 "array subscript is below array bounds");
6725 TREE_NO_WARNING (ref) = 1;
6729 /* Searches if the expr T, located at LOCATION computes
6730 address of an ARRAY_REF, and call check_array_ref on it. */
6732 static void
6733 search_for_addr_array (tree t, location_t location)
6735 /* Check each ARRAY_REFs in the reference chain. */
6738 if (TREE_CODE (t) == ARRAY_REF)
6739 check_array_ref (location, t, true /*ignore_off_by_one*/);
6741 t = TREE_OPERAND (t, 0);
6743 while (handled_component_p (t));
6745 if (TREE_CODE (t) == MEM_REF
6746 && TREE_CODE (TREE_OPERAND (t, 0)) == ADDR_EXPR
6747 && !TREE_NO_WARNING (t))
6749 tree tem = TREE_OPERAND (TREE_OPERAND (t, 0), 0);
6750 tree low_bound, up_bound, el_sz;
6751 offset_int idx;
6752 if (TREE_CODE (TREE_TYPE (tem)) != ARRAY_TYPE
6753 || TREE_CODE (TREE_TYPE (TREE_TYPE (tem))) == ARRAY_TYPE
6754 || !TYPE_DOMAIN (TREE_TYPE (tem)))
6755 return;
6757 low_bound = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
6758 up_bound = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
6759 el_sz = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (tem)));
6760 if (!low_bound
6761 || TREE_CODE (low_bound) != INTEGER_CST
6762 || !up_bound
6763 || TREE_CODE (up_bound) != INTEGER_CST
6764 || !el_sz
6765 || TREE_CODE (el_sz) != INTEGER_CST)
6766 return;
6768 idx = mem_ref_offset (t);
6769 idx = wi::sdiv_trunc (idx, wi::to_offset (el_sz));
6770 if (idx < 0)
6772 if (dump_file && (dump_flags & TDF_DETAILS))
6774 fprintf (dump_file, "Array bound warning for ");
6775 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
6776 fprintf (dump_file, "\n");
6778 warning_at (location, OPT_Warray_bounds,
6779 "array subscript is below array bounds");
6780 TREE_NO_WARNING (t) = 1;
6782 else if (idx > (wi::to_offset (up_bound)
6783 - wi::to_offset (low_bound) + 1))
6785 if (dump_file && (dump_flags & TDF_DETAILS))
6787 fprintf (dump_file, "Array bound warning for ");
6788 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
6789 fprintf (dump_file, "\n");
6791 warning_at (location, OPT_Warray_bounds,
6792 "array subscript is above array bounds");
6793 TREE_NO_WARNING (t) = 1;
6798 /* walk_tree() callback that checks if *TP is
6799 an ARRAY_REF inside an ADDR_EXPR (in which an array
6800 subscript one outside the valid range is allowed). Call
6801 check_array_ref for each ARRAY_REF found. The location is
6802 passed in DATA. */
6804 static tree
6805 check_array_bounds (tree *tp, int *walk_subtree, void *data)
6807 tree t = *tp;
6808 struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
6809 location_t location;
6811 if (EXPR_HAS_LOCATION (t))
6812 location = EXPR_LOCATION (t);
6813 else
6815 location_t *locp = (location_t *) wi->info;
6816 location = *locp;
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 location_t loc = gimple_location (stmt);
6865 wi.info = &loc;
6867 walk_gimple_op (gsi_stmt (si),
6868 check_array_bounds,
6869 &wi);
6874 /* Return true if all imm uses of VAR are either in STMT, or
6875 feed (optionally through a chain of single imm uses) GIMPLE_COND
6876 in basic block COND_BB. */
6878 static bool
6879 all_imm_uses_in_stmt_or_feed_cond (tree var, gimple *stmt, basic_block cond_bb)
6881 use_operand_p use_p, use2_p;
6882 imm_use_iterator iter;
6884 FOR_EACH_IMM_USE_FAST (use_p, iter, var)
6885 if (USE_STMT (use_p) != stmt)
6887 gimple *use_stmt = USE_STMT (use_p), *use_stmt2;
6888 if (is_gimple_debug (use_stmt))
6889 continue;
6890 while (is_gimple_assign (use_stmt)
6891 && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
6892 && single_imm_use (gimple_assign_lhs (use_stmt),
6893 &use2_p, &use_stmt2))
6894 use_stmt = use_stmt2;
6895 if (gimple_code (use_stmt) != GIMPLE_COND
6896 || gimple_bb (use_stmt) != cond_bb)
6897 return false;
6899 return true;
6902 /* Handle
6903 _4 = x_3 & 31;
6904 if (_4 != 0)
6905 goto <bb 6>;
6906 else
6907 goto <bb 7>;
6908 <bb 6>:
6909 __builtin_unreachable ();
6910 <bb 7>:
6911 x_5 = ASSERT_EXPR <x_3, ...>;
6912 If x_3 has no other immediate uses (checked by caller),
6913 var is the x_3 var from ASSERT_EXPR, we can clear low 5 bits
6914 from the non-zero bitmask. */
6916 static void
6917 maybe_set_nonzero_bits (basic_block bb, tree var)
6919 edge e = single_pred_edge (bb);
6920 basic_block cond_bb = e->src;
6921 gimple *stmt = last_stmt (cond_bb);
6922 tree cst;
6924 if (stmt == NULL
6925 || gimple_code (stmt) != GIMPLE_COND
6926 || gimple_cond_code (stmt) != ((e->flags & EDGE_TRUE_VALUE)
6927 ? EQ_EXPR : NE_EXPR)
6928 || TREE_CODE (gimple_cond_lhs (stmt)) != SSA_NAME
6929 || !integer_zerop (gimple_cond_rhs (stmt)))
6930 return;
6932 stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt));
6933 if (!is_gimple_assign (stmt)
6934 || gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
6935 || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
6936 return;
6937 if (gimple_assign_rhs1 (stmt) != var)
6939 gimple *stmt2;
6941 if (TREE_CODE (gimple_assign_rhs1 (stmt)) != SSA_NAME)
6942 return;
6943 stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
6944 if (!gimple_assign_cast_p (stmt2)
6945 || gimple_assign_rhs1 (stmt2) != var
6946 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt2))
6947 || (TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (stmt)))
6948 != TYPE_PRECISION (TREE_TYPE (var))))
6949 return;
6951 cst = gimple_assign_rhs2 (stmt);
6952 set_nonzero_bits (var, wi::bit_and_not (get_nonzero_bits (var), cst));
6955 /* Convert range assertion expressions into the implied copies and
6956 copy propagate away the copies. Doing the trivial copy propagation
6957 here avoids the need to run the full copy propagation pass after
6958 VRP.
6960 FIXME, this will eventually lead to copy propagation removing the
6961 names that had useful range information attached to them. For
6962 instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
6963 then N_i will have the range [3, +INF].
6965 However, by converting the assertion into the implied copy
6966 operation N_i = N_j, we will then copy-propagate N_j into the uses
6967 of N_i and lose the range information. We may want to hold on to
6968 ASSERT_EXPRs a little while longer as the ranges could be used in
6969 things like jump threading.
6971 The problem with keeping ASSERT_EXPRs around is that passes after
6972 VRP need to handle them appropriately.
6974 Another approach would be to make the range information a first
6975 class property of the SSA_NAME so that it can be queried from
6976 any pass. This is made somewhat more complex by the need for
6977 multiple ranges to be associated with one SSA_NAME. */
6979 static void
6980 remove_range_assertions (void)
6982 basic_block bb;
6983 gimple_stmt_iterator si;
6984 /* 1 if looking at ASSERT_EXPRs immediately at the beginning of
6985 a basic block preceeded by GIMPLE_COND branching to it and
6986 __builtin_trap, -1 if not yet checked, 0 otherwise. */
6987 int is_unreachable;
6989 /* Note that the BSI iterator bump happens at the bottom of the
6990 loop and no bump is necessary if we're removing the statement
6991 referenced by the current BSI. */
6992 FOR_EACH_BB_FN (bb, cfun)
6993 for (si = gsi_after_labels (bb), is_unreachable = -1; !gsi_end_p (si);)
6995 gimple *stmt = gsi_stmt (si);
6997 if (is_gimple_assign (stmt)
6998 && gimple_assign_rhs_code (stmt) == ASSERT_EXPR)
7000 tree lhs = gimple_assign_lhs (stmt);
7001 tree rhs = gimple_assign_rhs1 (stmt);
7002 tree var;
7004 var = ASSERT_EXPR_VAR (rhs);
7006 if (TREE_CODE (var) == SSA_NAME
7007 && !POINTER_TYPE_P (TREE_TYPE (lhs))
7008 && SSA_NAME_RANGE_INFO (lhs))
7010 if (is_unreachable == -1)
7012 is_unreachable = 0;
7013 if (single_pred_p (bb)
7014 && assert_unreachable_fallthru_edge_p
7015 (single_pred_edge (bb)))
7016 is_unreachable = 1;
7018 /* Handle
7019 if (x_7 >= 10 && x_7 < 20)
7020 __builtin_unreachable ();
7021 x_8 = ASSERT_EXPR <x_7, ...>;
7022 if the only uses of x_7 are in the ASSERT_EXPR and
7023 in the condition. In that case, we can copy the
7024 range info from x_8 computed in this pass also
7025 for x_7. */
7026 if (is_unreachable
7027 && all_imm_uses_in_stmt_or_feed_cond (var, stmt,
7028 single_pred (bb)))
7030 set_range_info (var, SSA_NAME_RANGE_TYPE (lhs),
7031 SSA_NAME_RANGE_INFO (lhs)->get_min (),
7032 SSA_NAME_RANGE_INFO (lhs)->get_max ());
7033 maybe_set_nonzero_bits (bb, var);
7037 /* Propagate the RHS into every use of the LHS. For SSA names
7038 also propagate abnormals as it merely restores the original
7039 IL in this case (an replace_uses_by would assert). */
7040 if (TREE_CODE (var) == SSA_NAME)
7042 imm_use_iterator iter;
7043 use_operand_p use_p;
7044 gimple *use_stmt;
7045 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
7046 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
7047 SET_USE (use_p, var);
7049 else
7050 replace_uses_by (lhs, var);
7052 /* And finally, remove the copy, it is not needed. */
7053 gsi_remove (&si, true);
7054 release_defs (stmt);
7056 else
7058 if (!is_gimple_debug (gsi_stmt (si)))
7059 is_unreachable = 0;
7060 gsi_next (&si);
7066 /* Return true if STMT is interesting for VRP. */
7068 static bool
7069 stmt_interesting_for_vrp (gimple *stmt)
7071 if (gimple_code (stmt) == GIMPLE_PHI)
7073 tree res = gimple_phi_result (stmt);
7074 return (!virtual_operand_p (res)
7075 && (INTEGRAL_TYPE_P (TREE_TYPE (res))
7076 || POINTER_TYPE_P (TREE_TYPE (res))));
7078 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
7080 tree lhs = gimple_get_lhs (stmt);
7082 /* In general, assignments with virtual operands are not useful
7083 for deriving ranges, with the obvious exception of calls to
7084 builtin functions. */
7085 if (lhs && TREE_CODE (lhs) == SSA_NAME
7086 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
7087 || POINTER_TYPE_P (TREE_TYPE (lhs)))
7088 && (is_gimple_call (stmt)
7089 || !gimple_vuse (stmt)))
7090 return true;
7091 else if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
7092 switch (gimple_call_internal_fn (stmt))
7094 case IFN_ADD_OVERFLOW:
7095 case IFN_SUB_OVERFLOW:
7096 case IFN_MUL_OVERFLOW:
7097 case IFN_ATOMIC_COMPARE_EXCHANGE:
7098 /* These internal calls return _Complex integer type,
7099 but are interesting to VRP nevertheless. */
7100 if (lhs && TREE_CODE (lhs) == SSA_NAME)
7101 return true;
7102 break;
7103 default:
7104 break;
7107 else if (gimple_code (stmt) == GIMPLE_COND
7108 || gimple_code (stmt) == GIMPLE_SWITCH)
7109 return true;
7111 return false;
7114 /* Initialize VRP lattice. */
7116 static void
7117 vrp_initialize_lattice ()
7119 values_propagated = false;
7120 num_vr_values = num_ssa_names;
7121 vr_value = XCNEWVEC (value_range *, num_vr_values);
7122 vr_phi_edge_counts = XCNEWVEC (int, num_ssa_names);
7123 bitmap_obstack_initialize (&vrp_equiv_obstack);
7126 /* Initialization required by ssa_propagate engine. */
7128 static void
7129 vrp_initialize ()
7131 basic_block bb;
7133 FOR_EACH_BB_FN (bb, cfun)
7135 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
7136 gsi_next (&si))
7138 gphi *phi = si.phi ();
7139 if (!stmt_interesting_for_vrp (phi))
7141 tree lhs = PHI_RESULT (phi);
7142 set_value_range_to_varying (get_value_range (lhs));
7143 prop_set_simulate_again (phi, false);
7145 else
7146 prop_set_simulate_again (phi, true);
7149 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
7150 gsi_next (&si))
7152 gimple *stmt = gsi_stmt (si);
7154 /* If the statement is a control insn, then we do not
7155 want to avoid simulating the statement once. Failure
7156 to do so means that those edges will never get added. */
7157 if (stmt_ends_bb_p (stmt))
7158 prop_set_simulate_again (stmt, true);
7159 else if (!stmt_interesting_for_vrp (stmt))
7161 set_defs_to_varying (stmt);
7162 prop_set_simulate_again (stmt, false);
7164 else
7165 prop_set_simulate_again (stmt, true);
7170 /* Return the singleton value-range for NAME or NAME. */
7172 static inline tree
7173 vrp_valueize (tree name)
7175 if (TREE_CODE (name) == SSA_NAME)
7177 value_range *vr = get_value_range (name);
7178 if (vr->type == VR_RANGE
7179 && (TREE_CODE (vr->min) == SSA_NAME
7180 || is_gimple_min_invariant (vr->min))
7181 && vrp_operand_equal_p (vr->min, vr->max))
7182 return vr->min;
7184 return name;
7187 /* Return the singleton value-range for NAME if that is a constant
7188 but signal to not follow SSA edges. */
7190 static inline tree
7191 vrp_valueize_1 (tree name)
7193 if (TREE_CODE (name) == SSA_NAME)
7195 /* If the definition may be simulated again we cannot follow
7196 this SSA edge as the SSA propagator does not necessarily
7197 re-visit the use. */
7198 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
7199 if (!gimple_nop_p (def_stmt)
7200 && prop_simulate_again_p (def_stmt))
7201 return NULL_TREE;
7202 value_range *vr = get_value_range (name);
7203 if (range_int_cst_singleton_p (vr))
7204 return vr->min;
7206 return name;
7209 /* Visit assignment STMT. If it produces an interesting range, record
7210 the range in VR and set LHS to OUTPUT_P. */
7212 static void
7213 vrp_visit_assignment_or_call (gimple *stmt, tree *output_p, value_range *vr)
7215 tree lhs;
7216 enum gimple_code code = gimple_code (stmt);
7217 lhs = gimple_get_lhs (stmt);
7218 *output_p = NULL_TREE;
7220 /* We only keep track of ranges in integral and pointer types. */
7221 if (TREE_CODE (lhs) == SSA_NAME
7222 && ((INTEGRAL_TYPE_P (TREE_TYPE (lhs))
7223 /* It is valid to have NULL MIN/MAX values on a type. See
7224 build_range_type. */
7225 && TYPE_MIN_VALUE (TREE_TYPE (lhs))
7226 && TYPE_MAX_VALUE (TREE_TYPE (lhs)))
7227 || POINTER_TYPE_P (TREE_TYPE (lhs))))
7229 *output_p = lhs;
7231 /* Try folding the statement to a constant first. */
7232 tree tem = gimple_fold_stmt_to_constant_1 (stmt, vrp_valueize,
7233 vrp_valueize_1);
7234 if (tem)
7236 if (TREE_CODE (tem) == SSA_NAME
7237 && (SSA_NAME_IS_DEFAULT_DEF (tem)
7238 || ! prop_simulate_again_p (SSA_NAME_DEF_STMT (tem))))
7240 extract_range_from_ssa_name (vr, tem);
7241 return;
7243 else if (is_gimple_min_invariant (tem))
7245 set_value_range_to_value (vr, tem, NULL);
7246 return;
7249 /* Then dispatch to value-range extracting functions. */
7250 if (code == GIMPLE_CALL)
7251 extract_range_basic (vr, stmt);
7252 else
7253 extract_range_from_assignment (vr, as_a <gassign *> (stmt));
7257 /* Helper that gets the value range of the SSA_NAME with version I
7258 or a symbolic range containing the SSA_NAME only if the value range
7259 is varying or undefined. */
7261 static inline value_range
7262 get_vr_for_comparison (int i)
7264 value_range vr = *get_value_range (ssa_name (i));
7266 /* If name N_i does not have a valid range, use N_i as its own
7267 range. This allows us to compare against names that may
7268 have N_i in their ranges. */
7269 if (vr.type == VR_VARYING || vr.type == VR_UNDEFINED)
7271 vr.type = VR_RANGE;
7272 vr.min = ssa_name (i);
7273 vr.max = ssa_name (i);
7276 return vr;
7279 /* Compare all the value ranges for names equivalent to VAR with VAL
7280 using comparison code COMP. Return the same value returned by
7281 compare_range_with_value, including the setting of
7282 *STRICT_OVERFLOW_P. */
7284 static tree
7285 compare_name_with_value (enum tree_code comp, tree var, tree val,
7286 bool *strict_overflow_p, bool use_equiv_p)
7288 bitmap_iterator bi;
7289 unsigned i;
7290 bitmap e;
7291 tree retval, t;
7292 int used_strict_overflow;
7293 bool sop;
7294 value_range equiv_vr;
7296 /* Get the set of equivalences for VAR. */
7297 e = get_value_range (var)->equiv;
7299 /* Start at -1. Set it to 0 if we do a comparison without relying
7300 on overflow, or 1 if all comparisons rely on overflow. */
7301 used_strict_overflow = -1;
7303 /* Compare vars' value range with val. */
7304 equiv_vr = get_vr_for_comparison (SSA_NAME_VERSION (var));
7305 sop = false;
7306 retval = compare_range_with_value (comp, &equiv_vr, val, &sop);
7307 if (retval)
7308 used_strict_overflow = sop ? 1 : 0;
7310 /* If the equiv set is empty we have done all work we need to do. */
7311 if (e == NULL)
7313 if (retval
7314 && used_strict_overflow > 0)
7315 *strict_overflow_p = true;
7316 return retval;
7319 EXECUTE_IF_SET_IN_BITMAP (e, 0, i, bi)
7321 tree name = ssa_name (i);
7322 if (! name)
7323 continue;
7325 if (! use_equiv_p
7326 && ! SSA_NAME_IS_DEFAULT_DEF (name)
7327 && prop_simulate_again_p (SSA_NAME_DEF_STMT (name)))
7328 continue;
7330 equiv_vr = get_vr_for_comparison (i);
7331 sop = false;
7332 t = compare_range_with_value (comp, &equiv_vr, val, &sop);
7333 if (t)
7335 /* If we get different answers from different members
7336 of the equivalence set this check must be in a dead
7337 code region. Folding it to a trap representation
7338 would be correct here. For now just return don't-know. */
7339 if (retval != NULL
7340 && t != retval)
7342 retval = NULL_TREE;
7343 break;
7345 retval = t;
7347 if (!sop)
7348 used_strict_overflow = 0;
7349 else if (used_strict_overflow < 0)
7350 used_strict_overflow = 1;
7354 if (retval
7355 && used_strict_overflow > 0)
7356 *strict_overflow_p = true;
7358 return retval;
7362 /* Given a comparison code COMP and names N1 and N2, compare all the
7363 ranges equivalent to N1 against all the ranges equivalent to N2
7364 to determine the value of N1 COMP N2. Return the same value
7365 returned by compare_ranges. Set *STRICT_OVERFLOW_P to indicate
7366 whether we relied on undefined signed overflow in the comparison. */
7369 static tree
7370 compare_names (enum tree_code comp, tree n1, tree n2,
7371 bool *strict_overflow_p)
7373 tree t, retval;
7374 bitmap e1, e2;
7375 bitmap_iterator bi1, bi2;
7376 unsigned i1, i2;
7377 int used_strict_overflow;
7378 static bitmap_obstack *s_obstack = NULL;
7379 static bitmap s_e1 = NULL, s_e2 = NULL;
7381 /* Compare the ranges of every name equivalent to N1 against the
7382 ranges of every name equivalent to N2. */
7383 e1 = get_value_range (n1)->equiv;
7384 e2 = get_value_range (n2)->equiv;
7386 /* Use the fake bitmaps if e1 or e2 are not available. */
7387 if (s_obstack == NULL)
7389 s_obstack = XNEW (bitmap_obstack);
7390 bitmap_obstack_initialize (s_obstack);
7391 s_e1 = BITMAP_ALLOC (s_obstack);
7392 s_e2 = BITMAP_ALLOC (s_obstack);
7394 if (e1 == NULL)
7395 e1 = s_e1;
7396 if (e2 == NULL)
7397 e2 = s_e2;
7399 /* Add N1 and N2 to their own set of equivalences to avoid
7400 duplicating the body of the loop just to check N1 and N2
7401 ranges. */
7402 bitmap_set_bit (e1, SSA_NAME_VERSION (n1));
7403 bitmap_set_bit (e2, SSA_NAME_VERSION (n2));
7405 /* If the equivalence sets have a common intersection, then the two
7406 names can be compared without checking their ranges. */
7407 if (bitmap_intersect_p (e1, e2))
7409 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7410 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7412 return (comp == EQ_EXPR || comp == GE_EXPR || comp == LE_EXPR)
7413 ? boolean_true_node
7414 : boolean_false_node;
7417 /* Start at -1. Set it to 0 if we do a comparison without relying
7418 on overflow, or 1 if all comparisons rely on overflow. */
7419 used_strict_overflow = -1;
7421 /* Otherwise, compare all the equivalent ranges. First, add N1 and
7422 N2 to their own set of equivalences to avoid duplicating the body
7423 of the loop just to check N1 and N2 ranges. */
7424 EXECUTE_IF_SET_IN_BITMAP (e1, 0, i1, bi1)
7426 if (! ssa_name (i1))
7427 continue;
7429 value_range vr1 = get_vr_for_comparison (i1);
7431 t = retval = NULL_TREE;
7432 EXECUTE_IF_SET_IN_BITMAP (e2, 0, i2, bi2)
7434 if (! ssa_name (i2))
7435 continue;
7437 bool sop = false;
7439 value_range vr2 = get_vr_for_comparison (i2);
7441 t = compare_ranges (comp, &vr1, &vr2, &sop);
7442 if (t)
7444 /* If we get different answers from different members
7445 of the equivalence set this check must be in a dead
7446 code region. Folding it to a trap representation
7447 would be correct here. For now just return don't-know. */
7448 if (retval != NULL
7449 && t != retval)
7451 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7452 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7453 return NULL_TREE;
7455 retval = t;
7457 if (!sop)
7458 used_strict_overflow = 0;
7459 else if (used_strict_overflow < 0)
7460 used_strict_overflow = 1;
7464 if (retval)
7466 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7467 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7468 if (used_strict_overflow > 0)
7469 *strict_overflow_p = true;
7470 return retval;
7474 /* None of the equivalent ranges are useful in computing this
7475 comparison. */
7476 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7477 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7478 return NULL_TREE;
7481 /* Helper function for vrp_evaluate_conditional_warnv & other
7482 optimizers. */
7484 static tree
7485 vrp_evaluate_conditional_warnv_with_ops_using_ranges (enum tree_code code,
7486 tree op0, tree op1,
7487 bool * strict_overflow_p)
7489 value_range *vr0, *vr1;
7491 vr0 = (TREE_CODE (op0) == SSA_NAME) ? get_value_range (op0) : NULL;
7492 vr1 = (TREE_CODE (op1) == SSA_NAME) ? get_value_range (op1) : NULL;
7494 tree res = NULL_TREE;
7495 if (vr0 && vr1)
7496 res = compare_ranges (code, vr0, vr1, strict_overflow_p);
7497 if (!res && vr0)
7498 res = compare_range_with_value (code, vr0, op1, strict_overflow_p);
7499 if (!res && vr1)
7500 res = (compare_range_with_value
7501 (swap_tree_comparison (code), vr1, op0, strict_overflow_p));
7502 return res;
7505 /* Helper function for vrp_evaluate_conditional_warnv. */
7507 static tree
7508 vrp_evaluate_conditional_warnv_with_ops (enum tree_code code, tree op0,
7509 tree op1, bool use_equiv_p,
7510 bool *strict_overflow_p, bool *only_ranges)
7512 tree ret;
7513 if (only_ranges)
7514 *only_ranges = true;
7516 /* We only deal with integral and pointer types. */
7517 if (!INTEGRAL_TYPE_P (TREE_TYPE (op0))
7518 && !POINTER_TYPE_P (TREE_TYPE (op0)))
7519 return NULL_TREE;
7521 /* If OP0 CODE OP1 is an overflow comparison, if it can be expressed
7522 as a simple equality test, then prefer that over its current form
7523 for evaluation.
7525 An overflow test which collapses to an equality test can always be
7526 expressed as a comparison of one argument against zero. Overflow
7527 occurs when the chosen argument is zero and does not occur if the
7528 chosen argument is not zero. */
7529 tree x;
7530 if (overflow_comparison_p (code, op0, op1, use_equiv_p, &x))
7532 wide_int max = wi::max_value (TYPE_PRECISION (TREE_TYPE (op0)), UNSIGNED);
7533 /* B = A - 1; if (A < B) -> B = A - 1; if (A == 0)
7534 B = A - 1; if (A > B) -> B = A - 1; if (A != 0)
7535 B = A + 1; if (B < A) -> B = A + 1; if (B == 0)
7536 B = A + 1; if (B > A) -> B = A + 1; if (B != 0) */
7537 if (integer_zerop (x))
7539 op1 = x;
7540 code = (code == LT_EXPR || code == LE_EXPR) ? EQ_EXPR : NE_EXPR;
7542 /* B = A + 1; if (A > B) -> B = A + 1; if (B == 0)
7543 B = A + 1; if (A < B) -> B = A + 1; if (B != 0)
7544 B = A - 1; if (B > A) -> B = A - 1; if (A == 0)
7545 B = A - 1; if (B < A) -> B = A - 1; if (A != 0) */
7546 else if (wi::eq_p (x, max - 1))
7548 op0 = op1;
7549 op1 = wide_int_to_tree (TREE_TYPE (op0), 0);
7550 code = (code == GT_EXPR || code == GE_EXPR) ? EQ_EXPR : NE_EXPR;
7554 if ((ret = vrp_evaluate_conditional_warnv_with_ops_using_ranges
7555 (code, op0, op1, strict_overflow_p)))
7556 return ret;
7557 if (only_ranges)
7558 *only_ranges = false;
7559 /* Do not use compare_names during propagation, it's quadratic. */
7560 if (TREE_CODE (op0) == SSA_NAME && TREE_CODE (op1) == SSA_NAME
7561 && use_equiv_p)
7562 return compare_names (code, op0, op1, strict_overflow_p);
7563 else if (TREE_CODE (op0) == SSA_NAME)
7564 return compare_name_with_value (code, op0, op1,
7565 strict_overflow_p, use_equiv_p);
7566 else if (TREE_CODE (op1) == SSA_NAME)
7567 return compare_name_with_value (swap_tree_comparison (code), op1, op0,
7568 strict_overflow_p, use_equiv_p);
7569 return NULL_TREE;
7572 /* Given (CODE OP0 OP1) within STMT, try to simplify it based on value range
7573 information. Return NULL if the conditional can not be evaluated.
7574 The ranges of all the names equivalent with the operands in COND
7575 will be used when trying to compute the value. If the result is
7576 based on undefined signed overflow, issue a warning if
7577 appropriate. */
7579 static tree
7580 vrp_evaluate_conditional (tree_code code, tree op0, tree op1, gimple *stmt)
7582 bool sop;
7583 tree ret;
7584 bool only_ranges;
7586 /* Some passes and foldings leak constants with overflow flag set
7587 into the IL. Avoid doing wrong things with these and bail out. */
7588 if ((TREE_CODE (op0) == INTEGER_CST
7589 && TREE_OVERFLOW (op0))
7590 || (TREE_CODE (op1) == INTEGER_CST
7591 && TREE_OVERFLOW (op1)))
7592 return NULL_TREE;
7594 sop = false;
7595 ret = vrp_evaluate_conditional_warnv_with_ops (code, op0, op1, true, &sop,
7596 &only_ranges);
7598 if (ret && sop)
7600 enum warn_strict_overflow_code wc;
7601 const char* warnmsg;
7603 if (is_gimple_min_invariant (ret))
7605 wc = WARN_STRICT_OVERFLOW_CONDITIONAL;
7606 warnmsg = G_("assuming signed overflow does not occur when "
7607 "simplifying conditional to constant");
7609 else
7611 wc = WARN_STRICT_OVERFLOW_COMPARISON;
7612 warnmsg = G_("assuming signed overflow does not occur when "
7613 "simplifying conditional");
7616 if (issue_strict_overflow_warning (wc))
7618 location_t location;
7620 if (!gimple_has_location (stmt))
7621 location = input_location;
7622 else
7623 location = gimple_location (stmt);
7624 warning_at (location, OPT_Wstrict_overflow, "%s", warnmsg);
7628 if (warn_type_limits
7629 && ret && only_ranges
7630 && TREE_CODE_CLASS (code) == tcc_comparison
7631 && TREE_CODE (op0) == SSA_NAME)
7633 /* If the comparison is being folded and the operand on the LHS
7634 is being compared against a constant value that is outside of
7635 the natural range of OP0's type, then the predicate will
7636 always fold regardless of the value of OP0. If -Wtype-limits
7637 was specified, emit a warning. */
7638 tree type = TREE_TYPE (op0);
7639 value_range *vr0 = get_value_range (op0);
7641 if (vr0->type == VR_RANGE
7642 && INTEGRAL_TYPE_P (type)
7643 && vrp_val_is_min (vr0->min)
7644 && vrp_val_is_max (vr0->max)
7645 && is_gimple_min_invariant (op1))
7647 location_t location;
7649 if (!gimple_has_location (stmt))
7650 location = input_location;
7651 else
7652 location = gimple_location (stmt);
7654 warning_at (location, OPT_Wtype_limits,
7655 integer_zerop (ret)
7656 ? G_("comparison always false "
7657 "due to limited range of data type")
7658 : G_("comparison always true "
7659 "due to limited range of data type"));
7663 return ret;
7667 /* Visit conditional statement STMT. If we can determine which edge
7668 will be taken out of STMT's basic block, record it in
7669 *TAKEN_EDGE_P. Otherwise, set *TAKEN_EDGE_P to NULL. */
7671 static void
7672 vrp_visit_cond_stmt (gcond *stmt, edge *taken_edge_p)
7674 tree val;
7676 *taken_edge_p = NULL;
7678 if (dump_file && (dump_flags & TDF_DETAILS))
7680 tree use;
7681 ssa_op_iter i;
7683 fprintf (dump_file, "\nVisiting conditional with predicate: ");
7684 print_gimple_stmt (dump_file, stmt, 0);
7685 fprintf (dump_file, "\nWith known ranges\n");
7687 FOR_EACH_SSA_TREE_OPERAND (use, stmt, i, SSA_OP_USE)
7689 fprintf (dump_file, "\t");
7690 print_generic_expr (dump_file, use);
7691 fprintf (dump_file, ": ");
7692 dump_value_range (dump_file, vr_value[SSA_NAME_VERSION (use)]);
7695 fprintf (dump_file, "\n");
7698 /* Compute the value of the predicate COND by checking the known
7699 ranges of each of its operands.
7701 Note that we cannot evaluate all the equivalent ranges here
7702 because those ranges may not yet be final and with the current
7703 propagation strategy, we cannot determine when the value ranges
7704 of the names in the equivalence set have changed.
7706 For instance, given the following code fragment
7708 i_5 = PHI <8, i_13>
7710 i_14 = ASSERT_EXPR <i_5, i_5 != 0>
7711 if (i_14 == 1)
7714 Assume that on the first visit to i_14, i_5 has the temporary
7715 range [8, 8] because the second argument to the PHI function is
7716 not yet executable. We derive the range ~[0, 0] for i_14 and the
7717 equivalence set { i_5 }. So, when we visit 'if (i_14 == 1)' for
7718 the first time, since i_14 is equivalent to the range [8, 8], we
7719 determine that the predicate is always false.
7721 On the next round of propagation, i_13 is determined to be
7722 VARYING, which causes i_5 to drop down to VARYING. So, another
7723 visit to i_14 is scheduled. In this second visit, we compute the
7724 exact same range and equivalence set for i_14, namely ~[0, 0] and
7725 { i_5 }. But we did not have the previous range for i_5
7726 registered, so vrp_visit_assignment thinks that the range for
7727 i_14 has not changed. Therefore, the predicate 'if (i_14 == 1)'
7728 is not visited again, which stops propagation from visiting
7729 statements in the THEN clause of that if().
7731 To properly fix this we would need to keep the previous range
7732 value for the names in the equivalence set. This way we would've
7733 discovered that from one visit to the other i_5 changed from
7734 range [8, 8] to VR_VARYING.
7736 However, fixing this apparent limitation may not be worth the
7737 additional checking. Testing on several code bases (GCC, DLV,
7738 MICO, TRAMP3D and SPEC2000) showed that doing this results in
7739 4 more predicates folded in SPEC. */
7741 bool sop;
7742 val = vrp_evaluate_conditional_warnv_with_ops (gimple_cond_code (stmt),
7743 gimple_cond_lhs (stmt),
7744 gimple_cond_rhs (stmt),
7745 false, &sop, NULL);
7746 if (val)
7747 *taken_edge_p = find_taken_edge (gimple_bb (stmt), val);
7749 if (dump_file && (dump_flags & TDF_DETAILS))
7751 fprintf (dump_file, "\nPredicate evaluates to: ");
7752 if (val == NULL_TREE)
7753 fprintf (dump_file, "DON'T KNOW\n");
7754 else
7755 print_generic_stmt (dump_file, val);
7759 /* Searches the case label vector VEC for the index *IDX of the CASE_LABEL
7760 that includes the value VAL. The search is restricted to the range
7761 [START_IDX, n - 1] where n is the size of VEC.
7763 If there is a CASE_LABEL for VAL, its index is placed in IDX and true is
7764 returned.
7766 If there is no CASE_LABEL for VAL and there is one that is larger than VAL,
7767 it is placed in IDX and false is returned.
7769 If VAL is larger than any CASE_LABEL, n is placed on IDX and false is
7770 returned. */
7772 static bool
7773 find_case_label_index (gswitch *stmt, size_t start_idx, tree val, size_t *idx)
7775 size_t n = gimple_switch_num_labels (stmt);
7776 size_t low, high;
7778 /* Find case label for minimum of the value range or the next one.
7779 At each iteration we are searching in [low, high - 1]. */
7781 for (low = start_idx, high = n; high != low; )
7783 tree t;
7784 int cmp;
7785 /* Note that i != high, so we never ask for n. */
7786 size_t i = (high + low) / 2;
7787 t = gimple_switch_label (stmt, i);
7789 /* Cache the result of comparing CASE_LOW and val. */
7790 cmp = tree_int_cst_compare (CASE_LOW (t), val);
7792 if (cmp == 0)
7794 /* Ranges cannot be empty. */
7795 *idx = i;
7796 return true;
7798 else if (cmp > 0)
7799 high = i;
7800 else
7802 low = i + 1;
7803 if (CASE_HIGH (t) != NULL
7804 && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
7806 *idx = i;
7807 return true;
7812 *idx = high;
7813 return false;
7816 /* Searches the case label vector VEC for the range of CASE_LABELs that is used
7817 for values between MIN and MAX. The first index is placed in MIN_IDX. The
7818 last index is placed in MAX_IDX. If the range of CASE_LABELs is empty
7819 then MAX_IDX < MIN_IDX.
7820 Returns true if the default label is not needed. */
7822 static bool
7823 find_case_label_range (gswitch *stmt, tree min, tree max, size_t *min_idx,
7824 size_t *max_idx)
7826 size_t i, j;
7827 bool min_take_default = !find_case_label_index (stmt, 1, min, &i);
7828 bool max_take_default = !find_case_label_index (stmt, i, max, &j);
7830 if (i == j
7831 && min_take_default
7832 && max_take_default)
7834 /* Only the default case label reached.
7835 Return an empty range. */
7836 *min_idx = 1;
7837 *max_idx = 0;
7838 return false;
7840 else
7842 bool take_default = min_take_default || max_take_default;
7843 tree low, high;
7844 size_t k;
7846 if (max_take_default)
7847 j--;
7849 /* If the case label range is continuous, we do not need
7850 the default case label. Verify that. */
7851 high = CASE_LOW (gimple_switch_label (stmt, i));
7852 if (CASE_HIGH (gimple_switch_label (stmt, i)))
7853 high = CASE_HIGH (gimple_switch_label (stmt, i));
7854 for (k = i + 1; k <= j; ++k)
7856 low = CASE_LOW (gimple_switch_label (stmt, k));
7857 if (!integer_onep (int_const_binop (MINUS_EXPR, low, high)))
7859 take_default = true;
7860 break;
7862 high = low;
7863 if (CASE_HIGH (gimple_switch_label (stmt, k)))
7864 high = CASE_HIGH (gimple_switch_label (stmt, k));
7867 *min_idx = i;
7868 *max_idx = j;
7869 return !take_default;
7873 /* Searches the case label vector VEC for the ranges of CASE_LABELs that are
7874 used in range VR. The indices are placed in MIN_IDX1, MAX_IDX, MIN_IDX2 and
7875 MAX_IDX2. If the ranges of CASE_LABELs are empty then MAX_IDX1 < MIN_IDX1.
7876 Returns true if the default label is not needed. */
7878 static bool
7879 find_case_label_ranges (gswitch *stmt, value_range *vr, size_t *min_idx1,
7880 size_t *max_idx1, size_t *min_idx2,
7881 size_t *max_idx2)
7883 size_t i, j, k, l;
7884 unsigned int n = gimple_switch_num_labels (stmt);
7885 bool take_default;
7886 tree case_low, case_high;
7887 tree min = vr->min, max = vr->max;
7889 gcc_checking_assert (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE);
7891 take_default = !find_case_label_range (stmt, min, max, &i, &j);
7893 /* Set second range to emtpy. */
7894 *min_idx2 = 1;
7895 *max_idx2 = 0;
7897 if (vr->type == VR_RANGE)
7899 *min_idx1 = i;
7900 *max_idx1 = j;
7901 return !take_default;
7904 /* Set first range to all case labels. */
7905 *min_idx1 = 1;
7906 *max_idx1 = n - 1;
7908 if (i > j)
7909 return false;
7911 /* Make sure all the values of case labels [i , j] are contained in
7912 range [MIN, MAX]. */
7913 case_low = CASE_LOW (gimple_switch_label (stmt, i));
7914 case_high = CASE_HIGH (gimple_switch_label (stmt, j));
7915 if (tree_int_cst_compare (case_low, min) < 0)
7916 i += 1;
7917 if (case_high != NULL_TREE
7918 && tree_int_cst_compare (max, case_high) < 0)
7919 j -= 1;
7921 if (i > j)
7922 return false;
7924 /* If the range spans case labels [i, j], the corresponding anti-range spans
7925 the labels [1, i - 1] and [j + 1, n - 1]. */
7926 k = j + 1;
7927 l = n - 1;
7928 if (k > l)
7930 k = 1;
7931 l = 0;
7934 j = i - 1;
7935 i = 1;
7936 if (i > j)
7938 i = k;
7939 j = l;
7940 k = 1;
7941 l = 0;
7944 *min_idx1 = i;
7945 *max_idx1 = j;
7946 *min_idx2 = k;
7947 *max_idx2 = l;
7948 return false;
7951 /* Visit switch statement STMT. If we can determine which edge
7952 will be taken out of STMT's basic block, record it in
7953 *TAKEN_EDGE_P. Otherwise, *TAKEN_EDGE_P set to NULL. */
7955 static void
7956 vrp_visit_switch_stmt (gswitch *stmt, edge *taken_edge_p)
7958 tree op, val;
7959 value_range *vr;
7960 size_t i = 0, j = 0, k, l;
7961 bool take_default;
7963 *taken_edge_p = NULL;
7964 op = gimple_switch_index (stmt);
7965 if (TREE_CODE (op) != SSA_NAME)
7966 return;
7968 vr = get_value_range (op);
7969 if (dump_file && (dump_flags & TDF_DETAILS))
7971 fprintf (dump_file, "\nVisiting switch expression with operand ");
7972 print_generic_expr (dump_file, op);
7973 fprintf (dump_file, " with known range ");
7974 dump_value_range (dump_file, vr);
7975 fprintf (dump_file, "\n");
7978 if ((vr->type != VR_RANGE
7979 && vr->type != VR_ANTI_RANGE)
7980 || symbolic_range_p (vr))
7981 return;
7983 /* Find the single edge that is taken from the switch expression. */
7984 take_default = !find_case_label_ranges (stmt, vr, &i, &j, &k, &l);
7986 /* Check if the range spans no CASE_LABEL. If so, we only reach the default
7987 label */
7988 if (j < i)
7990 gcc_assert (take_default);
7991 val = gimple_switch_default_label (stmt);
7993 else
7995 /* Check if labels with index i to j and maybe the default label
7996 are all reaching the same label. */
7998 val = gimple_switch_label (stmt, i);
7999 if (take_default
8000 && CASE_LABEL (gimple_switch_default_label (stmt))
8001 != CASE_LABEL (val))
8003 if (dump_file && (dump_flags & TDF_DETAILS))
8004 fprintf (dump_file, " not a single destination for this "
8005 "range\n");
8006 return;
8008 for (++i; i <= j; ++i)
8010 if (CASE_LABEL (gimple_switch_label (stmt, i)) != CASE_LABEL (val))
8012 if (dump_file && (dump_flags & TDF_DETAILS))
8013 fprintf (dump_file, " not a single destination for this "
8014 "range\n");
8015 return;
8018 for (; k <= l; ++k)
8020 if (CASE_LABEL (gimple_switch_label (stmt, k)) != CASE_LABEL (val))
8022 if (dump_file && (dump_flags & TDF_DETAILS))
8023 fprintf (dump_file, " not a single destination for this "
8024 "range\n");
8025 return;
8030 *taken_edge_p = find_edge (gimple_bb (stmt),
8031 label_to_block (CASE_LABEL (val)));
8033 if (dump_file && (dump_flags & TDF_DETAILS))
8035 fprintf (dump_file, " will take edge to ");
8036 print_generic_stmt (dump_file, CASE_LABEL (val));
8041 /* Evaluate statement STMT. If the statement produces a useful range,
8042 set VR and corepsponding OUTPUT_P.
8044 If STMT is a conditional branch and we can determine its truth
8045 value, the taken edge is recorded in *TAKEN_EDGE_P. */
8047 static void
8048 extract_range_from_stmt (gimple *stmt, edge *taken_edge_p,
8049 tree *output_p, value_range *vr)
8052 if (dump_file && (dump_flags & TDF_DETAILS))
8054 fprintf (dump_file, "\nVisiting statement:\n");
8055 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
8058 if (!stmt_interesting_for_vrp (stmt))
8059 gcc_assert (stmt_ends_bb_p (stmt));
8060 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
8061 vrp_visit_assignment_or_call (stmt, output_p, vr);
8062 else if (gimple_code (stmt) == GIMPLE_COND)
8063 vrp_visit_cond_stmt (as_a <gcond *> (stmt), taken_edge_p);
8064 else if (gimple_code (stmt) == GIMPLE_SWITCH)
8065 vrp_visit_switch_stmt (as_a <gswitch *> (stmt), taken_edge_p);
8068 /* Evaluate statement STMT. If the statement produces a useful range,
8069 return SSA_PROP_INTERESTING and record the SSA name with the
8070 interesting range into *OUTPUT_P.
8072 If STMT is a conditional branch and we can determine its truth
8073 value, the taken edge is recorded in *TAKEN_EDGE_P.
8075 If STMT produces a varying value, return SSA_PROP_VARYING. */
8077 static enum ssa_prop_result
8078 vrp_visit_stmt (gimple *stmt, edge *taken_edge_p, tree *output_p)
8080 value_range vr = VR_INITIALIZER;
8081 tree lhs = gimple_get_lhs (stmt);
8082 extract_range_from_stmt (stmt, taken_edge_p, output_p, &vr);
8084 if (*output_p)
8086 if (update_value_range (*output_p, &vr))
8088 if (dump_file && (dump_flags & TDF_DETAILS))
8090 fprintf (dump_file, "Found new range for ");
8091 print_generic_expr (dump_file, *output_p);
8092 fprintf (dump_file, ": ");
8093 dump_value_range (dump_file, &vr);
8094 fprintf (dump_file, "\n");
8097 if (vr.type == VR_VARYING)
8098 return SSA_PROP_VARYING;
8100 return SSA_PROP_INTERESTING;
8102 return SSA_PROP_NOT_INTERESTING;
8105 if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
8106 switch (gimple_call_internal_fn (stmt))
8108 case IFN_ADD_OVERFLOW:
8109 case IFN_SUB_OVERFLOW:
8110 case IFN_MUL_OVERFLOW:
8111 case IFN_ATOMIC_COMPARE_EXCHANGE:
8112 /* These internal calls return _Complex integer type,
8113 which VRP does not track, but the immediate uses
8114 thereof might be interesting. */
8115 if (lhs && TREE_CODE (lhs) == SSA_NAME)
8117 imm_use_iterator iter;
8118 use_operand_p use_p;
8119 enum ssa_prop_result res = SSA_PROP_VARYING;
8121 set_value_range_to_varying (get_value_range (lhs));
8123 FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
8125 gimple *use_stmt = USE_STMT (use_p);
8126 if (!is_gimple_assign (use_stmt))
8127 continue;
8128 enum tree_code rhs_code = gimple_assign_rhs_code (use_stmt);
8129 if (rhs_code != REALPART_EXPR && rhs_code != IMAGPART_EXPR)
8130 continue;
8131 tree rhs1 = gimple_assign_rhs1 (use_stmt);
8132 tree use_lhs = gimple_assign_lhs (use_stmt);
8133 if (TREE_CODE (rhs1) != rhs_code
8134 || TREE_OPERAND (rhs1, 0) != lhs
8135 || TREE_CODE (use_lhs) != SSA_NAME
8136 || !stmt_interesting_for_vrp (use_stmt)
8137 || (!INTEGRAL_TYPE_P (TREE_TYPE (use_lhs))
8138 || !TYPE_MIN_VALUE (TREE_TYPE (use_lhs))
8139 || !TYPE_MAX_VALUE (TREE_TYPE (use_lhs))))
8140 continue;
8142 /* If there is a change in the value range for any of the
8143 REALPART_EXPR/IMAGPART_EXPR immediate uses, return
8144 SSA_PROP_INTERESTING. If there are any REALPART_EXPR
8145 or IMAGPART_EXPR immediate uses, but none of them have
8146 a change in their value ranges, return
8147 SSA_PROP_NOT_INTERESTING. If there are no
8148 {REAL,IMAG}PART_EXPR uses at all,
8149 return SSA_PROP_VARYING. */
8150 value_range new_vr = VR_INITIALIZER;
8151 extract_range_basic (&new_vr, use_stmt);
8152 value_range *old_vr = get_value_range (use_lhs);
8153 if (old_vr->type != new_vr.type
8154 || !vrp_operand_equal_p (old_vr->min, new_vr.min)
8155 || !vrp_operand_equal_p (old_vr->max, new_vr.max)
8156 || !vrp_bitmap_equal_p (old_vr->equiv, new_vr.equiv))
8157 res = SSA_PROP_INTERESTING;
8158 else
8159 res = SSA_PROP_NOT_INTERESTING;
8160 BITMAP_FREE (new_vr.equiv);
8161 if (res == SSA_PROP_INTERESTING)
8163 *output_p = lhs;
8164 return res;
8168 return res;
8170 break;
8171 default:
8172 break;
8175 /* All other statements produce nothing of interest for VRP, so mark
8176 their outputs varying and prevent further simulation. */
8177 set_defs_to_varying (stmt);
8179 return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
8182 /* Union the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
8183 { VR1TYPE, VR0MIN, VR0MAX } and store the result
8184 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
8185 possible such range. The resulting range is not canonicalized. */
8187 static void
8188 union_ranges (enum value_range_type *vr0type,
8189 tree *vr0min, tree *vr0max,
8190 enum value_range_type vr1type,
8191 tree vr1min, tree vr1max)
8193 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
8194 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
8196 /* [] is vr0, () is vr1 in the following classification comments. */
8197 if (mineq && maxeq)
8199 /* [( )] */
8200 if (*vr0type == vr1type)
8201 /* Nothing to do for equal ranges. */
8203 else if ((*vr0type == VR_RANGE
8204 && vr1type == VR_ANTI_RANGE)
8205 || (*vr0type == VR_ANTI_RANGE
8206 && vr1type == VR_RANGE))
8208 /* For anti-range with range union the result is varying. */
8209 goto give_up;
8211 else
8212 gcc_unreachable ();
8214 else if (operand_less_p (*vr0max, vr1min) == 1
8215 || operand_less_p (vr1max, *vr0min) == 1)
8217 /* [ ] ( ) or ( ) [ ]
8218 If the ranges have an empty intersection, result of the union
8219 operation is the anti-range or if both are anti-ranges
8220 it covers all. */
8221 if (*vr0type == VR_ANTI_RANGE
8222 && vr1type == VR_ANTI_RANGE)
8223 goto give_up;
8224 else if (*vr0type == VR_ANTI_RANGE
8225 && vr1type == VR_RANGE)
8227 else if (*vr0type == VR_RANGE
8228 && vr1type == VR_ANTI_RANGE)
8230 *vr0type = vr1type;
8231 *vr0min = vr1min;
8232 *vr0max = vr1max;
8234 else if (*vr0type == VR_RANGE
8235 && vr1type == VR_RANGE)
8237 /* The result is the convex hull of both ranges. */
8238 if (operand_less_p (*vr0max, vr1min) == 1)
8240 /* If the result can be an anti-range, create one. */
8241 if (TREE_CODE (*vr0max) == INTEGER_CST
8242 && TREE_CODE (vr1min) == INTEGER_CST
8243 && vrp_val_is_min (*vr0min)
8244 && vrp_val_is_max (vr1max))
8246 tree min = int_const_binop (PLUS_EXPR,
8247 *vr0max,
8248 build_int_cst (TREE_TYPE (*vr0max), 1));
8249 tree max = int_const_binop (MINUS_EXPR,
8250 vr1min,
8251 build_int_cst (TREE_TYPE (vr1min), 1));
8252 if (!operand_less_p (max, min))
8254 *vr0type = VR_ANTI_RANGE;
8255 *vr0min = min;
8256 *vr0max = max;
8258 else
8259 *vr0max = vr1max;
8261 else
8262 *vr0max = vr1max;
8264 else
8266 /* If the result can be an anti-range, create one. */
8267 if (TREE_CODE (vr1max) == INTEGER_CST
8268 && TREE_CODE (*vr0min) == INTEGER_CST
8269 && vrp_val_is_min (vr1min)
8270 && vrp_val_is_max (*vr0max))
8272 tree min = int_const_binop (PLUS_EXPR,
8273 vr1max,
8274 build_int_cst (TREE_TYPE (vr1max), 1));
8275 tree max = int_const_binop (MINUS_EXPR,
8276 *vr0min,
8277 build_int_cst (TREE_TYPE (*vr0min), 1));
8278 if (!operand_less_p (max, min))
8280 *vr0type = VR_ANTI_RANGE;
8281 *vr0min = min;
8282 *vr0max = max;
8284 else
8285 *vr0min = vr1min;
8287 else
8288 *vr0min = vr1min;
8291 else
8292 gcc_unreachable ();
8294 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
8295 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
8297 /* [ ( ) ] or [( ) ] or [ ( )] */
8298 if (*vr0type == VR_RANGE
8299 && vr1type == VR_RANGE)
8301 else if (*vr0type == VR_ANTI_RANGE
8302 && vr1type == VR_ANTI_RANGE)
8304 *vr0type = vr1type;
8305 *vr0min = vr1min;
8306 *vr0max = vr1max;
8308 else if (*vr0type == VR_ANTI_RANGE
8309 && vr1type == VR_RANGE)
8311 /* Arbitrarily choose the right or left gap. */
8312 if (!mineq && TREE_CODE (vr1min) == INTEGER_CST)
8313 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8314 build_int_cst (TREE_TYPE (vr1min), 1));
8315 else if (!maxeq && TREE_CODE (vr1max) == INTEGER_CST)
8316 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
8317 build_int_cst (TREE_TYPE (vr1max), 1));
8318 else
8319 goto give_up;
8321 else if (*vr0type == VR_RANGE
8322 && vr1type == VR_ANTI_RANGE)
8323 /* The result covers everything. */
8324 goto give_up;
8325 else
8326 gcc_unreachable ();
8328 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
8329 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
8331 /* ( [ ] ) or ([ ] ) or ( [ ]) */
8332 if (*vr0type == VR_RANGE
8333 && vr1type == VR_RANGE)
8335 *vr0type = vr1type;
8336 *vr0min = vr1min;
8337 *vr0max = vr1max;
8339 else if (*vr0type == VR_ANTI_RANGE
8340 && vr1type == VR_ANTI_RANGE)
8342 else if (*vr0type == VR_RANGE
8343 && vr1type == VR_ANTI_RANGE)
8345 *vr0type = VR_ANTI_RANGE;
8346 if (!mineq && TREE_CODE (*vr0min) == INTEGER_CST)
8348 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
8349 build_int_cst (TREE_TYPE (*vr0min), 1));
8350 *vr0min = vr1min;
8352 else if (!maxeq && TREE_CODE (*vr0max) == INTEGER_CST)
8354 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8355 build_int_cst (TREE_TYPE (*vr0max), 1));
8356 *vr0max = vr1max;
8358 else
8359 goto give_up;
8361 else if (*vr0type == VR_ANTI_RANGE
8362 && vr1type == VR_RANGE)
8363 /* The result covers everything. */
8364 goto give_up;
8365 else
8366 gcc_unreachable ();
8368 else if ((operand_less_p (vr1min, *vr0max) == 1
8369 || operand_equal_p (vr1min, *vr0max, 0))
8370 && operand_less_p (*vr0min, vr1min) == 1
8371 && operand_less_p (*vr0max, vr1max) == 1)
8373 /* [ ( ] ) or [ ]( ) */
8374 if (*vr0type == VR_RANGE
8375 && vr1type == VR_RANGE)
8376 *vr0max = vr1max;
8377 else if (*vr0type == VR_ANTI_RANGE
8378 && vr1type == VR_ANTI_RANGE)
8379 *vr0min = vr1min;
8380 else if (*vr0type == VR_ANTI_RANGE
8381 && vr1type == VR_RANGE)
8383 if (TREE_CODE (vr1min) == INTEGER_CST)
8384 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8385 build_int_cst (TREE_TYPE (vr1min), 1));
8386 else
8387 goto give_up;
8389 else if (*vr0type == VR_RANGE
8390 && vr1type == VR_ANTI_RANGE)
8392 if (TREE_CODE (*vr0max) == INTEGER_CST)
8394 *vr0type = vr1type;
8395 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8396 build_int_cst (TREE_TYPE (*vr0max), 1));
8397 *vr0max = vr1max;
8399 else
8400 goto give_up;
8402 else
8403 gcc_unreachable ();
8405 else if ((operand_less_p (*vr0min, vr1max) == 1
8406 || operand_equal_p (*vr0min, vr1max, 0))
8407 && operand_less_p (vr1min, *vr0min) == 1
8408 && operand_less_p (vr1max, *vr0max) == 1)
8410 /* ( [ ) ] or ( )[ ] */
8411 if (*vr0type == VR_RANGE
8412 && vr1type == VR_RANGE)
8413 *vr0min = vr1min;
8414 else if (*vr0type == VR_ANTI_RANGE
8415 && vr1type == VR_ANTI_RANGE)
8416 *vr0max = vr1max;
8417 else if (*vr0type == VR_ANTI_RANGE
8418 && vr1type == VR_RANGE)
8420 if (TREE_CODE (vr1max) == INTEGER_CST)
8421 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
8422 build_int_cst (TREE_TYPE (vr1max), 1));
8423 else
8424 goto give_up;
8426 else if (*vr0type == VR_RANGE
8427 && vr1type == VR_ANTI_RANGE)
8429 if (TREE_CODE (*vr0min) == INTEGER_CST)
8431 *vr0type = vr1type;
8432 *vr0min = vr1min;
8433 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
8434 build_int_cst (TREE_TYPE (*vr0min), 1));
8436 else
8437 goto give_up;
8439 else
8440 gcc_unreachable ();
8442 else
8443 goto give_up;
8445 return;
8447 give_up:
8448 *vr0type = VR_VARYING;
8449 *vr0min = NULL_TREE;
8450 *vr0max = NULL_TREE;
8453 /* Intersect the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
8454 { VR1TYPE, VR0MIN, VR0MAX } and store the result
8455 in { *VR0TYPE, *VR0MIN, *VR0MAX }. This may not be the smallest
8456 possible such range. The resulting range is not canonicalized. */
8458 static void
8459 intersect_ranges (enum value_range_type *vr0type,
8460 tree *vr0min, tree *vr0max,
8461 enum value_range_type vr1type,
8462 tree vr1min, tree vr1max)
8464 bool mineq = vrp_operand_equal_p (*vr0min, vr1min);
8465 bool maxeq = vrp_operand_equal_p (*vr0max, vr1max);
8467 /* [] is vr0, () is vr1 in the following classification comments. */
8468 if (mineq && maxeq)
8470 /* [( )] */
8471 if (*vr0type == vr1type)
8472 /* Nothing to do for equal ranges. */
8474 else if ((*vr0type == VR_RANGE
8475 && vr1type == VR_ANTI_RANGE)
8476 || (*vr0type == VR_ANTI_RANGE
8477 && vr1type == VR_RANGE))
8479 /* For anti-range with range intersection the result is empty. */
8480 *vr0type = VR_UNDEFINED;
8481 *vr0min = NULL_TREE;
8482 *vr0max = NULL_TREE;
8484 else
8485 gcc_unreachable ();
8487 else if (operand_less_p (*vr0max, vr1min) == 1
8488 || operand_less_p (vr1max, *vr0min) == 1)
8490 /* [ ] ( ) or ( ) [ ]
8491 If the ranges have an empty intersection, the result of the
8492 intersect operation is the range for intersecting an
8493 anti-range with a range or empty when intersecting two ranges. */
8494 if (*vr0type == VR_RANGE
8495 && vr1type == VR_ANTI_RANGE)
8497 else if (*vr0type == VR_ANTI_RANGE
8498 && vr1type == VR_RANGE)
8500 *vr0type = vr1type;
8501 *vr0min = vr1min;
8502 *vr0max = vr1max;
8504 else if (*vr0type == VR_RANGE
8505 && vr1type == VR_RANGE)
8507 *vr0type = VR_UNDEFINED;
8508 *vr0min = NULL_TREE;
8509 *vr0max = NULL_TREE;
8511 else if (*vr0type == VR_ANTI_RANGE
8512 && vr1type == VR_ANTI_RANGE)
8514 /* If the anti-ranges are adjacent to each other merge them. */
8515 if (TREE_CODE (*vr0max) == INTEGER_CST
8516 && TREE_CODE (vr1min) == INTEGER_CST
8517 && operand_less_p (*vr0max, vr1min) == 1
8518 && integer_onep (int_const_binop (MINUS_EXPR,
8519 vr1min, *vr0max)))
8520 *vr0max = vr1max;
8521 else if (TREE_CODE (vr1max) == INTEGER_CST
8522 && TREE_CODE (*vr0min) == INTEGER_CST
8523 && operand_less_p (vr1max, *vr0min) == 1
8524 && integer_onep (int_const_binop (MINUS_EXPR,
8525 *vr0min, vr1max)))
8526 *vr0min = vr1min;
8527 /* Else arbitrarily take VR0. */
8530 else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
8531 && (mineq || operand_less_p (*vr0min, vr1min) == 1))
8533 /* [ ( ) ] or [( ) ] or [ ( )] */
8534 if (*vr0type == VR_RANGE
8535 && vr1type == VR_RANGE)
8537 /* If both are ranges the result is the inner one. */
8538 *vr0type = vr1type;
8539 *vr0min = vr1min;
8540 *vr0max = vr1max;
8542 else if (*vr0type == VR_RANGE
8543 && vr1type == VR_ANTI_RANGE)
8545 /* Choose the right gap if the left one is empty. */
8546 if (mineq)
8548 if (TREE_CODE (vr1max) != INTEGER_CST)
8549 *vr0min = vr1max;
8550 else if (TYPE_PRECISION (TREE_TYPE (vr1max)) == 1
8551 && !TYPE_UNSIGNED (TREE_TYPE (vr1max)))
8552 *vr0min
8553 = int_const_binop (MINUS_EXPR, vr1max,
8554 build_int_cst (TREE_TYPE (vr1max), -1));
8555 else
8556 *vr0min
8557 = int_const_binop (PLUS_EXPR, vr1max,
8558 build_int_cst (TREE_TYPE (vr1max), 1));
8560 /* Choose the left gap if the right one is empty. */
8561 else if (maxeq)
8563 if (TREE_CODE (vr1min) != INTEGER_CST)
8564 *vr0max = vr1min;
8565 else if (TYPE_PRECISION (TREE_TYPE (vr1min)) == 1
8566 && !TYPE_UNSIGNED (TREE_TYPE (vr1min)))
8567 *vr0max
8568 = int_const_binop (PLUS_EXPR, vr1min,
8569 build_int_cst (TREE_TYPE (vr1min), -1));
8570 else
8571 *vr0max
8572 = int_const_binop (MINUS_EXPR, vr1min,
8573 build_int_cst (TREE_TYPE (vr1min), 1));
8575 /* Choose the anti-range if the range is effectively varying. */
8576 else if (vrp_val_is_min (*vr0min)
8577 && vrp_val_is_max (*vr0max))
8579 *vr0type = vr1type;
8580 *vr0min = vr1min;
8581 *vr0max = vr1max;
8583 /* Else choose the range. */
8585 else if (*vr0type == VR_ANTI_RANGE
8586 && vr1type == VR_ANTI_RANGE)
8587 /* If both are anti-ranges the result is the outer one. */
8589 else if (*vr0type == VR_ANTI_RANGE
8590 && vr1type == VR_RANGE)
8592 /* The intersection is empty. */
8593 *vr0type = VR_UNDEFINED;
8594 *vr0min = NULL_TREE;
8595 *vr0max = NULL_TREE;
8597 else
8598 gcc_unreachable ();
8600 else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
8601 && (mineq || operand_less_p (vr1min, *vr0min) == 1))
8603 /* ( [ ] ) or ([ ] ) or ( [ ]) */
8604 if (*vr0type == VR_RANGE
8605 && vr1type == VR_RANGE)
8606 /* Choose the inner range. */
8608 else if (*vr0type == VR_ANTI_RANGE
8609 && vr1type == VR_RANGE)
8611 /* Choose the right gap if the left is empty. */
8612 if (mineq)
8614 *vr0type = VR_RANGE;
8615 if (TREE_CODE (*vr0max) != INTEGER_CST)
8616 *vr0min = *vr0max;
8617 else if (TYPE_PRECISION (TREE_TYPE (*vr0max)) == 1
8618 && !TYPE_UNSIGNED (TREE_TYPE (*vr0max)))
8619 *vr0min
8620 = int_const_binop (MINUS_EXPR, *vr0max,
8621 build_int_cst (TREE_TYPE (*vr0max), -1));
8622 else
8623 *vr0min
8624 = int_const_binop (PLUS_EXPR, *vr0max,
8625 build_int_cst (TREE_TYPE (*vr0max), 1));
8626 *vr0max = vr1max;
8628 /* Choose the left gap if the right is empty. */
8629 else if (maxeq)
8631 *vr0type = VR_RANGE;
8632 if (TREE_CODE (*vr0min) != INTEGER_CST)
8633 *vr0max = *vr0min;
8634 else if (TYPE_PRECISION (TREE_TYPE (*vr0min)) == 1
8635 && !TYPE_UNSIGNED (TREE_TYPE (*vr0min)))
8636 *vr0max
8637 = int_const_binop (PLUS_EXPR, *vr0min,
8638 build_int_cst (TREE_TYPE (*vr0min), -1));
8639 else
8640 *vr0max
8641 = int_const_binop (MINUS_EXPR, *vr0min,
8642 build_int_cst (TREE_TYPE (*vr0min), 1));
8643 *vr0min = vr1min;
8645 /* Choose the anti-range if the range is effectively varying. */
8646 else if (vrp_val_is_min (vr1min)
8647 && vrp_val_is_max (vr1max))
8649 /* Choose the anti-range if it is ~[0,0], that range is special
8650 enough to special case when vr1's range is relatively wide. */
8651 else if (*vr0min == *vr0max
8652 && integer_zerop (*vr0min)
8653 && (TYPE_PRECISION (TREE_TYPE (*vr0min))
8654 == TYPE_PRECISION (ptr_type_node))
8655 && TREE_CODE (vr1max) == INTEGER_CST
8656 && TREE_CODE (vr1min) == INTEGER_CST
8657 && (wi::clz (wi::sub (vr1max, vr1min))
8658 < TYPE_PRECISION (TREE_TYPE (*vr0min)) / 2))
8660 /* Else choose the range. */
8661 else
8663 *vr0type = vr1type;
8664 *vr0min = vr1min;
8665 *vr0max = vr1max;
8668 else if (*vr0type == VR_ANTI_RANGE
8669 && vr1type == VR_ANTI_RANGE)
8671 /* If both are anti-ranges the result is the outer one. */
8672 *vr0type = vr1type;
8673 *vr0min = vr1min;
8674 *vr0max = vr1max;
8676 else if (vr1type == VR_ANTI_RANGE
8677 && *vr0type == VR_RANGE)
8679 /* The intersection is empty. */
8680 *vr0type = VR_UNDEFINED;
8681 *vr0min = NULL_TREE;
8682 *vr0max = NULL_TREE;
8684 else
8685 gcc_unreachable ();
8687 else if ((operand_less_p (vr1min, *vr0max) == 1
8688 || operand_equal_p (vr1min, *vr0max, 0))
8689 && operand_less_p (*vr0min, vr1min) == 1)
8691 /* [ ( ] ) or [ ]( ) */
8692 if (*vr0type == VR_ANTI_RANGE
8693 && vr1type == VR_ANTI_RANGE)
8694 *vr0max = vr1max;
8695 else if (*vr0type == VR_RANGE
8696 && vr1type == VR_RANGE)
8697 *vr0min = vr1min;
8698 else if (*vr0type == VR_RANGE
8699 && vr1type == VR_ANTI_RANGE)
8701 if (TREE_CODE (vr1min) == INTEGER_CST)
8702 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8703 build_int_cst (TREE_TYPE (vr1min), 1));
8704 else
8705 *vr0max = vr1min;
8707 else if (*vr0type == VR_ANTI_RANGE
8708 && vr1type == VR_RANGE)
8710 *vr0type = VR_RANGE;
8711 if (TREE_CODE (*vr0max) == INTEGER_CST)
8712 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8713 build_int_cst (TREE_TYPE (*vr0max), 1));
8714 else
8715 *vr0min = *vr0max;
8716 *vr0max = vr1max;
8718 else
8719 gcc_unreachable ();
8721 else if ((operand_less_p (*vr0min, vr1max) == 1
8722 || operand_equal_p (*vr0min, vr1max, 0))
8723 && operand_less_p (vr1min, *vr0min) == 1)
8725 /* ( [ ) ] or ( )[ ] */
8726 if (*vr0type == VR_ANTI_RANGE
8727 && vr1type == VR_ANTI_RANGE)
8728 *vr0min = vr1min;
8729 else if (*vr0type == VR_RANGE
8730 && vr1type == VR_RANGE)
8731 *vr0max = vr1max;
8732 else if (*vr0type == VR_RANGE
8733 && vr1type == VR_ANTI_RANGE)
8735 if (TREE_CODE (vr1max) == INTEGER_CST)
8736 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
8737 build_int_cst (TREE_TYPE (vr1max), 1));
8738 else
8739 *vr0min = vr1max;
8741 else if (*vr0type == VR_ANTI_RANGE
8742 && vr1type == VR_RANGE)
8744 *vr0type = VR_RANGE;
8745 if (TREE_CODE (*vr0min) == INTEGER_CST)
8746 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
8747 build_int_cst (TREE_TYPE (*vr0min), 1));
8748 else
8749 *vr0max = *vr0min;
8750 *vr0min = vr1min;
8752 else
8753 gcc_unreachable ();
8756 /* As a fallback simply use { *VRTYPE, *VR0MIN, *VR0MAX } as
8757 result for the intersection. That's always a conservative
8758 correct estimate unless VR1 is a constant singleton range
8759 in which case we choose that. */
8760 if (vr1type == VR_RANGE
8761 && is_gimple_min_invariant (vr1min)
8762 && vrp_operand_equal_p (vr1min, vr1max))
8764 *vr0type = vr1type;
8765 *vr0min = vr1min;
8766 *vr0max = vr1max;
8769 return;
8773 /* Intersect the two value-ranges *VR0 and *VR1 and store the result
8774 in *VR0. This may not be the smallest possible such range. */
8776 static void
8777 vrp_intersect_ranges_1 (value_range *vr0, value_range *vr1)
8779 value_range saved;
8781 /* If either range is VR_VARYING the other one wins. */
8782 if (vr1->type == VR_VARYING)
8783 return;
8784 if (vr0->type == VR_VARYING)
8786 copy_value_range (vr0, vr1);
8787 return;
8790 /* When either range is VR_UNDEFINED the resulting range is
8791 VR_UNDEFINED, too. */
8792 if (vr0->type == VR_UNDEFINED)
8793 return;
8794 if (vr1->type == VR_UNDEFINED)
8796 set_value_range_to_undefined (vr0);
8797 return;
8800 /* Save the original vr0 so we can return it as conservative intersection
8801 result when our worker turns things to varying. */
8802 saved = *vr0;
8803 intersect_ranges (&vr0->type, &vr0->min, &vr0->max,
8804 vr1->type, vr1->min, vr1->max);
8805 /* Make sure to canonicalize the result though as the inversion of a
8806 VR_RANGE can still be a VR_RANGE. */
8807 set_and_canonicalize_value_range (vr0, vr0->type,
8808 vr0->min, vr0->max, vr0->equiv);
8809 /* If that failed, use the saved original VR0. */
8810 if (vr0->type == VR_VARYING)
8812 *vr0 = saved;
8813 return;
8815 /* If the result is VR_UNDEFINED there is no need to mess with
8816 the equivalencies. */
8817 if (vr0->type == VR_UNDEFINED)
8818 return;
8820 /* The resulting set of equivalences for range intersection is the union of
8821 the two sets. */
8822 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
8823 bitmap_ior_into (vr0->equiv, vr1->equiv);
8824 else if (vr1->equiv && !vr0->equiv)
8826 vr0->equiv = BITMAP_ALLOC (&vrp_equiv_obstack);
8827 bitmap_copy (vr0->equiv, vr1->equiv);
8831 void
8832 vrp_intersect_ranges (value_range *vr0, value_range *vr1)
8834 if (dump_file && (dump_flags & TDF_DETAILS))
8836 fprintf (dump_file, "Intersecting\n ");
8837 dump_value_range (dump_file, vr0);
8838 fprintf (dump_file, "\nand\n ");
8839 dump_value_range (dump_file, vr1);
8840 fprintf (dump_file, "\n");
8842 vrp_intersect_ranges_1 (vr0, vr1);
8843 if (dump_file && (dump_flags & TDF_DETAILS))
8845 fprintf (dump_file, "to\n ");
8846 dump_value_range (dump_file, vr0);
8847 fprintf (dump_file, "\n");
8851 /* Meet operation for value ranges. Given two value ranges VR0 and
8852 VR1, store in VR0 a range that contains both VR0 and VR1. This
8853 may not be the smallest possible such range. */
8855 static void
8856 vrp_meet_1 (value_range *vr0, const value_range *vr1)
8858 value_range saved;
8860 if (vr0->type == VR_UNDEFINED)
8862 set_value_range (vr0, vr1->type, vr1->min, vr1->max, vr1->equiv);
8863 return;
8866 if (vr1->type == VR_UNDEFINED)
8868 /* VR0 already has the resulting range. */
8869 return;
8872 if (vr0->type == VR_VARYING)
8874 /* Nothing to do. VR0 already has the resulting range. */
8875 return;
8878 if (vr1->type == VR_VARYING)
8880 set_value_range_to_varying (vr0);
8881 return;
8884 saved = *vr0;
8885 union_ranges (&vr0->type, &vr0->min, &vr0->max,
8886 vr1->type, vr1->min, vr1->max);
8887 if (vr0->type == VR_VARYING)
8889 /* Failed to find an efficient meet. Before giving up and setting
8890 the result to VARYING, see if we can at least derive a useful
8891 anti-range. FIXME, all this nonsense about distinguishing
8892 anti-ranges from ranges is necessary because of the odd
8893 semantics of range_includes_zero_p and friends. */
8894 if (((saved.type == VR_RANGE
8895 && range_includes_zero_p (saved.min, saved.max) == 0)
8896 || (saved.type == VR_ANTI_RANGE
8897 && range_includes_zero_p (saved.min, saved.max) == 1))
8898 && ((vr1->type == VR_RANGE
8899 && range_includes_zero_p (vr1->min, vr1->max) == 0)
8900 || (vr1->type == VR_ANTI_RANGE
8901 && range_includes_zero_p (vr1->min, vr1->max) == 1)))
8903 set_value_range_to_nonnull (vr0, TREE_TYPE (saved.min));
8905 /* Since this meet operation did not result from the meeting of
8906 two equivalent names, VR0 cannot have any equivalences. */
8907 if (vr0->equiv)
8908 bitmap_clear (vr0->equiv);
8909 return;
8912 set_value_range_to_varying (vr0);
8913 return;
8915 set_and_canonicalize_value_range (vr0, vr0->type, vr0->min, vr0->max,
8916 vr0->equiv);
8917 if (vr0->type == VR_VARYING)
8918 return;
8920 /* The resulting set of equivalences is always the intersection of
8921 the two sets. */
8922 if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
8923 bitmap_and_into (vr0->equiv, vr1->equiv);
8924 else if (vr0->equiv && !vr1->equiv)
8925 bitmap_clear (vr0->equiv);
8928 void
8929 vrp_meet (value_range *vr0, const value_range *vr1)
8931 if (dump_file && (dump_flags & TDF_DETAILS))
8933 fprintf (dump_file, "Meeting\n ");
8934 dump_value_range (dump_file, vr0);
8935 fprintf (dump_file, "\nand\n ");
8936 dump_value_range (dump_file, vr1);
8937 fprintf (dump_file, "\n");
8939 vrp_meet_1 (vr0, vr1);
8940 if (dump_file && (dump_flags & TDF_DETAILS))
8942 fprintf (dump_file, "to\n ");
8943 dump_value_range (dump_file, vr0);
8944 fprintf (dump_file, "\n");
8949 /* Visit all arguments for PHI node PHI that flow through executable
8950 edges. If a valid value range can be derived from all the incoming
8951 value ranges, set a new range in VR_RESULT. */
8953 static void
8954 extract_range_from_phi_node (gphi *phi, value_range *vr_result)
8956 size_t i;
8957 tree lhs = PHI_RESULT (phi);
8958 value_range *lhs_vr = get_value_range (lhs);
8959 bool first = true;
8960 int edges, old_edges;
8961 struct loop *l;
8963 if (dump_file && (dump_flags & TDF_DETAILS))
8965 fprintf (dump_file, "\nVisiting PHI node: ");
8966 print_gimple_stmt (dump_file, phi, 0, dump_flags);
8969 bool may_simulate_backedge_again = false;
8970 edges = 0;
8971 for (i = 0; i < gimple_phi_num_args (phi); i++)
8973 edge e = gimple_phi_arg_edge (phi, i);
8975 if (dump_file && (dump_flags & TDF_DETAILS))
8977 fprintf (dump_file,
8978 " Argument #%d (%d -> %d %sexecutable)\n",
8979 (int) i, e->src->index, e->dest->index,
8980 (e->flags & EDGE_EXECUTABLE) ? "" : "not ");
8983 if (e->flags & EDGE_EXECUTABLE)
8985 tree arg = PHI_ARG_DEF (phi, i);
8986 value_range vr_arg;
8988 ++edges;
8990 if (TREE_CODE (arg) == SSA_NAME)
8992 /* See if we are eventually going to change one of the args. */
8993 gimple *def_stmt = SSA_NAME_DEF_STMT (arg);
8994 if (! gimple_nop_p (def_stmt)
8995 && prop_simulate_again_p (def_stmt)
8996 && e->flags & EDGE_DFS_BACK)
8997 may_simulate_backedge_again = true;
8999 vr_arg = *(get_value_range (arg));
9000 /* Do not allow equivalences or symbolic ranges to leak in from
9001 backedges. That creates invalid equivalencies.
9002 See PR53465 and PR54767. */
9003 if (e->flags & EDGE_DFS_BACK)
9005 if (vr_arg.type == VR_RANGE
9006 || vr_arg.type == VR_ANTI_RANGE)
9008 vr_arg.equiv = NULL;
9009 if (symbolic_range_p (&vr_arg))
9011 vr_arg.type = VR_VARYING;
9012 vr_arg.min = NULL_TREE;
9013 vr_arg.max = NULL_TREE;
9017 else
9019 /* If the non-backedge arguments range is VR_VARYING then
9020 we can still try recording a simple equivalence. */
9021 if (vr_arg.type == VR_VARYING)
9023 vr_arg.type = VR_RANGE;
9024 vr_arg.min = arg;
9025 vr_arg.max = arg;
9026 vr_arg.equiv = NULL;
9030 else
9032 if (TREE_OVERFLOW_P (arg))
9033 arg = drop_tree_overflow (arg);
9035 vr_arg.type = VR_RANGE;
9036 vr_arg.min = arg;
9037 vr_arg.max = arg;
9038 vr_arg.equiv = NULL;
9041 if (dump_file && (dump_flags & TDF_DETAILS))
9043 fprintf (dump_file, "\t");
9044 print_generic_expr (dump_file, arg, dump_flags);
9045 fprintf (dump_file, ": ");
9046 dump_value_range (dump_file, &vr_arg);
9047 fprintf (dump_file, "\n");
9050 if (first)
9051 copy_value_range (vr_result, &vr_arg);
9052 else
9053 vrp_meet (vr_result, &vr_arg);
9054 first = false;
9056 if (vr_result->type == VR_VARYING)
9057 break;
9061 if (vr_result->type == VR_VARYING)
9062 goto varying;
9063 else if (vr_result->type == VR_UNDEFINED)
9064 goto update_range;
9066 old_edges = vr_phi_edge_counts[SSA_NAME_VERSION (lhs)];
9067 vr_phi_edge_counts[SSA_NAME_VERSION (lhs)] = edges;
9069 /* To prevent infinite iterations in the algorithm, derive ranges
9070 when the new value is slightly bigger or smaller than the
9071 previous one. We don't do this if we have seen a new executable
9072 edge; this helps us avoid an infinity for conditionals
9073 which are not in a loop. If the old value-range was VR_UNDEFINED
9074 use the updated range and iterate one more time. If we will not
9075 simulate this PHI again via the backedge allow us to iterate. */
9076 if (edges > 0
9077 && gimple_phi_num_args (phi) > 1
9078 && edges == old_edges
9079 && lhs_vr->type != VR_UNDEFINED
9080 && may_simulate_backedge_again)
9082 /* Compare old and new ranges, fall back to varying if the
9083 values are not comparable. */
9084 int cmp_min = compare_values (lhs_vr->min, vr_result->min);
9085 if (cmp_min == -2)
9086 goto varying;
9087 int cmp_max = compare_values (lhs_vr->max, vr_result->max);
9088 if (cmp_max == -2)
9089 goto varying;
9091 /* For non VR_RANGE or for pointers fall back to varying if
9092 the range changed. */
9093 if ((lhs_vr->type != VR_RANGE || vr_result->type != VR_RANGE
9094 || POINTER_TYPE_P (TREE_TYPE (lhs)))
9095 && (cmp_min != 0 || cmp_max != 0))
9096 goto varying;
9098 /* If the new minimum is larger than the previous one
9099 retain the old value. If the new minimum value is smaller
9100 than the previous one and not -INF go all the way to -INF + 1.
9101 In the first case, to avoid infinite bouncing between different
9102 minimums, and in the other case to avoid iterating millions of
9103 times to reach -INF. Going to -INF + 1 also lets the following
9104 iteration compute whether there will be any overflow, at the
9105 expense of one additional iteration. */
9106 if (cmp_min < 0)
9107 vr_result->min = lhs_vr->min;
9108 else if (cmp_min > 0
9109 && !vrp_val_is_min (vr_result->min))
9110 vr_result->min
9111 = int_const_binop (PLUS_EXPR,
9112 vrp_val_min (TREE_TYPE (vr_result->min)),
9113 build_int_cst (TREE_TYPE (vr_result->min), 1));
9115 /* Similarly for the maximum value. */
9116 if (cmp_max > 0)
9117 vr_result->max = lhs_vr->max;
9118 else if (cmp_max < 0
9119 && !vrp_val_is_max (vr_result->max))
9120 vr_result->max
9121 = int_const_binop (MINUS_EXPR,
9122 vrp_val_max (TREE_TYPE (vr_result->min)),
9123 build_int_cst (TREE_TYPE (vr_result->min), 1));
9125 /* If we dropped either bound to +-INF then if this is a loop
9126 PHI node SCEV may known more about its value-range. */
9127 if (cmp_min > 0 || cmp_min < 0
9128 || cmp_max < 0 || cmp_max > 0)
9129 goto scev_check;
9131 goto infinite_check;
9134 goto update_range;
9136 varying:
9137 set_value_range_to_varying (vr_result);
9139 scev_check:
9140 /* If this is a loop PHI node SCEV may known more about its value-range.
9141 scev_check can be reached from two paths, one is a fall through from above
9142 "varying" label, the other is direct goto from code block which tries to
9143 avoid infinite simulation. */
9144 if ((l = loop_containing_stmt (phi))
9145 && l->header == gimple_bb (phi))
9146 adjust_range_with_scev (vr_result, l, phi, lhs);
9148 infinite_check:
9149 /* If we will end up with a (-INF, +INF) range, set it to
9150 VARYING. Same if the previous max value was invalid for
9151 the type and we end up with vr_result.min > vr_result.max. */
9152 if ((vr_result->type == VR_RANGE || vr_result->type == VR_ANTI_RANGE)
9153 && !((vrp_val_is_max (vr_result->max) && vrp_val_is_min (vr_result->min))
9154 || compare_values (vr_result->min, vr_result->max) > 0))
9156 else
9157 set_value_range_to_varying (vr_result);
9159 /* If the new range is different than the previous value, keep
9160 iterating. */
9161 update_range:
9162 return;
9165 /* Visit all arguments for PHI node PHI that flow through executable
9166 edges. If a valid value range can be derived from all the incoming
9167 value ranges, set a new range for the LHS of PHI. */
9169 static enum ssa_prop_result
9170 vrp_visit_phi_node (gphi *phi)
9172 tree lhs = PHI_RESULT (phi);
9173 value_range vr_result = VR_INITIALIZER;
9174 extract_range_from_phi_node (phi, &vr_result);
9175 if (update_value_range (lhs, &vr_result))
9177 if (dump_file && (dump_flags & TDF_DETAILS))
9179 fprintf (dump_file, "Found new range for ");
9180 print_generic_expr (dump_file, lhs);
9181 fprintf (dump_file, ": ");
9182 dump_value_range (dump_file, &vr_result);
9183 fprintf (dump_file, "\n");
9186 if (vr_result.type == VR_VARYING)
9187 return SSA_PROP_VARYING;
9189 return SSA_PROP_INTERESTING;
9192 /* Nothing changed, don't add outgoing edges. */
9193 return SSA_PROP_NOT_INTERESTING;
9196 /* Simplify boolean operations if the source is known
9197 to be already a boolean. */
9198 static bool
9199 simplify_truth_ops_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9201 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
9202 tree lhs, op0, op1;
9203 bool need_conversion;
9205 /* We handle only !=/== case here. */
9206 gcc_assert (rhs_code == EQ_EXPR || rhs_code == NE_EXPR);
9208 op0 = gimple_assign_rhs1 (stmt);
9209 if (!op_with_boolean_value_range_p (op0))
9210 return false;
9212 op1 = gimple_assign_rhs2 (stmt);
9213 if (!op_with_boolean_value_range_p (op1))
9214 return false;
9216 /* Reduce number of cases to handle to NE_EXPR. As there is no
9217 BIT_XNOR_EXPR we cannot replace A == B with a single statement. */
9218 if (rhs_code == EQ_EXPR)
9220 if (TREE_CODE (op1) == INTEGER_CST)
9221 op1 = int_const_binop (BIT_XOR_EXPR, op1,
9222 build_int_cst (TREE_TYPE (op1), 1));
9223 else
9224 return false;
9227 lhs = gimple_assign_lhs (stmt);
9228 need_conversion
9229 = !useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (op0));
9231 /* Make sure to not sign-extend a 1-bit 1 when converting the result. */
9232 if (need_conversion
9233 && !TYPE_UNSIGNED (TREE_TYPE (op0))
9234 && TYPE_PRECISION (TREE_TYPE (op0)) == 1
9235 && TYPE_PRECISION (TREE_TYPE (lhs)) > 1)
9236 return false;
9238 /* For A != 0 we can substitute A itself. */
9239 if (integer_zerop (op1))
9240 gimple_assign_set_rhs_with_ops (gsi,
9241 need_conversion
9242 ? NOP_EXPR : TREE_CODE (op0), op0);
9243 /* For A != B we substitute A ^ B. Either with conversion. */
9244 else if (need_conversion)
9246 tree tem = make_ssa_name (TREE_TYPE (op0));
9247 gassign *newop
9248 = gimple_build_assign (tem, BIT_XOR_EXPR, op0, op1);
9249 gsi_insert_before (gsi, newop, GSI_SAME_STMT);
9250 if (INTEGRAL_TYPE_P (TREE_TYPE (tem))
9251 && TYPE_PRECISION (TREE_TYPE (tem)) > 1)
9252 set_range_info (tem, VR_RANGE,
9253 wi::zero (TYPE_PRECISION (TREE_TYPE (tem))),
9254 wi::one (TYPE_PRECISION (TREE_TYPE (tem))));
9255 gimple_assign_set_rhs_with_ops (gsi, NOP_EXPR, tem);
9257 /* Or without. */
9258 else
9259 gimple_assign_set_rhs_with_ops (gsi, BIT_XOR_EXPR, op0, op1);
9260 update_stmt (gsi_stmt (*gsi));
9261 fold_stmt (gsi, follow_single_use_edges);
9263 return true;
9266 /* Simplify a division or modulo operator to a right shift or bitwise and
9267 if the first operand is unsigned or is greater than zero and the second
9268 operand is an exact power of two. For TRUNC_MOD_EXPR op0 % op1 with
9269 constant op1 (op1min = op1) or with op1 in [op1min, op1max] range,
9270 optimize it into just op0 if op0's range is known to be a subset of
9271 [-op1min + 1, op1min - 1] for signed and [0, op1min - 1] for unsigned
9272 modulo. */
9274 static bool
9275 simplify_div_or_mod_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9277 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
9278 tree val = NULL;
9279 tree op0 = gimple_assign_rhs1 (stmt);
9280 tree op1 = gimple_assign_rhs2 (stmt);
9281 tree op0min = NULL_TREE, op0max = NULL_TREE;
9282 tree op1min = op1;
9283 value_range *vr = NULL;
9285 if (TREE_CODE (op0) == INTEGER_CST)
9287 op0min = op0;
9288 op0max = op0;
9290 else
9292 vr = get_value_range (op0);
9293 if (range_int_cst_p (vr))
9295 op0min = vr->min;
9296 op0max = vr->max;
9300 if (rhs_code == TRUNC_MOD_EXPR
9301 && TREE_CODE (op1) == SSA_NAME)
9303 value_range *vr1 = get_value_range (op1);
9304 if (range_int_cst_p (vr1))
9305 op1min = vr1->min;
9307 if (rhs_code == TRUNC_MOD_EXPR
9308 && TREE_CODE (op1min) == INTEGER_CST
9309 && tree_int_cst_sgn (op1min) == 1
9310 && op0max
9311 && tree_int_cst_lt (op0max, op1min))
9313 if (TYPE_UNSIGNED (TREE_TYPE (op0))
9314 || tree_int_cst_sgn (op0min) >= 0
9315 || tree_int_cst_lt (fold_unary (NEGATE_EXPR, TREE_TYPE (op1min), op1min),
9316 op0min))
9318 /* If op0 already has the range op0 % op1 has,
9319 then TRUNC_MOD_EXPR won't change anything. */
9320 gimple_assign_set_rhs_from_tree (gsi, op0);
9321 return true;
9325 if (TREE_CODE (op0) != SSA_NAME)
9326 return false;
9328 if (!integer_pow2p (op1))
9330 /* X % -Y can be only optimized into X % Y either if
9331 X is not INT_MIN, or Y is not -1. Fold it now, as after
9332 remove_range_assertions the range info might be not available
9333 anymore. */
9334 if (rhs_code == TRUNC_MOD_EXPR
9335 && fold_stmt (gsi, follow_single_use_edges))
9336 return true;
9337 return false;
9340 if (TYPE_UNSIGNED (TREE_TYPE (op0)))
9341 val = integer_one_node;
9342 else
9344 bool sop = false;
9346 val = compare_range_with_value (GE_EXPR, vr, integer_zero_node, &sop);
9348 if (val
9349 && sop
9350 && integer_onep (val)
9351 && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
9353 location_t location;
9355 if (!gimple_has_location (stmt))
9356 location = input_location;
9357 else
9358 location = gimple_location (stmt);
9359 warning_at (location, OPT_Wstrict_overflow,
9360 "assuming signed overflow does not occur when "
9361 "simplifying %</%> or %<%%%> to %<>>%> or %<&%>");
9365 if (val && integer_onep (val))
9367 tree t;
9369 if (rhs_code == TRUNC_DIV_EXPR)
9371 t = build_int_cst (integer_type_node, tree_log2 (op1));
9372 gimple_assign_set_rhs_code (stmt, RSHIFT_EXPR);
9373 gimple_assign_set_rhs1 (stmt, op0);
9374 gimple_assign_set_rhs2 (stmt, t);
9376 else
9378 t = build_int_cst (TREE_TYPE (op1), 1);
9379 t = int_const_binop (MINUS_EXPR, op1, t);
9380 t = fold_convert (TREE_TYPE (op0), t);
9382 gimple_assign_set_rhs_code (stmt, BIT_AND_EXPR);
9383 gimple_assign_set_rhs1 (stmt, op0);
9384 gimple_assign_set_rhs2 (stmt, t);
9387 update_stmt (stmt);
9388 fold_stmt (gsi, follow_single_use_edges);
9389 return true;
9392 return false;
9395 /* Simplify a min or max if the ranges of the two operands are
9396 disjoint. Return true if we do simplify. */
9398 static bool
9399 simplify_min_or_max_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9401 tree op0 = gimple_assign_rhs1 (stmt);
9402 tree op1 = gimple_assign_rhs2 (stmt);
9403 bool sop = false;
9404 tree val;
9406 val = (vrp_evaluate_conditional_warnv_with_ops_using_ranges
9407 (LE_EXPR, op0, op1, &sop));
9408 if (!val)
9410 sop = false;
9411 val = (vrp_evaluate_conditional_warnv_with_ops_using_ranges
9412 (LT_EXPR, op0, op1, &sop));
9415 if (val)
9417 if (sop && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
9419 location_t location;
9421 if (!gimple_has_location (stmt))
9422 location = input_location;
9423 else
9424 location = gimple_location (stmt);
9425 warning_at (location, OPT_Wstrict_overflow,
9426 "assuming signed overflow does not occur when "
9427 "simplifying %<min/max (X,Y)%> to %<X%> or %<Y%>");
9430 /* VAL == TRUE -> OP0 < or <= op1
9431 VAL == FALSE -> OP0 > or >= op1. */
9432 tree res = ((gimple_assign_rhs_code (stmt) == MAX_EXPR)
9433 == integer_zerop (val)) ? op0 : op1;
9434 gimple_assign_set_rhs_from_tree (gsi, res);
9435 return true;
9438 return false;
9441 /* If the operand to an ABS_EXPR is >= 0, then eliminate the
9442 ABS_EXPR. If the operand is <= 0, then simplify the
9443 ABS_EXPR into a NEGATE_EXPR. */
9445 static bool
9446 simplify_abs_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9448 tree op = gimple_assign_rhs1 (stmt);
9449 value_range *vr = get_value_range (op);
9451 if (vr)
9453 tree val = NULL;
9454 bool sop = false;
9456 val = compare_range_with_value (LE_EXPR, vr, integer_zero_node, &sop);
9457 if (!val)
9459 /* The range is neither <= 0 nor > 0. Now see if it is
9460 either < 0 or >= 0. */
9461 sop = false;
9462 val = compare_range_with_value (LT_EXPR, vr, integer_zero_node,
9463 &sop);
9466 if (val)
9468 if (sop && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
9470 location_t location;
9472 if (!gimple_has_location (stmt))
9473 location = input_location;
9474 else
9475 location = gimple_location (stmt);
9476 warning_at (location, OPT_Wstrict_overflow,
9477 "assuming signed overflow does not occur when "
9478 "simplifying %<abs (X)%> to %<X%> or %<-X%>");
9481 gimple_assign_set_rhs1 (stmt, op);
9482 if (integer_zerop (val))
9483 gimple_assign_set_rhs_code (stmt, SSA_NAME);
9484 else
9485 gimple_assign_set_rhs_code (stmt, NEGATE_EXPR);
9486 update_stmt (stmt);
9487 fold_stmt (gsi, follow_single_use_edges);
9488 return true;
9492 return false;
9495 /* Optimize away redundant BIT_AND_EXPR and BIT_IOR_EXPR.
9496 If all the bits that are being cleared by & are already
9497 known to be zero from VR, or all the bits that are being
9498 set by | are already known to be one from VR, the bit
9499 operation is redundant. */
9501 static bool
9502 simplify_bit_ops_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
9504 tree op0 = gimple_assign_rhs1 (stmt);
9505 tree op1 = gimple_assign_rhs2 (stmt);
9506 tree op = NULL_TREE;
9507 value_range vr0 = VR_INITIALIZER;
9508 value_range vr1 = VR_INITIALIZER;
9509 wide_int may_be_nonzero0, may_be_nonzero1;
9510 wide_int must_be_nonzero0, must_be_nonzero1;
9511 wide_int mask;
9513 if (TREE_CODE (op0) == SSA_NAME)
9514 vr0 = *(get_value_range (op0));
9515 else if (is_gimple_min_invariant (op0))
9516 set_value_range_to_value (&vr0, op0, NULL);
9517 else
9518 return false;
9520 if (TREE_CODE (op1) == SSA_NAME)
9521 vr1 = *(get_value_range (op1));
9522 else if (is_gimple_min_invariant (op1))
9523 set_value_range_to_value (&vr1, op1, NULL);
9524 else
9525 return false;
9527 if (!zero_nonzero_bits_from_vr (TREE_TYPE (op0), &vr0, &may_be_nonzero0,
9528 &must_be_nonzero0))
9529 return false;
9530 if (!zero_nonzero_bits_from_vr (TREE_TYPE (op1), &vr1, &may_be_nonzero1,
9531 &must_be_nonzero1))
9532 return false;
9534 switch (gimple_assign_rhs_code (stmt))
9536 case BIT_AND_EXPR:
9537 mask = may_be_nonzero0.and_not (must_be_nonzero1);
9538 if (mask == 0)
9540 op = op0;
9541 break;
9543 mask = may_be_nonzero1.and_not (must_be_nonzero0);
9544 if (mask == 0)
9546 op = op1;
9547 break;
9549 break;
9550 case BIT_IOR_EXPR:
9551 mask = may_be_nonzero0.and_not (must_be_nonzero1);
9552 if (mask == 0)
9554 op = op1;
9555 break;
9557 mask = may_be_nonzero1.and_not (must_be_nonzero0);
9558 if (mask == 0)
9560 op = op0;
9561 break;
9563 break;
9564 default:
9565 gcc_unreachable ();
9568 if (op == NULL_TREE)
9569 return false;
9571 gimple_assign_set_rhs_with_ops (gsi, TREE_CODE (op), op);
9572 update_stmt (gsi_stmt (*gsi));
9573 return true;
9576 /* We are comparing trees OP0 and OP1 using COND_CODE. OP0 has
9577 a known value range VR.
9579 If there is one and only one value which will satisfy the
9580 conditional, then return that value. Else return NULL.
9582 If signed overflow must be undefined for the value to satisfy
9583 the conditional, then set *STRICT_OVERFLOW_P to true. */
9585 static tree
9586 test_for_singularity (enum tree_code cond_code, tree op0,
9587 tree op1, value_range *vr)
9589 tree min = NULL;
9590 tree max = NULL;
9592 /* Extract minimum/maximum values which satisfy the conditional as it was
9593 written. */
9594 if (cond_code == LE_EXPR || cond_code == LT_EXPR)
9596 min = TYPE_MIN_VALUE (TREE_TYPE (op0));
9598 max = op1;
9599 if (cond_code == LT_EXPR)
9601 tree one = build_int_cst (TREE_TYPE (op0), 1);
9602 max = fold_build2 (MINUS_EXPR, TREE_TYPE (op0), max, one);
9603 /* Signal to compare_values_warnv this expr doesn't overflow. */
9604 if (EXPR_P (max))
9605 TREE_NO_WARNING (max) = 1;
9608 else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
9610 max = TYPE_MAX_VALUE (TREE_TYPE (op0));
9612 min = op1;
9613 if (cond_code == GT_EXPR)
9615 tree one = build_int_cst (TREE_TYPE (op0), 1);
9616 min = fold_build2 (PLUS_EXPR, TREE_TYPE (op0), min, one);
9617 /* Signal to compare_values_warnv this expr doesn't overflow. */
9618 if (EXPR_P (min))
9619 TREE_NO_WARNING (min) = 1;
9623 /* Now refine the minimum and maximum values using any
9624 value range information we have for op0. */
9625 if (min && max)
9627 if (compare_values (vr->min, min) == 1)
9628 min = vr->min;
9629 if (compare_values (vr->max, max) == -1)
9630 max = vr->max;
9632 /* If the new min/max values have converged to a single value,
9633 then there is only one value which can satisfy the condition,
9634 return that value. */
9635 if (operand_equal_p (min, max, 0) && is_gimple_min_invariant (min))
9636 return min;
9638 return NULL;
9641 /* Return whether the value range *VR fits in an integer type specified
9642 by PRECISION and UNSIGNED_P. */
9644 static bool
9645 range_fits_type_p (value_range *vr, unsigned dest_precision, signop dest_sgn)
9647 tree src_type;
9648 unsigned src_precision;
9649 widest_int tem;
9650 signop src_sgn;
9652 /* We can only handle integral and pointer types. */
9653 src_type = TREE_TYPE (vr->min);
9654 if (!INTEGRAL_TYPE_P (src_type)
9655 && !POINTER_TYPE_P (src_type))
9656 return false;
9658 /* An extension is fine unless VR is SIGNED and dest_sgn is UNSIGNED,
9659 and so is an identity transform. */
9660 src_precision = TYPE_PRECISION (TREE_TYPE (vr->min));
9661 src_sgn = TYPE_SIGN (src_type);
9662 if ((src_precision < dest_precision
9663 && !(dest_sgn == UNSIGNED && src_sgn == SIGNED))
9664 || (src_precision == dest_precision && src_sgn == dest_sgn))
9665 return true;
9667 /* Now we can only handle ranges with constant bounds. */
9668 if (vr->type != VR_RANGE
9669 || TREE_CODE (vr->min) != INTEGER_CST
9670 || TREE_CODE (vr->max) != INTEGER_CST)
9671 return false;
9673 /* For sign changes, the MSB of the wide_int has to be clear.
9674 An unsigned value with its MSB set cannot be represented by
9675 a signed wide_int, while a negative value cannot be represented
9676 by an unsigned wide_int. */
9677 if (src_sgn != dest_sgn
9678 && (wi::lts_p (vr->min, 0) || wi::lts_p (vr->max, 0)))
9679 return false;
9681 /* Then we can perform the conversion on both ends and compare
9682 the result for equality. */
9683 tem = wi::ext (wi::to_widest (vr->min), dest_precision, dest_sgn);
9684 if (tem != wi::to_widest (vr->min))
9685 return false;
9686 tem = wi::ext (wi::to_widest (vr->max), dest_precision, dest_sgn);
9687 if (tem != wi::to_widest (vr->max))
9688 return false;
9690 return true;
9693 /* Simplify a conditional using a relational operator to an equality
9694 test if the range information indicates only one value can satisfy
9695 the original conditional. */
9697 static bool
9698 simplify_cond_using_ranges_1 (gcond *stmt)
9700 tree op0 = gimple_cond_lhs (stmt);
9701 tree op1 = gimple_cond_rhs (stmt);
9702 enum tree_code cond_code = gimple_cond_code (stmt);
9704 if (cond_code != NE_EXPR
9705 && cond_code != EQ_EXPR
9706 && TREE_CODE (op0) == SSA_NAME
9707 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
9708 && is_gimple_min_invariant (op1))
9710 value_range *vr = get_value_range (op0);
9712 /* If we have range information for OP0, then we might be
9713 able to simplify this conditional. */
9714 if (vr->type == VR_RANGE)
9716 tree new_tree = test_for_singularity (cond_code, op0, op1, vr);
9717 if (new_tree)
9719 if (dump_file)
9721 fprintf (dump_file, "Simplified relational ");
9722 print_gimple_stmt (dump_file, stmt, 0);
9723 fprintf (dump_file, " into ");
9726 gimple_cond_set_code (stmt, EQ_EXPR);
9727 gimple_cond_set_lhs (stmt, op0);
9728 gimple_cond_set_rhs (stmt, new_tree);
9730 update_stmt (stmt);
9732 if (dump_file)
9734 print_gimple_stmt (dump_file, stmt, 0);
9735 fprintf (dump_file, "\n");
9738 return true;
9741 /* Try again after inverting the condition. We only deal
9742 with integral types here, so no need to worry about
9743 issues with inverting FP comparisons. */
9744 new_tree = test_for_singularity
9745 (invert_tree_comparison (cond_code, false),
9746 op0, op1, vr);
9747 if (new_tree)
9749 if (dump_file)
9751 fprintf (dump_file, "Simplified relational ");
9752 print_gimple_stmt (dump_file, stmt, 0);
9753 fprintf (dump_file, " into ");
9756 gimple_cond_set_code (stmt, NE_EXPR);
9757 gimple_cond_set_lhs (stmt, op0);
9758 gimple_cond_set_rhs (stmt, new_tree);
9760 update_stmt (stmt);
9762 if (dump_file)
9764 print_gimple_stmt (dump_file, stmt, 0);
9765 fprintf (dump_file, "\n");
9768 return true;
9772 return false;
9775 /* STMT is a conditional at the end of a basic block.
9777 If the conditional is of the form SSA_NAME op constant and the SSA_NAME
9778 was set via a type conversion, try to replace the SSA_NAME with the RHS
9779 of the type conversion. Doing so makes the conversion dead which helps
9780 subsequent passes. */
9782 static void
9783 simplify_cond_using_ranges_2 (gcond *stmt)
9785 tree op0 = gimple_cond_lhs (stmt);
9786 tree op1 = gimple_cond_rhs (stmt);
9788 /* If we have a comparison of an SSA_NAME (OP0) against a constant,
9789 see if OP0 was set by a type conversion where the source of
9790 the conversion is another SSA_NAME with a range that fits
9791 into the range of OP0's type.
9793 If so, the conversion is redundant as the earlier SSA_NAME can be
9794 used for the comparison directly if we just massage the constant in the
9795 comparison. */
9796 if (TREE_CODE (op0) == SSA_NAME
9797 && TREE_CODE (op1) == INTEGER_CST)
9799 gimple *def_stmt = SSA_NAME_DEF_STMT (op0);
9800 tree innerop;
9802 if (!is_gimple_assign (def_stmt)
9803 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)))
9804 return;
9806 innerop = gimple_assign_rhs1 (def_stmt);
9808 if (TREE_CODE (innerop) == SSA_NAME
9809 && !POINTER_TYPE_P (TREE_TYPE (innerop))
9810 && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (innerop)
9811 && desired_pro_or_demotion_p (TREE_TYPE (innerop), TREE_TYPE (op0)))
9813 value_range *vr = get_value_range (innerop);
9815 if (range_int_cst_p (vr)
9816 && range_fits_type_p (vr,
9817 TYPE_PRECISION (TREE_TYPE (op0)),
9818 TYPE_SIGN (TREE_TYPE (op0)))
9819 && int_fits_type_p (op1, TREE_TYPE (innerop)))
9821 tree newconst = fold_convert (TREE_TYPE (innerop), op1);
9822 gimple_cond_set_lhs (stmt, innerop);
9823 gimple_cond_set_rhs (stmt, newconst);
9824 update_stmt (stmt);
9825 if (dump_file && (dump_flags & TDF_DETAILS))
9827 fprintf (dump_file, "Folded into: ");
9828 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
9829 fprintf (dump_file, "\n");
9836 /* Simplify a switch statement using the value range of the switch
9837 argument. */
9839 static bool
9840 simplify_switch_using_ranges (gswitch *stmt)
9842 tree op = gimple_switch_index (stmt);
9843 value_range *vr = NULL;
9844 bool take_default;
9845 edge e;
9846 edge_iterator ei;
9847 size_t i = 0, j = 0, n, n2;
9848 tree vec2;
9849 switch_update su;
9850 size_t k = 1, l = 0;
9852 if (TREE_CODE (op) == SSA_NAME)
9854 vr = get_value_range (op);
9856 /* We can only handle integer ranges. */
9857 if ((vr->type != VR_RANGE
9858 && vr->type != VR_ANTI_RANGE)
9859 || symbolic_range_p (vr))
9860 return false;
9862 /* Find case label for min/max of the value range. */
9863 take_default = !find_case_label_ranges (stmt, vr, &i, &j, &k, &l);
9865 else if (TREE_CODE (op) == INTEGER_CST)
9867 take_default = !find_case_label_index (stmt, 1, op, &i);
9868 if (take_default)
9870 i = 1;
9871 j = 0;
9873 else
9875 j = i;
9878 else
9879 return false;
9881 n = gimple_switch_num_labels (stmt);
9883 /* We can truncate the case label ranges that partially overlap with OP's
9884 value range. */
9885 size_t min_idx = 1, max_idx = 0;
9886 if (vr != NULL)
9887 find_case_label_range (stmt, vr->min, vr->max, &min_idx, &max_idx);
9888 if (min_idx <= max_idx)
9890 tree min_label = gimple_switch_label (stmt, min_idx);
9891 tree max_label = gimple_switch_label (stmt, max_idx);
9893 /* Avoid changing the type of the case labels when truncating. */
9894 tree case_label_type = TREE_TYPE (CASE_LOW (min_label));
9895 tree vr_min = fold_convert (case_label_type, vr->min);
9896 tree vr_max = fold_convert (case_label_type, vr->max);
9898 if (vr->type == VR_RANGE)
9900 /* If OP's value range is [2,8] and the low label range is
9901 0 ... 3, truncate the label's range to 2 .. 3. */
9902 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
9903 && CASE_HIGH (min_label) != NULL_TREE
9904 && tree_int_cst_compare (CASE_HIGH (min_label), vr_min) >= 0)
9905 CASE_LOW (min_label) = vr_min;
9907 /* If OP's value range is [2,8] and the high label range is
9908 7 ... 10, truncate the label's range to 7 .. 8. */
9909 if (tree_int_cst_compare (CASE_LOW (max_label), vr_max) <= 0
9910 && CASE_HIGH (max_label) != NULL_TREE
9911 && tree_int_cst_compare (CASE_HIGH (max_label), vr_max) > 0)
9912 CASE_HIGH (max_label) = vr_max;
9914 else if (vr->type == VR_ANTI_RANGE)
9916 tree one_cst = build_one_cst (case_label_type);
9918 if (min_label == max_label)
9920 /* If OP's value range is ~[7,8] and the label's range is
9921 7 ... 10, truncate the label's range to 9 ... 10. */
9922 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) == 0
9923 && CASE_HIGH (min_label) != NULL_TREE
9924 && tree_int_cst_compare (CASE_HIGH (min_label), vr_max) > 0)
9925 CASE_LOW (min_label)
9926 = int_const_binop (PLUS_EXPR, vr_max, one_cst);
9928 /* If OP's value range is ~[7,8] and the label's range is
9929 5 ... 8, truncate the label's range to 5 ... 6. */
9930 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
9931 && CASE_HIGH (min_label) != NULL_TREE
9932 && tree_int_cst_compare (CASE_HIGH (min_label), vr_max) == 0)
9933 CASE_HIGH (min_label)
9934 = int_const_binop (MINUS_EXPR, vr_min, one_cst);
9936 else
9938 /* If OP's value range is ~[2,8] and the low label range is
9939 0 ... 3, truncate the label's range to 0 ... 1. */
9940 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
9941 && CASE_HIGH (min_label) != NULL_TREE
9942 && tree_int_cst_compare (CASE_HIGH (min_label), vr_min) >= 0)
9943 CASE_HIGH (min_label)
9944 = int_const_binop (MINUS_EXPR, vr_min, one_cst);
9946 /* If OP's value range is ~[2,8] and the high label range is
9947 7 ... 10, truncate the label's range to 9 ... 10. */
9948 if (tree_int_cst_compare (CASE_LOW (max_label), vr_max) <= 0
9949 && CASE_HIGH (max_label) != NULL_TREE
9950 && tree_int_cst_compare (CASE_HIGH (max_label), vr_max) > 0)
9951 CASE_LOW (max_label)
9952 = int_const_binop (PLUS_EXPR, vr_max, one_cst);
9956 /* Canonicalize singleton case ranges. */
9957 if (tree_int_cst_equal (CASE_LOW (min_label), CASE_HIGH (min_label)))
9958 CASE_HIGH (min_label) = NULL_TREE;
9959 if (tree_int_cst_equal (CASE_LOW (max_label), CASE_HIGH (max_label)))
9960 CASE_HIGH (max_label) = NULL_TREE;
9963 /* We can also eliminate case labels that lie completely outside OP's value
9964 range. */
9966 /* Bail out if this is just all edges taken. */
9967 if (i == 1
9968 && j == n - 1
9969 && take_default)
9970 return false;
9972 /* Build a new vector of taken case labels. */
9973 vec2 = make_tree_vec (j - i + 1 + l - k + 1 + (int)take_default);
9974 n2 = 0;
9976 /* Add the default edge, if necessary. */
9977 if (take_default)
9978 TREE_VEC_ELT (vec2, n2++) = gimple_switch_default_label (stmt);
9980 for (; i <= j; ++i, ++n2)
9981 TREE_VEC_ELT (vec2, n2) = gimple_switch_label (stmt, i);
9983 for (; k <= l; ++k, ++n2)
9984 TREE_VEC_ELT (vec2, n2) = gimple_switch_label (stmt, k);
9986 /* Mark needed edges. */
9987 for (i = 0; i < n2; ++i)
9989 e = find_edge (gimple_bb (stmt),
9990 label_to_block (CASE_LABEL (TREE_VEC_ELT (vec2, i))));
9991 e->aux = (void *)-1;
9994 /* Queue not needed edges for later removal. */
9995 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
9997 if (e->aux == (void *)-1)
9999 e->aux = NULL;
10000 continue;
10003 if (dump_file && (dump_flags & TDF_DETAILS))
10005 fprintf (dump_file, "removing unreachable case label\n");
10007 to_remove_edges.safe_push (e);
10008 e->flags &= ~EDGE_EXECUTABLE;
10011 /* And queue an update for the stmt. */
10012 su.stmt = stmt;
10013 su.vec = vec2;
10014 to_update_switch_stmts.safe_push (su);
10015 return false;
10018 /* Simplify an integral conversion from an SSA name in STMT. */
10020 static bool
10021 simplify_conversion_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
10023 tree innerop, middleop, finaltype;
10024 gimple *def_stmt;
10025 signop inner_sgn, middle_sgn, final_sgn;
10026 unsigned inner_prec, middle_prec, final_prec;
10027 widest_int innermin, innermed, innermax, middlemin, middlemed, middlemax;
10029 finaltype = TREE_TYPE (gimple_assign_lhs (stmt));
10030 if (!INTEGRAL_TYPE_P (finaltype))
10031 return false;
10032 middleop = gimple_assign_rhs1 (stmt);
10033 def_stmt = SSA_NAME_DEF_STMT (middleop);
10034 if (!is_gimple_assign (def_stmt)
10035 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)))
10036 return false;
10037 innerop = gimple_assign_rhs1 (def_stmt);
10038 if (TREE_CODE (innerop) != SSA_NAME
10039 || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (innerop))
10040 return false;
10042 /* Get the value-range of the inner operand. Use get_range_info in
10043 case innerop was created during substitute-and-fold. */
10044 wide_int imin, imax;
10045 if (!INTEGRAL_TYPE_P (TREE_TYPE (innerop))
10046 || get_range_info (innerop, &imin, &imax) != VR_RANGE)
10047 return false;
10048 innermin = widest_int::from (imin, TYPE_SIGN (TREE_TYPE (innerop)));
10049 innermax = widest_int::from (imax, TYPE_SIGN (TREE_TYPE (innerop)));
10051 /* Simulate the conversion chain to check if the result is equal if
10052 the middle conversion is removed. */
10053 inner_prec = TYPE_PRECISION (TREE_TYPE (innerop));
10054 middle_prec = TYPE_PRECISION (TREE_TYPE (middleop));
10055 final_prec = TYPE_PRECISION (finaltype);
10057 /* If the first conversion is not injective, the second must not
10058 be widening. */
10059 if (wi::gtu_p (innermax - innermin,
10060 wi::mask <widest_int> (middle_prec, false))
10061 && middle_prec < final_prec)
10062 return false;
10063 /* We also want a medium value so that we can track the effect that
10064 narrowing conversions with sign change have. */
10065 inner_sgn = TYPE_SIGN (TREE_TYPE (innerop));
10066 if (inner_sgn == UNSIGNED)
10067 innermed = wi::shifted_mask <widest_int> (1, inner_prec - 1, false);
10068 else
10069 innermed = 0;
10070 if (wi::cmp (innermin, innermed, inner_sgn) >= 0
10071 || wi::cmp (innermed, innermax, inner_sgn) >= 0)
10072 innermed = innermin;
10074 middle_sgn = TYPE_SIGN (TREE_TYPE (middleop));
10075 middlemin = wi::ext (innermin, middle_prec, middle_sgn);
10076 middlemed = wi::ext (innermed, middle_prec, middle_sgn);
10077 middlemax = wi::ext (innermax, middle_prec, middle_sgn);
10079 /* Require that the final conversion applied to both the original
10080 and the intermediate range produces the same result. */
10081 final_sgn = TYPE_SIGN (finaltype);
10082 if (wi::ext (middlemin, final_prec, final_sgn)
10083 != wi::ext (innermin, final_prec, final_sgn)
10084 || wi::ext (middlemed, final_prec, final_sgn)
10085 != wi::ext (innermed, final_prec, final_sgn)
10086 || wi::ext (middlemax, final_prec, final_sgn)
10087 != wi::ext (innermax, final_prec, final_sgn))
10088 return false;
10090 gimple_assign_set_rhs1 (stmt, innerop);
10091 fold_stmt (gsi, follow_single_use_edges);
10092 return true;
10095 /* Simplify a conversion from integral SSA name to float in STMT. */
10097 static bool
10098 simplify_float_conversion_using_ranges (gimple_stmt_iterator *gsi,
10099 gimple *stmt)
10101 tree rhs1 = gimple_assign_rhs1 (stmt);
10102 value_range *vr = get_value_range (rhs1);
10103 scalar_float_mode fltmode
10104 = SCALAR_FLOAT_TYPE_MODE (TREE_TYPE (gimple_assign_lhs (stmt)));
10105 scalar_int_mode mode;
10106 tree tem;
10107 gassign *conv;
10109 /* We can only handle constant ranges. */
10110 if (vr->type != VR_RANGE
10111 || TREE_CODE (vr->min) != INTEGER_CST
10112 || TREE_CODE (vr->max) != INTEGER_CST)
10113 return false;
10115 /* First check if we can use a signed type in place of an unsigned. */
10116 scalar_int_mode rhs_mode = SCALAR_INT_TYPE_MODE (TREE_TYPE (rhs1));
10117 if (TYPE_UNSIGNED (TREE_TYPE (rhs1))
10118 && can_float_p (fltmode, rhs_mode, 0) != CODE_FOR_nothing
10119 && range_fits_type_p (vr, TYPE_PRECISION (TREE_TYPE (rhs1)), SIGNED))
10120 mode = rhs_mode;
10121 /* If we can do the conversion in the current input mode do nothing. */
10122 else if (can_float_p (fltmode, rhs_mode,
10123 TYPE_UNSIGNED (TREE_TYPE (rhs1))) != CODE_FOR_nothing)
10124 return false;
10125 /* Otherwise search for a mode we can use, starting from the narrowest
10126 integer mode available. */
10127 else
10129 mode = NARROWEST_INT_MODE;
10130 for (;;)
10132 /* If we cannot do a signed conversion to float from mode
10133 or if the value-range does not fit in the signed type
10134 try with a wider mode. */
10135 if (can_float_p (fltmode, mode, 0) != CODE_FOR_nothing
10136 && range_fits_type_p (vr, GET_MODE_PRECISION (mode), SIGNED))
10137 break;
10139 /* But do not widen the input. Instead leave that to the
10140 optabs expansion code. */
10141 if (!GET_MODE_WIDER_MODE (mode).exists (&mode)
10142 || GET_MODE_PRECISION (mode) > TYPE_PRECISION (TREE_TYPE (rhs1)))
10143 return false;
10147 /* It works, insert a truncation or sign-change before the
10148 float conversion. */
10149 tem = make_ssa_name (build_nonstandard_integer_type
10150 (GET_MODE_PRECISION (mode), 0));
10151 conv = gimple_build_assign (tem, NOP_EXPR, rhs1);
10152 gsi_insert_before (gsi, conv, GSI_SAME_STMT);
10153 gimple_assign_set_rhs1 (stmt, tem);
10154 fold_stmt (gsi, follow_single_use_edges);
10156 return true;
10159 /* Simplify an internal fn call using ranges if possible. */
10161 static bool
10162 simplify_internal_call_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
10164 enum tree_code subcode;
10165 bool is_ubsan = false;
10166 bool ovf = false;
10167 switch (gimple_call_internal_fn (stmt))
10169 case IFN_UBSAN_CHECK_ADD:
10170 subcode = PLUS_EXPR;
10171 is_ubsan = true;
10172 break;
10173 case IFN_UBSAN_CHECK_SUB:
10174 subcode = MINUS_EXPR;
10175 is_ubsan = true;
10176 break;
10177 case IFN_UBSAN_CHECK_MUL:
10178 subcode = MULT_EXPR;
10179 is_ubsan = true;
10180 break;
10181 case IFN_ADD_OVERFLOW:
10182 subcode = PLUS_EXPR;
10183 break;
10184 case IFN_SUB_OVERFLOW:
10185 subcode = MINUS_EXPR;
10186 break;
10187 case IFN_MUL_OVERFLOW:
10188 subcode = MULT_EXPR;
10189 break;
10190 default:
10191 return false;
10194 tree op0 = gimple_call_arg (stmt, 0);
10195 tree op1 = gimple_call_arg (stmt, 1);
10196 tree type;
10197 if (is_ubsan)
10199 type = TREE_TYPE (op0);
10200 if (VECTOR_TYPE_P (type))
10201 return false;
10203 else if (gimple_call_lhs (stmt) == NULL_TREE)
10204 return false;
10205 else
10206 type = TREE_TYPE (TREE_TYPE (gimple_call_lhs (stmt)));
10207 if (!check_for_binary_op_overflow (subcode, type, op0, op1, &ovf)
10208 || (is_ubsan && ovf))
10209 return false;
10211 gimple *g;
10212 location_t loc = gimple_location (stmt);
10213 if (is_ubsan)
10214 g = gimple_build_assign (gimple_call_lhs (stmt), subcode, op0, op1);
10215 else
10217 int prec = TYPE_PRECISION (type);
10218 tree utype = type;
10219 if (ovf
10220 || !useless_type_conversion_p (type, TREE_TYPE (op0))
10221 || !useless_type_conversion_p (type, TREE_TYPE (op1)))
10222 utype = build_nonstandard_integer_type (prec, 1);
10223 if (TREE_CODE (op0) == INTEGER_CST)
10224 op0 = fold_convert (utype, op0);
10225 else if (!useless_type_conversion_p (utype, TREE_TYPE (op0)))
10227 g = gimple_build_assign (make_ssa_name (utype), NOP_EXPR, op0);
10228 gimple_set_location (g, loc);
10229 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10230 op0 = gimple_assign_lhs (g);
10232 if (TREE_CODE (op1) == INTEGER_CST)
10233 op1 = fold_convert (utype, op1);
10234 else if (!useless_type_conversion_p (utype, TREE_TYPE (op1)))
10236 g = gimple_build_assign (make_ssa_name (utype), NOP_EXPR, op1);
10237 gimple_set_location (g, loc);
10238 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10239 op1 = gimple_assign_lhs (g);
10241 g = gimple_build_assign (make_ssa_name (utype), subcode, op0, op1);
10242 gimple_set_location (g, loc);
10243 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10244 if (utype != type)
10246 g = gimple_build_assign (make_ssa_name (type), NOP_EXPR,
10247 gimple_assign_lhs (g));
10248 gimple_set_location (g, loc);
10249 gsi_insert_before (gsi, g, GSI_SAME_STMT);
10251 g = gimple_build_assign (gimple_call_lhs (stmt), COMPLEX_EXPR,
10252 gimple_assign_lhs (g),
10253 build_int_cst (type, ovf));
10255 gimple_set_location (g, loc);
10256 gsi_replace (gsi, g, false);
10257 return true;
10260 /* Return true if VAR is a two-valued variable. Set a and b with the
10261 two-values when it is true. Return false otherwise. */
10263 static bool
10264 two_valued_val_range_p (tree var, tree *a, tree *b)
10266 value_range *vr = get_value_range (var);
10267 if ((vr->type != VR_RANGE
10268 && vr->type != VR_ANTI_RANGE)
10269 || TREE_CODE (vr->min) != INTEGER_CST
10270 || TREE_CODE (vr->max) != INTEGER_CST)
10271 return false;
10273 if (vr->type == VR_RANGE
10274 && wi::sub (vr->max, vr->min) == 1)
10276 *a = vr->min;
10277 *b = vr->max;
10278 return true;
10281 /* ~[TYPE_MIN + 1, TYPE_MAX - 1] */
10282 if (vr->type == VR_ANTI_RANGE
10283 && wi::sub (vr->min, vrp_val_min (TREE_TYPE (var))) == 1
10284 && wi::sub (vrp_val_max (TREE_TYPE (var)), vr->max) == 1)
10286 *a = vrp_val_min (TREE_TYPE (var));
10287 *b = vrp_val_max (TREE_TYPE (var));
10288 return true;
10291 return false;
10294 /* Simplify STMT using ranges if possible. */
10296 static bool
10297 simplify_stmt_using_ranges (gimple_stmt_iterator *gsi)
10299 gimple *stmt = gsi_stmt (*gsi);
10300 if (is_gimple_assign (stmt))
10302 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
10303 tree rhs1 = gimple_assign_rhs1 (stmt);
10304 tree rhs2 = gimple_assign_rhs2 (stmt);
10305 tree lhs = gimple_assign_lhs (stmt);
10306 tree val1 = NULL_TREE, val2 = NULL_TREE;
10307 use_operand_p use_p;
10308 gimple *use_stmt;
10310 /* Convert:
10311 LHS = CST BINOP VAR
10312 Where VAR is two-valued and LHS is used in GIMPLE_COND only
10314 LHS = VAR == VAL1 ? (CST BINOP VAL1) : (CST BINOP VAL2)
10316 Also handles:
10317 LHS = VAR BINOP CST
10318 Where VAR is two-valued and LHS is used in GIMPLE_COND only
10320 LHS = VAR == VAL1 ? (VAL1 BINOP CST) : (VAL2 BINOP CST) */
10322 if (TREE_CODE_CLASS (rhs_code) == tcc_binary
10323 && INTEGRAL_TYPE_P (TREE_TYPE (lhs))
10324 && ((TREE_CODE (rhs1) == INTEGER_CST
10325 && TREE_CODE (rhs2) == SSA_NAME)
10326 || (TREE_CODE (rhs2) == INTEGER_CST
10327 && TREE_CODE (rhs1) == SSA_NAME))
10328 && single_imm_use (lhs, &use_p, &use_stmt)
10329 && gimple_code (use_stmt) == GIMPLE_COND)
10332 tree new_rhs1 = NULL_TREE;
10333 tree new_rhs2 = NULL_TREE;
10334 tree cmp_var = NULL_TREE;
10336 if (TREE_CODE (rhs2) == SSA_NAME
10337 && two_valued_val_range_p (rhs2, &val1, &val2))
10339 /* Optimize RHS1 OP [VAL1, VAL2]. */
10340 new_rhs1 = int_const_binop (rhs_code, rhs1, val1);
10341 new_rhs2 = int_const_binop (rhs_code, rhs1, val2);
10342 cmp_var = rhs2;
10344 else if (TREE_CODE (rhs1) == SSA_NAME
10345 && two_valued_val_range_p (rhs1, &val1, &val2))
10347 /* Optimize [VAL1, VAL2] OP RHS2. */
10348 new_rhs1 = int_const_binop (rhs_code, val1, rhs2);
10349 new_rhs2 = int_const_binop (rhs_code, val2, rhs2);
10350 cmp_var = rhs1;
10353 /* If we could not find two-vals or the optimzation is invalid as
10354 in divide by zero, new_rhs1 / new_rhs will be NULL_TREE. */
10355 if (new_rhs1 && new_rhs2)
10357 tree cond = build2 (EQ_EXPR, boolean_type_node, cmp_var, val1);
10358 gimple_assign_set_rhs_with_ops (gsi,
10359 COND_EXPR, cond,
10360 new_rhs1,
10361 new_rhs2);
10362 update_stmt (gsi_stmt (*gsi));
10363 fold_stmt (gsi, follow_single_use_edges);
10364 return true;
10368 switch (rhs_code)
10370 case EQ_EXPR:
10371 case NE_EXPR:
10372 /* Transform EQ_EXPR, NE_EXPR into BIT_XOR_EXPR or identity
10373 if the RHS is zero or one, and the LHS are known to be boolean
10374 values. */
10375 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10376 return simplify_truth_ops_using_ranges (gsi, stmt);
10377 break;
10379 /* Transform TRUNC_DIV_EXPR and TRUNC_MOD_EXPR into RSHIFT_EXPR
10380 and BIT_AND_EXPR respectively if the first operand is greater
10381 than zero and the second operand is an exact power of two.
10382 Also optimize TRUNC_MOD_EXPR away if the second operand is
10383 constant and the first operand already has the right value
10384 range. */
10385 case TRUNC_DIV_EXPR:
10386 case TRUNC_MOD_EXPR:
10387 if ((TREE_CODE (rhs1) == SSA_NAME
10388 || TREE_CODE (rhs1) == INTEGER_CST)
10389 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10390 return simplify_div_or_mod_using_ranges (gsi, stmt);
10391 break;
10393 /* Transform ABS (X) into X or -X as appropriate. */
10394 case ABS_EXPR:
10395 if (TREE_CODE (rhs1) == SSA_NAME
10396 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10397 return simplify_abs_using_ranges (gsi, stmt);
10398 break;
10400 case BIT_AND_EXPR:
10401 case BIT_IOR_EXPR:
10402 /* Optimize away BIT_AND_EXPR and BIT_IOR_EXPR
10403 if all the bits being cleared are already cleared or
10404 all the bits being set are already set. */
10405 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10406 return simplify_bit_ops_using_ranges (gsi, stmt);
10407 break;
10409 CASE_CONVERT:
10410 if (TREE_CODE (rhs1) == SSA_NAME
10411 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10412 return simplify_conversion_using_ranges (gsi, stmt);
10413 break;
10415 case FLOAT_EXPR:
10416 if (TREE_CODE (rhs1) == SSA_NAME
10417 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
10418 return simplify_float_conversion_using_ranges (gsi, stmt);
10419 break;
10421 case MIN_EXPR:
10422 case MAX_EXPR:
10423 return simplify_min_or_max_using_ranges (gsi, stmt);
10425 default:
10426 break;
10429 else if (gimple_code (stmt) == GIMPLE_COND)
10430 return simplify_cond_using_ranges_1 (as_a <gcond *> (stmt));
10431 else if (gimple_code (stmt) == GIMPLE_SWITCH)
10432 return simplify_switch_using_ranges (as_a <gswitch *> (stmt));
10433 else if (is_gimple_call (stmt)
10434 && gimple_call_internal_p (stmt))
10435 return simplify_internal_call_using_ranges (gsi, stmt);
10437 return false;
10440 /* If the statement pointed by SI has a predicate whose value can be
10441 computed using the value range information computed by VRP, compute
10442 its value and return true. Otherwise, return false. */
10444 static bool
10445 fold_predicate_in (gimple_stmt_iterator *si)
10447 bool assignment_p = false;
10448 tree val;
10449 gimple *stmt = gsi_stmt (*si);
10451 if (is_gimple_assign (stmt)
10452 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
10454 assignment_p = true;
10455 val = vrp_evaluate_conditional (gimple_assign_rhs_code (stmt),
10456 gimple_assign_rhs1 (stmt),
10457 gimple_assign_rhs2 (stmt),
10458 stmt);
10460 else if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
10461 val = vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
10462 gimple_cond_lhs (cond_stmt),
10463 gimple_cond_rhs (cond_stmt),
10464 stmt);
10465 else
10466 return false;
10468 if (val)
10470 if (assignment_p)
10471 val = fold_convert (gimple_expr_type (stmt), val);
10473 if (dump_file)
10475 fprintf (dump_file, "Folding predicate ");
10476 print_gimple_expr (dump_file, stmt, 0);
10477 fprintf (dump_file, " to ");
10478 print_generic_expr (dump_file, val);
10479 fprintf (dump_file, "\n");
10482 if (is_gimple_assign (stmt))
10483 gimple_assign_set_rhs_from_tree (si, val);
10484 else
10486 gcc_assert (gimple_code (stmt) == GIMPLE_COND);
10487 gcond *cond_stmt = as_a <gcond *> (stmt);
10488 if (integer_zerop (val))
10489 gimple_cond_make_false (cond_stmt);
10490 else if (integer_onep (val))
10491 gimple_cond_make_true (cond_stmt);
10492 else
10493 gcc_unreachable ();
10496 return true;
10499 return false;
10502 /* Callback for substitute_and_fold folding the stmt at *SI. */
10504 static bool
10505 vrp_fold_stmt (gimple_stmt_iterator *si)
10507 if (fold_predicate_in (si))
10508 return true;
10510 return simplify_stmt_using_ranges (si);
10513 /* Return the LHS of any ASSERT_EXPR where OP appears as the first
10514 argument to the ASSERT_EXPR and in which the ASSERT_EXPR dominates
10515 BB. If no such ASSERT_EXPR is found, return OP. */
10517 static tree
10518 lhs_of_dominating_assert (tree op, basic_block bb, gimple *stmt)
10520 imm_use_iterator imm_iter;
10521 gimple *use_stmt;
10522 use_operand_p use_p;
10524 if (TREE_CODE (op) == SSA_NAME)
10526 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, op)
10528 use_stmt = USE_STMT (use_p);
10529 if (use_stmt != stmt
10530 && gimple_assign_single_p (use_stmt)
10531 && TREE_CODE (gimple_assign_rhs1 (use_stmt)) == ASSERT_EXPR
10532 && TREE_OPERAND (gimple_assign_rhs1 (use_stmt), 0) == op
10533 && dominated_by_p (CDI_DOMINATORS, bb, gimple_bb (use_stmt)))
10534 return gimple_assign_lhs (use_stmt);
10537 return op;
10540 /* A trivial wrapper so that we can present the generic jump threading
10541 code with a simple API for simplifying statements. STMT is the
10542 statement we want to simplify, WITHIN_STMT provides the location
10543 for any overflow warnings. */
10545 static tree
10546 simplify_stmt_for_jump_threading (gimple *stmt, gimple *within_stmt,
10547 class avail_exprs_stack *avail_exprs_stack ATTRIBUTE_UNUSED,
10548 basic_block bb)
10550 /* First see if the conditional is in the hash table. */
10551 tree cached_lhs = avail_exprs_stack->lookup_avail_expr (stmt, false, true);
10552 if (cached_lhs && is_gimple_min_invariant (cached_lhs))
10553 return cached_lhs;
10555 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
10557 tree op0 = gimple_cond_lhs (cond_stmt);
10558 op0 = lhs_of_dominating_assert (op0, bb, stmt);
10560 tree op1 = gimple_cond_rhs (cond_stmt);
10561 op1 = lhs_of_dominating_assert (op1, bb, stmt);
10563 return vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
10564 op0, op1, within_stmt);
10567 /* We simplify a switch statement by trying to determine which case label
10568 will be taken. If we are successful then we return the corresponding
10569 CASE_LABEL_EXPR. */
10570 if (gswitch *switch_stmt = dyn_cast <gswitch *> (stmt))
10572 tree op = gimple_switch_index (switch_stmt);
10573 if (TREE_CODE (op) != SSA_NAME)
10574 return NULL_TREE;
10576 op = lhs_of_dominating_assert (op, bb, stmt);
10578 value_range *vr = get_value_range (op);
10579 if ((vr->type != VR_RANGE && vr->type != VR_ANTI_RANGE)
10580 || symbolic_range_p (vr))
10581 return NULL_TREE;
10583 if (vr->type == VR_RANGE)
10585 size_t i, j;
10586 /* Get the range of labels that contain a part of the operand's
10587 value range. */
10588 find_case_label_range (switch_stmt, vr->min, vr->max, &i, &j);
10590 /* Is there only one such label? */
10591 if (i == j)
10593 tree label = gimple_switch_label (switch_stmt, i);
10595 /* The i'th label will be taken only if the value range of the
10596 operand is entirely within the bounds of this label. */
10597 if (CASE_HIGH (label) != NULL_TREE
10598 ? (tree_int_cst_compare (CASE_LOW (label), vr->min) <= 0
10599 && tree_int_cst_compare (CASE_HIGH (label), vr->max) >= 0)
10600 : (tree_int_cst_equal (CASE_LOW (label), vr->min)
10601 && tree_int_cst_equal (vr->min, vr->max)))
10602 return label;
10605 /* If there are no such labels then the default label will be
10606 taken. */
10607 if (i > j)
10608 return gimple_switch_label (switch_stmt, 0);
10611 if (vr->type == VR_ANTI_RANGE)
10613 unsigned n = gimple_switch_num_labels (switch_stmt);
10614 tree min_label = gimple_switch_label (switch_stmt, 1);
10615 tree max_label = gimple_switch_label (switch_stmt, n - 1);
10617 /* The default label will be taken only if the anti-range of the
10618 operand is entirely outside the bounds of all the (non-default)
10619 case labels. */
10620 if (tree_int_cst_compare (vr->min, CASE_LOW (min_label)) <= 0
10621 && (CASE_HIGH (max_label) != NULL_TREE
10622 ? tree_int_cst_compare (vr->max, CASE_HIGH (max_label)) >= 0
10623 : tree_int_cst_compare (vr->max, CASE_LOW (max_label)) >= 0))
10624 return gimple_switch_label (switch_stmt, 0);
10627 return NULL_TREE;
10630 if (gassign *assign_stmt = dyn_cast <gassign *> (stmt))
10632 value_range new_vr = VR_INITIALIZER;
10633 tree lhs = gimple_assign_lhs (assign_stmt);
10635 if (TREE_CODE (lhs) == SSA_NAME
10636 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
10637 || POINTER_TYPE_P (TREE_TYPE (lhs))))
10639 extract_range_from_assignment (&new_vr, assign_stmt);
10640 if (range_int_cst_singleton_p (&new_vr))
10641 return new_vr.min;
10645 return NULL_TREE;
10648 class vrp_dom_walker : public dom_walker
10650 public:
10651 vrp_dom_walker (cdi_direction direction,
10652 class const_and_copies *const_and_copies,
10653 class avail_exprs_stack *avail_exprs_stack)
10654 : dom_walker (direction, true),
10655 m_const_and_copies (const_and_copies),
10656 m_avail_exprs_stack (avail_exprs_stack),
10657 m_dummy_cond (NULL) {}
10659 virtual edge before_dom_children (basic_block);
10660 virtual void after_dom_children (basic_block);
10662 private:
10663 class const_and_copies *m_const_and_copies;
10664 class avail_exprs_stack *m_avail_exprs_stack;
10666 gcond *m_dummy_cond;
10669 /* Called before processing dominator children of BB. We want to look
10670 at ASSERT_EXPRs and record information from them in the appropriate
10671 tables.
10673 We could look at other statements here. It's not seen as likely
10674 to significantly increase the jump threads we discover. */
10676 edge
10677 vrp_dom_walker::before_dom_children (basic_block bb)
10679 gimple_stmt_iterator gsi;
10681 m_avail_exprs_stack->push_marker ();
10682 m_const_and_copies->push_marker ();
10683 for (gsi = gsi_start_nondebug_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
10685 gimple *stmt = gsi_stmt (gsi);
10686 if (gimple_assign_single_p (stmt)
10687 && TREE_CODE (gimple_assign_rhs1 (stmt)) == ASSERT_EXPR)
10689 tree rhs1 = gimple_assign_rhs1 (stmt);
10690 tree cond = TREE_OPERAND (rhs1, 1);
10691 tree inverted = invert_truthvalue (cond);
10692 vec<cond_equivalence> p;
10693 p.create (3);
10694 record_conditions (&p, cond, inverted);
10695 for (unsigned int i = 0; i < p.length (); i++)
10696 m_avail_exprs_stack->record_cond (&p[i]);
10698 tree lhs = gimple_assign_lhs (stmt);
10699 m_const_and_copies->record_const_or_copy (lhs,
10700 TREE_OPERAND (rhs1, 0));
10701 p.release ();
10702 continue;
10704 break;
10706 return NULL;
10709 /* Called after processing dominator children of BB. This is where we
10710 actually call into the threader. */
10711 void
10712 vrp_dom_walker::after_dom_children (basic_block bb)
10714 if (!m_dummy_cond)
10715 m_dummy_cond = gimple_build_cond (NE_EXPR,
10716 integer_zero_node, integer_zero_node,
10717 NULL, NULL);
10719 thread_outgoing_edges (bb, m_dummy_cond, m_const_and_copies,
10720 m_avail_exprs_stack,
10721 simplify_stmt_for_jump_threading);
10723 m_avail_exprs_stack->pop_to_marker ();
10724 m_const_and_copies->pop_to_marker ();
10727 /* Blocks which have more than one predecessor and more than
10728 one successor present jump threading opportunities, i.e.,
10729 when the block is reached from a specific predecessor, we
10730 may be able to determine which of the outgoing edges will
10731 be traversed. When this optimization applies, we are able
10732 to avoid conditionals at runtime and we may expose secondary
10733 optimization opportunities.
10735 This routine is effectively a driver for the generic jump
10736 threading code. It basically just presents the generic code
10737 with edges that may be suitable for jump threading.
10739 Unlike DOM, we do not iterate VRP if jump threading was successful.
10740 While iterating may expose new opportunities for VRP, it is expected
10741 those opportunities would be very limited and the compile time cost
10742 to expose those opportunities would be significant.
10744 As jump threading opportunities are discovered, they are registered
10745 for later realization. */
10747 static void
10748 identify_jump_threads (void)
10750 int i;
10751 edge e;
10753 /* Ugh. When substituting values earlier in this pass we can
10754 wipe the dominance information. So rebuild the dominator
10755 information as we need it within the jump threading code. */
10756 calculate_dominance_info (CDI_DOMINATORS);
10758 /* We do not allow VRP information to be used for jump threading
10759 across a back edge in the CFG. Otherwise it becomes too
10760 difficult to avoid eliminating loop exit tests. Of course
10761 EDGE_DFS_BACK is not accurate at this time so we have to
10762 recompute it. */
10763 mark_dfs_back_edges ();
10765 /* Do not thread across edges we are about to remove. Just marking
10766 them as EDGE_IGNORE will do. */
10767 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
10768 e->flags |= EDGE_IGNORE;
10770 /* Allocate our unwinder stack to unwind any temporary equivalences
10771 that might be recorded. */
10772 const_and_copies *equiv_stack = new const_and_copies ();
10774 hash_table<expr_elt_hasher> *avail_exprs
10775 = new hash_table<expr_elt_hasher> (1024);
10776 avail_exprs_stack *avail_exprs_stack
10777 = new class avail_exprs_stack (avail_exprs);
10779 vrp_dom_walker walker (CDI_DOMINATORS, equiv_stack, avail_exprs_stack);
10780 walker.walk (cfun->cfg->x_entry_block_ptr);
10782 /* Clear EDGE_IGNORE. */
10783 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
10784 e->flags &= ~EDGE_IGNORE;
10786 /* We do not actually update the CFG or SSA graphs at this point as
10787 ASSERT_EXPRs are still in the IL and cfg cleanup code does not yet
10788 handle ASSERT_EXPRs gracefully. */
10789 delete equiv_stack;
10790 delete avail_exprs;
10791 delete avail_exprs_stack;
10794 /* Free VRP lattice. */
10796 static void
10797 vrp_free_lattice ()
10799 /* Free allocated memory. */
10800 free (vr_value);
10801 free (vr_phi_edge_counts);
10802 bitmap_obstack_release (&vrp_equiv_obstack);
10803 vrp_value_range_pool.release ();
10805 /* So that we can distinguish between VRP data being available
10806 and not available. */
10807 vr_value = NULL;
10808 vr_phi_edge_counts = NULL;
10811 /* Traverse all the blocks folding conditionals with known ranges. */
10813 static void
10814 vrp_finalize (bool warn_array_bounds_p)
10816 size_t i;
10818 values_propagated = true;
10820 if (dump_file)
10822 fprintf (dump_file, "\nValue ranges after VRP:\n\n");
10823 dump_all_value_ranges (dump_file);
10824 fprintf (dump_file, "\n");
10827 /* Set value range to non pointer SSA_NAMEs. */
10828 for (i = 0; i < num_vr_values; i++)
10829 if (vr_value[i])
10831 tree name = ssa_name (i);
10833 if (!name
10834 || (vr_value[i]->type == VR_VARYING)
10835 || (vr_value[i]->type == VR_UNDEFINED)
10836 || (TREE_CODE (vr_value[i]->min) != INTEGER_CST)
10837 || (TREE_CODE (vr_value[i]->max) != INTEGER_CST))
10838 continue;
10840 if (POINTER_TYPE_P (TREE_TYPE (name))
10841 && ((vr_value[i]->type == VR_RANGE
10842 && range_includes_zero_p (vr_value[i]->min,
10843 vr_value[i]->max) == 0)
10844 || (vr_value[i]->type == VR_ANTI_RANGE
10845 && range_includes_zero_p (vr_value[i]->min,
10846 vr_value[i]->max) == 1)))
10847 set_ptr_nonnull (name);
10848 else if (!POINTER_TYPE_P (TREE_TYPE (name)))
10849 set_range_info (name, vr_value[i]->type, vr_value[i]->min,
10850 vr_value[i]->max);
10853 substitute_and_fold (op_with_constant_singleton_value_range, vrp_fold_stmt);
10855 if (warn_array_bounds && warn_array_bounds_p)
10856 check_all_array_refs ();
10859 /* evrp_dom_walker visits the basic blocks in the dominance order and set
10860 the Value Ranges (VR) for SSA_NAMEs in the scope. Use this VR to
10861 discover more VRs. */
10863 class evrp_dom_walker : public dom_walker
10865 public:
10866 evrp_dom_walker ()
10867 : dom_walker (CDI_DOMINATORS), stack (10)
10869 need_eh_cleanup = BITMAP_ALLOC (NULL);
10871 ~evrp_dom_walker ()
10873 BITMAP_FREE (need_eh_cleanup);
10875 virtual edge before_dom_children (basic_block);
10876 virtual void after_dom_children (basic_block);
10877 void push_value_range (tree var, value_range *vr);
10878 value_range *pop_value_range (tree var);
10879 value_range *try_find_new_range (tree, tree op, tree_code code, tree limit);
10881 /* Cond_stack holds the old VR. */
10882 auto_vec<std::pair <tree, value_range*> > stack;
10883 bitmap need_eh_cleanup;
10884 auto_vec<gimple *> stmts_to_fixup;
10885 auto_vec<gimple *> stmts_to_remove;
10888 /* Find new range for NAME such that (OP CODE LIMIT) is true. */
10890 value_range *
10891 evrp_dom_walker::try_find_new_range (tree name,
10892 tree op, tree_code code, tree limit)
10894 value_range vr = VR_INITIALIZER;
10895 value_range *old_vr = get_value_range (name);
10897 /* Discover VR when condition is true. */
10898 extract_range_for_var_from_comparison_expr (name, code, op,
10899 limit, &vr);
10900 /* If we found any usable VR, set the VR to ssa_name and create a
10901 PUSH old value in the stack with the old VR. */
10902 if (vr.type == VR_RANGE || vr.type == VR_ANTI_RANGE)
10904 if (old_vr->type == vr.type
10905 && vrp_operand_equal_p (old_vr->min, vr.min)
10906 && vrp_operand_equal_p (old_vr->max, vr.max))
10907 return NULL;
10908 value_range *new_vr = vrp_value_range_pool.allocate ();
10909 *new_vr = vr;
10910 return new_vr;
10912 return NULL;
10915 /* See if there is any new scope is entered with new VR and set that VR to
10916 ssa_name before visiting the statements in the scope. */
10918 edge
10919 evrp_dom_walker::before_dom_children (basic_block bb)
10921 tree op0 = NULL_TREE;
10922 edge_iterator ei;
10923 edge e;
10925 if (dump_file && (dump_flags & TDF_DETAILS))
10926 fprintf (dump_file, "Visiting BB%d\n", bb->index);
10928 stack.safe_push (std::make_pair (NULL_TREE, (value_range *)NULL));
10930 edge pred_e = NULL;
10931 FOR_EACH_EDGE (e, ei, bb->preds)
10933 /* Ignore simple backedges from this to allow recording conditions
10934 in loop headers. */
10935 if (dominated_by_p (CDI_DOMINATORS, e->src, e->dest))
10936 continue;
10937 if (! pred_e)
10938 pred_e = e;
10939 else
10941 pred_e = NULL;
10942 break;
10945 if (pred_e)
10947 gimple *stmt = last_stmt (pred_e->src);
10948 if (stmt
10949 && gimple_code (stmt) == GIMPLE_COND
10950 && (op0 = gimple_cond_lhs (stmt))
10951 && TREE_CODE (op0) == SSA_NAME
10952 && (INTEGRAL_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)))
10953 || POINTER_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)))))
10955 if (dump_file && (dump_flags & TDF_DETAILS))
10957 fprintf (dump_file, "Visiting controlling predicate ");
10958 print_gimple_stmt (dump_file, stmt, 0);
10960 /* Entering a new scope. Try to see if we can find a VR
10961 here. */
10962 tree op1 = gimple_cond_rhs (stmt);
10963 if (TREE_OVERFLOW_P (op1))
10964 op1 = drop_tree_overflow (op1);
10965 tree_code code = gimple_cond_code (stmt);
10967 auto_vec<assert_info, 8> asserts;
10968 register_edge_assert_for (op0, pred_e, code, op0, op1, asserts);
10969 if (TREE_CODE (op1) == SSA_NAME)
10970 register_edge_assert_for (op1, pred_e, code, op0, op1, asserts);
10972 auto_vec<std::pair<tree, value_range *>, 8> vrs;
10973 for (unsigned i = 0; i < asserts.length (); ++i)
10975 value_range *vr = try_find_new_range (asserts[i].name,
10976 asserts[i].expr,
10977 asserts[i].comp_code,
10978 asserts[i].val);
10979 if (vr)
10980 vrs.safe_push (std::make_pair (asserts[i].name, vr));
10982 /* Push updated ranges only after finding all of them to avoid
10983 ordering issues that can lead to worse ranges. */
10984 for (unsigned i = 0; i < vrs.length (); ++i)
10985 push_value_range (vrs[i].first, vrs[i].second);
10989 /* Visit PHI stmts and discover any new VRs possible. */
10990 bool has_unvisited_preds = false;
10991 FOR_EACH_EDGE (e, ei, bb->preds)
10992 if (e->flags & EDGE_EXECUTABLE
10993 && !(e->src->flags & BB_VISITED))
10995 has_unvisited_preds = true;
10996 break;
10999 for (gphi_iterator gpi = gsi_start_phis (bb);
11000 !gsi_end_p (gpi); gsi_next (&gpi))
11002 gphi *phi = gpi.phi ();
11003 tree lhs = PHI_RESULT (phi);
11004 if (virtual_operand_p (lhs))
11005 continue;
11006 value_range vr_result = VR_INITIALIZER;
11007 bool interesting = stmt_interesting_for_vrp (phi);
11008 if (interesting && dump_file && (dump_flags & TDF_DETAILS))
11010 fprintf (dump_file, "Visiting PHI node ");
11011 print_gimple_stmt (dump_file, phi, 0);
11013 if (!has_unvisited_preds
11014 && interesting)
11015 extract_range_from_phi_node (phi, &vr_result);
11016 else
11018 set_value_range_to_varying (&vr_result);
11019 /* When we have an unvisited executable predecessor we can't
11020 use PHI arg ranges which may be still UNDEFINED but have
11021 to use VARYING for them. But we can still resort to
11022 SCEV for loop header PHIs. */
11023 struct loop *l;
11024 if (interesting
11025 && (l = loop_containing_stmt (phi))
11026 && l->header == gimple_bb (phi))
11027 adjust_range_with_scev (&vr_result, l, phi, lhs);
11029 update_value_range (lhs, &vr_result);
11031 /* Mark PHIs whose lhs we fully propagate for removal. */
11032 tree val = op_with_constant_singleton_value_range (lhs);
11033 if (val && may_propagate_copy (lhs, val))
11035 stmts_to_remove.safe_push (phi);
11036 continue;
11039 /* Set the SSA with the value range. */
11040 if (INTEGRAL_TYPE_P (TREE_TYPE (lhs)))
11042 if ((vr_result.type == VR_RANGE
11043 || vr_result.type == VR_ANTI_RANGE)
11044 && (TREE_CODE (vr_result.min) == INTEGER_CST)
11045 && (TREE_CODE (vr_result.max) == INTEGER_CST))
11046 set_range_info (lhs,
11047 vr_result.type, vr_result.min, vr_result.max);
11049 else if (POINTER_TYPE_P (TREE_TYPE (lhs))
11050 && ((vr_result.type == VR_RANGE
11051 && range_includes_zero_p (vr_result.min,
11052 vr_result.max) == 0)
11053 || (vr_result.type == VR_ANTI_RANGE
11054 && range_includes_zero_p (vr_result.min,
11055 vr_result.max) == 1)))
11056 set_ptr_nonnull (lhs);
11059 edge taken_edge = NULL;
11061 /* Visit all other stmts and discover any new VRs possible. */
11062 for (gimple_stmt_iterator gsi = gsi_start_bb (bb);
11063 !gsi_end_p (gsi); gsi_next (&gsi))
11065 gimple *stmt = gsi_stmt (gsi);
11066 tree output = NULL_TREE;
11067 gimple *old_stmt = stmt;
11068 bool was_noreturn = (is_gimple_call (stmt)
11069 && gimple_call_noreturn_p (stmt));
11071 if (dump_file && (dump_flags & TDF_DETAILS))
11073 fprintf (dump_file, "Visiting stmt ");
11074 print_gimple_stmt (dump_file, stmt, 0);
11077 if (gcond *cond = dyn_cast <gcond *> (stmt))
11079 vrp_visit_cond_stmt (cond, &taken_edge);
11080 if (taken_edge)
11082 if (taken_edge->flags & EDGE_TRUE_VALUE)
11083 gimple_cond_make_true (cond);
11084 else if (taken_edge->flags & EDGE_FALSE_VALUE)
11085 gimple_cond_make_false (cond);
11086 else
11087 gcc_unreachable ();
11088 update_stmt (stmt);
11091 else if (stmt_interesting_for_vrp (stmt))
11093 edge taken_edge;
11094 value_range vr = VR_INITIALIZER;
11095 extract_range_from_stmt (stmt, &taken_edge, &output, &vr);
11096 if (output
11097 && (vr.type == VR_RANGE || vr.type == VR_ANTI_RANGE))
11099 update_value_range (output, &vr);
11100 vr = *get_value_range (output);
11102 /* Mark stmts whose output we fully propagate for removal. */
11103 tree val;
11104 if ((val = op_with_constant_singleton_value_range (output))
11105 && may_propagate_copy (output, val)
11106 && !stmt_could_throw_p (stmt)
11107 && !gimple_has_side_effects (stmt))
11109 stmts_to_remove.safe_push (stmt);
11110 continue;
11113 /* Set the SSA with the value range. */
11114 if (INTEGRAL_TYPE_P (TREE_TYPE (output)))
11116 if ((vr.type == VR_RANGE
11117 || vr.type == VR_ANTI_RANGE)
11118 && (TREE_CODE (vr.min) == INTEGER_CST)
11119 && (TREE_CODE (vr.max) == INTEGER_CST))
11120 set_range_info (output, vr.type, vr.min, vr.max);
11122 else if (POINTER_TYPE_P (TREE_TYPE (output))
11123 && ((vr.type == VR_RANGE
11124 && range_includes_zero_p (vr.min,
11125 vr.max) == 0)
11126 || (vr.type == VR_ANTI_RANGE
11127 && range_includes_zero_p (vr.min,
11128 vr.max) == 1)))
11129 set_ptr_nonnull (output);
11131 else
11132 set_defs_to_varying (stmt);
11134 else
11135 set_defs_to_varying (stmt);
11137 /* See if we can derive a range for any of STMT's operands. */
11138 tree op;
11139 ssa_op_iter i;
11140 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
11142 tree value;
11143 enum tree_code comp_code;
11145 /* If OP is used in such a way that we can infer a value
11146 range for it, and we don't find a previous assertion for
11147 it, create a new assertion location node for OP. */
11148 if (infer_value_range (stmt, op, &comp_code, &value))
11150 /* If we are able to infer a nonzero value range for OP,
11151 then walk backwards through the use-def chain to see if OP
11152 was set via a typecast.
11153 If so, then we can also infer a nonzero value range
11154 for the operand of the NOP_EXPR. */
11155 if (comp_code == NE_EXPR && integer_zerop (value))
11157 tree t = op;
11158 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
11159 while (is_gimple_assign (def_stmt)
11160 && CONVERT_EXPR_CODE_P
11161 (gimple_assign_rhs_code (def_stmt))
11162 && TREE_CODE
11163 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
11164 && POINTER_TYPE_P
11165 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
11167 t = gimple_assign_rhs1 (def_stmt);
11168 def_stmt = SSA_NAME_DEF_STMT (t);
11170 /* Add VR when (T COMP_CODE value) condition is
11171 true. */
11172 value_range *op_range
11173 = try_find_new_range (t, t, comp_code, value);
11174 if (op_range)
11175 push_value_range (t, op_range);
11178 /* Add VR when (OP COMP_CODE value) condition is true. */
11179 value_range *op_range = try_find_new_range (op, op,
11180 comp_code, value);
11181 if (op_range)
11182 push_value_range (op, op_range);
11186 /* Try folding stmts with the VR discovered. */
11187 bool did_replace
11188 = replace_uses_in (stmt, op_with_constant_singleton_value_range);
11189 if (fold_stmt (&gsi, follow_single_use_edges)
11190 || did_replace)
11192 stmt = gsi_stmt (gsi);
11193 update_stmt (stmt);
11194 did_replace = true;
11197 if (did_replace)
11199 /* If we cleaned up EH information from the statement,
11200 remove EH edges. */
11201 if (maybe_clean_or_replace_eh_stmt (old_stmt, stmt))
11202 bitmap_set_bit (need_eh_cleanup, bb->index);
11204 /* If we turned a not noreturn call into a noreturn one
11205 schedule it for fixup. */
11206 if (!was_noreturn
11207 && is_gimple_call (stmt)
11208 && gimple_call_noreturn_p (stmt))
11209 stmts_to_fixup.safe_push (stmt);
11211 if (gimple_assign_single_p (stmt))
11213 tree rhs = gimple_assign_rhs1 (stmt);
11214 if (TREE_CODE (rhs) == ADDR_EXPR)
11215 recompute_tree_invariant_for_addr_expr (rhs);
11220 /* Visit BB successor PHI nodes and replace PHI args. */
11221 FOR_EACH_EDGE (e, ei, bb->succs)
11223 for (gphi_iterator gpi = gsi_start_phis (e->dest);
11224 !gsi_end_p (gpi); gsi_next (&gpi))
11226 gphi *phi = gpi.phi ();
11227 use_operand_p use_p = PHI_ARG_DEF_PTR_FROM_EDGE (phi, e);
11228 tree arg = USE_FROM_PTR (use_p);
11229 if (TREE_CODE (arg) != SSA_NAME
11230 || virtual_operand_p (arg))
11231 continue;
11232 tree val = op_with_constant_singleton_value_range (arg);
11233 if (val && may_propagate_copy (arg, val))
11234 propagate_value (use_p, val);
11238 bb->flags |= BB_VISITED;
11240 return taken_edge;
11243 /* Restore/pop VRs valid only for BB when we leave BB. */
11245 void
11246 evrp_dom_walker::after_dom_children (basic_block bb ATTRIBUTE_UNUSED)
11248 gcc_checking_assert (!stack.is_empty ());
11249 while (stack.last ().first != NULL_TREE)
11250 pop_value_range (stack.last ().first);
11251 stack.pop ();
11254 /* Push the Value Range of VAR to the stack and update it with new VR. */
11256 void
11257 evrp_dom_walker::push_value_range (tree var, value_range *vr)
11259 if (SSA_NAME_VERSION (var) >= num_vr_values)
11260 return;
11261 if (dump_file && (dump_flags & TDF_DETAILS))
11263 fprintf (dump_file, "pushing new range for ");
11264 print_generic_expr (dump_file, var);
11265 fprintf (dump_file, ": ");
11266 dump_value_range (dump_file, vr);
11267 fprintf (dump_file, "\n");
11269 stack.safe_push (std::make_pair (var, get_value_range (var)));
11270 vr_value[SSA_NAME_VERSION (var)] = vr;
11273 /* Pop the Value Range from the vrp_stack and update VAR with it. */
11275 value_range *
11276 evrp_dom_walker::pop_value_range (tree var)
11278 value_range *vr = stack.last ().second;
11279 gcc_checking_assert (var == stack.last ().first);
11280 if (dump_file && (dump_flags & TDF_DETAILS))
11282 fprintf (dump_file, "popping range for ");
11283 print_generic_expr (dump_file, var);
11284 fprintf (dump_file, ", restoring ");
11285 dump_value_range (dump_file, vr);
11286 fprintf (dump_file, "\n");
11288 vr_value[SSA_NAME_VERSION (var)] = vr;
11289 stack.pop ();
11290 return vr;
11294 /* Main entry point for the early vrp pass which is a simplified non-iterative
11295 version of vrp where basic blocks are visited in dominance order. Value
11296 ranges discovered in early vrp will also be used by ipa-vrp. */
11298 static unsigned int
11299 execute_early_vrp ()
11301 edge e;
11302 edge_iterator ei;
11303 basic_block bb;
11305 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
11306 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
11307 scev_initialize ();
11308 calculate_dominance_info (CDI_DOMINATORS);
11309 FOR_EACH_BB_FN (bb, cfun)
11311 bb->flags &= ~BB_VISITED;
11312 FOR_EACH_EDGE (e, ei, bb->preds)
11313 e->flags |= EDGE_EXECUTABLE;
11315 vrp_initialize_lattice ();
11317 /* Walk stmts in dominance order and propagate VRP. */
11318 evrp_dom_walker walker;
11319 walker.walk (ENTRY_BLOCK_PTR_FOR_FN (cfun));
11321 if (dump_file)
11323 fprintf (dump_file, "\nValue ranges after Early VRP:\n\n");
11324 dump_all_value_ranges (dump_file);
11325 fprintf (dump_file, "\n");
11328 /* Remove stmts in reverse order to make debug stmt creation possible. */
11329 while (! walker.stmts_to_remove.is_empty ())
11331 gimple *stmt = walker.stmts_to_remove.pop ();
11332 if (dump_file && dump_flags & TDF_DETAILS)
11334 fprintf (dump_file, "Removing dead stmt ");
11335 print_gimple_stmt (dump_file, stmt, 0);
11336 fprintf (dump_file, "\n");
11338 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
11339 if (gimple_code (stmt) == GIMPLE_PHI)
11340 remove_phi_node (&gsi, true);
11341 else
11343 unlink_stmt_vdef (stmt);
11344 gsi_remove (&gsi, true);
11345 release_defs (stmt);
11349 if (!bitmap_empty_p (walker.need_eh_cleanup))
11350 gimple_purge_all_dead_eh_edges (walker.need_eh_cleanup);
11352 /* Fixup stmts that became noreturn calls. This may require splitting
11353 blocks and thus isn't possible during the dominator walk. Do this
11354 in reverse order so we don't inadvertedly remove a stmt we want to
11355 fixup by visiting a dominating now noreturn call first. */
11356 while (!walker.stmts_to_fixup.is_empty ())
11358 gimple *stmt = walker.stmts_to_fixup.pop ();
11359 fixup_noreturn_call (stmt);
11362 vrp_free_lattice ();
11363 scev_finalize ();
11364 loop_optimizer_finalize ();
11365 return 0;
11369 /* Main entry point to VRP (Value Range Propagation). This pass is
11370 loosely based on J. R. C. Patterson, ``Accurate Static Branch
11371 Prediction by Value Range Propagation,'' in SIGPLAN Conference on
11372 Programming Language Design and Implementation, pp. 67-78, 1995.
11373 Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
11375 This is essentially an SSA-CCP pass modified to deal with ranges
11376 instead of constants.
11378 While propagating ranges, we may find that two or more SSA name
11379 have equivalent, though distinct ranges. For instance,
11381 1 x_9 = p_3->a;
11382 2 p_4 = ASSERT_EXPR <p_3, p_3 != 0>
11383 3 if (p_4 == q_2)
11384 4 p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
11385 5 endif
11386 6 if (q_2)
11388 In the code above, pointer p_5 has range [q_2, q_2], but from the
11389 code we can also determine that p_5 cannot be NULL and, if q_2 had
11390 a non-varying range, p_5's range should also be compatible with it.
11392 These equivalences are created by two expressions: ASSERT_EXPR and
11393 copy operations. Since p_5 is an assertion on p_4, and p_4 was the
11394 result of another assertion, then we can use the fact that p_5 and
11395 p_4 are equivalent when evaluating p_5's range.
11397 Together with value ranges, we also propagate these equivalences
11398 between names so that we can take advantage of information from
11399 multiple ranges when doing final replacement. Note that this
11400 equivalency relation is transitive but not symmetric.
11402 In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
11403 cannot assert that q_2 is equivalent to p_5 because q_2 may be used
11404 in contexts where that assertion does not hold (e.g., in line 6).
11406 TODO, the main difference between this pass and Patterson's is that
11407 we do not propagate edge probabilities. We only compute whether
11408 edges can be taken or not. That is, instead of having a spectrum
11409 of jump probabilities between 0 and 1, we only deal with 0, 1 and
11410 DON'T KNOW. In the future, it may be worthwhile to propagate
11411 probabilities to aid branch prediction. */
11413 static unsigned int
11414 execute_vrp (bool warn_array_bounds_p)
11416 int i;
11417 edge e;
11418 switch_update *su;
11420 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
11421 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
11422 scev_initialize ();
11424 /* ??? This ends up using stale EDGE_DFS_BACK for liveness computation.
11425 Inserting assertions may split edges which will invalidate
11426 EDGE_DFS_BACK. */
11427 insert_range_assertions ();
11429 to_remove_edges.create (10);
11430 to_update_switch_stmts.create (5);
11431 threadedge_initialize_values ();
11433 /* For visiting PHI nodes we need EDGE_DFS_BACK computed. */
11434 mark_dfs_back_edges ();
11436 vrp_initialize_lattice ();
11437 vrp_initialize ();
11438 ssa_propagate (vrp_visit_stmt, vrp_visit_phi_node);
11439 vrp_finalize (warn_array_bounds_p);
11441 /* We must identify jump threading opportunities before we release
11442 the datastructures built by VRP. */
11443 identify_jump_threads ();
11445 /* A comparison of an SSA_NAME against a constant where the SSA_NAME
11446 was set by a type conversion can often be rewritten to use the
11447 RHS of the type conversion.
11449 However, doing so inhibits jump threading through the comparison.
11450 So that transformation is not performed until after jump threading
11451 is complete. */
11452 basic_block bb;
11453 FOR_EACH_BB_FN (bb, cfun)
11455 gimple *last = last_stmt (bb);
11456 if (last && gimple_code (last) == GIMPLE_COND)
11457 simplify_cond_using_ranges_2 (as_a <gcond *> (last));
11460 vrp_free_lattice ();
11462 free_numbers_of_iterations_estimates (cfun);
11464 /* ASSERT_EXPRs must be removed before finalizing jump threads
11465 as finalizing jump threads calls the CFG cleanup code which
11466 does not properly handle ASSERT_EXPRs. */
11467 remove_range_assertions ();
11469 /* If we exposed any new variables, go ahead and put them into
11470 SSA form now, before we handle jump threading. This simplifies
11471 interactions between rewriting of _DECL nodes into SSA form
11472 and rewriting SSA_NAME nodes into SSA form after block
11473 duplication and CFG manipulation. */
11474 update_ssa (TODO_update_ssa);
11476 /* We identified all the jump threading opportunities earlier, but could
11477 not transform the CFG at that time. This routine transforms the
11478 CFG and arranges for the dominator tree to be rebuilt if necessary.
11480 Note the SSA graph update will occur during the normal TODO
11481 processing by the pass manager. */
11482 thread_through_all_blocks (false);
11484 /* Remove dead edges from SWITCH_EXPR optimization. This leaves the
11485 CFG in a broken state and requires a cfg_cleanup run. */
11486 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
11487 remove_edge (e);
11488 /* Update SWITCH_EXPR case label vector. */
11489 FOR_EACH_VEC_ELT (to_update_switch_stmts, i, su)
11491 size_t j;
11492 size_t n = TREE_VEC_LENGTH (su->vec);
11493 tree label;
11494 gimple_switch_set_num_labels (su->stmt, n);
11495 for (j = 0; j < n; j++)
11496 gimple_switch_set_label (su->stmt, j, TREE_VEC_ELT (su->vec, j));
11497 /* As we may have replaced the default label with a regular one
11498 make sure to make it a real default label again. This ensures
11499 optimal expansion. */
11500 label = gimple_switch_label (su->stmt, 0);
11501 CASE_LOW (label) = NULL_TREE;
11502 CASE_HIGH (label) = NULL_TREE;
11505 if (to_remove_edges.length () > 0)
11507 free_dominance_info (CDI_DOMINATORS);
11508 loops_state_set (LOOPS_NEED_FIXUP);
11511 to_remove_edges.release ();
11512 to_update_switch_stmts.release ();
11513 threadedge_finalize_values ();
11515 scev_finalize ();
11516 loop_optimizer_finalize ();
11517 return 0;
11520 namespace {
11522 const pass_data pass_data_vrp =
11524 GIMPLE_PASS, /* type */
11525 "vrp", /* name */
11526 OPTGROUP_NONE, /* optinfo_flags */
11527 TV_TREE_VRP, /* tv_id */
11528 PROP_ssa, /* properties_required */
11529 0, /* properties_provided */
11530 0, /* properties_destroyed */
11531 0, /* todo_flags_start */
11532 ( TODO_cleanup_cfg | TODO_update_ssa ), /* todo_flags_finish */
11535 class pass_vrp : public gimple_opt_pass
11537 public:
11538 pass_vrp (gcc::context *ctxt)
11539 : gimple_opt_pass (pass_data_vrp, ctxt), warn_array_bounds_p (false)
11542 /* opt_pass methods: */
11543 opt_pass * clone () { return new pass_vrp (m_ctxt); }
11544 void set_pass_param (unsigned int n, bool param)
11546 gcc_assert (n == 0);
11547 warn_array_bounds_p = param;
11549 virtual bool gate (function *) { return flag_tree_vrp != 0; }
11550 virtual unsigned int execute (function *)
11551 { return execute_vrp (warn_array_bounds_p); }
11553 private:
11554 bool warn_array_bounds_p;
11555 }; // class pass_vrp
11557 } // anon namespace
11559 gimple_opt_pass *
11560 make_pass_vrp (gcc::context *ctxt)
11562 return new pass_vrp (ctxt);
11565 namespace {
11567 const pass_data pass_data_early_vrp =
11569 GIMPLE_PASS, /* type */
11570 "evrp", /* name */
11571 OPTGROUP_NONE, /* optinfo_flags */
11572 TV_TREE_EARLY_VRP, /* tv_id */
11573 PROP_ssa, /* properties_required */
11574 0, /* properties_provided */
11575 0, /* properties_destroyed */
11576 0, /* todo_flags_start */
11577 ( TODO_cleanup_cfg | TODO_update_ssa | TODO_verify_all ),
11580 class pass_early_vrp : public gimple_opt_pass
11582 public:
11583 pass_early_vrp (gcc::context *ctxt)
11584 : gimple_opt_pass (pass_data_early_vrp, ctxt)
11587 /* opt_pass methods: */
11588 opt_pass * clone () { return new pass_early_vrp (m_ctxt); }
11589 virtual bool gate (function *)
11591 return flag_tree_vrp != 0;
11593 virtual unsigned int execute (function *)
11594 { return execute_early_vrp (); }
11596 }; // class pass_vrp
11597 } // anon namespace
11599 gimple_opt_pass *
11600 make_pass_early_vrp (gcc::context *ctxt)
11602 return new pass_early_vrp (ctxt);