OSDN Git Service

Add newlib-stdint.h to moxie-eld config.
[pf3gnuchains/gcc-fork.git] / gcc / tree-vrp.c
1 /* Support routines for Value Range Propagation (VRP).
2    Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010
3    Free Software Foundation, Inc.
4    Contributed by Diego Novillo <dnovillo@redhat.com>.
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
12
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "ggc.h"
27 #include "flags.h"
28 #include "tree.h"
29 #include "basic-block.h"
30 #include "tree-flow.h"
31 #include "tree-pass.h"
32 #include "tree-dump.h"
33 #include "timevar.h"
34 #include "tree-pretty-print.h"
35 #include "gimple-pretty-print.h"
36 #include "diagnostic-core.h"
37 #include "intl.h"
38 #include "cfgloop.h"
39 #include "tree-scalar-evolution.h"
40 #include "tree-ssa-propagate.h"
41 #include "tree-chrec.h"
42
43
44 /* Type of value ranges.  See value_range_d for a description of these
45    types.  */
46 enum value_range_type { VR_UNDEFINED, VR_RANGE, VR_ANTI_RANGE, VR_VARYING };
47
48 /* Range of values that can be associated with an SSA_NAME after VRP
49    has executed.  */
50 struct value_range_d
51 {
52   /* Lattice value represented by this range.  */
53   enum value_range_type type;
54
55   /* Minimum and maximum values represented by this range.  These
56      values should be interpreted as follows:
57
58         - If TYPE is VR_UNDEFINED or VR_VARYING then MIN and MAX must
59           be NULL.
60
61         - If TYPE == VR_RANGE then MIN holds the minimum value and
62           MAX holds the maximum value of the range [MIN, MAX].
63
64         - If TYPE == ANTI_RANGE the variable is known to NOT
65           take any values in the range [MIN, MAX].  */
66   tree min;
67   tree max;
68
69   /* Set of SSA names whose value ranges are equivalent to this one.
70      This set is only valid when TYPE is VR_RANGE or VR_ANTI_RANGE.  */
71   bitmap equiv;
72 };
73
74 typedef struct value_range_d value_range_t;
75
76 /* Set of SSA names found live during the RPO traversal of the function
77    for still active basic-blocks.  */
78 static sbitmap *live;
79
80 /* Return true if the SSA name NAME is live on the edge E.  */
81
82 static bool
83 live_on_edge (edge e, tree name)
84 {
85   return (live[e->dest->index]
86           && TEST_BIT (live[e->dest->index], SSA_NAME_VERSION (name)));
87 }
88
89 /* Local functions.  */
90 static int compare_values (tree val1, tree val2);
91 static int compare_values_warnv (tree val1, tree val2, bool *);
92 static void vrp_meet (value_range_t *, value_range_t *);
93 static tree vrp_evaluate_conditional_warnv_with_ops (enum tree_code,
94                                                      tree, tree, bool, bool *,
95                                                      bool *);
96
97 /* Location information for ASSERT_EXPRs.  Each instance of this
98    structure describes an ASSERT_EXPR for an SSA name.  Since a single
99    SSA name may have more than one assertion associated with it, these
100    locations are kept in a linked list attached to the corresponding
101    SSA name.  */
102 struct assert_locus_d
103 {
104   /* Basic block where the assertion would be inserted.  */
105   basic_block bb;
106
107   /* Some assertions need to be inserted on an edge (e.g., assertions
108      generated by COND_EXPRs).  In those cases, BB will be NULL.  */
109   edge e;
110
111   /* Pointer to the statement that generated this assertion.  */
112   gimple_stmt_iterator si;
113
114   /* Predicate code for the ASSERT_EXPR.  Must be COMPARISON_CLASS_P.  */
115   enum tree_code comp_code;
116
117   /* Value being compared against.  */
118   tree val;
119
120   /* Expression to compare.  */
121   tree expr;
122
123   /* Next node in the linked list.  */
124   struct assert_locus_d *next;
125 };
126
127 typedef struct assert_locus_d *assert_locus_t;
128
129 /* If bit I is present, it means that SSA name N_i has a list of
130    assertions that should be inserted in the IL.  */
131 static bitmap need_assert_for;
132
133 /* Array of locations lists where to insert assertions.  ASSERTS_FOR[I]
134    holds a list of ASSERT_LOCUS_T nodes that describe where
135    ASSERT_EXPRs for SSA name N_I should be inserted.  */
136 static assert_locus_t *asserts_for;
137
138 /* Value range array.  After propagation, VR_VALUE[I] holds the range
139    of values that SSA name N_I may take.  */
140 static value_range_t **vr_value;
141
142 /* For a PHI node which sets SSA name N_I, VR_COUNTS[I] holds the
143    number of executable edges we saw the last time we visited the
144    node.  */
145 static int *vr_phi_edge_counts;
146
147 typedef struct {
148   gimple stmt;
149   tree vec;
150 } switch_update;
151
152 static VEC (edge, heap) *to_remove_edges;
153 DEF_VEC_O(switch_update);
154 DEF_VEC_ALLOC_O(switch_update, heap);
155 static VEC (switch_update, heap) *to_update_switch_stmts;
156
157
158 /* Return the maximum value for TYPE.  */
159
160 static inline tree
161 vrp_val_max (const_tree type)
162 {
163   if (!INTEGRAL_TYPE_P (type))
164     return NULL_TREE;
165
166   return TYPE_MAX_VALUE (type);
167 }
168
169 /* Return the minimum value for TYPE.  */
170
171 static inline tree
172 vrp_val_min (const_tree type)
173 {
174   if (!INTEGRAL_TYPE_P (type))
175     return NULL_TREE;
176
177   return TYPE_MIN_VALUE (type);
178 }
179
180 /* Return whether VAL is equal to the maximum value of its type.  This
181    will be true for a positive overflow infinity.  We can't do a
182    simple equality comparison with TYPE_MAX_VALUE because C typedefs
183    and Ada subtypes can produce types whose TYPE_MAX_VALUE is not ==
184    to the integer constant with the same value in the type.  */
185
186 static inline bool
187 vrp_val_is_max (const_tree val)
188 {
189   tree type_max = vrp_val_max (TREE_TYPE (val));
190   return (val == type_max
191           || (type_max != NULL_TREE
192               && operand_equal_p (val, type_max, 0)));
193 }
194
195 /* Return whether VAL is equal to the minimum value of its type.  This
196    will be true for a negative overflow infinity.  */
197
198 static inline bool
199 vrp_val_is_min (const_tree val)
200 {
201   tree type_min = vrp_val_min (TREE_TYPE (val));
202   return (val == type_min
203           || (type_min != NULL_TREE
204               && operand_equal_p (val, type_min, 0)));
205 }
206
207
208 /* Return whether TYPE should use an overflow infinity distinct from
209    TYPE_{MIN,MAX}_VALUE.  We use an overflow infinity value to
210    represent a signed overflow during VRP computations.  An infinity
211    is distinct from a half-range, which will go from some number to
212    TYPE_{MIN,MAX}_VALUE.  */
213
214 static inline bool
215 needs_overflow_infinity (const_tree type)
216 {
217   return INTEGRAL_TYPE_P (type) && !TYPE_OVERFLOW_WRAPS (type);
218 }
219
220 /* Return whether TYPE can support our overflow infinity
221    representation: we use the TREE_OVERFLOW flag, which only exists
222    for constants.  If TYPE doesn't support this, we don't optimize
223    cases which would require signed overflow--we drop them to
224    VARYING.  */
225
226 static inline bool
227 supports_overflow_infinity (const_tree type)
228 {
229   tree min = vrp_val_min (type), max = vrp_val_max (type);
230 #ifdef ENABLE_CHECKING
231   gcc_assert (needs_overflow_infinity (type));
232 #endif
233   return (min != NULL_TREE
234           && CONSTANT_CLASS_P (min)
235           && max != NULL_TREE
236           && CONSTANT_CLASS_P (max));
237 }
238
239 /* VAL is the maximum or minimum value of a type.  Return a
240    corresponding overflow infinity.  */
241
242 static inline tree
243 make_overflow_infinity (tree val)
244 {
245   gcc_checking_assert (val != NULL_TREE && CONSTANT_CLASS_P (val));
246   val = copy_node (val);
247   TREE_OVERFLOW (val) = 1;
248   return val;
249 }
250
251 /* Return a negative overflow infinity for TYPE.  */
252
253 static inline tree
254 negative_overflow_infinity (tree type)
255 {
256   gcc_checking_assert (supports_overflow_infinity (type));
257   return make_overflow_infinity (vrp_val_min (type));
258 }
259
260 /* Return a positive overflow infinity for TYPE.  */
261
262 static inline tree
263 positive_overflow_infinity (tree type)
264 {
265   gcc_checking_assert (supports_overflow_infinity (type));
266   return make_overflow_infinity (vrp_val_max (type));
267 }
268
269 /* Return whether VAL is a negative overflow infinity.  */
270
271 static inline bool
272 is_negative_overflow_infinity (const_tree val)
273 {
274   return (needs_overflow_infinity (TREE_TYPE (val))
275           && CONSTANT_CLASS_P (val)
276           && TREE_OVERFLOW (val)
277           && vrp_val_is_min (val));
278 }
279
280 /* Return whether VAL is a positive overflow infinity.  */
281
282 static inline bool
283 is_positive_overflow_infinity (const_tree val)
284 {
285   return (needs_overflow_infinity (TREE_TYPE (val))
286           && CONSTANT_CLASS_P (val)
287           && TREE_OVERFLOW (val)
288           && vrp_val_is_max (val));
289 }
290
291 /* Return whether VAL is a positive or negative overflow infinity.  */
292
293 static inline bool
294 is_overflow_infinity (const_tree val)
295 {
296   return (needs_overflow_infinity (TREE_TYPE (val))
297           && CONSTANT_CLASS_P (val)
298           && TREE_OVERFLOW (val)
299           && (vrp_val_is_min (val) || vrp_val_is_max (val)));
300 }
301
302 /* Return whether STMT has a constant rhs that is_overflow_infinity. */
303
304 static inline bool
305 stmt_overflow_infinity (gimple stmt)
306 {
307   if (is_gimple_assign (stmt)
308       && get_gimple_rhs_class (gimple_assign_rhs_code (stmt)) ==
309       GIMPLE_SINGLE_RHS)
310     return is_overflow_infinity (gimple_assign_rhs1 (stmt));
311   return false;
312 }
313
314 /* If VAL is now an overflow infinity, return VAL.  Otherwise, return
315    the same value with TREE_OVERFLOW clear.  This can be used to avoid
316    confusing a regular value with an overflow value.  */
317
318 static inline tree
319 avoid_overflow_infinity (tree val)
320 {
321   if (!is_overflow_infinity (val))
322     return val;
323
324   if (vrp_val_is_max (val))
325     return vrp_val_max (TREE_TYPE (val));
326   else
327     {
328       gcc_checking_assert (vrp_val_is_min (val));
329       return vrp_val_min (TREE_TYPE (val));
330     }
331 }
332
333
334 /* Return true if ARG is marked with the nonnull attribute in the
335    current function signature.  */
336
337 static bool
338 nonnull_arg_p (const_tree arg)
339 {
340   tree t, attrs, fntype;
341   unsigned HOST_WIDE_INT arg_num;
342
343   gcc_assert (TREE_CODE (arg) == PARM_DECL && POINTER_TYPE_P (TREE_TYPE (arg)));
344
345   /* The static chain decl is always non null.  */
346   if (arg == cfun->static_chain_decl)
347     return true;
348
349   fntype = TREE_TYPE (current_function_decl);
350   attrs = lookup_attribute ("nonnull", TYPE_ATTRIBUTES (fntype));
351
352   /* If "nonnull" wasn't specified, we know nothing about the argument.  */
353   if (attrs == NULL_TREE)
354     return false;
355
356   /* If "nonnull" applies to all the arguments, then ARG is non-null.  */
357   if (TREE_VALUE (attrs) == NULL_TREE)
358     return true;
359
360   /* Get the position number for ARG in the function signature.  */
361   for (arg_num = 1, t = DECL_ARGUMENTS (current_function_decl);
362        t;
363        t = DECL_CHAIN (t), arg_num++)
364     {
365       if (t == arg)
366         break;
367     }
368
369   gcc_assert (t == arg);
370
371   /* Now see if ARG_NUM is mentioned in the nonnull list.  */
372   for (t = TREE_VALUE (attrs); t; t = TREE_CHAIN (t))
373     {
374       if (compare_tree_int (TREE_VALUE (t), arg_num) == 0)
375         return true;
376     }
377
378   return false;
379 }
380
381
382 /* Set value range VR to VR_VARYING.  */
383
384 static inline void
385 set_value_range_to_varying (value_range_t *vr)
386 {
387   vr->type = VR_VARYING;
388   vr->min = vr->max = NULL_TREE;
389   if (vr->equiv)
390     bitmap_clear (vr->equiv);
391 }
392
393
394 /* Set value range VR to {T, MIN, MAX, EQUIV}.  */
395
396 static void
397 set_value_range (value_range_t *vr, enum value_range_type t, tree min,
398                  tree max, bitmap equiv)
399 {
400 #if defined ENABLE_CHECKING
401   /* Check the validity of the range.  */
402   if (t == VR_RANGE || t == VR_ANTI_RANGE)
403     {
404       int cmp;
405
406       gcc_assert (min && max);
407
408       if (INTEGRAL_TYPE_P (TREE_TYPE (min)) && t == VR_ANTI_RANGE)
409         gcc_assert (!vrp_val_is_min (min) || !vrp_val_is_max (max));
410
411       cmp = compare_values (min, max);
412       gcc_assert (cmp == 0 || cmp == -1 || cmp == -2);
413
414       if (needs_overflow_infinity (TREE_TYPE (min)))
415         gcc_assert (!is_overflow_infinity (min)
416                     || !is_overflow_infinity (max));
417     }
418
419   if (t == VR_UNDEFINED || t == VR_VARYING)
420     gcc_assert (min == NULL_TREE && max == NULL_TREE);
421
422   if (t == VR_UNDEFINED || t == VR_VARYING)
423     gcc_assert (equiv == NULL || bitmap_empty_p (equiv));
424 #endif
425
426   vr->type = t;
427   vr->min = min;
428   vr->max = max;
429
430   /* Since updating the equivalence set involves deep copying the
431      bitmaps, only do it if absolutely necessary.  */
432   if (vr->equiv == NULL
433       && equiv != NULL)
434     vr->equiv = BITMAP_ALLOC (NULL);
435
436   if (equiv != vr->equiv)
437     {
438       if (equiv && !bitmap_empty_p (equiv))
439         bitmap_copy (vr->equiv, equiv);
440       else
441         bitmap_clear (vr->equiv);
442     }
443 }
444
445
446 /* Set value range VR to the canonical form of {T, MIN, MAX, EQUIV}.
447    This means adjusting T, MIN and MAX representing the case of a
448    wrapping range with MAX < MIN covering [MIN, type_max] U [type_min, MAX]
449    as anti-rage ~[MAX+1, MIN-1].  Likewise for wrapping anti-ranges.
450    In corner cases where MAX+1 or MIN-1 wraps this will fall back
451    to varying.
452    This routine exists to ease canonicalization in the case where we
453    extract ranges from var + CST op limit.  */
454
455 static void
456 set_and_canonicalize_value_range (value_range_t *vr, enum value_range_type t,
457                                   tree min, tree max, bitmap equiv)
458 {
459   /* Nothing to canonicalize for symbolic or unknown or varying ranges.  */
460   if ((t != VR_RANGE
461        && t != VR_ANTI_RANGE)
462       || TREE_CODE (min) != INTEGER_CST
463       || TREE_CODE (max) != INTEGER_CST)
464     {
465       set_value_range (vr, t, min, max, equiv);
466       return;
467     }
468
469   /* Wrong order for min and max, to swap them and the VR type we need
470      to adjust them.  */
471   if (tree_int_cst_lt (max, min))
472     {
473       tree one = build_int_cst (TREE_TYPE (min), 1);
474       tree tmp = int_const_binop (PLUS_EXPR, max, one, 0);
475       max = int_const_binop (MINUS_EXPR, min, one, 0);
476       min = tmp;
477
478       /* There's one corner case, if we had [C+1, C] before we now have
479          that again.  But this represents an empty value range, so drop
480          to varying in this case.  */
481       if (tree_int_cst_lt (max, min))
482         {
483           set_value_range_to_varying (vr);
484           return;
485         }
486
487       t = t == VR_RANGE ? VR_ANTI_RANGE : VR_RANGE;
488     }
489
490   /* Anti-ranges that can be represented as ranges should be so.  */
491   if (t == VR_ANTI_RANGE)
492     {
493       bool is_min = vrp_val_is_min (min);
494       bool is_max = vrp_val_is_max (max);
495
496       if (is_min && is_max)
497         {
498           /* We cannot deal with empty ranges, drop to varying.  */
499           set_value_range_to_varying (vr);
500           return;
501         }
502       else if (is_min
503                /* As a special exception preserve non-null ranges.  */
504                && !(TYPE_UNSIGNED (TREE_TYPE (min))
505                     && integer_zerop (max)))
506         {
507           tree one = build_int_cst (TREE_TYPE (max), 1);
508           min = int_const_binop (PLUS_EXPR, max, one, 0);
509           max = vrp_val_max (TREE_TYPE (max));
510           t = VR_RANGE;
511         }
512       else if (is_max)
513         {
514           tree one = build_int_cst (TREE_TYPE (min), 1);
515           max = int_const_binop (MINUS_EXPR, min, one, 0);
516           min = vrp_val_min (TREE_TYPE (min));
517           t = VR_RANGE;
518         }
519     }
520
521   set_value_range (vr, t, min, max, equiv);
522 }
523
524 /* Copy value range FROM into value range TO.  */
525
526 static inline void
527 copy_value_range (value_range_t *to, value_range_t *from)
528 {
529   set_value_range (to, from->type, from->min, from->max, from->equiv);
530 }
531
532 /* Set value range VR to a single value.  This function is only called
533    with values we get from statements, and exists to clear the
534    TREE_OVERFLOW flag so that we don't think we have an overflow
535    infinity when we shouldn't.  */
536
537 static inline void
538 set_value_range_to_value (value_range_t *vr, tree val, bitmap equiv)
539 {
540   gcc_assert (is_gimple_min_invariant (val));
541   val = avoid_overflow_infinity (val);
542   set_value_range (vr, VR_RANGE, val, val, equiv);
543 }
544
545 /* Set value range VR to a non-negative range of type TYPE.
546    OVERFLOW_INFINITY indicates whether to use an overflow infinity
547    rather than TYPE_MAX_VALUE; this should be true if we determine
548    that the range is nonnegative based on the assumption that signed
549    overflow does not occur.  */
550
551 static inline void
552 set_value_range_to_nonnegative (value_range_t *vr, tree type,
553                                 bool overflow_infinity)
554 {
555   tree zero;
556
557   if (overflow_infinity && !supports_overflow_infinity (type))
558     {
559       set_value_range_to_varying (vr);
560       return;
561     }
562
563   zero = build_int_cst (type, 0);
564   set_value_range (vr, VR_RANGE, zero,
565                    (overflow_infinity
566                     ? positive_overflow_infinity (type)
567                     : TYPE_MAX_VALUE (type)),
568                    vr->equiv);
569 }
570
571 /* Set value range VR to a non-NULL range of type TYPE.  */
572
573 static inline void
574 set_value_range_to_nonnull (value_range_t *vr, tree type)
575 {
576   tree zero = build_int_cst (type, 0);
577   set_value_range (vr, VR_ANTI_RANGE, zero, zero, vr->equiv);
578 }
579
580
581 /* Set value range VR to a NULL range of type TYPE.  */
582
583 static inline void
584 set_value_range_to_null (value_range_t *vr, tree type)
585 {
586   set_value_range_to_value (vr, build_int_cst (type, 0), vr->equiv);
587 }
588
589
590 /* Set value range VR to a range of a truthvalue of type TYPE.  */
591
592 static inline void
593 set_value_range_to_truthvalue (value_range_t *vr, tree type)
594 {
595   if (TYPE_PRECISION (type) == 1)
596     set_value_range_to_varying (vr);
597   else
598     set_value_range (vr, VR_RANGE,
599                      build_int_cst (type, 0), build_int_cst (type, 1),
600                      vr->equiv);
601 }
602
603
604 /* Set value range VR to VR_UNDEFINED.  */
605
606 static inline void
607 set_value_range_to_undefined (value_range_t *vr)
608 {
609   vr->type = VR_UNDEFINED;
610   vr->min = vr->max = NULL_TREE;
611   if (vr->equiv)
612     bitmap_clear (vr->equiv);
613 }
614
615
616 /* If abs (min) < abs (max), set VR to [-max, max], if
617    abs (min) >= abs (max), set VR to [-min, min].  */
618
619 static void
620 abs_extent_range (value_range_t *vr, tree min, tree max)
621 {
622   int cmp;
623
624   gcc_assert (TREE_CODE (min) == INTEGER_CST);
625   gcc_assert (TREE_CODE (max) == INTEGER_CST);
626   gcc_assert (INTEGRAL_TYPE_P (TREE_TYPE (min)));
627   gcc_assert (!TYPE_UNSIGNED (TREE_TYPE (min)));
628   min = fold_unary (ABS_EXPR, TREE_TYPE (min), min);
629   max = fold_unary (ABS_EXPR, TREE_TYPE (max), max);
630   if (TREE_OVERFLOW (min) || TREE_OVERFLOW (max))
631     {
632       set_value_range_to_varying (vr);
633       return;
634     }
635   cmp = compare_values (min, max);
636   if (cmp == -1)
637     min = fold_unary (NEGATE_EXPR, TREE_TYPE (min), max);
638   else if (cmp == 0 || cmp == 1)
639     {
640       max = min;
641       min = fold_unary (NEGATE_EXPR, TREE_TYPE (min), min);
642     }
643   else
644     {
645       set_value_range_to_varying (vr);
646       return;
647     }
648   set_and_canonicalize_value_range (vr, VR_RANGE, min, max, NULL);
649 }
650
651
652 /* Return value range information for VAR.
653
654    If we have no values ranges recorded (ie, VRP is not running), then
655    return NULL.  Otherwise create an empty range if none existed for VAR.  */
656
657 static value_range_t *
658 get_value_range (const_tree var)
659 {
660   value_range_t *vr;
661   tree sym;
662   unsigned ver = SSA_NAME_VERSION (var);
663
664   /* If we have no recorded ranges, then return NULL.  */
665   if (! vr_value)
666     return NULL;
667
668   vr = vr_value[ver];
669   if (vr)
670     return vr;
671
672   /* Create a default value range.  */
673   vr_value[ver] = vr = XCNEW (value_range_t);
674
675   /* Defer allocating the equivalence set.  */
676   vr->equiv = NULL;
677
678   /* If VAR is a default definition, the variable can take any value
679      in VAR's type.  */
680   sym = SSA_NAME_VAR (var);
681   if (SSA_NAME_IS_DEFAULT_DEF (var))
682     {
683       /* Try to use the "nonnull" attribute to create ~[0, 0]
684          anti-ranges for pointers.  Note that this is only valid with
685          default definitions of PARM_DECLs.  */
686       if (TREE_CODE (sym) == PARM_DECL
687           && POINTER_TYPE_P (TREE_TYPE (sym))
688           && nonnull_arg_p (sym))
689         set_value_range_to_nonnull (vr, TREE_TYPE (sym));
690       else
691         set_value_range_to_varying (vr);
692     }
693
694   return vr;
695 }
696
697 /* Return true, if VAL1 and VAL2 are equal values for VRP purposes.  */
698
699 static inline bool
700 vrp_operand_equal_p (const_tree val1, const_tree val2)
701 {
702   if (val1 == val2)
703     return true;
704   if (!val1 || !val2 || !operand_equal_p (val1, val2, 0))
705     return false;
706   if (is_overflow_infinity (val1))
707     return is_overflow_infinity (val2);
708   return true;
709 }
710
711 /* Return true, if the bitmaps B1 and B2 are equal.  */
712
713 static inline bool
714 vrp_bitmap_equal_p (const_bitmap b1, const_bitmap b2)
715 {
716   return (b1 == b2
717           || ((!b1 || bitmap_empty_p (b1))
718               && (!b2 || bitmap_empty_p (b2)))
719           || (b1 && b2
720               && bitmap_equal_p (b1, b2)));
721 }
722
723 /* Update the value range and equivalence set for variable VAR to
724    NEW_VR.  Return true if NEW_VR is different from VAR's previous
725    value.
726
727    NOTE: This function assumes that NEW_VR is a temporary value range
728    object created for the sole purpose of updating VAR's range.  The
729    storage used by the equivalence set from NEW_VR will be freed by
730    this function.  Do not call update_value_range when NEW_VR
731    is the range object associated with another SSA name.  */
732
733 static inline bool
734 update_value_range (const_tree var, value_range_t *new_vr)
735 {
736   value_range_t *old_vr;
737   bool is_new;
738
739   /* Update the value range, if necessary.  */
740   old_vr = get_value_range (var);
741   is_new = old_vr->type != new_vr->type
742            || !vrp_operand_equal_p (old_vr->min, new_vr->min)
743            || !vrp_operand_equal_p (old_vr->max, new_vr->max)
744            || !vrp_bitmap_equal_p (old_vr->equiv, new_vr->equiv);
745
746   if (is_new)
747     set_value_range (old_vr, new_vr->type, new_vr->min, new_vr->max,
748                      new_vr->equiv);
749
750   BITMAP_FREE (new_vr->equiv);
751
752   return is_new;
753 }
754
755
756 /* Add VAR and VAR's equivalence set to EQUIV.  This is the central
757    point where equivalence processing can be turned on/off.  */
758
759 static void
760 add_equivalence (bitmap *equiv, const_tree var)
761 {
762   unsigned ver = SSA_NAME_VERSION (var);
763   value_range_t *vr = vr_value[ver];
764
765   if (*equiv == NULL)
766     *equiv = BITMAP_ALLOC (NULL);
767   bitmap_set_bit (*equiv, ver);
768   if (vr && vr->equiv)
769     bitmap_ior_into (*equiv, vr->equiv);
770 }
771
772
773 /* Return true if VR is ~[0, 0].  */
774
775 static inline bool
776 range_is_nonnull (value_range_t *vr)
777 {
778   return vr->type == VR_ANTI_RANGE
779          && integer_zerop (vr->min)
780          && integer_zerop (vr->max);
781 }
782
783
784 /* Return true if VR is [0, 0].  */
785
786 static inline bool
787 range_is_null (value_range_t *vr)
788 {
789   return vr->type == VR_RANGE
790          && integer_zerop (vr->min)
791          && integer_zerop (vr->max);
792 }
793
794 /* Return true if max and min of VR are INTEGER_CST.  It's not necessary
795    a singleton.  */
796
797 static inline bool
798 range_int_cst_p (value_range_t *vr)
799 {
800   return (vr->type == VR_RANGE
801           && TREE_CODE (vr->max) == INTEGER_CST
802           && TREE_CODE (vr->min) == INTEGER_CST
803           && !TREE_OVERFLOW (vr->max)
804           && !TREE_OVERFLOW (vr->min));
805 }
806
807 /* Return true if VR is a INTEGER_CST singleton.  */
808
809 static inline bool
810 range_int_cst_singleton_p (value_range_t *vr)
811 {
812   return (range_int_cst_p (vr)
813           && tree_int_cst_equal (vr->min, vr->max));
814 }
815
816 /* Return true if value range VR involves at least one symbol.  */
817
818 static inline bool
819 symbolic_range_p (value_range_t *vr)
820 {
821   return (!is_gimple_min_invariant (vr->min)
822           || !is_gimple_min_invariant (vr->max));
823 }
824
825 /* Return true if value range VR uses an overflow infinity.  */
826
827 static inline bool
828 overflow_infinity_range_p (value_range_t *vr)
829 {
830   return (vr->type == VR_RANGE
831           && (is_overflow_infinity (vr->min)
832               || is_overflow_infinity (vr->max)));
833 }
834
835 /* Return false if we can not make a valid comparison based on VR;
836    this will be the case if it uses an overflow infinity and overflow
837    is not undefined (i.e., -fno-strict-overflow is in effect).
838    Otherwise return true, and set *STRICT_OVERFLOW_P to true if VR
839    uses an overflow infinity.  */
840
841 static bool
842 usable_range_p (value_range_t *vr, bool *strict_overflow_p)
843 {
844   gcc_assert (vr->type == VR_RANGE);
845   if (is_overflow_infinity (vr->min))
846     {
847       *strict_overflow_p = true;
848       if (!TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (vr->min)))
849         return false;
850     }
851   if (is_overflow_infinity (vr->max))
852     {
853       *strict_overflow_p = true;
854       if (!TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (vr->max)))
855         return false;
856     }
857   return true;
858 }
859
860
861 /* Like tree_expr_nonnegative_warnv_p, but this function uses value
862    ranges obtained so far.  */
863
864 static bool
865 vrp_expr_computes_nonnegative (tree expr, bool *strict_overflow_p)
866 {
867   return (tree_expr_nonnegative_warnv_p (expr, strict_overflow_p)
868           || (TREE_CODE (expr) == SSA_NAME
869               && ssa_name_nonnegative_p (expr)));
870 }
871
872 /* Return true if the result of assignment STMT is know to be non-negative.
873    If the return value is based on the assumption that signed overflow is
874    undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
875    *STRICT_OVERFLOW_P.*/
876
877 static bool
878 gimple_assign_nonnegative_warnv_p (gimple stmt, bool *strict_overflow_p)
879 {
880   enum tree_code code = gimple_assign_rhs_code (stmt);
881   switch (get_gimple_rhs_class (code))
882     {
883     case GIMPLE_UNARY_RHS:
884       return tree_unary_nonnegative_warnv_p (gimple_assign_rhs_code (stmt),
885                                              gimple_expr_type (stmt),
886                                              gimple_assign_rhs1 (stmt),
887                                              strict_overflow_p);
888     case GIMPLE_BINARY_RHS:
889       return tree_binary_nonnegative_warnv_p (gimple_assign_rhs_code (stmt),
890                                               gimple_expr_type (stmt),
891                                               gimple_assign_rhs1 (stmt),
892                                               gimple_assign_rhs2 (stmt),
893                                               strict_overflow_p);
894     case GIMPLE_TERNARY_RHS:
895       return false;
896     case GIMPLE_SINGLE_RHS:
897       return tree_single_nonnegative_warnv_p (gimple_assign_rhs1 (stmt),
898                                               strict_overflow_p);
899     case GIMPLE_INVALID_RHS:
900       gcc_unreachable ();
901     default:
902       gcc_unreachable ();
903     }
904 }
905
906 /* Return true if return value of call STMT is know to be non-negative.
907    If the return value is based on the assumption that signed overflow is
908    undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
909    *STRICT_OVERFLOW_P.*/
910
911 static bool
912 gimple_call_nonnegative_warnv_p (gimple stmt, bool *strict_overflow_p)
913 {
914   tree arg0 = gimple_call_num_args (stmt) > 0 ?
915     gimple_call_arg (stmt, 0) : NULL_TREE;
916   tree arg1 = gimple_call_num_args (stmt) > 1 ?
917     gimple_call_arg (stmt, 1) : NULL_TREE;
918
919   return tree_call_nonnegative_warnv_p (gimple_expr_type (stmt),
920                                         gimple_call_fndecl (stmt),
921                                         arg0,
922                                         arg1,
923                                         strict_overflow_p);
924 }
925
926 /* Return true if STMT is know to to compute a non-negative value.
927    If the return value is based on the assumption that signed overflow is
928    undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
929    *STRICT_OVERFLOW_P.*/
930
931 static bool
932 gimple_stmt_nonnegative_warnv_p (gimple stmt, bool *strict_overflow_p)
933 {
934   switch (gimple_code (stmt))
935     {
936     case GIMPLE_ASSIGN:
937       return gimple_assign_nonnegative_warnv_p (stmt, strict_overflow_p);
938     case GIMPLE_CALL:
939       return gimple_call_nonnegative_warnv_p (stmt, strict_overflow_p);
940     default:
941       gcc_unreachable ();
942     }
943 }
944
945 /* Return true if the result of assignment STMT is know to be non-zero.
946    If the return value is based on the assumption that signed overflow is
947    undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
948    *STRICT_OVERFLOW_P.*/
949
950 static bool
951 gimple_assign_nonzero_warnv_p (gimple stmt, bool *strict_overflow_p)
952 {
953   enum tree_code code = gimple_assign_rhs_code (stmt);
954   switch (get_gimple_rhs_class (code))
955     {
956     case GIMPLE_UNARY_RHS:
957       return tree_unary_nonzero_warnv_p (gimple_assign_rhs_code (stmt),
958                                          gimple_expr_type (stmt),
959                                          gimple_assign_rhs1 (stmt),
960                                          strict_overflow_p);
961     case GIMPLE_BINARY_RHS:
962       return tree_binary_nonzero_warnv_p (gimple_assign_rhs_code (stmt),
963                                           gimple_expr_type (stmt),
964                                           gimple_assign_rhs1 (stmt),
965                                           gimple_assign_rhs2 (stmt),
966                                           strict_overflow_p);
967     case GIMPLE_TERNARY_RHS:
968       return false;
969     case GIMPLE_SINGLE_RHS:
970       return tree_single_nonzero_warnv_p (gimple_assign_rhs1 (stmt),
971                                           strict_overflow_p);
972     case GIMPLE_INVALID_RHS:
973       gcc_unreachable ();
974     default:
975       gcc_unreachable ();
976     }
977 }
978
979 /* Return true if STMT is know to to compute a non-zero value.
980    If the return value is based on the assumption that signed overflow is
981    undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
982    *STRICT_OVERFLOW_P.*/
983
984 static bool
985 gimple_stmt_nonzero_warnv_p (gimple stmt, bool *strict_overflow_p)
986 {
987   switch (gimple_code (stmt))
988     {
989     case GIMPLE_ASSIGN:
990       return gimple_assign_nonzero_warnv_p (stmt, strict_overflow_p);
991     case GIMPLE_CALL:
992       return gimple_alloca_call_p (stmt);
993     default:
994       gcc_unreachable ();
995     }
996 }
997
998 /* Like tree_expr_nonzero_warnv_p, but this function uses value ranges
999    obtained so far.  */
1000
1001 static bool
1002 vrp_stmt_computes_nonzero (gimple stmt, bool *strict_overflow_p)
1003 {
1004   if (gimple_stmt_nonzero_warnv_p (stmt, strict_overflow_p))
1005     return true;
1006
1007   /* If we have an expression of the form &X->a, then the expression
1008      is nonnull if X is nonnull.  */
1009   if (is_gimple_assign (stmt)
1010       && gimple_assign_rhs_code (stmt) == ADDR_EXPR)
1011     {
1012       tree expr = gimple_assign_rhs1 (stmt);
1013       tree base = get_base_address (TREE_OPERAND (expr, 0));
1014
1015       if (base != NULL_TREE
1016           && TREE_CODE (base) == MEM_REF
1017           && TREE_CODE (TREE_OPERAND (base, 0)) == SSA_NAME)
1018         {
1019           value_range_t *vr = get_value_range (TREE_OPERAND (base, 0));
1020           if (range_is_nonnull (vr))
1021             return true;
1022         }
1023     }
1024
1025   return false;
1026 }
1027
1028 /* Returns true if EXPR is a valid value (as expected by compare_values) --
1029    a gimple invariant, or SSA_NAME +- CST.  */
1030
1031 static bool
1032 valid_value_p (tree expr)
1033 {
1034   if (TREE_CODE (expr) == SSA_NAME)
1035     return true;
1036
1037   if (TREE_CODE (expr) == PLUS_EXPR
1038       || TREE_CODE (expr) == MINUS_EXPR)
1039     return (TREE_CODE (TREE_OPERAND (expr, 0)) == SSA_NAME
1040             && TREE_CODE (TREE_OPERAND (expr, 1)) == INTEGER_CST);
1041
1042   return is_gimple_min_invariant (expr);
1043 }
1044
1045 /* Return
1046    1 if VAL < VAL2
1047    0 if !(VAL < VAL2)
1048    -2 if those are incomparable.  */
1049 static inline int
1050 operand_less_p (tree val, tree val2)
1051 {
1052   /* LT is folded faster than GE and others.  Inline the common case.  */
1053   if (TREE_CODE (val) == INTEGER_CST && TREE_CODE (val2) == INTEGER_CST)
1054     {
1055       if (TYPE_UNSIGNED (TREE_TYPE (val)))
1056         return INT_CST_LT_UNSIGNED (val, val2);
1057       else
1058         {
1059           if (INT_CST_LT (val, val2))
1060             return 1;
1061         }
1062     }
1063   else
1064     {
1065       tree tcmp;
1066
1067       fold_defer_overflow_warnings ();
1068
1069       tcmp = fold_binary_to_constant (LT_EXPR, boolean_type_node, val, val2);
1070
1071       fold_undefer_and_ignore_overflow_warnings ();
1072
1073       if (!tcmp
1074           || TREE_CODE (tcmp) != INTEGER_CST)
1075         return -2;
1076
1077       if (!integer_zerop (tcmp))
1078         return 1;
1079     }
1080
1081   /* val >= val2, not considering overflow infinity.  */
1082   if (is_negative_overflow_infinity (val))
1083     return is_negative_overflow_infinity (val2) ? 0 : 1;
1084   else if (is_positive_overflow_infinity (val2))
1085     return is_positive_overflow_infinity (val) ? 0 : 1;
1086
1087   return 0;
1088 }
1089
1090 /* Compare two values VAL1 and VAL2.  Return
1091
1092         -2 if VAL1 and VAL2 cannot be compared at compile-time,
1093         -1 if VAL1 < VAL2,
1094          0 if VAL1 == VAL2,
1095         +1 if VAL1 > VAL2, and
1096         +2 if VAL1 != VAL2
1097
1098    This is similar to tree_int_cst_compare but supports pointer values
1099    and values that cannot be compared at compile time.
1100
1101    If STRICT_OVERFLOW_P is not NULL, then set *STRICT_OVERFLOW_P to
1102    true if the return value is only valid if we assume that signed
1103    overflow is undefined.  */
1104
1105 static int
1106 compare_values_warnv (tree val1, tree val2, bool *strict_overflow_p)
1107 {
1108   if (val1 == val2)
1109     return 0;
1110
1111   /* Below we rely on the fact that VAL1 and VAL2 are both pointers or
1112      both integers.  */
1113   gcc_assert (POINTER_TYPE_P (TREE_TYPE (val1))
1114               == POINTER_TYPE_P (TREE_TYPE (val2)));
1115   /* Convert the two values into the same type.  This is needed because
1116      sizetype causes sign extension even for unsigned types.  */
1117   val2 = fold_convert (TREE_TYPE (val1), val2);
1118   STRIP_USELESS_TYPE_CONVERSION (val2);
1119
1120   if ((TREE_CODE (val1) == SSA_NAME
1121        || TREE_CODE (val1) == PLUS_EXPR
1122        || TREE_CODE (val1) == MINUS_EXPR)
1123       && (TREE_CODE (val2) == SSA_NAME
1124           || TREE_CODE (val2) == PLUS_EXPR
1125           || TREE_CODE (val2) == MINUS_EXPR))
1126     {
1127       tree n1, c1, n2, c2;
1128       enum tree_code code1, code2;
1129
1130       /* If VAL1 and VAL2 are of the form 'NAME [+-] CST' or 'NAME',
1131          return -1 or +1 accordingly.  If VAL1 and VAL2 don't use the
1132          same name, return -2.  */
1133       if (TREE_CODE (val1) == SSA_NAME)
1134         {
1135           code1 = SSA_NAME;
1136           n1 = val1;
1137           c1 = NULL_TREE;
1138         }
1139       else
1140         {
1141           code1 = TREE_CODE (val1);
1142           n1 = TREE_OPERAND (val1, 0);
1143           c1 = TREE_OPERAND (val1, 1);
1144           if (tree_int_cst_sgn (c1) == -1)
1145             {
1146               if (is_negative_overflow_infinity (c1))
1147                 return -2;
1148               c1 = fold_unary_to_constant (NEGATE_EXPR, TREE_TYPE (c1), c1);
1149               if (!c1)
1150                 return -2;
1151               code1 = code1 == MINUS_EXPR ? PLUS_EXPR : MINUS_EXPR;
1152             }
1153         }
1154
1155       if (TREE_CODE (val2) == SSA_NAME)
1156         {
1157           code2 = SSA_NAME;
1158           n2 = val2;
1159           c2 = NULL_TREE;
1160         }
1161       else
1162         {
1163           code2 = TREE_CODE (val2);
1164           n2 = TREE_OPERAND (val2, 0);
1165           c2 = TREE_OPERAND (val2, 1);
1166           if (tree_int_cst_sgn (c2) == -1)
1167             {
1168               if (is_negative_overflow_infinity (c2))
1169                 return -2;
1170               c2 = fold_unary_to_constant (NEGATE_EXPR, TREE_TYPE (c2), c2);
1171               if (!c2)
1172                 return -2;
1173               code2 = code2 == MINUS_EXPR ? PLUS_EXPR : MINUS_EXPR;
1174             }
1175         }
1176
1177       /* Both values must use the same name.  */
1178       if (n1 != n2)
1179         return -2;
1180
1181       if (code1 == SSA_NAME
1182           && code2 == SSA_NAME)
1183         /* NAME == NAME  */
1184         return 0;
1185
1186       /* If overflow is defined we cannot simplify more.  */
1187       if (!TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1)))
1188         return -2;
1189
1190       if (strict_overflow_p != NULL
1191           && (code1 == SSA_NAME || !TREE_NO_WARNING (val1))
1192           && (code2 == SSA_NAME || !TREE_NO_WARNING (val2)))
1193         *strict_overflow_p = true;
1194
1195       if (code1 == SSA_NAME)
1196         {
1197           if (code2 == PLUS_EXPR)
1198             /* NAME < NAME + CST  */
1199             return -1;
1200           else if (code2 == MINUS_EXPR)
1201             /* NAME > NAME - CST  */
1202             return 1;
1203         }
1204       else if (code1 == PLUS_EXPR)
1205         {
1206           if (code2 == SSA_NAME)
1207             /* NAME + CST > NAME  */
1208             return 1;
1209           else if (code2 == PLUS_EXPR)
1210             /* NAME + CST1 > NAME + CST2, if CST1 > CST2  */
1211             return compare_values_warnv (c1, c2, strict_overflow_p);
1212           else if (code2 == MINUS_EXPR)
1213             /* NAME + CST1 > NAME - CST2  */
1214             return 1;
1215         }
1216       else if (code1 == MINUS_EXPR)
1217         {
1218           if (code2 == SSA_NAME)
1219             /* NAME - CST < NAME  */
1220             return -1;
1221           else if (code2 == PLUS_EXPR)
1222             /* NAME - CST1 < NAME + CST2  */
1223             return -1;
1224           else if (code2 == MINUS_EXPR)
1225             /* NAME - CST1 > NAME - CST2, if CST1 < CST2.  Notice that
1226                C1 and C2 are swapped in the call to compare_values.  */
1227             return compare_values_warnv (c2, c1, strict_overflow_p);
1228         }
1229
1230       gcc_unreachable ();
1231     }
1232
1233   /* We cannot compare non-constants.  */
1234   if (!is_gimple_min_invariant (val1) || !is_gimple_min_invariant (val2))
1235     return -2;
1236
1237   if (!POINTER_TYPE_P (TREE_TYPE (val1)))
1238     {
1239       /* We cannot compare overflowed values, except for overflow
1240          infinities.  */
1241       if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
1242         {
1243           if (strict_overflow_p != NULL)
1244             *strict_overflow_p = true;
1245           if (is_negative_overflow_infinity (val1))
1246             return is_negative_overflow_infinity (val2) ? 0 : -1;
1247           else if (is_negative_overflow_infinity (val2))
1248             return 1;
1249           else if (is_positive_overflow_infinity (val1))
1250             return is_positive_overflow_infinity (val2) ? 0 : 1;
1251           else if (is_positive_overflow_infinity (val2))
1252             return -1;
1253           return -2;
1254         }
1255
1256       return tree_int_cst_compare (val1, val2);
1257     }
1258   else
1259     {
1260       tree t;
1261
1262       /* First see if VAL1 and VAL2 are not the same.  */
1263       if (val1 == val2 || operand_equal_p (val1, val2, 0))
1264         return 0;
1265
1266       /* If VAL1 is a lower address than VAL2, return -1.  */
1267       if (operand_less_p (val1, val2) == 1)
1268         return -1;
1269
1270       /* If VAL1 is a higher address than VAL2, return +1.  */
1271       if (operand_less_p (val2, val1) == 1)
1272         return 1;
1273
1274       /* If VAL1 is different than VAL2, return +2.
1275          For integer constants we either have already returned -1 or 1
1276          or they are equivalent.  We still might succeed in proving
1277          something about non-trivial operands.  */
1278       if (TREE_CODE (val1) != INTEGER_CST
1279           || TREE_CODE (val2) != INTEGER_CST)
1280         {
1281           t = fold_binary_to_constant (NE_EXPR, boolean_type_node, val1, val2);
1282           if (t && integer_onep (t))
1283             return 2;
1284         }
1285
1286       return -2;
1287     }
1288 }
1289
1290 /* Compare values like compare_values_warnv, but treat comparisons of
1291    nonconstants which rely on undefined overflow as incomparable.  */
1292
1293 static int
1294 compare_values (tree val1, tree val2)
1295 {
1296   bool sop;
1297   int ret;
1298
1299   sop = false;
1300   ret = compare_values_warnv (val1, val2, &sop);
1301   if (sop
1302       && (!is_gimple_min_invariant (val1) || !is_gimple_min_invariant (val2)))
1303     ret = -2;
1304   return ret;
1305 }
1306
1307
1308 /* Return 1 if VAL is inside value range VR (VR->MIN <= VAL <= VR->MAX),
1309           0 if VAL is not inside VR,
1310          -2 if we cannot tell either way.
1311
1312    FIXME, the current semantics of this functions are a bit quirky
1313           when taken in the context of VRP.  In here we do not care
1314           about VR's type.  If VR is the anti-range ~[3, 5] the call
1315           value_inside_range (4, VR) will return 1.
1316
1317           This is counter-intuitive in a strict sense, but the callers
1318           currently expect this.  They are calling the function
1319           merely to determine whether VR->MIN <= VAL <= VR->MAX.  The
1320           callers are applying the VR_RANGE/VR_ANTI_RANGE semantics
1321           themselves.
1322
1323           This also applies to value_ranges_intersect_p and
1324           range_includes_zero_p.  The semantics of VR_RANGE and
1325           VR_ANTI_RANGE should be encoded here, but that also means
1326           adapting the users of these functions to the new semantics.
1327
1328    Benchmark compile/20001226-1.c compilation time after changing this
1329    function.  */
1330
1331 static inline int
1332 value_inside_range (tree val, value_range_t * vr)
1333 {
1334   int cmp1, cmp2;
1335
1336   cmp1 = operand_less_p (val, vr->min);
1337   if (cmp1 == -2)
1338     return -2;
1339   if (cmp1 == 1)
1340     return 0;
1341
1342   cmp2 = operand_less_p (vr->max, val);
1343   if (cmp2 == -2)
1344     return -2;
1345
1346   return !cmp2;
1347 }
1348
1349
1350 /* Return true if value ranges VR0 and VR1 have a non-empty
1351    intersection.
1352
1353    Benchmark compile/20001226-1.c compilation time after changing this
1354    function.
1355    */
1356
1357 static inline bool
1358 value_ranges_intersect_p (value_range_t *vr0, value_range_t *vr1)
1359 {
1360   /* The value ranges do not intersect if the maximum of the first range is
1361      less than the minimum of the second range or vice versa.
1362      When those relations are unknown, we can't do any better.  */
1363   if (operand_less_p (vr0->max, vr1->min) != 0)
1364     return false;
1365   if (operand_less_p (vr1->max, vr0->min) != 0)
1366     return false;
1367   return true;
1368 }
1369
1370
1371 /* Return true if VR includes the value zero, false otherwise.  FIXME,
1372    currently this will return false for an anti-range like ~[-4, 3].
1373    This will be wrong when the semantics of value_inside_range are
1374    modified (currently the users of this function expect these
1375    semantics).  */
1376
1377 static inline bool
1378 range_includes_zero_p (value_range_t *vr)
1379 {
1380   tree zero;
1381
1382   gcc_assert (vr->type != VR_UNDEFINED
1383               && vr->type != VR_VARYING
1384               && !symbolic_range_p (vr));
1385
1386   zero = build_int_cst (TREE_TYPE (vr->min), 0);
1387   return (value_inside_range (zero, vr) == 1);
1388 }
1389
1390 /* Return true if T, an SSA_NAME, is known to be nonnegative.  Return
1391    false otherwise or if no value range information is available.  */
1392
1393 bool
1394 ssa_name_nonnegative_p (const_tree t)
1395 {
1396   value_range_t *vr = get_value_range (t);
1397
1398   if (INTEGRAL_TYPE_P (t)
1399       && TYPE_UNSIGNED (t))
1400     return true;
1401
1402   if (!vr)
1403     return false;
1404
1405   /* Testing for VR_ANTI_RANGE is not useful here as any anti-range
1406      which would return a useful value should be encoded as a VR_RANGE.  */
1407   if (vr->type == VR_RANGE)
1408     {
1409       int result = compare_values (vr->min, integer_zero_node);
1410
1411       return (result == 0 || result == 1);
1412     }
1413   return false;
1414 }
1415
1416 /* If OP has a value range with a single constant value return that,
1417    otherwise return NULL_TREE.  This returns OP itself if OP is a
1418    constant.  */
1419
1420 static tree
1421 op_with_constant_singleton_value_range (tree op)
1422 {
1423   value_range_t *vr;
1424
1425   if (is_gimple_min_invariant (op))
1426     return op;
1427
1428   if (TREE_CODE (op) != SSA_NAME)
1429     return NULL_TREE;
1430
1431   vr = get_value_range (op);
1432   if (vr->type == VR_RANGE
1433       && operand_equal_p (vr->min, vr->max, 0)
1434       && is_gimple_min_invariant (vr->min))
1435     return vr->min;
1436
1437   return NULL_TREE;
1438 }
1439
1440
1441 /* Extract value range information from an ASSERT_EXPR EXPR and store
1442    it in *VR_P.  */
1443
1444 static void
1445 extract_range_from_assert (value_range_t *vr_p, tree expr)
1446 {
1447   tree var, cond, limit, min, max, type;
1448   value_range_t *var_vr, *limit_vr;
1449   enum tree_code cond_code;
1450
1451   var = ASSERT_EXPR_VAR (expr);
1452   cond = ASSERT_EXPR_COND (expr);
1453
1454   gcc_assert (COMPARISON_CLASS_P (cond));
1455
1456   /* Find VAR in the ASSERT_EXPR conditional.  */
1457   if (var == TREE_OPERAND (cond, 0)
1458       || TREE_CODE (TREE_OPERAND (cond, 0)) == PLUS_EXPR
1459       || TREE_CODE (TREE_OPERAND (cond, 0)) == NOP_EXPR)
1460     {
1461       /* If the predicate is of the form VAR COMP LIMIT, then we just
1462          take LIMIT from the RHS and use the same comparison code.  */
1463       cond_code = TREE_CODE (cond);
1464       limit = TREE_OPERAND (cond, 1);
1465       cond = TREE_OPERAND (cond, 0);
1466     }
1467   else
1468     {
1469       /* If the predicate is of the form LIMIT COMP VAR, then we need
1470          to flip around the comparison code to create the proper range
1471          for VAR.  */
1472       cond_code = swap_tree_comparison (TREE_CODE (cond));
1473       limit = TREE_OPERAND (cond, 0);
1474       cond = TREE_OPERAND (cond, 1);
1475     }
1476
1477   limit = avoid_overflow_infinity (limit);
1478
1479   type = TREE_TYPE (limit);
1480   gcc_assert (limit != var);
1481
1482   /* For pointer arithmetic, we only keep track of pointer equality
1483      and inequality.  */
1484   if (POINTER_TYPE_P (type) && cond_code != NE_EXPR && cond_code != EQ_EXPR)
1485     {
1486       set_value_range_to_varying (vr_p);
1487       return;
1488     }
1489
1490   /* If LIMIT is another SSA name and LIMIT has a range of its own,
1491      try to use LIMIT's range to avoid creating symbolic ranges
1492      unnecessarily. */
1493   limit_vr = (TREE_CODE (limit) == SSA_NAME) ? get_value_range (limit) : NULL;
1494
1495   /* LIMIT's range is only interesting if it has any useful information.  */
1496   if (limit_vr
1497       && (limit_vr->type == VR_UNDEFINED
1498           || limit_vr->type == VR_VARYING
1499           || symbolic_range_p (limit_vr)))
1500     limit_vr = NULL;
1501
1502   /* Initially, the new range has the same set of equivalences of
1503      VAR's range.  This will be revised before returning the final
1504      value.  Since assertions may be chained via mutually exclusive
1505      predicates, we will need to trim the set of equivalences before
1506      we are done.  */
1507   gcc_assert (vr_p->equiv == NULL);
1508   add_equivalence (&vr_p->equiv, var);
1509
1510   /* Extract a new range based on the asserted comparison for VAR and
1511      LIMIT's value range.  Notice that if LIMIT has an anti-range, we
1512      will only use it for equality comparisons (EQ_EXPR).  For any
1513      other kind of assertion, we cannot derive a range from LIMIT's
1514      anti-range that can be used to describe the new range.  For
1515      instance, ASSERT_EXPR <x_2, x_2 <= b_4>.  If b_4 is ~[2, 10],
1516      then b_4 takes on the ranges [-INF, 1] and [11, +INF].  There is
1517      no single range for x_2 that could describe LE_EXPR, so we might
1518      as well build the range [b_4, +INF] for it.
1519      One special case we handle is extracting a range from a
1520      range test encoded as (unsigned)var + CST <= limit.  */
1521   if (TREE_CODE (cond) == NOP_EXPR
1522       || TREE_CODE (cond) == PLUS_EXPR)
1523     {
1524       if (TREE_CODE (cond) == PLUS_EXPR)
1525         {
1526           min = fold_build1 (NEGATE_EXPR, TREE_TYPE (TREE_OPERAND (cond, 1)),
1527                              TREE_OPERAND (cond, 1));
1528           max = int_const_binop (PLUS_EXPR, limit, min, 0);
1529           cond = TREE_OPERAND (cond, 0);
1530         }
1531       else
1532         {
1533           min = build_int_cst (TREE_TYPE (var), 0);
1534           max = limit;
1535         }
1536
1537       /* Make sure to not set TREE_OVERFLOW on the final type
1538          conversion.  We are willingly interpreting large positive
1539          unsigned values as negative singed values here.  */
1540       min = force_fit_type_double (TREE_TYPE (var), tree_to_double_int (min),
1541                                    0, false);
1542       max = force_fit_type_double (TREE_TYPE (var), tree_to_double_int (max),
1543                                    0, false);
1544
1545       /* We can transform a max, min range to an anti-range or
1546          vice-versa.  Use set_and_canonicalize_value_range which does
1547          this for us.  */
1548       if (cond_code == LE_EXPR)
1549         set_and_canonicalize_value_range (vr_p, VR_RANGE,
1550                                           min, max, vr_p->equiv);
1551       else if (cond_code == GT_EXPR)
1552         set_and_canonicalize_value_range (vr_p, VR_ANTI_RANGE,
1553                                           min, max, vr_p->equiv);
1554       else
1555         gcc_unreachable ();
1556     }
1557   else if (cond_code == EQ_EXPR)
1558     {
1559       enum value_range_type range_type;
1560
1561       if (limit_vr)
1562         {
1563           range_type = limit_vr->type;
1564           min = limit_vr->min;
1565           max = limit_vr->max;
1566         }
1567       else
1568         {
1569           range_type = VR_RANGE;
1570           min = limit;
1571           max = limit;
1572         }
1573
1574       set_value_range (vr_p, range_type, min, max, vr_p->equiv);
1575
1576       /* When asserting the equality VAR == LIMIT and LIMIT is another
1577          SSA name, the new range will also inherit the equivalence set
1578          from LIMIT.  */
1579       if (TREE_CODE (limit) == SSA_NAME)
1580         add_equivalence (&vr_p->equiv, limit);
1581     }
1582   else if (cond_code == NE_EXPR)
1583     {
1584       /* As described above, when LIMIT's range is an anti-range and
1585          this assertion is an inequality (NE_EXPR), then we cannot
1586          derive anything from the anti-range.  For instance, if
1587          LIMIT's range was ~[0, 0], the assertion 'VAR != LIMIT' does
1588          not imply that VAR's range is [0, 0].  So, in the case of
1589          anti-ranges, we just assert the inequality using LIMIT and
1590          not its anti-range.
1591
1592          If LIMIT_VR is a range, we can only use it to build a new
1593          anti-range if LIMIT_VR is a single-valued range.  For
1594          instance, if LIMIT_VR is [0, 1], the predicate
1595          VAR != [0, 1] does not mean that VAR's range is ~[0, 1].
1596          Rather, it means that for value 0 VAR should be ~[0, 0]
1597          and for value 1, VAR should be ~[1, 1].  We cannot
1598          represent these ranges.
1599
1600          The only situation in which we can build a valid
1601          anti-range is when LIMIT_VR is a single-valued range
1602          (i.e., LIMIT_VR->MIN == LIMIT_VR->MAX).  In that case,
1603          build the anti-range ~[LIMIT_VR->MIN, LIMIT_VR->MAX].  */
1604       if (limit_vr
1605           && limit_vr->type == VR_RANGE
1606           && compare_values (limit_vr->min, limit_vr->max) == 0)
1607         {
1608           min = limit_vr->min;
1609           max = limit_vr->max;
1610         }
1611       else
1612         {
1613           /* In any other case, we cannot use LIMIT's range to build a
1614              valid anti-range.  */
1615           min = max = limit;
1616         }
1617
1618       /* If MIN and MAX cover the whole range for their type, then
1619          just use the original LIMIT.  */
1620       if (INTEGRAL_TYPE_P (type)
1621           && vrp_val_is_min (min)
1622           && vrp_val_is_max (max))
1623         min = max = limit;
1624
1625       set_value_range (vr_p, VR_ANTI_RANGE, min, max, vr_p->equiv);
1626     }
1627   else if (cond_code == LE_EXPR || cond_code == LT_EXPR)
1628     {
1629       min = TYPE_MIN_VALUE (type);
1630
1631       if (limit_vr == NULL || limit_vr->type == VR_ANTI_RANGE)
1632         max = limit;
1633       else
1634         {
1635           /* If LIMIT_VR is of the form [N1, N2], we need to build the
1636              range [MIN, N2] for LE_EXPR and [MIN, N2 - 1] for
1637              LT_EXPR.  */
1638           max = limit_vr->max;
1639         }
1640
1641       /* If the maximum value forces us to be out of bounds, simply punt.
1642          It would be pointless to try and do anything more since this
1643          all should be optimized away above us.  */
1644       if ((cond_code == LT_EXPR
1645            && compare_values (max, min) == 0)
1646           || (CONSTANT_CLASS_P (max) && TREE_OVERFLOW (max)))
1647         set_value_range_to_varying (vr_p);
1648       else
1649         {
1650           /* For LT_EXPR, we create the range [MIN, MAX - 1].  */
1651           if (cond_code == LT_EXPR)
1652             {
1653               tree one = build_int_cst (type, 1);
1654               max = fold_build2 (MINUS_EXPR, type, max, one);
1655               if (EXPR_P (max))
1656                 TREE_NO_WARNING (max) = 1;
1657             }
1658
1659           set_value_range (vr_p, VR_RANGE, min, max, vr_p->equiv);
1660         }
1661     }
1662   else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
1663     {
1664       max = TYPE_MAX_VALUE (type);
1665
1666       if (limit_vr == NULL || limit_vr->type == VR_ANTI_RANGE)
1667         min = limit;
1668       else
1669         {
1670           /* If LIMIT_VR is of the form [N1, N2], we need to build the
1671              range [N1, MAX] for GE_EXPR and [N1 + 1, MAX] for
1672              GT_EXPR.  */
1673           min = limit_vr->min;
1674         }
1675
1676       /* If the minimum value forces us to be out of bounds, simply punt.
1677          It would be pointless to try and do anything more since this
1678          all should be optimized away above us.  */
1679       if ((cond_code == GT_EXPR
1680            && compare_values (min, max) == 0)
1681           || (CONSTANT_CLASS_P (min) && TREE_OVERFLOW (min)))
1682         set_value_range_to_varying (vr_p);
1683       else
1684         {
1685           /* For GT_EXPR, we create the range [MIN + 1, MAX].  */
1686           if (cond_code == GT_EXPR)
1687             {
1688               tree one = build_int_cst (type, 1);
1689               min = fold_build2 (PLUS_EXPR, type, min, one);
1690               if (EXPR_P (min))
1691                 TREE_NO_WARNING (min) = 1;
1692             }
1693
1694           set_value_range (vr_p, VR_RANGE, min, max, vr_p->equiv);
1695         }
1696     }
1697   else
1698     gcc_unreachable ();
1699
1700   /* If VAR already had a known range, it may happen that the new
1701      range we have computed and VAR's range are not compatible.  For
1702      instance,
1703
1704         if (p_5 == NULL)
1705           p_6 = ASSERT_EXPR <p_5, p_5 == NULL>;
1706           x_7 = p_6->fld;
1707           p_8 = ASSERT_EXPR <p_6, p_6 != NULL>;
1708
1709      While the above comes from a faulty program, it will cause an ICE
1710      later because p_8 and p_6 will have incompatible ranges and at
1711      the same time will be considered equivalent.  A similar situation
1712      would arise from
1713
1714         if (i_5 > 10)
1715           i_6 = ASSERT_EXPR <i_5, i_5 > 10>;
1716           if (i_5 < 5)
1717             i_7 = ASSERT_EXPR <i_6, i_6 < 5>;
1718
1719      Again i_6 and i_7 will have incompatible ranges.  It would be
1720      pointless to try and do anything with i_7's range because
1721      anything dominated by 'if (i_5 < 5)' will be optimized away.
1722      Note, due to the wa in which simulation proceeds, the statement
1723      i_7 = ASSERT_EXPR <...> we would never be visited because the
1724      conditional 'if (i_5 < 5)' always evaluates to false.  However,
1725      this extra check does not hurt and may protect against future
1726      changes to VRP that may get into a situation similar to the
1727      NULL pointer dereference example.
1728
1729      Note that these compatibility tests are only needed when dealing
1730      with ranges or a mix of range and anti-range.  If VAR_VR and VR_P
1731      are both anti-ranges, they will always be compatible, because two
1732      anti-ranges will always have a non-empty intersection.  */
1733
1734   var_vr = get_value_range (var);
1735
1736   /* We may need to make adjustments when VR_P and VAR_VR are numeric
1737      ranges or anti-ranges.  */
1738   if (vr_p->type == VR_VARYING
1739       || vr_p->type == VR_UNDEFINED
1740       || var_vr->type == VR_VARYING
1741       || var_vr->type == VR_UNDEFINED
1742       || symbolic_range_p (vr_p)
1743       || symbolic_range_p (var_vr))
1744     return;
1745
1746   if (var_vr->type == VR_RANGE && vr_p->type == VR_RANGE)
1747     {
1748       /* If the two ranges have a non-empty intersection, we can
1749          refine the resulting range.  Since the assert expression
1750          creates an equivalency and at the same time it asserts a
1751          predicate, we can take the intersection of the two ranges to
1752          get better precision.  */
1753       if (value_ranges_intersect_p (var_vr, vr_p))
1754         {
1755           /* Use the larger of the two minimums.  */
1756           if (compare_values (vr_p->min, var_vr->min) == -1)
1757             min = var_vr->min;
1758           else
1759             min = vr_p->min;
1760
1761           /* Use the smaller of the two maximums.  */
1762           if (compare_values (vr_p->max, var_vr->max) == 1)
1763             max = var_vr->max;
1764           else
1765             max = vr_p->max;
1766
1767           set_value_range (vr_p, vr_p->type, min, max, vr_p->equiv);
1768         }
1769       else
1770         {
1771           /* The two ranges do not intersect, set the new range to
1772              VARYING, because we will not be able to do anything
1773              meaningful with it.  */
1774           set_value_range_to_varying (vr_p);
1775         }
1776     }
1777   else if ((var_vr->type == VR_RANGE && vr_p->type == VR_ANTI_RANGE)
1778            || (var_vr->type == VR_ANTI_RANGE && vr_p->type == VR_RANGE))
1779     {
1780       /* A range and an anti-range will cancel each other only if
1781          their ends are the same.  For instance, in the example above,
1782          p_8's range ~[0, 0] and p_6's range [0, 0] are incompatible,
1783          so VR_P should be set to VR_VARYING.  */
1784       if (compare_values (var_vr->min, vr_p->min) == 0
1785           && compare_values (var_vr->max, vr_p->max) == 0)
1786         set_value_range_to_varying (vr_p);
1787       else
1788         {
1789           tree min, max, anti_min, anti_max, real_min, real_max;
1790           int cmp;
1791
1792           /* We want to compute the logical AND of the two ranges;
1793              there are three cases to consider.
1794
1795
1796              1. The VR_ANTI_RANGE range is completely within the
1797                 VR_RANGE and the endpoints of the ranges are
1798                 different.  In that case the resulting range
1799                 should be whichever range is more precise.
1800                 Typically that will be the VR_RANGE.
1801
1802              2. The VR_ANTI_RANGE is completely disjoint from
1803                 the VR_RANGE.  In this case the resulting range
1804                 should be the VR_RANGE.
1805
1806              3. There is some overlap between the VR_ANTI_RANGE
1807                 and the VR_RANGE.
1808
1809                 3a. If the high limit of the VR_ANTI_RANGE resides
1810                     within the VR_RANGE, then the result is a new
1811                     VR_RANGE starting at the high limit of the
1812                     VR_ANTI_RANGE + 1 and extending to the
1813                     high limit of the original VR_RANGE.
1814
1815                 3b. If the low limit of the VR_ANTI_RANGE resides
1816                     within the VR_RANGE, then the result is a new
1817                     VR_RANGE starting at the low limit of the original
1818                     VR_RANGE and extending to the low limit of the
1819                     VR_ANTI_RANGE - 1.  */
1820           if (vr_p->type == VR_ANTI_RANGE)
1821             {
1822               anti_min = vr_p->min;
1823               anti_max = vr_p->max;
1824               real_min = var_vr->min;
1825               real_max = var_vr->max;
1826             }
1827           else
1828             {
1829               anti_min = var_vr->min;
1830               anti_max = var_vr->max;
1831               real_min = vr_p->min;
1832               real_max = vr_p->max;
1833             }
1834
1835
1836           /* Case 1, VR_ANTI_RANGE completely within VR_RANGE,
1837              not including any endpoints.  */
1838           if (compare_values (anti_max, real_max) == -1
1839               && compare_values (anti_min, real_min) == 1)
1840             {
1841               /* If the range is covering the whole valid range of
1842                  the type keep the anti-range.  */
1843               if (!vrp_val_is_min (real_min)
1844                   || !vrp_val_is_max (real_max))
1845                 set_value_range (vr_p, VR_RANGE, real_min,
1846                                  real_max, vr_p->equiv);
1847             }
1848           /* Case 2, VR_ANTI_RANGE completely disjoint from
1849              VR_RANGE.  */
1850           else if (compare_values (anti_min, real_max) == 1
1851                    || compare_values (anti_max, real_min) == -1)
1852             {
1853               set_value_range (vr_p, VR_RANGE, real_min,
1854                                real_max, vr_p->equiv);
1855             }
1856           /* Case 3a, the anti-range extends into the low
1857              part of the real range.  Thus creating a new
1858              low for the real range.  */
1859           else if (((cmp = compare_values (anti_max, real_min)) == 1
1860                     || cmp == 0)
1861                    && compare_values (anti_max, real_max) == -1)
1862             {
1863               gcc_assert (!is_positive_overflow_infinity (anti_max));
1864               if (needs_overflow_infinity (TREE_TYPE (anti_max))
1865                   && vrp_val_is_max (anti_max))
1866                 {
1867                   if (!supports_overflow_infinity (TREE_TYPE (var_vr->min)))
1868                     {
1869                       set_value_range_to_varying (vr_p);
1870                       return;
1871                     }
1872                   min = positive_overflow_infinity (TREE_TYPE (var_vr->min));
1873                 }
1874               else if (!POINTER_TYPE_P (TREE_TYPE (var_vr->min)))
1875                 min = fold_build2 (PLUS_EXPR, TREE_TYPE (var_vr->min),
1876                                    anti_max,
1877                                    build_int_cst (TREE_TYPE (var_vr->min), 1));
1878               else
1879                 min = fold_build2 (POINTER_PLUS_EXPR, TREE_TYPE (var_vr->min),
1880                                    anti_max, size_int (1));
1881               max = real_max;
1882               set_value_range (vr_p, VR_RANGE, min, max, vr_p->equiv);
1883             }
1884           /* Case 3b, the anti-range extends into the high
1885              part of the real range.  Thus creating a new
1886              higher for the real range.  */
1887           else if (compare_values (anti_min, real_min) == 1
1888                    && ((cmp = compare_values (anti_min, real_max)) == -1
1889                        || cmp == 0))
1890             {
1891               gcc_assert (!is_negative_overflow_infinity (anti_min));
1892               if (needs_overflow_infinity (TREE_TYPE (anti_min))
1893                   && vrp_val_is_min (anti_min))
1894                 {
1895                   if (!supports_overflow_infinity (TREE_TYPE (var_vr->min)))
1896                     {
1897                       set_value_range_to_varying (vr_p);
1898                       return;
1899                     }
1900                   max = negative_overflow_infinity (TREE_TYPE (var_vr->min));
1901                 }
1902               else if (!POINTER_TYPE_P (TREE_TYPE (var_vr->min)))
1903                 max = fold_build2 (MINUS_EXPR, TREE_TYPE (var_vr->min),
1904                                    anti_min,
1905                                    build_int_cst (TREE_TYPE (var_vr->min), 1));
1906               else
1907                 max = fold_build2 (POINTER_PLUS_EXPR, TREE_TYPE (var_vr->min),
1908                                    anti_min,
1909                                    size_int (-1));
1910               min = real_min;
1911               set_value_range (vr_p, VR_RANGE, min, max, vr_p->equiv);
1912             }
1913         }
1914     }
1915 }
1916
1917
1918 /* Extract range information from SSA name VAR and store it in VR.  If
1919    VAR has an interesting range, use it.  Otherwise, create the
1920    range [VAR, VAR] and return it.  This is useful in situations where
1921    we may have conditionals testing values of VARYING names.  For
1922    instance,
1923
1924         x_3 = y_5;
1925         if (x_3 > y_5)
1926           ...
1927
1928     Even if y_5 is deemed VARYING, we can determine that x_3 > y_5 is
1929     always false.  */
1930
1931 static void
1932 extract_range_from_ssa_name (value_range_t *vr, tree var)
1933 {
1934   value_range_t *var_vr = get_value_range (var);
1935
1936   if (var_vr->type != VR_UNDEFINED && var_vr->type != VR_VARYING)
1937     copy_value_range (vr, var_vr);
1938   else
1939     set_value_range (vr, VR_RANGE, var, var, NULL);
1940
1941   add_equivalence (&vr->equiv, var);
1942 }
1943
1944
1945 /* Wrapper around int_const_binop.  If the operation overflows and we
1946    are not using wrapping arithmetic, then adjust the result to be
1947    -INF or +INF depending on CODE, VAL1 and VAL2.  This can return
1948    NULL_TREE if we need to use an overflow infinity representation but
1949    the type does not support it.  */
1950
1951 static tree
1952 vrp_int_const_binop (enum tree_code code, tree val1, tree val2)
1953 {
1954   tree res;
1955
1956   res = int_const_binop (code, val1, val2, 0);
1957
1958   /* If we are using unsigned arithmetic, operate symbolically
1959      on -INF and +INF as int_const_binop only handles signed overflow.  */
1960   if (TYPE_UNSIGNED (TREE_TYPE (val1)))
1961     {
1962       int checkz = compare_values (res, val1);
1963       bool overflow = false;
1964
1965       /* Ensure that res = val1 [+*] val2 >= val1
1966          or that res = val1 - val2 <= val1.  */
1967       if ((code == PLUS_EXPR
1968            && !(checkz == 1 || checkz == 0))
1969           || (code == MINUS_EXPR
1970               && !(checkz == 0 || checkz == -1)))
1971         {
1972           overflow = true;
1973         }
1974       /* Checking for multiplication overflow is done by dividing the
1975          output of the multiplication by the first input of the
1976          multiplication.  If the result of that division operation is
1977          not equal to the second input of the multiplication, then the
1978          multiplication overflowed.  */
1979       else if (code == MULT_EXPR && !integer_zerop (val1))
1980         {
1981           tree tmp = int_const_binop (TRUNC_DIV_EXPR,
1982                                       res,
1983                                       val1, 0);
1984           int check = compare_values (tmp, val2);
1985
1986           if (check != 0)
1987             overflow = true;
1988         }
1989
1990       if (overflow)
1991         {
1992           res = copy_node (res);
1993           TREE_OVERFLOW (res) = 1;
1994         }
1995
1996     }
1997   else if (TYPE_OVERFLOW_WRAPS (TREE_TYPE (val1)))
1998     /* If the singed operation wraps then int_const_binop has done
1999        everything we want.  */
2000     ;
2001   else if ((TREE_OVERFLOW (res)
2002             && !TREE_OVERFLOW (val1)
2003             && !TREE_OVERFLOW (val2))
2004            || is_overflow_infinity (val1)
2005            || is_overflow_infinity (val2))
2006     {
2007       /* If the operation overflowed but neither VAL1 nor VAL2 are
2008          overflown, return -INF or +INF depending on the operation
2009          and the combination of signs of the operands.  */
2010       int sgn1 = tree_int_cst_sgn (val1);
2011       int sgn2 = tree_int_cst_sgn (val2);
2012
2013       if (needs_overflow_infinity (TREE_TYPE (res))
2014           && !supports_overflow_infinity (TREE_TYPE (res)))
2015         return NULL_TREE;
2016
2017       /* We have to punt on adding infinities of different signs,
2018          since we can't tell what the sign of the result should be.
2019          Likewise for subtracting infinities of the same sign.  */
2020       if (((code == PLUS_EXPR && sgn1 != sgn2)
2021            || (code == MINUS_EXPR && sgn1 == sgn2))
2022           && is_overflow_infinity (val1)
2023           && is_overflow_infinity (val2))
2024         return NULL_TREE;
2025
2026       /* Don't try to handle division or shifting of infinities.  */
2027       if ((code == TRUNC_DIV_EXPR
2028            || code == FLOOR_DIV_EXPR
2029            || code == CEIL_DIV_EXPR
2030            || code == EXACT_DIV_EXPR
2031            || code == ROUND_DIV_EXPR
2032            || code == RSHIFT_EXPR)
2033           && (is_overflow_infinity (val1)
2034               || is_overflow_infinity (val2)))
2035         return NULL_TREE;
2036
2037       /* Notice that we only need to handle the restricted set of
2038          operations handled by extract_range_from_binary_expr.
2039          Among them, only multiplication, addition and subtraction
2040          can yield overflow without overflown operands because we
2041          are working with integral types only... except in the
2042          case VAL1 = -INF and VAL2 = -1 which overflows to +INF
2043          for division too.  */
2044
2045       /* For multiplication, the sign of the overflow is given
2046          by the comparison of the signs of the operands.  */
2047       if ((code == MULT_EXPR && sgn1 == sgn2)
2048           /* For addition, the operands must be of the same sign
2049              to yield an overflow.  Its sign is therefore that
2050              of one of the operands, for example the first.  For
2051              infinite operands X + -INF is negative, not positive.  */
2052           || (code == PLUS_EXPR
2053               && (sgn1 >= 0
2054                   ? !is_negative_overflow_infinity (val2)
2055                   : is_positive_overflow_infinity (val2)))
2056           /* For subtraction, non-infinite operands must be of
2057              different signs to yield an overflow.  Its sign is
2058              therefore that of the first operand or the opposite of
2059              that of the second operand.  A first operand of 0 counts
2060              as positive here, for the corner case 0 - (-INF), which
2061              overflows, but must yield +INF.  For infinite operands 0
2062              - INF is negative, not positive.  */
2063           || (code == MINUS_EXPR
2064               && (sgn1 >= 0
2065                   ? !is_positive_overflow_infinity (val2)
2066                   : is_negative_overflow_infinity (val2)))
2067           /* We only get in here with positive shift count, so the
2068              overflow direction is the same as the sign of val1.
2069              Actually rshift does not overflow at all, but we only
2070              handle the case of shifting overflowed -INF and +INF.  */
2071           || (code == RSHIFT_EXPR
2072               && sgn1 >= 0)
2073           /* For division, the only case is -INF / -1 = +INF.  */
2074           || code == TRUNC_DIV_EXPR
2075           || code == FLOOR_DIV_EXPR
2076           || code == CEIL_DIV_EXPR
2077           || code == EXACT_DIV_EXPR
2078           || code == ROUND_DIV_EXPR)
2079         return (needs_overflow_infinity (TREE_TYPE (res))
2080                 ? positive_overflow_infinity (TREE_TYPE (res))
2081                 : TYPE_MAX_VALUE (TREE_TYPE (res)));
2082       else
2083         return (needs_overflow_infinity (TREE_TYPE (res))
2084                 ? negative_overflow_infinity (TREE_TYPE (res))
2085                 : TYPE_MIN_VALUE (TREE_TYPE (res)));
2086     }
2087
2088   return res;
2089 }
2090
2091
2092 /* For range VR compute two double_int bitmasks.  In *MAY_BE_NONZERO
2093    bitmask if some bit is unset, it means for all numbers in the range
2094    the bit is 0, otherwise it might be 0 or 1.  In *MUST_BE_NONZERO
2095    bitmask if some bit is set, it means for all numbers in the range
2096    the bit is 1, otherwise it might be 0 or 1.  */
2097
2098 static bool
2099 zero_nonzero_bits_from_vr (value_range_t *vr, double_int *may_be_nonzero,
2100                            double_int *must_be_nonzero)
2101 {
2102   if (range_int_cst_p (vr))
2103     {
2104       if (range_int_cst_singleton_p (vr))
2105         {
2106           *may_be_nonzero = tree_to_double_int (vr->min);
2107           *must_be_nonzero = *may_be_nonzero;
2108           return true;
2109         }
2110       if (tree_int_cst_sgn (vr->min) >= 0)
2111         {
2112           double_int dmin = tree_to_double_int (vr->min);
2113           double_int dmax = tree_to_double_int (vr->max);
2114           double_int xor_mask = double_int_xor (dmin, dmax);
2115           *may_be_nonzero = double_int_ior (dmin, dmax);
2116           *must_be_nonzero = double_int_and (dmin, dmax);
2117           if (xor_mask.high != 0)
2118             {
2119               unsigned HOST_WIDE_INT mask
2120                 = ((unsigned HOST_WIDE_INT) 1
2121                    << floor_log2 (xor_mask.high)) - 1;
2122               may_be_nonzero->low = ALL_ONES;
2123               may_be_nonzero->high |= mask;
2124               must_be_nonzero->low = 0;
2125               must_be_nonzero->high &= ~mask;
2126             }
2127           else if (xor_mask.low != 0)
2128             {
2129               unsigned HOST_WIDE_INT mask
2130                 = ((unsigned HOST_WIDE_INT) 1
2131                    << floor_log2 (xor_mask.low)) - 1;
2132               may_be_nonzero->low |= mask;
2133               must_be_nonzero->low &= ~mask;
2134             }
2135           return true;
2136         }
2137     }
2138   may_be_nonzero->low = ALL_ONES;
2139   may_be_nonzero->high = ALL_ONES;
2140   must_be_nonzero->low = 0;
2141   must_be_nonzero->high = 0;
2142   return false;
2143 }
2144
2145
2146 /* Extract range information from a binary expression EXPR based on
2147    the ranges of each of its operands and the expression code.  */
2148
2149 static void
2150 extract_range_from_binary_expr (value_range_t *vr,
2151                                 enum tree_code code,
2152                                 tree expr_type, tree op0, tree op1)
2153 {
2154   enum value_range_type type;
2155   tree min, max;
2156   int cmp;
2157   value_range_t vr0 = { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL };
2158   value_range_t vr1 = { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL };
2159
2160   /* Not all binary expressions can be applied to ranges in a
2161      meaningful way.  Handle only arithmetic operations.  */
2162   if (code != PLUS_EXPR
2163       && code != MINUS_EXPR
2164       && code != POINTER_PLUS_EXPR
2165       && code != MULT_EXPR
2166       && code != TRUNC_DIV_EXPR
2167       && code != FLOOR_DIV_EXPR
2168       && code != CEIL_DIV_EXPR
2169       && code != EXACT_DIV_EXPR
2170       && code != ROUND_DIV_EXPR
2171       && code != TRUNC_MOD_EXPR
2172       && code != RSHIFT_EXPR
2173       && code != MIN_EXPR
2174       && code != MAX_EXPR
2175       && code != BIT_AND_EXPR
2176       && code != BIT_IOR_EXPR
2177       && code != TRUTH_AND_EXPR
2178       && code != TRUTH_OR_EXPR)
2179     {
2180       /* We can still do constant propagation here.  */
2181       tree const_op0 = op_with_constant_singleton_value_range (op0);
2182       tree const_op1 = op_with_constant_singleton_value_range (op1);
2183       if (const_op0 || const_op1)
2184         {
2185           tree tem = fold_binary (code, expr_type,
2186                                   const_op0 ? const_op0 : op0,
2187                                   const_op1 ? const_op1 : op1);
2188           if (tem
2189               && is_gimple_min_invariant (tem)
2190               && !is_overflow_infinity (tem))
2191             {
2192               set_value_range (vr, VR_RANGE, tem, tem, NULL);
2193               return;
2194             }
2195         }
2196       set_value_range_to_varying (vr);
2197       return;
2198     }
2199
2200   /* Get value ranges for each operand.  For constant operands, create
2201      a new value range with the operand to simplify processing.  */
2202   if (TREE_CODE (op0) == SSA_NAME)
2203     vr0 = *(get_value_range (op0));
2204   else if (is_gimple_min_invariant (op0))
2205     set_value_range_to_value (&vr0, op0, NULL);
2206   else
2207     set_value_range_to_varying (&vr0);
2208
2209   if (TREE_CODE (op1) == SSA_NAME)
2210     vr1 = *(get_value_range (op1));
2211   else if (is_gimple_min_invariant (op1))
2212     set_value_range_to_value (&vr1, op1, NULL);
2213   else
2214     set_value_range_to_varying (&vr1);
2215
2216   /* If either range is UNDEFINED, so is the result.  */
2217   if (vr0.type == VR_UNDEFINED || vr1.type == VR_UNDEFINED)
2218     {
2219       set_value_range_to_undefined (vr);
2220       return;
2221     }
2222
2223   /* The type of the resulting value range defaults to VR0.TYPE.  */
2224   type = vr0.type;
2225
2226   /* Refuse to operate on VARYING ranges, ranges of different kinds
2227      and symbolic ranges.  As an exception, we allow BIT_AND_EXPR
2228      because we may be able to derive a useful range even if one of
2229      the operands is VR_VARYING or symbolic range.  Similarly for
2230      divisions.  TODO, we may be able to derive anti-ranges in
2231      some cases.  */
2232   if (code != BIT_AND_EXPR
2233       && code != TRUTH_AND_EXPR
2234       && code != TRUTH_OR_EXPR
2235       && code != TRUNC_DIV_EXPR
2236       && code != FLOOR_DIV_EXPR
2237       && code != CEIL_DIV_EXPR
2238       && code != EXACT_DIV_EXPR
2239       && code != ROUND_DIV_EXPR
2240       && code != TRUNC_MOD_EXPR
2241       && (vr0.type == VR_VARYING
2242           || vr1.type == VR_VARYING
2243           || vr0.type != vr1.type
2244           || symbolic_range_p (&vr0)
2245           || symbolic_range_p (&vr1)))
2246     {
2247       set_value_range_to_varying (vr);
2248       return;
2249     }
2250
2251   /* Now evaluate the expression to determine the new range.  */
2252   if (POINTER_TYPE_P (expr_type)
2253       || POINTER_TYPE_P (TREE_TYPE (op0))
2254       || POINTER_TYPE_P (TREE_TYPE (op1)))
2255     {
2256       if (code == MIN_EXPR || code == MAX_EXPR)
2257         {
2258           /* For MIN/MAX expressions with pointers, we only care about
2259              nullness, if both are non null, then the result is nonnull.
2260              If both are null, then the result is null. Otherwise they
2261              are varying.  */
2262           if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
2263             set_value_range_to_nonnull (vr, expr_type);
2264           else if (range_is_null (&vr0) && range_is_null (&vr1))
2265             set_value_range_to_null (vr, expr_type);
2266           else
2267             set_value_range_to_varying (vr);
2268
2269           return;
2270         }
2271       if (code == POINTER_PLUS_EXPR)
2272         {
2273           /* For pointer types, we are really only interested in asserting
2274              whether the expression evaluates to non-NULL.  */
2275           if (range_is_nonnull (&vr0) || range_is_nonnull (&vr1))
2276             set_value_range_to_nonnull (vr, expr_type);
2277           else if (range_is_null (&vr0) && range_is_null (&vr1))
2278             set_value_range_to_null (vr, expr_type);
2279           else
2280             set_value_range_to_varying (vr);
2281         }
2282       else if (code == BIT_AND_EXPR)
2283         {
2284           /* For pointer types, we are really only interested in asserting
2285              whether the expression evaluates to non-NULL.  */
2286           if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
2287             set_value_range_to_nonnull (vr, expr_type);
2288           else if (range_is_null (&vr0) || range_is_null (&vr1))
2289             set_value_range_to_null (vr, expr_type);
2290           else
2291             set_value_range_to_varying (vr);
2292         }
2293       else
2294         gcc_unreachable ();
2295
2296       return;
2297     }
2298
2299   /* For integer ranges, apply the operation to each end of the
2300      range and see what we end up with.  */
2301   if (code == TRUTH_AND_EXPR
2302       || code == TRUTH_OR_EXPR)
2303     {
2304       /* If one of the operands is zero, we know that the whole
2305          expression evaluates zero.  */
2306       if (code == TRUTH_AND_EXPR
2307           && ((vr0.type == VR_RANGE
2308                && integer_zerop (vr0.min)
2309                && integer_zerop (vr0.max))
2310               || (vr1.type == VR_RANGE
2311                   && integer_zerop (vr1.min)
2312                   && integer_zerop (vr1.max))))
2313         {
2314           type = VR_RANGE;
2315           min = max = build_int_cst (expr_type, 0);
2316         }
2317       /* If one of the operands is one, we know that the whole
2318          expression evaluates one.  */
2319       else if (code == TRUTH_OR_EXPR
2320                && ((vr0.type == VR_RANGE
2321                     && integer_onep (vr0.min)
2322                     && integer_onep (vr0.max))
2323                    || (vr1.type == VR_RANGE
2324                        && integer_onep (vr1.min)
2325                        && integer_onep (vr1.max))))
2326         {
2327           type = VR_RANGE;
2328           min = max = build_int_cst (expr_type, 1);
2329         }
2330       else if (vr0.type != VR_VARYING
2331                && vr1.type != VR_VARYING
2332                && vr0.type == vr1.type
2333                && !symbolic_range_p (&vr0)
2334                && !overflow_infinity_range_p (&vr0)
2335                && !symbolic_range_p (&vr1)
2336                && !overflow_infinity_range_p (&vr1))
2337         {
2338           /* Boolean expressions cannot be folded with int_const_binop.  */
2339           min = fold_binary (code, expr_type, vr0.min, vr1.min);
2340           max = fold_binary (code, expr_type, vr0.max, vr1.max);
2341         }
2342       else
2343         {
2344           /* The result of a TRUTH_*_EXPR is always true or false.  */
2345           set_value_range_to_truthvalue (vr, expr_type);
2346           return;
2347         }
2348     }
2349   else if (code == PLUS_EXPR
2350            || code == MIN_EXPR
2351            || code == MAX_EXPR)
2352     {
2353       /* If we have a PLUS_EXPR with two VR_ANTI_RANGEs, drop to
2354          VR_VARYING.  It would take more effort to compute a precise
2355          range for such a case.  For example, if we have op0 == 1 and
2356          op1 == -1 with their ranges both being ~[0,0], we would have
2357          op0 + op1 == 0, so we cannot claim that the sum is in ~[0,0].
2358          Note that we are guaranteed to have vr0.type == vr1.type at
2359          this point.  */
2360       if (code == PLUS_EXPR && vr0.type == VR_ANTI_RANGE)
2361         {
2362           set_value_range_to_varying (vr);
2363           return;
2364         }
2365
2366       /* For operations that make the resulting range directly
2367          proportional to the original ranges, apply the operation to
2368          the same end of each range.  */
2369       min = vrp_int_const_binop (code, vr0.min, vr1.min);
2370       max = vrp_int_const_binop (code, vr0.max, vr1.max);
2371
2372       /* If both additions overflowed the range kind is still correct.
2373          This happens regularly with subtracting something in unsigned
2374          arithmetic.
2375          ???  See PR30318 for all the cases we do not handle.  */
2376       if (code == PLUS_EXPR
2377           && (TREE_OVERFLOW (min) && !is_overflow_infinity (min))
2378           && (TREE_OVERFLOW (max) && !is_overflow_infinity (max)))
2379         {
2380           min = build_int_cst_wide (TREE_TYPE (min),
2381                                     TREE_INT_CST_LOW (min),
2382                                     TREE_INT_CST_HIGH (min));
2383           max = build_int_cst_wide (TREE_TYPE (max),
2384                                     TREE_INT_CST_LOW (max),
2385                                     TREE_INT_CST_HIGH (max));
2386         }
2387     }
2388   else if (code == MULT_EXPR
2389            || code == TRUNC_DIV_EXPR
2390            || code == FLOOR_DIV_EXPR
2391            || code == CEIL_DIV_EXPR
2392            || code == EXACT_DIV_EXPR
2393            || code == ROUND_DIV_EXPR
2394            || code == RSHIFT_EXPR)
2395     {
2396       tree val[4];
2397       size_t i;
2398       bool sop;
2399
2400       /* If we have an unsigned MULT_EXPR with two VR_ANTI_RANGEs,
2401          drop to VR_VARYING.  It would take more effort to compute a
2402          precise range for such a case.  For example, if we have
2403          op0 == 65536 and op1 == 65536 with their ranges both being
2404          ~[0,0] on a 32-bit machine, we would have op0 * op1 == 0, so
2405          we cannot claim that the product is in ~[0,0].  Note that we
2406          are guaranteed to have vr0.type == vr1.type at this
2407          point.  */
2408       if (code == MULT_EXPR
2409           && vr0.type == VR_ANTI_RANGE
2410           && !TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (op0)))
2411         {
2412           set_value_range_to_varying (vr);
2413           return;
2414         }
2415
2416       /* If we have a RSHIFT_EXPR with any shift values outside [0..prec-1],
2417          then drop to VR_VARYING.  Outside of this range we get undefined
2418          behavior from the shift operation.  We cannot even trust
2419          SHIFT_COUNT_TRUNCATED at this stage, because that applies to rtl
2420          shifts, and the operation at the tree level may be widened.  */
2421       if (code == RSHIFT_EXPR)
2422         {
2423           if (vr1.type == VR_ANTI_RANGE
2424               || !vrp_expr_computes_nonnegative (op1, &sop)
2425               || (operand_less_p
2426                   (build_int_cst (TREE_TYPE (vr1.max),
2427                                   TYPE_PRECISION (expr_type) - 1),
2428                    vr1.max) != 0))
2429             {
2430               set_value_range_to_varying (vr);
2431               return;
2432             }
2433         }
2434
2435       else if ((code == TRUNC_DIV_EXPR
2436                 || code == FLOOR_DIV_EXPR
2437                 || code == CEIL_DIV_EXPR
2438                 || code == EXACT_DIV_EXPR
2439                 || code == ROUND_DIV_EXPR)
2440                && (vr0.type != VR_RANGE || symbolic_range_p (&vr0)))
2441         {
2442           /* For division, if op1 has VR_RANGE but op0 does not, something
2443              can be deduced just from that range.  Say [min, max] / [4, max]
2444              gives [min / 4, max / 4] range.  */
2445           if (vr1.type == VR_RANGE
2446               && !symbolic_range_p (&vr1)
2447               && !range_includes_zero_p (&vr1))
2448             {
2449               vr0.type = type = VR_RANGE;
2450               vr0.min = vrp_val_min (TREE_TYPE (op0));
2451               vr0.max = vrp_val_max (TREE_TYPE (op1));
2452             }
2453           else
2454             {
2455               set_value_range_to_varying (vr);
2456               return;
2457             }
2458         }
2459
2460       /* For divisions, if flag_non_call_exceptions is true, we must
2461          not eliminate a division by zero.  */
2462       if ((code == TRUNC_DIV_EXPR
2463            || code == FLOOR_DIV_EXPR
2464            || code == CEIL_DIV_EXPR
2465            || code == EXACT_DIV_EXPR
2466            || code == ROUND_DIV_EXPR)
2467           && cfun->can_throw_non_call_exceptions
2468           && (vr1.type != VR_RANGE
2469               || symbolic_range_p (&vr1)
2470               || range_includes_zero_p (&vr1)))
2471         {
2472           set_value_range_to_varying (vr);
2473           return;
2474         }
2475
2476       /* For divisions, if op0 is VR_RANGE, we can deduce a range
2477          even if op1 is VR_VARYING, VR_ANTI_RANGE, symbolic or can
2478          include 0.  */
2479       if ((code == TRUNC_DIV_EXPR
2480            || code == FLOOR_DIV_EXPR
2481            || code == CEIL_DIV_EXPR
2482            || code == EXACT_DIV_EXPR
2483            || code == ROUND_DIV_EXPR)
2484           && vr0.type == VR_RANGE
2485           && (vr1.type != VR_RANGE
2486               || symbolic_range_p (&vr1)
2487               || range_includes_zero_p (&vr1)))
2488         {
2489           tree zero = build_int_cst (TREE_TYPE (vr0.min), 0);
2490           int cmp;
2491
2492           sop = false;
2493           min = NULL_TREE;
2494           max = NULL_TREE;
2495           if (vrp_expr_computes_nonnegative (op1, &sop) && !sop)
2496             {
2497               /* For unsigned division or when divisor is known
2498                  to be non-negative, the range has to cover
2499                  all numbers from 0 to max for positive max
2500                  and all numbers from min to 0 for negative min.  */
2501               cmp = compare_values (vr0.max, zero);
2502               if (cmp == -1)
2503                 max = zero;
2504               else if (cmp == 0 || cmp == 1)
2505                 max = vr0.max;
2506               else
2507                 type = VR_VARYING;
2508               cmp = compare_values (vr0.min, zero);
2509               if (cmp == 1)
2510                 min = zero;
2511               else if (cmp == 0 || cmp == -1)
2512                 min = vr0.min;
2513               else
2514                 type = VR_VARYING;
2515             }
2516           else
2517             {
2518               /* Otherwise the range is -max .. max or min .. -min
2519                  depending on which bound is bigger in absolute value,
2520                  as the division can change the sign.  */
2521               abs_extent_range (vr, vr0.min, vr0.max);
2522               return;
2523             }
2524           if (type == VR_VARYING)
2525             {
2526               set_value_range_to_varying (vr);
2527               return;
2528             }
2529         }
2530
2531       /* Multiplications and divisions are a bit tricky to handle,
2532          depending on the mix of signs we have in the two ranges, we
2533          need to operate on different values to get the minimum and
2534          maximum values for the new range.  One approach is to figure
2535          out all the variations of range combinations and do the
2536          operations.
2537
2538          However, this involves several calls to compare_values and it
2539          is pretty convoluted.  It's simpler to do the 4 operations
2540          (MIN0 OP MIN1, MIN0 OP MAX1, MAX0 OP MIN1 and MAX0 OP MAX0 OP
2541          MAX1) and then figure the smallest and largest values to form
2542          the new range.  */
2543       else
2544         {
2545           gcc_assert ((vr0.type == VR_RANGE
2546                        || (code == MULT_EXPR && vr0.type == VR_ANTI_RANGE))
2547                       && vr0.type == vr1.type);
2548
2549           /* Compute the 4 cross operations.  */
2550           sop = false;
2551           val[0] = vrp_int_const_binop (code, vr0.min, vr1.min);
2552           if (val[0] == NULL_TREE)
2553             sop = true;
2554
2555           if (vr1.max == vr1.min)
2556             val[1] = NULL_TREE;
2557           else
2558             {
2559               val[1] = vrp_int_const_binop (code, vr0.min, vr1.max);
2560               if (val[1] == NULL_TREE)
2561                 sop = true;
2562             }
2563
2564           if (vr0.max == vr0.min)
2565             val[2] = NULL_TREE;
2566           else
2567             {
2568               val[2] = vrp_int_const_binop (code, vr0.max, vr1.min);
2569               if (val[2] == NULL_TREE)
2570                 sop = true;
2571             }
2572
2573           if (vr0.min == vr0.max || vr1.min == vr1.max)
2574             val[3] = NULL_TREE;
2575           else
2576             {
2577               val[3] = vrp_int_const_binop (code, vr0.max, vr1.max);
2578               if (val[3] == NULL_TREE)
2579                 sop = true;
2580             }
2581
2582           if (sop)
2583             {
2584               set_value_range_to_varying (vr);
2585               return;
2586             }
2587
2588           /* Set MIN to the minimum of VAL[i] and MAX to the maximum
2589              of VAL[i].  */
2590           min = val[0];
2591           max = val[0];
2592           for (i = 1; i < 4; i++)
2593             {
2594               if (!is_gimple_min_invariant (min)
2595                   || (TREE_OVERFLOW (min) && !is_overflow_infinity (min))
2596                   || !is_gimple_min_invariant (max)
2597                   || (TREE_OVERFLOW (max) && !is_overflow_infinity (max)))
2598                 break;
2599
2600               if (val[i])
2601                 {
2602                   if (!is_gimple_min_invariant (val[i])
2603                       || (TREE_OVERFLOW (val[i])
2604                           && !is_overflow_infinity (val[i])))
2605                     {
2606                       /* If we found an overflowed value, set MIN and MAX
2607                          to it so that we set the resulting range to
2608                          VARYING.  */
2609                       min = max = val[i];
2610                       break;
2611                     }
2612
2613                   if (compare_values (val[i], min) == -1)
2614                     min = val[i];
2615
2616                   if (compare_values (val[i], max) == 1)
2617                     max = val[i];
2618                 }
2619             }
2620         }
2621     }
2622   else if (code == TRUNC_MOD_EXPR)
2623     {
2624       bool sop = false;
2625       if (vr1.type != VR_RANGE
2626           || symbolic_range_p (&vr1)
2627           || range_includes_zero_p (&vr1)
2628           || vrp_val_is_min (vr1.min))
2629         {
2630           set_value_range_to_varying (vr);
2631           return;
2632         }
2633       type = VR_RANGE;
2634       /* Compute MAX <|vr1.min|, |vr1.max|> - 1.  */
2635       max = fold_unary_to_constant (ABS_EXPR, TREE_TYPE (vr1.min), vr1.min);
2636       if (tree_int_cst_lt (max, vr1.max))
2637         max = vr1.max;
2638       max = int_const_binop (MINUS_EXPR, max, integer_one_node, 0);
2639       /* If the dividend is non-negative the modulus will be
2640          non-negative as well.  */
2641       if (TYPE_UNSIGNED (TREE_TYPE (max))
2642           || (vrp_expr_computes_nonnegative (op0, &sop) && !sop))
2643         min = build_int_cst (TREE_TYPE (max), 0);
2644       else
2645         min = fold_unary_to_constant (NEGATE_EXPR, TREE_TYPE (max), max);
2646     }
2647   else if (code == MINUS_EXPR)
2648     {
2649       /* If we have a MINUS_EXPR with two VR_ANTI_RANGEs, drop to
2650          VR_VARYING.  It would take more effort to compute a precise
2651          range for such a case.  For example, if we have op0 == 1 and
2652          op1 == 1 with their ranges both being ~[0,0], we would have
2653          op0 - op1 == 0, so we cannot claim that the difference is in
2654          ~[0,0].  Note that we are guaranteed to have
2655          vr0.type == vr1.type at this point.  */
2656       if (vr0.type == VR_ANTI_RANGE)
2657         {
2658           set_value_range_to_varying (vr);
2659           return;
2660         }
2661
2662       /* For MINUS_EXPR, apply the operation to the opposite ends of
2663          each range.  */
2664       min = vrp_int_const_binop (code, vr0.min, vr1.max);
2665       max = vrp_int_const_binop (code, vr0.max, vr1.min);
2666     }
2667   else if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR)
2668     {
2669       bool vr0_int_cst_singleton_p, vr1_int_cst_singleton_p;
2670       bool int_cst_range0, int_cst_range1;
2671       double_int may_be_nonzero0, may_be_nonzero1;
2672       double_int must_be_nonzero0, must_be_nonzero1;
2673
2674       vr0_int_cst_singleton_p = range_int_cst_singleton_p (&vr0);
2675       vr1_int_cst_singleton_p = range_int_cst_singleton_p (&vr1);
2676       int_cst_range0 = zero_nonzero_bits_from_vr (&vr0, &may_be_nonzero0,
2677                                                   &must_be_nonzero0);
2678       int_cst_range1 = zero_nonzero_bits_from_vr (&vr1, &may_be_nonzero1,
2679                                                   &must_be_nonzero1);
2680
2681       type = VR_RANGE;
2682       if (vr0_int_cst_singleton_p && vr1_int_cst_singleton_p)
2683         min = max = int_const_binop (code, vr0.max, vr1.max, 0);
2684       else if (!int_cst_range0 && !int_cst_range1)
2685         {
2686           set_value_range_to_varying (vr);
2687           return;
2688         }
2689       else if (code == BIT_AND_EXPR)
2690         {
2691           min = double_int_to_tree (expr_type,
2692                                     double_int_and (must_be_nonzero0,
2693                                                     must_be_nonzero1));
2694           max = double_int_to_tree (expr_type,
2695                                     double_int_and (may_be_nonzero0,
2696                                                     may_be_nonzero1));
2697           if (TREE_OVERFLOW (min) || tree_int_cst_sgn (min) < 0)
2698             min = NULL_TREE;
2699           if (TREE_OVERFLOW (max) || tree_int_cst_sgn (max) < 0)
2700             max = NULL_TREE;
2701           if (int_cst_range0 && tree_int_cst_sgn (vr0.min) >= 0)
2702             {
2703               if (min == NULL_TREE)
2704                 min = build_int_cst (expr_type, 0);
2705               if (max == NULL_TREE || tree_int_cst_lt (vr0.max, max))
2706                 max = vr0.max;
2707             }
2708           if (int_cst_range1 && tree_int_cst_sgn (vr1.min) >= 0)
2709             {
2710               if (min == NULL_TREE)
2711                 min = build_int_cst (expr_type, 0);
2712               if (max == NULL_TREE || tree_int_cst_lt (vr1.max, max))
2713                 max = vr1.max;
2714             }
2715         }
2716       else if (!int_cst_range0
2717                || !int_cst_range1
2718                || tree_int_cst_sgn (vr0.min) < 0
2719                || tree_int_cst_sgn (vr1.min) < 0)
2720         {
2721           set_value_range_to_varying (vr);
2722           return;
2723         }
2724       else
2725         {
2726           min = double_int_to_tree (expr_type,
2727                                     double_int_ior (must_be_nonzero0,
2728                                                     must_be_nonzero1));
2729           max = double_int_to_tree (expr_type,
2730                                     double_int_ior (may_be_nonzero0,
2731                                                     may_be_nonzero1));
2732           if (TREE_OVERFLOW (min) || tree_int_cst_sgn (min) < 0)
2733             min = vr0.min;
2734           else
2735             min = vrp_int_const_binop (MAX_EXPR, min, vr0.min);
2736           if (TREE_OVERFLOW (max) || tree_int_cst_sgn (max) < 0)
2737             max = NULL_TREE;
2738           min = vrp_int_const_binop (MAX_EXPR, min, vr1.min);
2739         }
2740     }
2741   else
2742     gcc_unreachable ();
2743
2744   /* If either MIN or MAX overflowed, then set the resulting range to
2745      VARYING.  But we do accept an overflow infinity
2746      representation.  */
2747   if (min == NULL_TREE
2748       || !is_gimple_min_invariant (min)
2749       || (TREE_OVERFLOW (min) && !is_overflow_infinity (min))
2750       || max == NULL_TREE
2751       || !is_gimple_min_invariant (max)
2752       || (TREE_OVERFLOW (max) && !is_overflow_infinity (max)))
2753     {
2754       set_value_range_to_varying (vr);
2755       return;
2756     }
2757
2758   /* We punt if:
2759      1) [-INF, +INF]
2760      2) [-INF, +-INF(OVF)]
2761      3) [+-INF(OVF), +INF]
2762      4) [+-INF(OVF), +-INF(OVF)]
2763      We learn nothing when we have INF and INF(OVF) on both sides.
2764      Note that we do accept [-INF, -INF] and [+INF, +INF] without
2765      overflow.  */
2766   if ((vrp_val_is_min (min) || is_overflow_infinity (min))
2767       && (vrp_val_is_max (max) || is_overflow_infinity (max)))
2768     {
2769       set_value_range_to_varying (vr);
2770       return;
2771     }
2772
2773   cmp = compare_values (min, max);
2774   if (cmp == -2 || cmp == 1)
2775     {
2776       /* If the new range has its limits swapped around (MIN > MAX),
2777          then the operation caused one of them to wrap around, mark
2778          the new range VARYING.  */
2779       set_value_range_to_varying (vr);
2780     }
2781   else
2782     set_value_range (vr, type, min, max, NULL);
2783 }
2784
2785
2786 /* Extract range information from a unary expression EXPR based on
2787    the range of its operand and the expression code.  */
2788
2789 static void
2790 extract_range_from_unary_expr (value_range_t *vr, enum tree_code code,
2791                                tree type, tree op0)
2792 {
2793   tree min, max;
2794   int cmp;
2795   value_range_t vr0 = { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL };
2796
2797   /* Refuse to operate on certain unary expressions for which we
2798      cannot easily determine a resulting range.  */
2799   if (code == FIX_TRUNC_EXPR
2800       || code == FLOAT_EXPR
2801       || code == BIT_NOT_EXPR
2802       || code == CONJ_EXPR)
2803     {
2804       /* We can still do constant propagation here.  */
2805       if ((op0 = op_with_constant_singleton_value_range (op0)) != NULL_TREE)
2806         {
2807           tree tem = fold_unary (code, type, op0);
2808           if (tem
2809               && is_gimple_min_invariant (tem)
2810               && !is_overflow_infinity (tem))
2811             {
2812               set_value_range (vr, VR_RANGE, tem, tem, NULL);
2813               return;
2814             }
2815         }
2816       set_value_range_to_varying (vr);
2817       return;
2818     }
2819
2820   /* Get value ranges for the operand.  For constant operands, create
2821      a new value range with the operand to simplify processing.  */
2822   if (TREE_CODE (op0) == SSA_NAME)
2823     vr0 = *(get_value_range (op0));
2824   else if (is_gimple_min_invariant (op0))
2825     set_value_range_to_value (&vr0, op0, NULL);
2826   else
2827     set_value_range_to_varying (&vr0);
2828
2829   /* If VR0 is UNDEFINED, so is the result.  */
2830   if (vr0.type == VR_UNDEFINED)
2831     {
2832       set_value_range_to_undefined (vr);
2833       return;
2834     }
2835
2836   /* Refuse to operate on symbolic ranges, or if neither operand is
2837      a pointer or integral type.  */
2838   if ((!INTEGRAL_TYPE_P (TREE_TYPE (op0))
2839        && !POINTER_TYPE_P (TREE_TYPE (op0)))
2840       || (vr0.type != VR_VARYING
2841           && symbolic_range_p (&vr0)))
2842     {
2843       set_value_range_to_varying (vr);
2844       return;
2845     }
2846
2847   /* If the expression involves pointers, we are only interested in
2848      determining if it evaluates to NULL [0, 0] or non-NULL (~[0, 0]).  */
2849   if (POINTER_TYPE_P (type) || POINTER_TYPE_P (TREE_TYPE (op0)))
2850     {
2851       bool sop;
2852
2853       sop = false;
2854       if (range_is_nonnull (&vr0)
2855           || (tree_unary_nonzero_warnv_p (code, type, op0, &sop)
2856               && !sop))
2857         set_value_range_to_nonnull (vr, type);
2858       else if (range_is_null (&vr0))
2859         set_value_range_to_null (vr, type);
2860       else
2861         set_value_range_to_varying (vr);
2862
2863       return;
2864     }
2865
2866   /* Handle unary expressions on integer ranges.  */
2867   if (CONVERT_EXPR_CODE_P (code)
2868       && INTEGRAL_TYPE_P (type)
2869       && INTEGRAL_TYPE_P (TREE_TYPE (op0)))
2870     {
2871       tree inner_type = TREE_TYPE (op0);
2872       tree outer_type = type;
2873
2874       /* If VR0 is varying and we increase the type precision, assume
2875          a full range for the following transformation.  */
2876       if (vr0.type == VR_VARYING
2877           && TYPE_PRECISION (inner_type) < TYPE_PRECISION (outer_type))
2878         {
2879           vr0.type = VR_RANGE;
2880           vr0.min = TYPE_MIN_VALUE (inner_type);
2881           vr0.max = TYPE_MAX_VALUE (inner_type);
2882         }
2883
2884       /* If VR0 is a constant range or anti-range and the conversion is
2885          not truncating we can convert the min and max values and
2886          canonicalize the resulting range.  Otherwise we can do the
2887          conversion if the size of the range is less than what the
2888          precision of the target type can represent and the range is
2889          not an anti-range.  */
2890       if ((vr0.type == VR_RANGE
2891            || vr0.type == VR_ANTI_RANGE)
2892           && TREE_CODE (vr0.min) == INTEGER_CST
2893           && TREE_CODE (vr0.max) == INTEGER_CST
2894           && (!is_overflow_infinity (vr0.min)
2895               || (vr0.type == VR_RANGE
2896                   && TYPE_PRECISION (outer_type) > TYPE_PRECISION (inner_type)
2897                   && needs_overflow_infinity (outer_type)
2898                   && supports_overflow_infinity (outer_type)))
2899           && (!is_overflow_infinity (vr0.max)
2900               || (vr0.type == VR_RANGE
2901                   && TYPE_PRECISION (outer_type) > TYPE_PRECISION (inner_type)
2902                   && needs_overflow_infinity (outer_type)
2903                   && supports_overflow_infinity (outer_type)))
2904           && (TYPE_PRECISION (outer_type) >= TYPE_PRECISION (inner_type)
2905               || (vr0.type == VR_RANGE
2906                   && integer_zerop (int_const_binop (RSHIFT_EXPR,
2907                        int_const_binop (MINUS_EXPR, vr0.max, vr0.min, 0),
2908                          size_int (TYPE_PRECISION (outer_type)), 0)))))
2909         {
2910           tree new_min, new_max;
2911           new_min = force_fit_type_double (outer_type,
2912                                            tree_to_double_int (vr0.min),
2913                                            0, false);
2914           new_max = force_fit_type_double (outer_type,
2915                                            tree_to_double_int (vr0.max),
2916                                            0, false);
2917           if (is_overflow_infinity (vr0.min))
2918             new_min = negative_overflow_infinity (outer_type);
2919           if (is_overflow_infinity (vr0.max))
2920             new_max = positive_overflow_infinity (outer_type);
2921           set_and_canonicalize_value_range (vr, vr0.type,
2922                                             new_min, new_max, NULL);
2923           return;
2924         }
2925
2926       set_value_range_to_varying (vr);
2927       return;
2928     }
2929
2930   /* Conversion of a VR_VARYING value to a wider type can result
2931      in a usable range.  So wait until after we've handled conversions
2932      before dropping the result to VR_VARYING if we had a source
2933      operand that is VR_VARYING.  */
2934   if (vr0.type == VR_VARYING)
2935     {
2936       set_value_range_to_varying (vr);
2937       return;
2938     }
2939
2940   /* Apply the operation to each end of the range and see what we end
2941      up with.  */
2942   if (code == NEGATE_EXPR
2943       && !TYPE_UNSIGNED (type))
2944     {
2945       /* NEGATE_EXPR flips the range around.  We need to treat
2946          TYPE_MIN_VALUE specially.  */
2947       if (is_positive_overflow_infinity (vr0.max))
2948         min = negative_overflow_infinity (type);
2949       else if (is_negative_overflow_infinity (vr0.max))
2950         min = positive_overflow_infinity (type);
2951       else if (!vrp_val_is_min (vr0.max))
2952         min = fold_unary_to_constant (code, type, vr0.max);
2953       else if (needs_overflow_infinity (type))
2954         {
2955           if (supports_overflow_infinity (type)
2956               && !is_overflow_infinity (vr0.min)
2957               && !vrp_val_is_min (vr0.min))
2958             min = positive_overflow_infinity (type);
2959           else
2960             {
2961               set_value_range_to_varying (vr);
2962               return;
2963             }
2964         }
2965       else
2966         min = TYPE_MIN_VALUE (type);
2967
2968       if (is_positive_overflow_infinity (vr0.min))
2969         max = negative_overflow_infinity (type);
2970       else if (is_negative_overflow_infinity (vr0.min))
2971         max = positive_overflow_infinity (type);
2972       else if (!vrp_val_is_min (vr0.min))
2973         max = fold_unary_to_constant (code, type, vr0.min);
2974       else if (needs_overflow_infinity (type))
2975         {
2976           if (supports_overflow_infinity (type))
2977             max = positive_overflow_infinity (type);
2978           else
2979             {
2980               set_value_range_to_varying (vr);
2981               return;
2982             }
2983         }
2984       else
2985         max = TYPE_MIN_VALUE (type);
2986     }
2987   else if (code == NEGATE_EXPR
2988            && TYPE_UNSIGNED (type))
2989     {
2990       if (!range_includes_zero_p (&vr0))
2991         {
2992           max = fold_unary_to_constant (code, type, vr0.min);
2993           min = fold_unary_to_constant (code, type, vr0.max);
2994         }
2995       else
2996         {
2997           if (range_is_null (&vr0))
2998             set_value_range_to_null (vr, type);
2999           else
3000             set_value_range_to_varying (vr);
3001           return;
3002         }
3003     }
3004   else if (code == ABS_EXPR
3005            && !TYPE_UNSIGNED (type))
3006     {
3007       /* -TYPE_MIN_VALUE = TYPE_MIN_VALUE with flag_wrapv so we can't get a
3008          useful range.  */
3009       if (!TYPE_OVERFLOW_UNDEFINED (type)
3010           && ((vr0.type == VR_RANGE
3011                && vrp_val_is_min (vr0.min))
3012               || (vr0.type == VR_ANTI_RANGE
3013                   && !vrp_val_is_min (vr0.min)
3014                   && !range_includes_zero_p (&vr0))))
3015         {
3016           set_value_range_to_varying (vr);
3017           return;
3018         }
3019
3020       /* ABS_EXPR may flip the range around, if the original range
3021          included negative values.  */
3022       if (is_overflow_infinity (vr0.min))
3023         min = positive_overflow_infinity (type);
3024       else if (!vrp_val_is_min (vr0.min))
3025         min = fold_unary_to_constant (code, type, vr0.min);
3026       else if (!needs_overflow_infinity (type))
3027         min = TYPE_MAX_VALUE (type);
3028       else if (supports_overflow_infinity (type))
3029         min = positive_overflow_infinity (type);
3030       else
3031         {
3032           set_value_range_to_varying (vr);
3033           return;
3034         }
3035
3036       if (is_overflow_infinity (vr0.max))
3037         max = positive_overflow_infinity (type);
3038       else if (!vrp_val_is_min (vr0.max))
3039         max = fold_unary_to_constant (code, type, vr0.max);
3040       else if (!needs_overflow_infinity (type))
3041         max = TYPE_MAX_VALUE (type);
3042       else if (supports_overflow_infinity (type)
3043                /* We shouldn't generate [+INF, +INF] as set_value_range
3044                   doesn't like this and ICEs.  */
3045                && !is_positive_overflow_infinity (min))
3046         max = positive_overflow_infinity (type);
3047       else
3048         {
3049           set_value_range_to_varying (vr);
3050           return;
3051         }
3052
3053       cmp = compare_values (min, max);
3054
3055       /* If a VR_ANTI_RANGEs contains zero, then we have
3056          ~[-INF, min(MIN, MAX)].  */
3057       if (vr0.type == VR_ANTI_RANGE)
3058         {
3059           if (range_includes_zero_p (&vr0))
3060             {
3061               /* Take the lower of the two values.  */
3062               if (cmp != 1)
3063                 max = min;
3064
3065               /* Create ~[-INF, min (abs(MIN), abs(MAX))]
3066                  or ~[-INF + 1, min (abs(MIN), abs(MAX))] when
3067                  flag_wrapv is set and the original anti-range doesn't include
3068                  TYPE_MIN_VALUE, remember -TYPE_MIN_VALUE = TYPE_MIN_VALUE.  */
3069               if (TYPE_OVERFLOW_WRAPS (type))
3070                 {
3071                   tree type_min_value = TYPE_MIN_VALUE (type);
3072
3073                   min = (vr0.min != type_min_value
3074                          ? int_const_binop (PLUS_EXPR, type_min_value,
3075                                             integer_one_node, 0)
3076                          : type_min_value);
3077                 }
3078               else
3079                 {
3080                   if (overflow_infinity_range_p (&vr0))
3081                     min = negative_overflow_infinity (type);
3082                   else
3083                     min = TYPE_MIN_VALUE (type);
3084                 }
3085             }
3086           else
3087             {
3088               /* All else has failed, so create the range [0, INF], even for
3089                  flag_wrapv since TYPE_MIN_VALUE is in the original
3090                  anti-range.  */
3091               vr0.type = VR_RANGE;
3092               min = build_int_cst (type, 0);
3093               if (needs_overflow_infinity (type))
3094                 {
3095                   if (supports_overflow_infinity (type))
3096                     max = positive_overflow_infinity (type);
3097                   else
3098                     {
3099                       set_value_range_to_varying (vr);
3100                       return;
3101                     }
3102                 }
3103               else
3104                 max = TYPE_MAX_VALUE (type);
3105             }
3106         }
3107
3108       /* If the range contains zero then we know that the minimum value in the
3109          range will be zero.  */
3110       else if (range_includes_zero_p (&vr0))
3111         {
3112           if (cmp == 1)
3113             max = min;
3114           min = build_int_cst (type, 0);
3115         }
3116       else
3117         {
3118           /* If the range was reversed, swap MIN and MAX.  */
3119           if (cmp == 1)
3120             {
3121               tree t = min;
3122               min = max;
3123               max = t;
3124             }
3125         }
3126     }
3127   else
3128     {
3129       /* Otherwise, operate on each end of the range.  */
3130       min = fold_unary_to_constant (code, type, vr0.min);
3131       max = fold_unary_to_constant (code, type, vr0.max);
3132
3133       if (needs_overflow_infinity (type))
3134         {
3135           gcc_assert (code != NEGATE_EXPR && code != ABS_EXPR);
3136
3137           /* If both sides have overflowed, we don't know
3138              anything.  */
3139           if ((is_overflow_infinity (vr0.min)
3140                || TREE_OVERFLOW (min))
3141               && (is_overflow_infinity (vr0.max)
3142                   || TREE_OVERFLOW (max)))
3143             {
3144               set_value_range_to_varying (vr);
3145               return;
3146             }
3147
3148           if (is_overflow_infinity (vr0.min))
3149             min = vr0.min;
3150           else if (TREE_OVERFLOW (min))
3151             {
3152               if (supports_overflow_infinity (type))
3153                 min = (tree_int_cst_sgn (min) >= 0
3154                        ? positive_overflow_infinity (TREE_TYPE (min))
3155                        : negative_overflow_infinity (TREE_TYPE (min)));
3156               else
3157                 {
3158                   set_value_range_to_varying (vr);
3159                   return;
3160                 }
3161             }
3162
3163           if (is_overflow_infinity (vr0.max))
3164             max = vr0.max;
3165           else if (TREE_OVERFLOW (max))
3166             {
3167               if (supports_overflow_infinity (type))
3168                 max = (tree_int_cst_sgn (max) >= 0
3169                        ? positive_overflow_infinity (TREE_TYPE (max))
3170                        : negative_overflow_infinity (TREE_TYPE (max)));
3171               else
3172                 {
3173                   set_value_range_to_varying (vr);
3174                   return;
3175                 }
3176             }
3177         }
3178     }
3179
3180   cmp = compare_values (min, max);
3181   if (cmp == -2 || cmp == 1)
3182     {
3183       /* If the new range has its limits swapped around (MIN > MAX),
3184          then the operation caused one of them to wrap around, mark
3185          the new range VARYING.  */
3186       set_value_range_to_varying (vr);
3187     }
3188   else
3189     set_value_range (vr, vr0.type, min, max, NULL);
3190 }
3191
3192
3193 /* Extract range information from a conditional expression EXPR based on
3194    the ranges of each of its operands and the expression code.  */
3195
3196 static void
3197 extract_range_from_cond_expr (value_range_t *vr, tree expr)
3198 {
3199   tree op0, op1;
3200   value_range_t vr0 = { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL };
3201   value_range_t vr1 = { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL };
3202
3203   /* Get value ranges for each operand.  For constant operands, create
3204      a new value range with the operand to simplify processing.  */
3205   op0 = COND_EXPR_THEN (expr);
3206   if (TREE_CODE (op0) == SSA_NAME)
3207     vr0 = *(get_value_range (op0));
3208   else if (is_gimple_min_invariant (op0))
3209     set_value_range_to_value (&vr0, op0, NULL);
3210   else
3211     set_value_range_to_varying (&vr0);
3212
3213   op1 = COND_EXPR_ELSE (expr);
3214   if (TREE_CODE (op1) == SSA_NAME)
3215     vr1 = *(get_value_range (op1));
3216   else if (is_gimple_min_invariant (op1))
3217     set_value_range_to_value (&vr1, op1, NULL);
3218   else
3219     set_value_range_to_varying (&vr1);
3220
3221   /* The resulting value range is the union of the operand ranges */
3222   vrp_meet (&vr0, &vr1);
3223   copy_value_range (vr, &vr0);
3224 }
3225
3226
3227 /* Extract range information from a comparison expression EXPR based
3228    on the range of its operand and the expression code.  */
3229
3230 static void
3231 extract_range_from_comparison (value_range_t *vr, enum tree_code code,
3232                                tree type, tree op0, tree op1)
3233 {
3234   bool sop = false;
3235   tree val;
3236
3237   val = vrp_evaluate_conditional_warnv_with_ops (code, op0, op1, false, &sop,
3238                                                  NULL);
3239
3240   /* A disadvantage of using a special infinity as an overflow
3241      representation is that we lose the ability to record overflow
3242      when we don't have an infinity.  So we have to ignore a result
3243      which relies on overflow.  */
3244
3245   if (val && !is_overflow_infinity (val) && !sop)
3246     {
3247       /* Since this expression was found on the RHS of an assignment,
3248          its type may be different from _Bool.  Convert VAL to EXPR's
3249          type.  */
3250       val = fold_convert (type, val);
3251       if (is_gimple_min_invariant (val))
3252         set_value_range_to_value (vr, val, vr->equiv);
3253       else
3254         set_value_range (vr, VR_RANGE, val, val, vr->equiv);
3255     }
3256   else
3257     /* The result of a comparison is always true or false.  */
3258     set_value_range_to_truthvalue (vr, type);
3259 }
3260
3261 /* Try to derive a nonnegative or nonzero range out of STMT relying
3262    primarily on generic routines in fold in conjunction with range data.
3263    Store the result in *VR */
3264
3265 static void
3266 extract_range_basic (value_range_t *vr, gimple stmt)
3267 {
3268   bool sop = false;
3269   tree type = gimple_expr_type (stmt);
3270
3271   if (INTEGRAL_TYPE_P (type)
3272       && gimple_stmt_nonnegative_warnv_p (stmt, &sop))
3273     set_value_range_to_nonnegative (vr, type,
3274                                     sop || stmt_overflow_infinity (stmt));
3275   else if (vrp_stmt_computes_nonzero (stmt, &sop)
3276            && !sop)
3277     set_value_range_to_nonnull (vr, type);
3278   else
3279     set_value_range_to_varying (vr);
3280 }
3281
3282
3283 /* Try to compute a useful range out of assignment STMT and store it
3284    in *VR.  */
3285
3286 static void
3287 extract_range_from_assignment (value_range_t *vr, gimple stmt)
3288 {
3289   enum tree_code code = gimple_assign_rhs_code (stmt);
3290
3291   if (code == ASSERT_EXPR)
3292     extract_range_from_assert (vr, gimple_assign_rhs1 (stmt));
3293   else if (code == SSA_NAME)
3294     extract_range_from_ssa_name (vr, gimple_assign_rhs1 (stmt));
3295   else if (TREE_CODE_CLASS (code) == tcc_binary
3296            || code == TRUTH_AND_EXPR
3297            || code == TRUTH_OR_EXPR
3298            || code == TRUTH_XOR_EXPR)
3299     extract_range_from_binary_expr (vr, gimple_assign_rhs_code (stmt),
3300                                     gimple_expr_type (stmt),
3301                                     gimple_assign_rhs1 (stmt),
3302                                     gimple_assign_rhs2 (stmt));
3303   else if (TREE_CODE_CLASS (code) == tcc_unary)
3304     extract_range_from_unary_expr (vr, gimple_assign_rhs_code (stmt),
3305                                    gimple_expr_type (stmt),
3306                                    gimple_assign_rhs1 (stmt));
3307   else if (code == COND_EXPR)
3308     extract_range_from_cond_expr (vr, gimple_assign_rhs1 (stmt));
3309   else if (TREE_CODE_CLASS (code) == tcc_comparison)
3310     extract_range_from_comparison (vr, gimple_assign_rhs_code (stmt),
3311                                    gimple_expr_type (stmt),
3312                                    gimple_assign_rhs1 (stmt),
3313                                    gimple_assign_rhs2 (stmt));
3314   else if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS
3315            && is_gimple_min_invariant (gimple_assign_rhs1 (stmt)))
3316     set_value_range_to_value (vr, gimple_assign_rhs1 (stmt), NULL);
3317   else
3318     set_value_range_to_varying (vr);
3319
3320   if (vr->type == VR_VARYING)
3321     extract_range_basic (vr, stmt);
3322 }
3323
3324 /* Given a range VR, a LOOP and a variable VAR, determine whether it
3325    would be profitable to adjust VR using scalar evolution information
3326    for VAR.  If so, update VR with the new limits.  */
3327
3328 static void
3329 adjust_range_with_scev (value_range_t *vr, struct loop *loop,
3330                         gimple stmt, tree var)
3331 {
3332   tree init, step, chrec, tmin, tmax, min, max, type, tem;
3333   enum ev_direction dir;
3334
3335   /* TODO.  Don't adjust anti-ranges.  An anti-range may provide
3336      better opportunities than a regular range, but I'm not sure.  */
3337   if (vr->type == VR_ANTI_RANGE)
3338     return;
3339
3340   chrec = instantiate_parameters (loop, analyze_scalar_evolution (loop, var));
3341
3342   /* Like in PR19590, scev can return a constant function.  */
3343   if (is_gimple_min_invariant (chrec))
3344     {
3345       set_value_range_to_value (vr, chrec, vr->equiv);
3346       return;
3347     }
3348
3349   if (TREE_CODE (chrec) != POLYNOMIAL_CHREC)
3350     return;
3351
3352   init = initial_condition_in_loop_num (chrec, loop->num);
3353   tem = op_with_constant_singleton_value_range (init);
3354   if (tem)
3355     init = tem;
3356   step = evolution_part_in_loop_num (chrec, loop->num);
3357   tem = op_with_constant_singleton_value_range (step);
3358   if (tem)
3359     step = tem;
3360
3361   /* If STEP is symbolic, we can't know whether INIT will be the
3362      minimum or maximum value in the range.  Also, unless INIT is
3363      a simple expression, compare_values and possibly other functions
3364      in tree-vrp won't be able to handle it.  */
3365   if (step == NULL_TREE
3366       || !is_gimple_min_invariant (step)
3367       || !valid_value_p (init))
3368     return;
3369
3370   dir = scev_direction (chrec);
3371   if (/* Do not adjust ranges if we do not know whether the iv increases
3372          or decreases,  ... */
3373       dir == EV_DIR_UNKNOWN
3374       /* ... or if it may wrap.  */
3375       || scev_probably_wraps_p (init, step, stmt, get_chrec_loop (chrec),
3376                                 true))
3377     return;
3378
3379   /* We use TYPE_MIN_VALUE and TYPE_MAX_VALUE here instead of
3380      negative_overflow_infinity and positive_overflow_infinity,
3381      because we have concluded that the loop probably does not
3382      wrap.  */
3383
3384   type = TREE_TYPE (var);
3385   if (POINTER_TYPE_P (type) || !TYPE_MIN_VALUE (type))
3386     tmin = lower_bound_in_type (type, type);
3387   else
3388     tmin = TYPE_MIN_VALUE (type);
3389   if (POINTER_TYPE_P (type) || !TYPE_MAX_VALUE (type))
3390     tmax = upper_bound_in_type (type, type);
3391   else
3392     tmax = TYPE_MAX_VALUE (type);
3393
3394   /* Try to use estimated number of iterations for the loop to constrain the
3395      final value in the evolution.
3396      We are interested in the number of executions of the latch, while
3397      nb_iterations_upper_bound includes the last execution of the exit test.  */
3398   if (TREE_CODE (step) == INTEGER_CST
3399       && loop->any_upper_bound
3400       && !double_int_zero_p (loop->nb_iterations_upper_bound)
3401       && is_gimple_val (init)
3402       && (TREE_CODE (init) != SSA_NAME
3403           || get_value_range (init)->type == VR_RANGE))
3404     {
3405       value_range_t maxvr = { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL };
3406       double_int dtmp;
3407       bool unsigned_p = TYPE_UNSIGNED (TREE_TYPE (step));
3408       int overflow = 0;
3409
3410       dtmp = double_int_mul_with_sign (tree_to_double_int (step),
3411                                        double_int_sub (
3412                                            loop->nb_iterations_upper_bound,
3413                                            double_int_one),
3414                                        unsigned_p, &overflow);
3415       tem = double_int_to_tree (TREE_TYPE (init), dtmp);
3416       /* If the multiplication overflowed we can't do a meaningful
3417          adjustment.  */
3418       if (!overflow && double_int_equal_p (dtmp, tree_to_double_int (tem)))
3419         {
3420           extract_range_from_binary_expr (&maxvr, PLUS_EXPR,
3421                                           TREE_TYPE (init), init, tem);
3422           /* Likewise if the addition did.  */
3423           if (maxvr.type == VR_RANGE)
3424             {
3425               tmin = maxvr.min;
3426               tmax = maxvr.max;
3427             }
3428         }
3429     }
3430
3431   if (vr->type == VR_VARYING || vr->type == VR_UNDEFINED)
3432     {
3433       min = tmin;
3434       max = tmax;
3435
3436       /* For VARYING or UNDEFINED ranges, just about anything we get
3437          from scalar evolutions should be better.  */
3438
3439       if (dir == EV_DIR_DECREASES)
3440         max = init;
3441       else
3442         min = init;
3443
3444       /* If we would create an invalid range, then just assume we
3445          know absolutely nothing.  This may be over-conservative,
3446          but it's clearly safe, and should happen only in unreachable
3447          parts of code, or for invalid programs.  */
3448       if (compare_values (min, max) == 1)
3449         return;
3450
3451       set_value_range (vr, VR_RANGE, min, max, vr->equiv);
3452     }
3453   else if (vr->type == VR_RANGE)
3454     {
3455       min = vr->min;
3456       max = vr->max;
3457
3458       if (dir == EV_DIR_DECREASES)
3459         {
3460           /* INIT is the maximum value.  If INIT is lower than VR->MAX
3461              but no smaller than VR->MIN, set VR->MAX to INIT.  */
3462           if (compare_values (init, max) == -1)
3463             max = init;
3464
3465           /* According to the loop information, the variable does not
3466              overflow.  If we think it does, probably because of an
3467              overflow due to arithmetic on a different INF value,
3468              reset now.  */
3469           if (is_negative_overflow_infinity (min)
3470               || compare_values (min, tmin) == -1)
3471             min = tmin;
3472
3473         }
3474       else
3475         {
3476           /* If INIT is bigger than VR->MIN, set VR->MIN to INIT.  */
3477           if (compare_values (init, min) == 1)
3478             min = init;
3479
3480           if (is_positive_overflow_infinity (max)
3481               || compare_values (tmax, max) == -1)
3482             max = tmax;
3483         }
3484
3485       /* If we just created an invalid range with the minimum
3486          greater than the maximum, we fail conservatively.
3487          This should happen only in unreachable
3488          parts of code, or for invalid programs.  */
3489       if (compare_values (min, max) == 1)
3490         return;
3491
3492       set_value_range (vr, VR_RANGE, min, max, vr->equiv);
3493     }
3494 }
3495
3496 /* Return true if VAR may overflow at STMT.  This checks any available
3497    loop information to see if we can determine that VAR does not
3498    overflow.  */
3499
3500 static bool
3501 vrp_var_may_overflow (tree var, gimple stmt)
3502 {
3503   struct loop *l;
3504   tree chrec, init, step;
3505
3506   if (current_loops == NULL)
3507     return true;
3508
3509   l = loop_containing_stmt (stmt);
3510   if (l == NULL
3511       || !loop_outer (l))
3512     return true;
3513
3514   chrec = instantiate_parameters (l, analyze_scalar_evolution (l, var));
3515   if (TREE_CODE (chrec) != POLYNOMIAL_CHREC)
3516     return true;
3517
3518   init = initial_condition_in_loop_num (chrec, l->num);
3519   step = evolution_part_in_loop_num (chrec, l->num);
3520
3521   if (step == NULL_TREE
3522       || !is_gimple_min_invariant (step)
3523       || !valid_value_p (init))
3524     return true;
3525
3526   /* If we get here, we know something useful about VAR based on the
3527      loop information.  If it wraps, it may overflow.  */
3528
3529   if (scev_probably_wraps_p (init, step, stmt, get_chrec_loop (chrec),
3530                              true))
3531     return true;
3532
3533   if (dump_file && (dump_flags & TDF_DETAILS) != 0)
3534     {
3535       print_generic_expr (dump_file, var, 0);
3536       fprintf (dump_file, ": loop information indicates does not overflow\n");
3537     }
3538
3539   return false;
3540 }
3541
3542
3543 /* Given two numeric value ranges VR0, VR1 and a comparison code COMP:
3544
3545    - Return BOOLEAN_TRUE_NODE if VR0 COMP VR1 always returns true for
3546      all the values in the ranges.
3547
3548    - Return BOOLEAN_FALSE_NODE if the comparison always returns false.
3549
3550    - Return NULL_TREE if it is not always possible to determine the
3551      value of the comparison.
3552
3553    Also set *STRICT_OVERFLOW_P to indicate whether a range with an
3554    overflow infinity was used in the test.  */
3555
3556
3557 static tree
3558 compare_ranges (enum tree_code comp, value_range_t *vr0, value_range_t *vr1,
3559                 bool *strict_overflow_p)
3560 {
3561   /* VARYING or UNDEFINED ranges cannot be compared.  */
3562   if (vr0->type == VR_VARYING
3563       || vr0->type == VR_UNDEFINED
3564       || vr1->type == VR_VARYING
3565       || vr1->type == VR_UNDEFINED)
3566     return NULL_TREE;
3567
3568   /* Anti-ranges need to be handled separately.  */
3569   if (vr0->type == VR_ANTI_RANGE || vr1->type == VR_ANTI_RANGE)
3570     {
3571       /* If both are anti-ranges, then we cannot compute any
3572          comparison.  */
3573       if (vr0->type == VR_ANTI_RANGE && vr1->type == VR_ANTI_RANGE)
3574         return NULL_TREE;
3575
3576       /* These comparisons are never statically computable.  */
3577       if (comp == GT_EXPR
3578           || comp == GE_EXPR
3579           || comp == LT_EXPR
3580           || comp == LE_EXPR)
3581         return NULL_TREE;
3582
3583       /* Equality can be computed only between a range and an
3584          anti-range.  ~[VAL1, VAL2] == [VAL1, VAL2] is always false.  */
3585       if (vr0->type == VR_RANGE)
3586         {
3587           /* To simplify processing, make VR0 the anti-range.  */
3588           value_range_t *tmp = vr0;
3589           vr0 = vr1;
3590           vr1 = tmp;
3591         }
3592
3593       gcc_assert (comp == NE_EXPR || comp == EQ_EXPR);
3594
3595       if (compare_values_warnv (vr0->min, vr1->min, strict_overflow_p) == 0
3596           && compare_values_warnv (vr0->max, vr1->max, strict_overflow_p) == 0)
3597         return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
3598
3599       return NULL_TREE;
3600     }
3601
3602   if (!usable_range_p (vr0, strict_overflow_p)
3603       || !usable_range_p (vr1, strict_overflow_p))
3604     return NULL_TREE;
3605
3606   /* Simplify processing.  If COMP is GT_EXPR or GE_EXPR, switch the
3607      operands around and change the comparison code.  */
3608   if (comp == GT_EXPR || comp == GE_EXPR)
3609     {
3610       value_range_t *tmp;
3611       comp = (comp == GT_EXPR) ? LT_EXPR : LE_EXPR;
3612       tmp = vr0;
3613       vr0 = vr1;
3614       vr1 = tmp;
3615     }
3616
3617   if (comp == EQ_EXPR)
3618     {
3619       /* Equality may only be computed if both ranges represent
3620          exactly one value.  */
3621       if (compare_values_warnv (vr0->min, vr0->max, strict_overflow_p) == 0
3622           && compare_values_warnv (vr1->min, vr1->max, strict_overflow_p) == 0)
3623         {
3624           int cmp_min = compare_values_warnv (vr0->min, vr1->min,
3625                                               strict_overflow_p);
3626           int cmp_max = compare_values_warnv (vr0->max, vr1->max,
3627                                               strict_overflow_p);
3628           if (cmp_min == 0 && cmp_max == 0)
3629             return boolean_true_node;
3630           else if (cmp_min != -2 && cmp_max != -2)
3631             return boolean_false_node;
3632         }
3633       /* If [V0_MIN, V1_MAX] < [V1_MIN, V1_MAX] then V0 != V1.  */
3634       else if (compare_values_warnv (vr0->min, vr1->max,
3635                                      strict_overflow_p) == 1
3636                || compare_values_warnv (vr1->min, vr0->max,
3637                                         strict_overflow_p) == 1)
3638         return boolean_false_node;
3639
3640       return NULL_TREE;
3641     }
3642   else if (comp == NE_EXPR)
3643     {
3644       int cmp1, cmp2;
3645
3646       /* If VR0 is completely to the left or completely to the right
3647          of VR1, they are always different.  Notice that we need to
3648          make sure that both comparisons yield similar results to
3649          avoid comparing values that cannot be compared at
3650          compile-time.  */
3651       cmp1 = compare_values_warnv (vr0->max, vr1->min, strict_overflow_p);
3652       cmp2 = compare_values_warnv (vr0->min, vr1->max, strict_overflow_p);
3653       if ((cmp1 == -1 && cmp2 == -1) || (cmp1 == 1 && cmp2 == 1))
3654         return boolean_true_node;
3655
3656       /* If VR0 and VR1 represent a single value and are identical,
3657          return false.  */
3658       else if (compare_values_warnv (vr0->min, vr0->max,
3659                                      strict_overflow_p) == 0
3660                && compare_values_warnv (vr1->min, vr1->max,
3661                                         strict_overflow_p) == 0
3662                && compare_values_warnv (vr0->min, vr1->min,
3663                                         strict_overflow_p) == 0
3664                && compare_values_warnv (vr0->max, vr1->max,
3665                                         strict_overflow_p) == 0)
3666         return boolean_false_node;
3667
3668       /* Otherwise, they may or may not be different.  */
3669       else
3670         return NULL_TREE;
3671     }
3672   else if (comp == LT_EXPR || comp == LE_EXPR)
3673     {
3674       int tst;
3675
3676       /* If VR0 is to the left of VR1, return true.  */
3677       tst = compare_values_warnv (vr0->max, vr1->min, strict_overflow_p);
3678       if ((comp == LT_EXPR && tst == -1)
3679           || (comp == LE_EXPR && (tst == -1 || tst == 0)))
3680         {
3681           if (overflow_infinity_range_p (vr0)
3682               || overflow_infinity_range_p (vr1))
3683             *strict_overflow_p = true;
3684           return boolean_true_node;
3685         }
3686
3687       /* If VR0 is to the right of VR1, return false.  */
3688       tst = compare_values_warnv (vr0->min, vr1->max, strict_overflow_p);
3689       if ((comp == LT_EXPR && (tst == 0 || tst == 1))
3690           || (comp == LE_EXPR && tst == 1))
3691         {
3692           if (overflow_infinity_range_p (vr0)
3693               || overflow_infinity_range_p (vr1))
3694             *strict_overflow_p = true;
3695           return boolean_false_node;
3696         }
3697
3698       /* Otherwise, we don't know.  */
3699       return NULL_TREE;
3700     }
3701
3702   gcc_unreachable ();
3703 }
3704
3705
3706 /* Given a value range VR, a value VAL and a comparison code COMP, return
3707    BOOLEAN_TRUE_NODE if VR COMP VAL always returns true for all the
3708    values in VR.  Return BOOLEAN_FALSE_NODE if the comparison
3709    always returns false.  Return NULL_TREE if it is not always
3710    possible to determine the value of the comparison.  Also set
3711    *STRICT_OVERFLOW_P to indicate whether a range with an overflow
3712    infinity was used in the test.  */
3713
3714 static tree
3715 compare_range_with_value (enum tree_code comp, value_range_t *vr, tree val,
3716                           bool *strict_overflow_p)
3717 {
3718   if (vr->type == VR_VARYING || vr->type == VR_UNDEFINED)
3719     return NULL_TREE;
3720
3721   /* Anti-ranges need to be handled separately.  */
3722   if (vr->type == VR_ANTI_RANGE)
3723     {
3724       /* For anti-ranges, the only predicates that we can compute at
3725          compile time are equality and inequality.  */
3726       if (comp == GT_EXPR
3727           || comp == GE_EXPR
3728           || comp == LT_EXPR
3729           || comp == LE_EXPR)
3730         return NULL_TREE;
3731
3732       /* ~[VAL_1, VAL_2] OP VAL is known if VAL_1 <= VAL <= VAL_2.  */
3733       if (value_inside_range (val, vr) == 1)
3734         return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
3735
3736       return NULL_TREE;
3737     }
3738
3739   if (!usable_range_p (vr, strict_overflow_p))
3740     return NULL_TREE;
3741
3742   if (comp == EQ_EXPR)
3743     {
3744       /* EQ_EXPR may only be computed if VR represents exactly
3745          one value.  */
3746       if (compare_values_warnv (vr->min, vr->max, strict_overflow_p) == 0)
3747         {
3748           int cmp = compare_values_warnv (vr->min, val, strict_overflow_p);
3749           if (cmp == 0)
3750             return boolean_true_node;
3751           else if (cmp == -1 || cmp == 1 || cmp == 2)
3752             return boolean_false_node;
3753         }
3754       else if (compare_values_warnv (val, vr->min, strict_overflow_p) == -1
3755                || compare_values_warnv (vr->max, val, strict_overflow_p) == -1)
3756         return boolean_false_node;
3757
3758       return NULL_TREE;
3759     }
3760   else if (comp == NE_EXPR)
3761     {
3762       /* If VAL is not inside VR, then they are always different.  */
3763       if (compare_values_warnv (vr->max, val, strict_overflow_p) == -1
3764           || compare_values_warnv (vr->min, val, strict_overflow_p) == 1)
3765         return boolean_true_node;
3766
3767       /* If VR represents exactly one value equal to VAL, then return
3768          false.  */
3769       if (compare_values_warnv (vr->min, vr->max, strict_overflow_p) == 0
3770           && compare_values_warnv (vr->min, val, strict_overflow_p) == 0)
3771         return boolean_false_node;
3772
3773       /* Otherwise, they may or may not be different.  */
3774       return NULL_TREE;
3775     }
3776   else if (comp == LT_EXPR || comp == LE_EXPR)
3777     {
3778       int tst;
3779
3780       /* If VR is to the left of VAL, return true.  */
3781       tst = compare_values_warnv (vr->max, val, strict_overflow_p);
3782       if ((comp == LT_EXPR && tst == -1)
3783           || (comp == LE_EXPR && (tst == -1 || tst == 0)))
3784         {
3785           if (overflow_infinity_range_p (vr))
3786             *strict_overflow_p = true;
3787           return boolean_true_node;
3788         }
3789
3790       /* If VR is to the right of VAL, return false.  */
3791       tst = compare_values_warnv (vr->min, val, strict_overflow_p);
3792       if ((comp == LT_EXPR && (tst == 0 || tst == 1))
3793           || (comp == LE_EXPR && tst == 1))
3794         {
3795           if (overflow_infinity_range_p (vr))
3796             *strict_overflow_p = true;
3797           return boolean_false_node;
3798         }
3799
3800       /* Otherwise, we don't know.  */
3801       return NULL_TREE;
3802     }
3803   else if (comp == GT_EXPR || comp == GE_EXPR)
3804     {
3805       int tst;
3806
3807       /* If VR is to the right of VAL, return true.  */
3808       tst = compare_values_warnv (vr->min, val, strict_overflow_p);
3809       if ((comp == GT_EXPR && tst == 1)
3810           || (comp == GE_EXPR && (tst == 0 || tst == 1)))
3811         {
3812           if (overflow_infinity_range_p (vr))
3813             *strict_overflow_p = true;
3814           return boolean_true_node;
3815         }
3816
3817       /* If VR is to the left of VAL, return false.  */
3818       tst = compare_values_warnv (vr->max, val, strict_overflow_p);
3819       if ((comp == GT_EXPR && (tst == -1 || tst == 0))
3820           || (comp == GE_EXPR && tst == -1))
3821         {
3822           if (overflow_infinity_range_p (vr))
3823             *strict_overflow_p = true;
3824           return boolean_false_node;
3825         }
3826
3827       /* Otherwise, we don't know.  */
3828       return NULL_TREE;
3829     }
3830
3831   gcc_unreachable ();
3832 }
3833
3834
3835 /* Debugging dumps.  */
3836
3837 void dump_value_range (FILE *, value_range_t *);
3838 void debug_value_range (value_range_t *);
3839 void dump_all_value_ranges (FILE *);
3840 void debug_all_value_ranges (void);
3841 void dump_vr_equiv (FILE *, bitmap);
3842 void debug_vr_equiv (bitmap);
3843
3844
3845 /* Dump value range VR to FILE.  */
3846
3847 void
3848 dump_value_range (FILE *file, value_range_t *vr)
3849 {
3850   if (vr == NULL)
3851     fprintf (file, "[]");
3852   else if (vr->type == VR_UNDEFINED)
3853     fprintf (file, "UNDEFINED");
3854   else if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
3855     {
3856       tree type = TREE_TYPE (vr->min);
3857
3858       fprintf (file, "%s[", (vr->type == VR_ANTI_RANGE) ? "~" : "");
3859
3860       if (is_negative_overflow_infinity (vr->min))
3861         fprintf (file, "-INF(OVF)");
3862       else if (INTEGRAL_TYPE_P (type)
3863                && !TYPE_UNSIGNED (type)
3864                && vrp_val_is_min (vr->min))
3865         fprintf (file, "-INF");
3866       else
3867         print_generic_expr (file, vr->min, 0);
3868
3869       fprintf (file, ", ");
3870
3871       if (is_positive_overflow_infinity (vr->max))
3872         fprintf (file, "+INF(OVF)");
3873       else if (INTEGRAL_TYPE_P (type)
3874                && vrp_val_is_max (vr->max))
3875         fprintf (file, "+INF");
3876       else
3877         print_generic_expr (file, vr->max, 0);
3878
3879       fprintf (file, "]");
3880
3881       if (vr->equiv)
3882         {
3883           bitmap_iterator bi;
3884           unsigned i, c = 0;
3885
3886           fprintf (file, "  EQUIVALENCES: { ");
3887
3888           EXECUTE_IF_SET_IN_BITMAP (vr->equiv, 0, i, bi)
3889             {
3890               print_generic_expr (file, ssa_name (i), 0);
3891               fprintf (file, " ");
3892               c++;
3893             }
3894
3895           fprintf (file, "} (%u elements)", c);
3896         }
3897     }
3898   else if (vr->type == VR_VARYING)
3899     fprintf (file, "VARYING");
3900   else
3901     fprintf (file, "INVALID RANGE");
3902 }
3903
3904
3905 /* Dump value range VR to stderr.  */
3906
3907 DEBUG_FUNCTION void
3908 debug_value_range (value_range_t *vr)
3909 {
3910   dump_value_range (stderr, vr);
3911   fprintf (stderr, "\n");
3912 }
3913
3914
3915 /* Dump value ranges of all SSA_NAMEs to FILE.  */
3916
3917 void
3918 dump_all_value_ranges (FILE *file)
3919 {
3920   size_t i;
3921
3922   for (i = 0; i < num_ssa_names; i++)
3923     {
3924       if (vr_value[i])
3925         {
3926           print_generic_expr (file, ssa_name (i), 0);
3927           fprintf (file, ": ");
3928           dump_value_range (file, vr_value[i]);
3929           fprintf (file, "\n");
3930         }
3931     }
3932
3933   fprintf (file, "\n");
3934 }
3935
3936
3937 /* Dump all value ranges to stderr.  */
3938
3939 DEBUG_FUNCTION void
3940 debug_all_value_ranges (void)
3941 {
3942   dump_all_value_ranges (stderr);
3943 }
3944
3945
3946 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
3947    create a new SSA name N and return the assertion assignment
3948    'V = ASSERT_EXPR <V, V OP W>'.  */
3949
3950 static gimple
3951 build_assert_expr_for (tree cond, tree v)
3952 {
3953   tree n;
3954   gimple assertion;
3955
3956   gcc_assert (TREE_CODE (v) == SSA_NAME);
3957   n = duplicate_ssa_name (v, NULL);
3958
3959   if (COMPARISON_CLASS_P (cond))
3960     {
3961       tree a = build2 (ASSERT_EXPR, TREE_TYPE (v), v, cond);
3962       assertion = gimple_build_assign (n, a);
3963     }
3964   else if (TREE_CODE (cond) == TRUTH_NOT_EXPR)
3965     {
3966       /* Given !V, build the assignment N = false.  */
3967       tree op0 = TREE_OPERAND (cond, 0);
3968       gcc_assert (op0 == v);
3969       assertion = gimple_build_assign (n, boolean_false_node);
3970     }
3971   else if (TREE_CODE (cond) == SSA_NAME)
3972     {
3973       /* Given V, build the assignment N = true.  */
3974       gcc_assert (v == cond);
3975       assertion = gimple_build_assign (n, boolean_true_node);
3976     }
3977   else
3978     gcc_unreachable ();
3979
3980   SSA_NAME_DEF_STMT (n) = assertion;
3981
3982   /* The new ASSERT_EXPR, creates a new SSA name that replaces the
3983      operand of the ASSERT_EXPR. Register the new name and the old one
3984      in the replacement table so that we can fix the SSA web after
3985      adding all the ASSERT_EXPRs.  */
3986   register_new_name_mapping (n, v);
3987
3988   return assertion;
3989 }
3990
3991
3992 /* Return false if EXPR is a predicate expression involving floating
3993    point values.  */
3994
3995 static inline bool
3996 fp_predicate (gimple stmt)
3997 {
3998   GIMPLE_CHECK (stmt, GIMPLE_COND);
3999
4000   return FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)));
4001 }
4002
4003
4004 /* If the range of values taken by OP can be inferred after STMT executes,
4005    return the comparison code (COMP_CODE_P) and value (VAL_P) that
4006    describes the inferred range.  Return true if a range could be
4007    inferred.  */
4008
4009 static bool
4010 infer_value_range (gimple stmt, tree op, enum tree_code *comp_code_p, tree *val_p)
4011 {
4012   *val_p = NULL_TREE;
4013   *comp_code_p = ERROR_MARK;
4014
4015   /* Do not attempt to infer anything in names that flow through
4016      abnormal edges.  */
4017   if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
4018     return false;
4019
4020   /* Similarly, don't infer anything from statements that may throw
4021      exceptions.  */
4022   if (stmt_could_throw_p (stmt))
4023     return false;
4024
4025   /* If STMT is the last statement of a basic block with no
4026      successors, there is no point inferring anything about any of its
4027      operands.  We would not be able to find a proper insertion point
4028      for the assertion, anyway.  */
4029   if (stmt_ends_bb_p (stmt) && EDGE_COUNT (gimple_bb (stmt)->succs) == 0)
4030     return false;
4031
4032   /* We can only assume that a pointer dereference will yield
4033      non-NULL if -fdelete-null-pointer-checks is enabled.  */
4034   if (flag_delete_null_pointer_checks
4035       && POINTER_TYPE_P (TREE_TYPE (op))
4036       && gimple_code (stmt) != GIMPLE_ASM)
4037     {
4038       unsigned num_uses, num_loads, num_stores;
4039
4040       count_uses_and_derefs (op, stmt, &num_uses, &num_loads, &num_stores);
4041       if (num_loads + num_stores > 0)
4042         {
4043           *val_p = build_int_cst (TREE_TYPE (op), 0);
4044           *comp_code_p = NE_EXPR;
4045           return true;
4046         }
4047     }
4048
4049   return false;
4050 }
4051
4052
4053 void dump_asserts_for (FILE *, tree);
4054 void debug_asserts_for (tree);
4055 void dump_all_asserts (FILE *);
4056 void debug_all_asserts (void);
4057
4058 /* Dump all the registered assertions for NAME to FILE.  */
4059
4060 void
4061 dump_asserts_for (FILE *file, tree name)
4062 {
4063   assert_locus_t loc;
4064
4065   fprintf (file, "Assertions to be inserted for ");
4066   print_generic_expr (file, name, 0);
4067   fprintf (file, "\n");
4068
4069   loc = asserts_for[SSA_NAME_VERSION (name)];
4070   while (loc)
4071     {
4072       fprintf (file, "\t");
4073       print_gimple_stmt (file, gsi_stmt (loc->si), 0, 0);
4074       fprintf (file, "\n\tBB #%d", loc->bb->index);
4075       if (loc->e)
4076         {
4077           fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
4078                    loc->e->dest->index);
4079           dump_edge_info (file, loc->e, 0);
4080         }
4081       fprintf (file, "\n\tPREDICATE: ");
4082       print_generic_expr (file, name, 0);
4083       fprintf (file, " %s ", tree_code_name[(int)loc->comp_code]);
4084       print_generic_expr (file, loc->val, 0);
4085       fprintf (file, "\n\n");
4086       loc = loc->next;
4087     }
4088
4089   fprintf (file, "\n");
4090 }
4091
4092
4093 /* Dump all the registered assertions for NAME to stderr.  */
4094
4095 DEBUG_FUNCTION void
4096 debug_asserts_for (tree name)
4097 {
4098   dump_asserts_for (stderr, name);
4099 }
4100
4101
4102 /* Dump all the registered assertions for all the names to FILE.  */
4103
4104 void
4105 dump_all_asserts (FILE *file)
4106 {
4107   unsigned i;
4108   bitmap_iterator bi;
4109
4110   fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
4111   EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
4112     dump_asserts_for (file, ssa_name (i));
4113   fprintf (file, "\n");
4114 }
4115
4116
4117 /* Dump all the registered assertions for all the names to stderr.  */
4118
4119 DEBUG_FUNCTION void
4120 debug_all_asserts (void)
4121 {
4122   dump_all_asserts (stderr);
4123 }
4124
4125
4126 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
4127    'EXPR COMP_CODE VAL' at a location that dominates block BB or
4128    E->DEST, then register this location as a possible insertion point
4129    for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
4130
4131    BB, E and SI provide the exact insertion point for the new
4132    ASSERT_EXPR.  If BB is NULL, then the ASSERT_EXPR is to be inserted
4133    on edge E.  Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
4134    BB.  If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
4135    must not be NULL.  */
4136
4137 static void
4138 register_new_assert_for (tree name, tree expr,
4139                          enum tree_code comp_code,
4140                          tree val,
4141                          basic_block bb,
4142                          edge e,
4143                          gimple_stmt_iterator si)
4144 {
4145   assert_locus_t n, loc, last_loc;
4146   basic_block dest_bb;
4147
4148   gcc_checking_assert (bb == NULL || e == NULL);
4149
4150   if (e == NULL)
4151     gcc_checking_assert (gimple_code (gsi_stmt (si)) != GIMPLE_COND
4152                          && gimple_code (gsi_stmt (si)) != GIMPLE_SWITCH);
4153
4154   /* Never build an assert comparing against an integer constant with
4155      TREE_OVERFLOW set.  This confuses our undefined overflow warning
4156      machinery.  */
4157   if (TREE_CODE (val) == INTEGER_CST
4158       && TREE_OVERFLOW (val))
4159     val = build_int_cst_wide (TREE_TYPE (val),
4160                               TREE_INT_CST_LOW (val), TREE_INT_CST_HIGH (val));
4161
4162   /* The new assertion A will be inserted at BB or E.  We need to
4163      determine if the new location is dominated by a previously
4164      registered location for A.  If we are doing an edge insertion,
4165      assume that A will be inserted at E->DEST.  Note that this is not
4166      necessarily true.
4167
4168      If E is a critical edge, it will be split.  But even if E is
4169      split, the new block will dominate the same set of blocks that
4170      E->DEST dominates.
4171
4172      The reverse, however, is not true, blocks dominated by E->DEST
4173      will not be dominated by the new block created to split E.  So,
4174      if the insertion location is on a critical edge, we will not use
4175      the new location to move another assertion previously registered
4176      at a block dominated by E->DEST.  */
4177   dest_bb = (bb) ? bb : e->dest;
4178
4179   /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
4180      VAL at a block dominating DEST_BB, then we don't need to insert a new
4181      one.  Similarly, if the same assertion already exists at a block
4182      dominated by DEST_BB and the new location is not on a critical
4183      edge, then update the existing location for the assertion (i.e.,
4184      move the assertion up in the dominance tree).
4185
4186      Note, this is implemented as a simple linked list because there
4187      should not be more than a handful of assertions registered per
4188      name.  If this becomes a performance problem, a table hashed by
4189      COMP_CODE and VAL could be implemented.  */
4190   loc = asserts_for[SSA_NAME_VERSION (name)];
4191   last_loc = loc;
4192   while (loc)
4193     {
4194       if (loc->comp_code == comp_code
4195           && (loc->val == val
4196               || operand_equal_p (loc->val, val, 0))
4197           && (loc->expr == expr
4198               || operand_equal_p (loc->expr, expr, 0)))
4199         {
4200           /* If the assertion NAME COMP_CODE VAL has already been
4201              registered at a basic block that dominates DEST_BB, then
4202              we don't need to insert the same assertion again.  Note
4203              that we don't check strict dominance here to avoid
4204              replicating the same assertion inside the same basic
4205              block more than once (e.g., when a pointer is
4206              dereferenced several times inside a block).
4207
4208              An exception to this rule are edge insertions.  If the
4209              new assertion is to be inserted on edge E, then it will
4210              dominate all the other insertions that we may want to
4211              insert in DEST_BB.  So, if we are doing an edge
4212              insertion, don't do this dominance check.  */
4213           if (e == NULL
4214               && dominated_by_p (CDI_DOMINATORS, dest_bb, loc->bb))
4215             return;
4216
4217           /* Otherwise, if E is not a critical edge and DEST_BB
4218              dominates the existing location for the assertion, move
4219              the assertion up in the dominance tree by updating its
4220              location information.  */
4221           if ((e == NULL || !EDGE_CRITICAL_P (e))
4222               && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
4223             {
4224               loc->bb = dest_bb;
4225               loc->e = e;
4226               loc->si = si;
4227               return;
4228             }
4229         }
4230
4231       /* Update the last node of the list and move to the next one.  */
4232       last_loc = loc;
4233       loc = loc->next;
4234     }
4235
4236   /* If we didn't find an assertion already registered for
4237      NAME COMP_CODE VAL, add a new one at the end of the list of
4238      assertions associated with NAME.  */
4239   n = XNEW (struct assert_locus_d);
4240   n->bb = dest_bb;
4241   n->e = e;
4242   n->si = si;
4243   n->comp_code = comp_code;
4244   n->val = val;
4245   n->expr = expr;
4246   n->next = NULL;
4247
4248   if (last_loc)
4249     last_loc->next = n;
4250   else
4251     asserts_for[SSA_NAME_VERSION (name)] = n;
4252
4253   bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
4254 }
4255
4256 /* (COND_OP0 COND_CODE COND_OP1) is a predicate which uses NAME.
4257    Extract a suitable test code and value and store them into *CODE_P and
4258    *VAL_P so the predicate is normalized to NAME *CODE_P *VAL_P.
4259
4260    If no extraction was possible, return FALSE, otherwise return TRUE.
4261
4262    If INVERT is true, then we invert the result stored into *CODE_P.  */
4263
4264 static bool
4265 extract_code_and_val_from_cond_with_ops (tree name, enum tree_code cond_code,
4266                                          tree cond_op0, tree cond_op1,
4267                                          bool invert, enum tree_code *code_p,
4268                                          tree *val_p)
4269 {
4270   enum tree_code comp_code;
4271   tree val;
4272
4273   /* Otherwise, we have a comparison of the form NAME COMP VAL
4274      or VAL COMP NAME.  */
4275   if (name == cond_op1)
4276     {
4277       /* If the predicate is of the form VAL COMP NAME, flip
4278          COMP around because we need to register NAME as the
4279          first operand in the predicate.  */
4280       comp_code = swap_tree_comparison (cond_code);
4281       val = cond_op0;
4282     }
4283   else
4284     {
4285       /* The comparison is of the form NAME COMP VAL, so the
4286          comparison code remains unchanged.  */
4287       comp_code = cond_code;
4288       val = cond_op1;
4289     }
4290
4291   /* Invert the comparison code as necessary.  */
4292   if (invert)
4293     comp_code = invert_tree_comparison (comp_code, 0);
4294
4295   /* VRP does not handle float types.  */
4296   if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (val)))
4297     return false;
4298
4299   /* Do not register always-false predicates.
4300      FIXME:  this works around a limitation in fold() when dealing with
4301      enumerations.  Given 'enum { N1, N2 } x;', fold will not
4302      fold 'if (x > N2)' to 'if (0)'.  */
4303   if ((comp_code == GT_EXPR || comp_code == LT_EXPR)
4304       && INTEGRAL_TYPE_P (TREE_TYPE (val)))
4305     {
4306       tree min = TYPE_MIN_VALUE (TREE_TYPE (val));
4307       tree max = TYPE_MAX_VALUE (TREE_TYPE (val));
4308
4309       if (comp_code == GT_EXPR
4310           && (!max
4311               || compare_values (val, max) == 0))
4312         return false;
4313
4314       if (comp_code == LT_EXPR
4315           && (!min
4316               || compare_values (val, min) == 0))
4317         return false;
4318     }
4319   *code_p = comp_code;
4320   *val_p = val;
4321   return true;
4322 }
4323
4324 /* Try to register an edge assertion for SSA name NAME on edge E for
4325    the condition COND contributing to the conditional jump pointed to by BSI.
4326    Invert the condition COND if INVERT is true.
4327    Return true if an assertion for NAME could be registered.  */
4328
4329 static bool
4330 register_edge_assert_for_2 (tree name, edge e, gimple_stmt_iterator bsi,
4331                             enum tree_code cond_code,
4332                             tree cond_op0, tree cond_op1, bool invert)
4333 {
4334   tree val;
4335   enum tree_code comp_code;
4336   bool retval = false;
4337
4338   if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
4339                                                 cond_op0,
4340                                                 cond_op1,
4341                                                 invert, &comp_code, &val))
4342     return false;
4343
4344   /* Only register an ASSERT_EXPR if NAME was found in the sub-graph
4345      reachable from E.  */
4346   if (live_on_edge (e, name)
4347       && !has_single_use (name))
4348     {
4349       register_new_assert_for (name, name, comp_code, val, NULL, e, bsi);
4350       retval = true;
4351     }
4352
4353   /* In the case of NAME <= CST and NAME being defined as
4354      NAME = (unsigned) NAME2 + CST2 we can assert NAME2 >= -CST2
4355      and NAME2 <= CST - CST2.  We can do the same for NAME > CST.
4356      This catches range and anti-range tests.  */
4357   if ((comp_code == LE_EXPR
4358        || comp_code == GT_EXPR)
4359       && TREE_CODE (val) == INTEGER_CST
4360       && TYPE_UNSIGNED (TREE_TYPE (val)))
4361     {
4362       gimple def_stmt = SSA_NAME_DEF_STMT (name);
4363       tree cst2 = NULL_TREE, name2 = NULL_TREE, name3 = NULL_TREE;
4364
4365       /* Extract CST2 from the (optional) addition.  */
4366       if (is_gimple_assign (def_stmt)
4367           && gimple_assign_rhs_code (def_stmt) == PLUS_EXPR)
4368         {
4369           name2 = gimple_assign_rhs1 (def_stmt);
4370           cst2 = gimple_assign_rhs2 (def_stmt);
4371           if (TREE_CODE (name2) == SSA_NAME
4372               && TREE_CODE (cst2) == INTEGER_CST)
4373             def_stmt = SSA_NAME_DEF_STMT (name2);
4374         }
4375
4376       /* Extract NAME2 from the (optional) sign-changing cast.  */
4377       if (gimple_assign_cast_p (def_stmt))
4378         {
4379           if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt))
4380               && ! TYPE_UNSIGNED (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
4381               && (TYPE_PRECISION (gimple_expr_type (def_stmt))
4382                   == TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))))
4383             name3 = gimple_assign_rhs1 (def_stmt);
4384         }
4385
4386       /* If name3 is used later, create an ASSERT_EXPR for it.  */
4387       if (name3 != NULL_TREE
4388           && TREE_CODE (name3) == SSA_NAME
4389           && (cst2 == NULL_TREE
4390               || TREE_CODE (cst2) == INTEGER_CST)
4391           && INTEGRAL_TYPE_P (TREE_TYPE (name3))
4392           && live_on_edge (e, name3)
4393           && !has_single_use (name3))
4394         {
4395           tree tmp;
4396
4397           /* Build an expression for the range test.  */
4398           tmp = build1 (NOP_EXPR, TREE_TYPE (name), name3);
4399           if (cst2 != NULL_TREE)
4400             tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
4401
4402           if (dump_file)
4403             {
4404               fprintf (dump_file, "Adding assert for ");
4405               print_generic_expr (dump_file, name3, 0);
4406               fprintf (dump_file, " from ");
4407               print_generic_expr (dump_file, tmp, 0);
4408               fprintf (dump_file, "\n");
4409             }
4410
4411           register_new_assert_for (name3, tmp, comp_code, val, NULL, e, bsi);
4412
4413           retval = true;
4414         }
4415
4416       /* If name2 is used later, create an ASSERT_EXPR for it.  */
4417       if (name2 != NULL_TREE
4418           && TREE_CODE (name2) == SSA_NAME
4419           && TREE_CODE (cst2) == INTEGER_CST
4420           && INTEGRAL_TYPE_P (TREE_TYPE (name2))
4421           && live_on_edge (e, name2)
4422           && !has_single_use (name2))
4423         {
4424           tree tmp;
4425
4426           /* Build an expression for the range test.  */
4427           tmp = name2;
4428           if (TREE_TYPE (name) != TREE_TYPE (name2))
4429             tmp = build1 (NOP_EXPR, TREE_TYPE (name), tmp);
4430           if (cst2 != NULL_TREE)
4431             tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
4432
4433           if (dump_file)
4434             {
4435               fprintf (dump_file, "Adding assert for ");
4436               print_generic_expr (dump_file, name2, 0);
4437               fprintf (dump_file, " from ");
4438               print_generic_expr (dump_file, tmp, 0);
4439               fprintf (dump_file, "\n");
4440             }
4441
4442           register_new_assert_for (name2, tmp, comp_code, val, NULL, e, bsi);
4443
4444           retval = true;
4445         }
4446     }
4447
4448   return retval;
4449 }
4450
4451 /* OP is an operand of a truth value expression which is known to have
4452    a particular value.  Register any asserts for OP and for any
4453    operands in OP's defining statement.
4454
4455    If CODE is EQ_EXPR, then we want to register OP is zero (false),
4456    if CODE is NE_EXPR, then we want to register OP is nonzero (true).   */
4457
4458 static bool
4459 register_edge_assert_for_1 (tree op, enum tree_code code,
4460                             edge e, gimple_stmt_iterator bsi)
4461 {
4462   bool retval = false;
4463   gimple op_def;
4464   tree val;
4465   enum tree_code rhs_code;
4466
4467   /* We only care about SSA_NAMEs.  */
4468   if (TREE_CODE (op) != SSA_NAME)
4469     return false;
4470
4471   /* We know that OP will have a zero or nonzero value.  If OP is used
4472      more than once go ahead and register an assert for OP.
4473
4474      The FOUND_IN_SUBGRAPH support is not helpful in this situation as
4475      it will always be set for OP (because OP is used in a COND_EXPR in
4476      the subgraph).  */
4477   if (!has_single_use (op))
4478     {
4479       val = build_int_cst (TREE_TYPE (op), 0);
4480       register_new_assert_for (op, op, code, val, NULL, e, bsi);
4481       retval = true;
4482     }
4483
4484   /* Now look at how OP is set.  If it's set from a comparison,
4485      a truth operation or some bit operations, then we may be able
4486      to register information about the operands of that assignment.  */
4487   op_def = SSA_NAME_DEF_STMT (op);
4488   if (gimple_code (op_def) != GIMPLE_ASSIGN)
4489     return retval;
4490
4491   rhs_code = gimple_assign_rhs_code (op_def);
4492
4493   if (TREE_CODE_CLASS (rhs_code) == tcc_comparison)
4494     {
4495       bool invert = (code == EQ_EXPR ? true : false);
4496       tree op0 = gimple_assign_rhs1 (op_def);
4497       tree op1 = gimple_assign_rhs2 (op_def);
4498
4499       if (TREE_CODE (op0) == SSA_NAME)
4500         retval |= register_edge_assert_for_2 (op0, e, bsi, rhs_code, op0, op1,
4501                                               invert);
4502       if (TREE_CODE (op1) == SSA_NAME)
4503         retval |= register_edge_assert_for_2 (op1, e, bsi, rhs_code, op0, op1,
4504                                               invert);
4505     }
4506   else if ((code == NE_EXPR
4507             && (gimple_assign_rhs_code (op_def) == TRUTH_AND_EXPR
4508                 || gimple_assign_rhs_code (op_def) == BIT_AND_EXPR))
4509            || (code == EQ_EXPR
4510                && (gimple_assign_rhs_code (op_def) == TRUTH_OR_EXPR
4511                    || gimple_assign_rhs_code (op_def) == BIT_IOR_EXPR)))
4512     {
4513       /* Recurse on each operand.  */
4514       retval |= register_edge_assert_for_1 (gimple_assign_rhs1 (op_def),
4515                                             code, e, bsi);
4516       retval |= register_edge_assert_for_1 (gimple_assign_rhs2 (op_def),
4517                                             code, e, bsi);
4518     }
4519   else if (gimple_assign_rhs_code (op_def) == TRUTH_NOT_EXPR)
4520     {
4521       /* Recurse, flipping CODE.  */
4522       code = invert_tree_comparison (code, false);
4523       retval |= register_edge_assert_for_1 (gimple_assign_rhs1 (op_def),
4524                                             code, e, bsi);
4525     }
4526   else if (gimple_assign_rhs_code (op_def) == SSA_NAME)
4527     {
4528       /* Recurse through the copy.  */
4529       retval |= register_edge_assert_for_1 (gimple_assign_rhs1 (op_def),
4530                                             code, e, bsi);
4531     }
4532   else if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (op_def)))
4533     {
4534       /* Recurse through the type conversion.  */
4535       retval |= register_edge_assert_for_1 (gimple_assign_rhs1 (op_def),
4536                                             code, e, bsi);
4537     }
4538
4539   return retval;
4540 }
4541
4542 /* Try to register an edge assertion for SSA name NAME on edge E for
4543    the condition COND contributing to the conditional jump pointed to by SI.
4544    Return true if an assertion for NAME could be registered.  */
4545
4546 static bool
4547 register_edge_assert_for (tree name, edge e, gimple_stmt_iterator si,
4548                           enum tree_code cond_code, tree cond_op0,
4549                           tree cond_op1)
4550 {
4551   tree val;
4552   enum tree_code comp_code;
4553   bool retval = false;
4554   bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
4555
4556   /* Do not attempt to infer anything in names that flow through
4557      abnormal edges.  */
4558   if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
4559     return false;
4560
4561   if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
4562                                                 cond_op0, cond_op1,
4563                                                 is_else_edge,
4564                                                 &comp_code, &val))
4565     return false;
4566
4567   /* Register ASSERT_EXPRs for name.  */
4568   retval |= register_edge_assert_for_2 (name, e, si, cond_code, cond_op0,
4569                                         cond_op1, is_else_edge);
4570
4571
4572   /* If COND is effectively an equality test of an SSA_NAME against
4573      the value zero or one, then we may be able to assert values
4574      for SSA_NAMEs which flow into COND.  */
4575
4576   /* In the case of NAME == 1 or NAME != 0, for TRUTH_AND_EXPR defining
4577      statement of NAME we can assert both operands of the TRUTH_AND_EXPR
4578      have nonzero value.  */
4579   if (((comp_code == EQ_EXPR && integer_onep (val))
4580        || (comp_code == NE_EXPR && integer_zerop (val))))
4581     {
4582       gimple def_stmt = SSA_NAME_DEF_STMT (name);
4583
4584       if (is_gimple_assign (def_stmt)
4585           && (gimple_assign_rhs_code (def_stmt) == TRUTH_AND_EXPR
4586               || gimple_assign_rhs_code (def_stmt) == BIT_AND_EXPR))
4587         {
4588           tree op0 = gimple_assign_rhs1 (def_stmt);
4589           tree op1 = gimple_assign_rhs2 (def_stmt);
4590           retval |= register_edge_assert_for_1 (op0, NE_EXPR, e, si);
4591           retval |= register_edge_assert_for_1 (op1, NE_EXPR, e, si);
4592         }
4593     }
4594
4595   /* In the case of NAME == 0 or NAME != 1, for TRUTH_OR_EXPR defining
4596      statement of NAME we can assert both operands of the TRUTH_OR_EXPR
4597      have zero value.  */
4598   if (((comp_code == EQ_EXPR && integer_zerop (val))
4599        || (comp_code == NE_EXPR && integer_onep (val))))
4600     {
4601       gimple def_stmt = SSA_NAME_DEF_STMT (name);
4602
4603       if (is_gimple_assign (def_stmt)
4604           && (gimple_assign_rhs_code (def_stmt) == TRUTH_OR_EXPR
4605               /* For BIT_IOR_EXPR only if NAME == 0 both operands have
4606                  necessarily zero value.  */
4607               || (comp_code == EQ_EXPR
4608                   && (gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR))))
4609         {
4610           tree op0 = gimple_assign_rhs1 (def_stmt);
4611           tree op1 = gimple_assign_rhs2 (def_stmt);
4612           retval |= register_edge_assert_for_1 (op0, EQ_EXPR, e, si);
4613           retval |= register_edge_assert_for_1 (op1, EQ_EXPR, e, si);
4614         }
4615     }
4616
4617   return retval;
4618 }
4619
4620
4621 /* Determine whether the outgoing edges of BB should receive an
4622    ASSERT_EXPR for each of the operands of BB's LAST statement.
4623    The last statement of BB must be a COND_EXPR.
4624
4625    If any of the sub-graphs rooted at BB have an interesting use of
4626    the predicate operands, an assert location node is added to the
4627    list of assertions for the corresponding operands.  */
4628
4629 static bool
4630 find_conditional_asserts (basic_block bb, gimple last)
4631 {
4632   bool need_assert;
4633   gimple_stmt_iterator bsi;
4634   tree op;
4635   edge_iterator ei;
4636   edge e;
4637   ssa_op_iter iter;
4638
4639   need_assert = false;
4640   bsi = gsi_for_stmt (last);
4641
4642   /* Look for uses of the operands in each of the sub-graphs
4643      rooted at BB.  We need to check each of the outgoing edges
4644      separately, so that we know what kind of ASSERT_EXPR to
4645      insert.  */
4646   FOR_EACH_EDGE (e, ei, bb->succs)
4647     {
4648       if (e->dest == bb)
4649         continue;
4650
4651       /* Register the necessary assertions for each operand in the
4652          conditional predicate.  */
4653       FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
4654         {
4655           need_assert |= register_edge_assert_for (op, e, bsi,
4656                                                    gimple_cond_code (last),
4657                                                    gimple_cond_lhs (last),
4658                                                    gimple_cond_rhs (last));
4659         }
4660     }
4661
4662   return need_assert;
4663 }
4664
4665 /* Compare two case labels sorting first by the destination label uid
4666    and then by the case value.  */
4667
4668 static int
4669 compare_case_labels (const void *p1, const void *p2)
4670 {
4671   const_tree const case1 = *(const_tree const*)p1;
4672   const_tree const case2 = *(const_tree const*)p2;
4673   unsigned int uid1 = DECL_UID (CASE_LABEL (case1));
4674   unsigned int uid2 = DECL_UID (CASE_LABEL (case2));
4675
4676   if (uid1 < uid2)
4677     return -1;
4678   else if (uid1 == uid2)
4679     {
4680       /* Make sure the default label is first in a group.  */
4681       if (!CASE_LOW (case1))
4682         return -1;
4683       else if (!CASE_LOW (case2))
4684         return 1;
4685       else
4686         return tree_int_cst_compare (CASE_LOW (case1), CASE_LOW (case2));
4687     }
4688   else
4689     return 1;
4690 }
4691
4692 /* Determine whether the outgoing edges of BB should receive an
4693    ASSERT_EXPR for each of the operands of BB's LAST statement.
4694    The last statement of BB must be a SWITCH_EXPR.
4695
4696    If any of the sub-graphs rooted at BB have an interesting use of
4697    the predicate operands, an assert location node is added to the
4698    list of assertions for the corresponding operands.  */
4699
4700 static bool
4701 find_switch_asserts (basic_block bb, gimple last)
4702 {
4703   bool need_assert;
4704   gimple_stmt_iterator bsi;
4705   tree op;
4706   edge e;
4707   tree vec2;
4708   size_t n = gimple_switch_num_labels(last);
4709 #if GCC_VERSION >= 4000
4710   unsigned int idx;
4711 #else
4712   /* Work around GCC 3.4 bug (PR 37086).  */
4713   volatile unsigned int idx;
4714 #endif
4715
4716   need_assert = false;
4717   bsi = gsi_for_stmt (last);
4718   op = gimple_switch_index (last);
4719   if (TREE_CODE (op) != SSA_NAME)
4720     return false;
4721
4722   /* Build a vector of case labels sorted by destination label.  */
4723   vec2 = make_tree_vec (n);
4724   for (idx = 0; idx < n; ++idx)
4725     TREE_VEC_ELT (vec2, idx) = gimple_switch_label (last, idx);
4726   qsort (&TREE_VEC_ELT (vec2, 0), n, sizeof (tree), compare_case_labels);
4727
4728   for (idx = 0; idx < n; ++idx)
4729     {
4730       tree min, max;
4731       tree cl = TREE_VEC_ELT (vec2, idx);
4732
4733       min = CASE_LOW (cl);
4734       max = CASE_HIGH (cl);
4735
4736       /* If there are multiple case labels with the same destination
4737          we need to combine them to a single value range for the edge.  */
4738       if (idx + 1 < n
4739           && CASE_LABEL (cl) == CASE_LABEL (TREE_VEC_ELT (vec2, idx + 1)))
4740         {
4741           /* Skip labels until the last of the group.  */
4742           do {
4743             ++idx;
4744           } while (idx < n
4745                    && CASE_LABEL (cl) == CASE_LABEL (TREE_VEC_ELT (vec2, idx)));
4746           --idx;
4747
4748           /* Pick up the maximum of the case label range.  */
4749           if (CASE_HIGH (TREE_VEC_ELT (vec2, idx)))
4750             max = CASE_HIGH (TREE_VEC_ELT (vec2, idx));
4751           else
4752             max = CASE_LOW (TREE_VEC_ELT (vec2, idx));
4753         }
4754
4755       /* Nothing to do if the range includes the default label until we
4756          can register anti-ranges.  */
4757       if (min == NULL_TREE)
4758         continue;
4759
4760       /* Find the edge to register the assert expr on.  */
4761       e = find_edge (bb, label_to_block (CASE_LABEL (cl)));
4762
4763       /* Register the necessary assertions for the operand in the
4764          SWITCH_EXPR.  */
4765       need_assert |= register_edge_assert_for (op, e, bsi,
4766                                                max ? GE_EXPR : EQ_EXPR,
4767                                                op,
4768                                                fold_convert (TREE_TYPE (op),
4769                                                              min));
4770       if (max)
4771         {
4772           need_assert |= register_edge_assert_for (op, e, bsi, LE_EXPR,
4773                                                    op,
4774                                                    fold_convert (TREE_TYPE (op),
4775                                                                  max));
4776         }
4777     }
4778
4779   return need_assert;
4780 }
4781
4782
4783 /* Traverse all the statements in block BB looking for statements that
4784    may generate useful assertions for the SSA names in their operand.
4785    If a statement produces a useful assertion A for name N_i, then the
4786    list of assertions already generated for N_i is scanned to
4787    determine if A is actually needed.
4788
4789    If N_i already had the assertion A at a location dominating the
4790    current location, then nothing needs to be done.  Otherwise, the
4791    new location for A is recorded instead.
4792
4793    1- For every statement S in BB, all the variables used by S are
4794       added to bitmap FOUND_IN_SUBGRAPH.
4795
4796    2- If statement S uses an operand N in a way that exposes a known
4797       value range for N, then if N was not already generated by an
4798       ASSERT_EXPR, create a new assert location for N.  For instance,
4799       if N is a pointer and the statement dereferences it, we can
4800       assume that N is not NULL.
4801
4802    3- COND_EXPRs are a special case of #2.  We can derive range
4803       information from the predicate but need to insert different
4804       ASSERT_EXPRs for each of the sub-graphs rooted at the
4805       conditional block.  If the last statement of BB is a conditional
4806       expression of the form 'X op Y', then
4807
4808       a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
4809
4810       b) If the conditional is the only entry point to the sub-graph
4811          corresponding to the THEN_CLAUSE, recurse into it.  On
4812          return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
4813          an ASSERT_EXPR is added for the corresponding variable.
4814
4815       c) Repeat step (b) on the ELSE_CLAUSE.
4816
4817       d) Mark X and Y in FOUND_IN_SUBGRAPH.
4818
4819       For instance,
4820
4821             if (a == 9)
4822               b = a;
4823             else
4824               b = c + 1;
4825
4826       In this case, an assertion on the THEN clause is useful to
4827       determine that 'a' is always 9 on that edge.  However, an assertion
4828       on the ELSE clause would be unnecessary.
4829
4830    4- If BB does not end in a conditional expression, then we recurse
4831       into BB's dominator children.
4832
4833    At the end of the recursive traversal, every SSA name will have a
4834    list of locations where ASSERT_EXPRs should be added.  When a new
4835    location for name N is found, it is registered by calling
4836    register_new_assert_for.  That function keeps track of all the
4837    registered assertions to prevent adding unnecessary assertions.
4838    For instance, if a pointer P_4 is dereferenced more than once in a
4839    dominator tree, only the location dominating all the dereference of
4840    P_4 will receive an ASSERT_EXPR.
4841
4842    If this function returns true, then it means that there are names
4843    for which we need to generate ASSERT_EXPRs.  Those assertions are
4844    inserted by process_assert_insertions.  */
4845
4846 static bool
4847 find_assert_locations_1 (basic_block bb, sbitmap live)
4848 {
4849   gimple_stmt_iterator si;
4850   gimple last;
4851   gimple phi;
4852   bool need_assert;
4853
4854   need_assert = false;
4855   last = last_stmt (bb);
4856
4857   /* If BB's last statement is a conditional statement involving integer
4858      operands, determine if we need to add ASSERT_EXPRs.  */
4859   if (last
4860       && gimple_code (last) == GIMPLE_COND
4861       && !fp_predicate (last)
4862       && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
4863     need_assert |= find_conditional_asserts (bb, last);
4864
4865   /* If BB's last statement is a switch statement involving integer
4866      operands, determine if we need to add ASSERT_EXPRs.  */
4867   if (last
4868       && gimple_code (last) == GIMPLE_SWITCH
4869       && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
4870     need_assert |= find_switch_asserts (bb, last);
4871
4872   /* Traverse all the statements in BB marking used names and looking
4873      for statements that may infer assertions for their used operands.  */
4874   for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
4875     {
4876       gimple stmt;
4877       tree op;
4878       ssa_op_iter i;
4879
4880       stmt = gsi_stmt (si);
4881
4882       if (is_gimple_debug (stmt))
4883         continue;
4884
4885       /* See if we can derive an assertion for any of STMT's operands.  */
4886       FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
4887         {
4888           tree value;
4889           enum tree_code comp_code;
4890
4891           /* Mark OP in our live bitmap.  */
4892           SET_BIT (live, SSA_NAME_VERSION (op));
4893
4894           /* If OP is used in such a way that we can infer a value
4895              range for it, and we don't find a previous assertion for
4896              it, create a new assertion location node for OP.  */
4897           if (infer_value_range (stmt, op, &comp_code, &value))
4898             {
4899               /* If we are able to infer a nonzero value range for OP,
4900                  then walk backwards through the use-def chain to see if OP
4901                  was set via a typecast.
4902
4903                  If so, then we can also infer a nonzero value range
4904                  for the operand of the NOP_EXPR.  */
4905               if (comp_code == NE_EXPR && integer_zerop (value))
4906                 {
4907                   tree t = op;
4908                   gimple def_stmt = SSA_NAME_DEF_STMT (t);
4909
4910                   while (is_gimple_assign (def_stmt)
4911                          && gimple_assign_rhs_code (def_stmt)  == NOP_EXPR
4912                          && TREE_CODE
4913                              (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
4914                          && POINTER_TYPE_P
4915                              (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
4916                     {
4917                       t = gimple_assign_rhs1 (def_stmt);
4918                       def_stmt = SSA_NAME_DEF_STMT (t);
4919
4920                       /* Note we want to register the assert for the
4921                          operand of the NOP_EXPR after SI, not after the
4922                          conversion.  */
4923                       if (! has_single_use (t))
4924                         {
4925                           register_new_assert_for (t, t, comp_code, value,
4926                                                    bb, NULL, si);
4927                           need_assert = true;
4928                         }
4929                     }
4930                 }
4931
4932               /* If OP is used only once, namely in this STMT, don't
4933                  bother creating an ASSERT_EXPR for it.  Such an
4934                  ASSERT_EXPR would do nothing but increase compile time.  */
4935               if (!has_single_use (op))
4936                 {
4937                   register_new_assert_for (op, op, comp_code, value,
4938                                            bb, NULL, si);
4939                   need_assert = true;
4940                 }
4941             }
4942         }
4943     }
4944
4945   /* Traverse all PHI nodes in BB marking used operands.  */
4946   for (si = gsi_start_phis (bb); !gsi_end_p(si); gsi_next (&si))
4947     {
4948       use_operand_p arg_p;
4949       ssa_op_iter i;
4950       phi = gsi_stmt (si);
4951
4952       FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
4953         {
4954           tree arg = USE_FROM_PTR (arg_p);
4955           if (TREE_CODE (arg) == SSA_NAME)
4956             SET_BIT (live, SSA_NAME_VERSION (arg));
4957         }
4958     }
4959
4960   return need_assert;
4961 }
4962
4963 /* Do an RPO walk over the function computing SSA name liveness
4964    on-the-fly and deciding on assert expressions to insert.
4965    Returns true if there are assert expressions to be inserted.  */
4966
4967 static bool
4968 find_assert_locations (void)
4969 {
4970   int *rpo = XCNEWVEC (int, last_basic_block + NUM_FIXED_BLOCKS);
4971   int *bb_rpo = XCNEWVEC (int, last_basic_block + NUM_FIXED_BLOCKS);
4972   int *last_rpo = XCNEWVEC (int, last_basic_block + NUM_FIXED_BLOCKS);
4973   int rpo_cnt, i;
4974   bool need_asserts;
4975
4976   live = XCNEWVEC (sbitmap, last_basic_block + NUM_FIXED_BLOCKS);
4977   rpo_cnt = pre_and_rev_post_order_compute (NULL, rpo, false);
4978   for (i = 0; i < rpo_cnt; ++i)
4979     bb_rpo[rpo[i]] = i;
4980
4981   need_asserts = false;
4982   for (i = rpo_cnt-1; i >= 0; --i)
4983     {
4984       basic_block bb = BASIC_BLOCK (rpo[i]);
4985       edge e;
4986       edge_iterator ei;
4987
4988       if (!live[rpo[i]])
4989         {
4990           live[rpo[i]] = sbitmap_alloc (num_ssa_names);
4991           sbitmap_zero (live[rpo[i]]);
4992         }
4993
4994       /* Process BB and update the live information with uses in
4995          this block.  */
4996       need_asserts |= find_assert_locations_1 (bb, live[rpo[i]]);
4997
4998       /* Merge liveness into the predecessor blocks and free it.  */
4999       if (!sbitmap_empty_p (live[rpo[i]]))
5000         {
5001           int pred_rpo = i;
5002           FOR_EACH_EDGE (e, ei, bb->preds)
5003             {
5004               int pred = e->src->index;
5005               if (e->flags & EDGE_DFS_BACK)
5006                 continue;
5007
5008               if (!live[pred])
5009                 {
5010                   live[pred] = sbitmap_alloc (num_ssa_names);
5011                   sbitmap_zero (live[pred]);
5012                 }
5013               sbitmap_a_or_b (live[pred], live[pred], live[rpo[i]]);
5014
5015               if (bb_rpo[pred] < pred_rpo)
5016                 pred_rpo = bb_rpo[pred];
5017             }
5018
5019           /* Record the RPO number of the last visited block that needs
5020              live information from this block.  */
5021           last_rpo[rpo[i]] = pred_rpo;
5022         }
5023       else
5024         {
5025           sbitmap_free (live[rpo[i]]);
5026           live[rpo[i]] = NULL;
5027         }
5028
5029       /* We can free all successors live bitmaps if all their
5030          predecessors have been visited already.  */
5031       FOR_EACH_EDGE (e, ei, bb->succs)
5032         if (last_rpo[e->dest->index] == i
5033             && live[e->dest->index])
5034           {
5035             sbitmap_free (live[e->dest->index]);
5036             live[e->dest->index] = NULL;
5037           }
5038     }
5039
5040   XDELETEVEC (rpo);
5041   XDELETEVEC (bb_rpo);
5042   XDELETEVEC (last_rpo);
5043   for (i = 0; i < last_basic_block + NUM_FIXED_BLOCKS; ++i)
5044     if (live[i])
5045       sbitmap_free (live[i]);
5046   XDELETEVEC (live);
5047
5048   return need_asserts;
5049 }
5050
5051 /* Create an ASSERT_EXPR for NAME and insert it in the location
5052    indicated by LOC.  Return true if we made any edge insertions.  */
5053
5054 static bool
5055 process_assert_insertions_for (tree name, assert_locus_t loc)
5056 {
5057   /* Build the comparison expression NAME_i COMP_CODE VAL.  */
5058   gimple stmt;
5059   tree cond;
5060   gimple assert_stmt;
5061   edge_iterator ei;
5062   edge e;
5063
5064   /* If we have X <=> X do not insert an assert expr for that.  */
5065   if (loc->expr == loc->val)
5066     return false;
5067
5068   cond = build2 (loc->comp_code, boolean_type_node, loc->expr, loc->val);
5069   assert_stmt = build_assert_expr_for (cond, name);
5070   if (loc->e)
5071     {
5072       /* We have been asked to insert the assertion on an edge.  This
5073          is used only by COND_EXPR and SWITCH_EXPR assertions.  */
5074       gcc_checking_assert (gimple_code (gsi_stmt (loc->si)) == GIMPLE_COND
5075                            || (gimple_code (gsi_stmt (loc->si))
5076                                == GIMPLE_SWITCH));
5077
5078       gsi_insert_on_edge (loc->e, assert_stmt);
5079       return true;
5080     }
5081
5082   /* Otherwise, we can insert right after LOC->SI iff the
5083      statement must not be the last statement in the block.  */
5084   stmt = gsi_stmt (loc->si);
5085   if (!stmt_ends_bb_p (stmt))
5086     {
5087       gsi_insert_after (&loc->si, assert_stmt, GSI_SAME_STMT);
5088       return false;
5089     }
5090
5091   /* If STMT must be the last statement in BB, we can only insert new
5092      assertions on the non-abnormal edge out of BB.  Note that since
5093      STMT is not control flow, there may only be one non-abnormal edge
5094      out of BB.  */
5095   FOR_EACH_EDGE (e, ei, loc->bb->succs)
5096     if (!(e->flags & EDGE_ABNORMAL))
5097       {
5098         gsi_insert_on_edge (e, assert_stmt);
5099         return true;
5100       }
5101
5102   gcc_unreachable ();
5103 }
5104
5105
5106 /* Process all the insertions registered for every name N_i registered
5107    in NEED_ASSERT_FOR.  The list of assertions to be inserted are
5108    found in ASSERTS_FOR[i].  */
5109
5110 static void
5111 process_assert_insertions (void)
5112 {
5113   unsigned i;
5114   bitmap_iterator bi;
5115   bool update_edges_p = false;
5116   int num_asserts = 0;
5117
5118   if (dump_file && (dump_flags & TDF_DETAILS))
5119     dump_all_asserts (dump_file);
5120
5121   EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
5122     {
5123       assert_locus_t loc = asserts_for[i];
5124       gcc_assert (loc);
5125
5126       while (loc)
5127         {
5128           assert_locus_t next = loc->next;
5129           update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
5130           free (loc);
5131           loc = next;
5132           num_asserts++;
5133         }
5134     }
5135
5136   if (update_edges_p)
5137     gsi_commit_edge_inserts ();
5138
5139   statistics_counter_event (cfun, "Number of ASSERT_EXPR expressions inserted",
5140                             num_asserts);
5141 }
5142
5143
5144 /* Traverse the flowgraph looking for conditional jumps to insert range
5145    expressions.  These range expressions are meant to provide information
5146    to optimizations that need to reason in terms of value ranges.  They
5147    will not be expanded into RTL.  For instance, given:
5148
5149    x = ...
5150    y = ...
5151    if (x < y)
5152      y = x - 2;
5153    else
5154      x = y + 3;
5155
5156    this pass will transform the code into:
5157
5158    x = ...
5159    y = ...
5160    if (x < y)
5161     {
5162       x = ASSERT_EXPR <x, x < y>
5163       y = x - 2
5164     }
5165    else
5166     {
5167       y = ASSERT_EXPR <y, x <= y>
5168       x = y + 3
5169     }
5170
5171    The idea is that once copy and constant propagation have run, other
5172    optimizations will be able to determine what ranges of values can 'x'
5173    take in different paths of the code, simply by checking the reaching
5174    definition of 'x'.  */
5175
5176 static void
5177 insert_range_assertions (void)
5178 {
5179   need_assert_for = BITMAP_ALLOC (NULL);
5180   asserts_for = XCNEWVEC (assert_locus_t, num_ssa_names);
5181
5182   calculate_dominance_info (CDI_DOMINATORS);
5183
5184   if (find_assert_locations ())
5185     {
5186       process_assert_insertions ();
5187       update_ssa (TODO_update_ssa_no_phi);
5188     }
5189
5190   if (dump_file && (dump_flags & TDF_DETAILS))
5191     {
5192       fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
5193       dump_function_to_file (current_function_decl, dump_file, dump_flags);
5194     }
5195
5196   free (asserts_for);
5197   BITMAP_FREE (need_assert_for);
5198 }
5199
5200 /* Checks one ARRAY_REF in REF, located at LOCUS. Ignores flexible arrays
5201    and "struct" hacks. If VRP can determine that the
5202    array subscript is a constant, check if it is outside valid
5203    range. If the array subscript is a RANGE, warn if it is
5204    non-overlapping with valid range.
5205    IGNORE_OFF_BY_ONE is true if the ARRAY_REF is inside a ADDR_EXPR.  */
5206
5207 static void
5208 check_array_ref (location_t location, tree ref, bool ignore_off_by_one)
5209 {
5210   value_range_t* vr = NULL;
5211   tree low_sub, up_sub;
5212   tree low_bound, up_bound, up_bound_p1;
5213   tree base;
5214
5215   if (TREE_NO_WARNING (ref))
5216     return;
5217
5218   low_sub = up_sub = TREE_OPERAND (ref, 1);
5219   up_bound = array_ref_up_bound (ref);
5220
5221   /* Can not check flexible arrays.  */
5222   if (!up_bound
5223       || TREE_CODE (up_bound) != INTEGER_CST)
5224     return;
5225
5226   /* Accesses to trailing arrays via pointers may access storage
5227      beyond the types array bounds.  */
5228   base = get_base_address (ref);
5229   if (base && TREE_CODE (base) == MEM_REF)
5230     {
5231       tree cref, next = NULL_TREE;
5232
5233       if (TREE_CODE (TREE_OPERAND (ref, 0)) != COMPONENT_REF)
5234         return;
5235
5236       cref = TREE_OPERAND (ref, 0);
5237       if (TREE_CODE (TREE_TYPE (TREE_OPERAND (cref, 0))) == RECORD_TYPE)
5238         for (next = DECL_CHAIN (TREE_OPERAND (cref, 1));
5239              next && TREE_CODE (next) != FIELD_DECL;
5240              next = DECL_CHAIN (next))
5241           ;
5242
5243       /* If this is the last field in a struct type or a field in a
5244          union type do not warn.  */
5245       if (!next)
5246         return;
5247     }
5248
5249   low_bound = array_ref_low_bound (ref);
5250   up_bound_p1 = int_const_binop (PLUS_EXPR, up_bound, integer_one_node, 0);
5251
5252   if (TREE_CODE (low_sub) == SSA_NAME)
5253     {
5254       vr = get_value_range (low_sub);
5255       if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
5256         {
5257           low_sub = vr->type == VR_RANGE ? vr->max : vr->min;
5258           up_sub = vr->type == VR_RANGE ? vr->min : vr->max;
5259         }
5260     }
5261
5262   if (vr && vr->type == VR_ANTI_RANGE)
5263     {
5264       if (TREE_CODE (up_sub) == INTEGER_CST
5265           && tree_int_cst_lt (up_bound, up_sub)
5266           && TREE_CODE (low_sub) == INTEGER_CST
5267           && tree_int_cst_lt (low_sub, low_bound))
5268         {
5269           warning_at (location, OPT_Warray_bounds,
5270                       "array subscript is outside array bounds");
5271           TREE_NO_WARNING (ref) = 1;
5272         }
5273     }
5274   else if (TREE_CODE (up_sub) == INTEGER_CST
5275            && (ignore_off_by_one
5276                ? (tree_int_cst_lt (up_bound, up_sub)
5277                   && !tree_int_cst_equal (up_bound_p1, up_sub))
5278                : (tree_int_cst_lt (up_bound, up_sub)
5279                   || tree_int_cst_equal (up_bound_p1, up_sub))))
5280     {
5281       warning_at (location, OPT_Warray_bounds,
5282                   "array subscript is above array bounds");
5283       TREE_NO_WARNING (ref) = 1;
5284     }
5285   else if (TREE_CODE (low_sub) == INTEGER_CST
5286            && tree_int_cst_lt (low_sub, low_bound))
5287     {
5288       warning_at (location, OPT_Warray_bounds,
5289                   "array subscript is below array bounds");
5290       TREE_NO_WARNING (ref) = 1;
5291     }
5292 }
5293
5294 /* Searches if the expr T, located at LOCATION computes
5295    address of an ARRAY_REF, and call check_array_ref on it.  */
5296
5297 static void
5298 search_for_addr_array (tree t, location_t location)
5299 {
5300   while (TREE_CODE (t) == SSA_NAME)
5301     {
5302       gimple g = SSA_NAME_DEF_STMT (t);
5303
5304       if (gimple_code (g) != GIMPLE_ASSIGN)
5305         return;
5306
5307       if (get_gimple_rhs_class (gimple_assign_rhs_code (g))
5308           != GIMPLE_SINGLE_RHS)
5309         return;
5310
5311       t = gimple_assign_rhs1 (g);
5312     }
5313
5314
5315   /* We are only interested in addresses of ARRAY_REF's.  */
5316   if (TREE_CODE (t) != ADDR_EXPR)
5317     return;
5318
5319   /* Check each ARRAY_REFs in the reference chain. */
5320   do
5321     {
5322       if (TREE_CODE (t) == ARRAY_REF)
5323         check_array_ref (location, t, true /*ignore_off_by_one*/);
5324
5325       t = TREE_OPERAND (t, 0);
5326     }
5327   while (handled_component_p (t));
5328
5329   if (TREE_CODE (t) == MEM_REF
5330       && TREE_CODE (TREE_OPERAND (t, 0)) == ADDR_EXPR
5331       && !TREE_NO_WARNING (t))
5332     {
5333       tree tem = TREE_OPERAND (TREE_OPERAND (t, 0), 0);
5334       tree low_bound, up_bound, el_sz;
5335       double_int idx;
5336       if (TREE_CODE (TREE_TYPE (tem)) != ARRAY_TYPE
5337           || TREE_CODE (TREE_TYPE (TREE_TYPE (tem))) == ARRAY_TYPE
5338           || !TYPE_DOMAIN (TREE_TYPE (tem)))
5339         return;
5340
5341       low_bound = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
5342       up_bound = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
5343       el_sz = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (tem)));
5344       if (!low_bound
5345           || TREE_CODE (low_bound) != INTEGER_CST
5346           || !up_bound
5347           || TREE_CODE (up_bound) != INTEGER_CST
5348           || !el_sz
5349           || TREE_CODE (el_sz) != INTEGER_CST)
5350         return;
5351
5352       idx = mem_ref_offset (t);
5353       idx = double_int_sdiv (idx, tree_to_double_int (el_sz), TRUNC_DIV_EXPR);
5354       if (double_int_scmp (idx, double_int_zero) < 0)
5355         {
5356           warning_at (location, OPT_Warray_bounds,
5357                       "array subscript is below array bounds");
5358           TREE_NO_WARNING (t) = 1;
5359         }
5360       else if (double_int_scmp (idx,
5361                                 double_int_add
5362                                   (double_int_add
5363                                     (tree_to_double_int (up_bound),
5364                                      double_int_neg
5365                                        (tree_to_double_int (low_bound))),
5366                                     double_int_one)) > 0)
5367         {
5368           warning_at (location, OPT_Warray_bounds,
5369                       "array subscript is above array bounds");
5370           TREE_NO_WARNING (t) = 1;
5371         }
5372     }
5373 }
5374
5375 /* walk_tree() callback that checks if *TP is
5376    an ARRAY_REF inside an ADDR_EXPR (in which an array
5377    subscript one outside the valid range is allowed). Call
5378    check_array_ref for each ARRAY_REF found. The location is
5379    passed in DATA.  */
5380
5381 static tree
5382 check_array_bounds (tree *tp, int *walk_subtree, void *data)
5383 {
5384   tree t = *tp;
5385   struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
5386   location_t location;
5387
5388   if (EXPR_HAS_LOCATION (t))
5389     location = EXPR_LOCATION (t);
5390   else
5391     {
5392       location_t *locp = (location_t *) wi->info;
5393       location = *locp;
5394     }
5395
5396   *walk_subtree = TRUE;
5397
5398   if (TREE_CODE (t) == ARRAY_REF)
5399     check_array_ref (location, t, false /*ignore_off_by_one*/);
5400
5401   if (TREE_CODE (t) == MEM_REF
5402       || (TREE_CODE (t) == RETURN_EXPR && TREE_OPERAND (t, 0)))
5403     search_for_addr_array (TREE_OPERAND (t, 0), location);
5404
5405   if (TREE_CODE (t) == ADDR_EXPR)
5406     *walk_subtree = FALSE;
5407
5408   return NULL_TREE;
5409 }
5410
5411 /* Walk over all statements of all reachable BBs and call check_array_bounds
5412    on them.  */
5413
5414 static void
5415 check_all_array_refs (void)
5416 {
5417   basic_block bb;
5418   gimple_stmt_iterator si;
5419
5420   FOR_EACH_BB (bb)
5421     {
5422       edge_iterator ei;
5423       edge e;
5424       bool executable = false;
5425
5426       /* Skip blocks that were found to be unreachable.  */
5427       FOR_EACH_EDGE (e, ei, bb->preds)
5428         executable |= !!(e->flags & EDGE_EXECUTABLE);
5429       if (!executable)
5430         continue;
5431
5432       for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
5433         {
5434           gimple stmt = gsi_stmt (si);
5435           struct walk_stmt_info wi;
5436           if (!gimple_has_location (stmt))
5437             continue;
5438
5439           if (is_gimple_call (stmt))
5440             {
5441               size_t i;
5442               size_t n = gimple_call_num_args (stmt);
5443               for (i = 0; i < n; i++)
5444                 {
5445                   tree arg = gimple_call_arg (stmt, i);
5446                   search_for_addr_array (arg, gimple_location (stmt));
5447                 }
5448             }
5449           else
5450             {
5451               memset (&wi, 0, sizeof (wi));
5452               wi.info = CONST_CAST (void *, (const void *)
5453                                     gimple_location_ptr (stmt));
5454
5455               walk_gimple_op (gsi_stmt (si),
5456                               check_array_bounds,
5457                               &wi);
5458             }
5459         }
5460     }
5461 }
5462
5463 /* Convert range assertion expressions into the implied copies and
5464    copy propagate away the copies.  Doing the trivial copy propagation
5465    here avoids the need to run the full copy propagation pass after
5466    VRP.
5467
5468    FIXME, this will eventually lead to copy propagation removing the
5469    names that had useful range information attached to them.  For
5470    instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
5471    then N_i will have the range [3, +INF].
5472
5473    However, by converting the assertion into the implied copy
5474    operation N_i = N_j, we will then copy-propagate N_j into the uses
5475    of N_i and lose the range information.  We may want to hold on to
5476    ASSERT_EXPRs a little while longer as the ranges could be used in
5477    things like jump threading.
5478
5479    The problem with keeping ASSERT_EXPRs around is that passes after
5480    VRP need to handle them appropriately.
5481
5482    Another approach would be to make the range information a first
5483    class property of the SSA_NAME so that it can be queried from
5484    any pass.  This is made somewhat more complex by the need for
5485    multiple ranges to be associated with one SSA_NAME.  */
5486
5487 static void
5488 remove_range_assertions (void)
5489 {
5490   basic_block bb;
5491   gimple_stmt_iterator si;
5492
5493   /* Note that the BSI iterator bump happens at the bottom of the
5494      loop and no bump is necessary if we're removing the statement
5495      referenced by the current BSI.  */
5496   FOR_EACH_BB (bb)
5497     for (si = gsi_start_bb (bb); !gsi_end_p (si);)
5498       {
5499         gimple stmt = gsi_stmt (si);
5500         gimple use_stmt;
5501
5502         if (is_gimple_assign (stmt)
5503             && gimple_assign_rhs_code (stmt) == ASSERT_EXPR)
5504           {
5505             tree rhs = gimple_assign_rhs1 (stmt);
5506             tree var;
5507             tree cond = fold (ASSERT_EXPR_COND (rhs));
5508             use_operand_p use_p;
5509             imm_use_iterator iter;
5510
5511             gcc_assert (cond != boolean_false_node);
5512
5513             /* Propagate the RHS into every use of the LHS.  */
5514             var = ASSERT_EXPR_VAR (rhs);
5515             FOR_EACH_IMM_USE_STMT (use_stmt, iter,
5516                                    gimple_assign_lhs (stmt))
5517               FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
5518                 {
5519                   SET_USE (use_p, var);
5520                   gcc_assert (TREE_CODE (var) == SSA_NAME);
5521                 }
5522
5523             /* And finally, remove the copy, it is not needed.  */
5524             gsi_remove (&si, true);
5525             release_defs (stmt);
5526           }
5527         else
5528           gsi_next (&si);
5529       }
5530 }
5531
5532
5533 /* Return true if STMT is interesting for VRP.  */
5534
5535 static bool
5536 stmt_interesting_for_vrp (gimple stmt)
5537 {
5538   if (gimple_code (stmt) == GIMPLE_PHI
5539       && is_gimple_reg (gimple_phi_result (stmt))
5540       && (INTEGRAL_TYPE_P (TREE_TYPE (gimple_phi_result (stmt)))
5541           || POINTER_TYPE_P (TREE_TYPE (gimple_phi_result (stmt)))))
5542     return true;
5543   else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
5544     {
5545       tree lhs = gimple_get_lhs (stmt);
5546
5547       /* In general, assignments with virtual operands are not useful
5548          for deriving ranges, with the obvious exception of calls to
5549          builtin functions.  */
5550       if (lhs && TREE_CODE (lhs) == SSA_NAME
5551           && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
5552               || POINTER_TYPE_P (TREE_TYPE (lhs)))
5553           && ((is_gimple_call (stmt)
5554                && gimple_call_fndecl (stmt) != NULL_TREE
5555                && DECL_IS_BUILTIN (gimple_call_fndecl (stmt)))
5556               || !gimple_vuse (stmt)))
5557         return true;
5558     }
5559   else if (gimple_code (stmt) == GIMPLE_COND
5560            || gimple_code (stmt) == GIMPLE_SWITCH)
5561     return true;
5562
5563   return false;
5564 }
5565
5566
5567 /* Initialize local data structures for VRP.  */
5568
5569 static void
5570 vrp_initialize (void)
5571 {
5572   basic_block bb;
5573
5574   vr_value = XCNEWVEC (value_range_t *, num_ssa_names);
5575   vr_phi_edge_counts = XCNEWVEC (int, num_ssa_names);
5576
5577   FOR_EACH_BB (bb)
5578     {
5579       gimple_stmt_iterator si;
5580
5581       for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
5582         {
5583           gimple phi = gsi_stmt (si);
5584           if (!stmt_interesting_for_vrp (phi))
5585             {
5586               tree lhs = PHI_RESULT (phi);
5587               set_value_range_to_varying (get_value_range (lhs));
5588               prop_set_simulate_again (phi, false);
5589             }
5590           else
5591             prop_set_simulate_again (phi, true);
5592         }
5593
5594       for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
5595         {
5596           gimple stmt = gsi_stmt (si);
5597
5598           /* If the statement is a control insn, then we do not
5599              want to avoid simulating the statement once.  Failure
5600              to do so means that those edges will never get added.  */
5601           if (stmt_ends_bb_p (stmt))
5602             prop_set_simulate_again (stmt, true);
5603           else if (!stmt_interesting_for_vrp (stmt))
5604             {
5605               ssa_op_iter i;
5606               tree def;
5607               FOR_EACH_SSA_TREE_OPERAND (def, stmt, i, SSA_OP_DEF)
5608                 set_value_range_to_varying (get_value_range (def));
5609               prop_set_simulate_again (stmt, false);
5610             }
5611           else
5612             prop_set_simulate_again (stmt, true);
5613         }
5614     }
5615 }
5616
5617
5618 /* Visit assignment STMT.  If it produces an interesting range, record
5619    the SSA name in *OUTPUT_P.  */
5620
5621 static enum ssa_prop_result
5622 vrp_visit_assignment_or_call (gimple stmt, tree *output_p)
5623 {
5624   tree def, lhs;
5625   ssa_op_iter iter;
5626   enum gimple_code code = gimple_code (stmt);
5627   lhs = gimple_get_lhs (stmt);
5628
5629   /* We only keep track of ranges in integral and pointer types.  */
5630   if (TREE_CODE (lhs) == SSA_NAME
5631       && ((INTEGRAL_TYPE_P (TREE_TYPE (lhs))
5632            /* It is valid to have NULL MIN/MAX values on a type.  See
5633               build_range_type.  */
5634            && TYPE_MIN_VALUE (TREE_TYPE (lhs))
5635            && TYPE_MAX_VALUE (TREE_TYPE (lhs)))
5636           || POINTER_TYPE_P (TREE_TYPE (lhs))))
5637     {
5638       value_range_t new_vr = { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL };
5639
5640       if (code == GIMPLE_CALL)
5641         extract_range_basic (&new_vr, stmt);
5642       else
5643         extract_range_from_assignment (&new_vr, stmt);
5644
5645       if (update_value_range (lhs, &new_vr))
5646         {
5647           *output_p = lhs;
5648
5649           if (dump_file && (dump_flags & TDF_DETAILS))
5650             {
5651               fprintf (dump_file, "Found new range for ");
5652               print_generic_expr (dump_file, lhs, 0);
5653               fprintf (dump_file, ": ");
5654               dump_value_range (dump_file, &new_vr);
5655               fprintf (dump_file, "\n\n");
5656             }
5657
5658           if (new_vr.type == VR_VARYING)
5659             return SSA_PROP_VARYING;
5660
5661           return SSA_PROP_INTERESTING;
5662         }
5663
5664       return SSA_PROP_NOT_INTERESTING;
5665     }
5666
5667   /* Every other statement produces no useful ranges.  */
5668   FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF)
5669     set_value_range_to_varying (get_value_range (def));
5670
5671   return SSA_PROP_VARYING;
5672 }
5673
5674 /* Helper that gets the value range of the SSA_NAME with version I
5675    or a symbolic range containing the SSA_NAME only if the value range
5676    is varying or undefined.  */
5677
5678 static inline value_range_t
5679 get_vr_for_comparison (int i)
5680 {
5681   value_range_t vr = *(vr_value[i]);
5682
5683   /* If name N_i does not have a valid range, use N_i as its own
5684      range.  This allows us to compare against names that may
5685      have N_i in their ranges.  */
5686   if (vr.type == VR_VARYING || vr.type == VR_UNDEFINED)
5687     {
5688       vr.type = VR_RANGE;
5689       vr.min = ssa_name (i);
5690       vr.max = ssa_name (i);
5691     }
5692
5693   return vr;
5694 }
5695
5696 /* Compare all the value ranges for names equivalent to VAR with VAL
5697    using comparison code COMP.  Return the same value returned by
5698    compare_range_with_value, including the setting of
5699    *STRICT_OVERFLOW_P.  */
5700
5701 static tree
5702 compare_name_with_value (enum tree_code comp, tree var, tree val,
5703                          bool *strict_overflow_p)
5704 {
5705   bitmap_iterator bi;
5706   unsigned i;
5707   bitmap e;
5708   tree retval, t;
5709   int used_strict_overflow;
5710   bool sop;
5711   value_range_t equiv_vr;
5712
5713   /* Get the set of equivalences for VAR.  */
5714   e = get_value_range (var)->equiv;
5715
5716   /* Start at -1.  Set it to 0 if we do a comparison without relying
5717      on overflow, or 1 if all comparisons rely on overflow.  */
5718   used_strict_overflow = -1;
5719
5720   /* Compare vars' value range with val.  */
5721   equiv_vr = get_vr_for_comparison (SSA_NAME_VERSION (var));
5722   sop = false;
5723   retval = compare_range_with_value (comp, &equiv_vr, val, &sop);
5724   if (retval)
5725     used_strict_overflow = sop ? 1 : 0;
5726
5727   /* If the equiv set is empty we have done all work we need to do.  */
5728   if (e == NULL)
5729     {
5730       if (retval
5731           && used_strict_overflow > 0)
5732         *strict_overflow_p = true;
5733       return retval;
5734     }
5735
5736   EXECUTE_IF_SET_IN_BITMAP (e, 0, i, bi)
5737     {
5738       equiv_vr = get_vr_for_comparison (i);
5739       sop = false;
5740       t = compare_range_with_value (comp, &equiv_vr, val, &sop);
5741       if (t)
5742         {
5743           /* If we get different answers from different members
5744              of the equivalence set this check must be in a dead
5745              code region.  Folding it to a trap representation
5746              would be correct here.  For now just return don't-know.  */
5747           if (retval != NULL
5748               && t != retval)
5749             {
5750               retval = NULL_TREE;
5751               break;
5752             }
5753           retval = t;
5754
5755           if (!sop)
5756             used_strict_overflow = 0;
5757           else if (used_strict_overflow < 0)
5758             used_strict_overflow = 1;
5759         }
5760     }
5761
5762   if (retval
5763       && used_strict_overflow > 0)
5764     *strict_overflow_p = true;
5765
5766   return retval;
5767 }
5768
5769
5770 /* Given a comparison code COMP and names N1 and N2, compare all the
5771    ranges equivalent to N1 against all the ranges equivalent to N2
5772    to determine the value of N1 COMP N2.  Return the same value
5773    returned by compare_ranges.  Set *STRICT_OVERFLOW_P to indicate
5774    whether we relied on an overflow infinity in the comparison.  */
5775
5776
5777 static tree
5778 compare_names (enum tree_code comp, tree n1, tree n2,
5779                bool *strict_overflow_p)
5780 {
5781   tree t, retval;
5782   bitmap e1, e2;
5783   bitmap_iterator bi1, bi2;
5784   unsigned i1, i2;
5785   int used_strict_overflow;
5786   static bitmap_obstack *s_obstack = NULL;
5787   static bitmap s_e1 = NULL, s_e2 = NULL;
5788
5789   /* Compare the ranges of every name equivalent to N1 against the
5790      ranges of every name equivalent to N2.  */
5791   e1 = get_value_range (n1)->equiv;
5792   e2 = get_value_range (n2)->equiv;
5793
5794   /* Use the fake bitmaps if e1 or e2 are not available.  */
5795   if (s_obstack == NULL)
5796     {
5797       s_obstack = XNEW (bitmap_obstack);
5798       bitmap_obstack_initialize (s_obstack);
5799       s_e1 = BITMAP_ALLOC (s_obstack);
5800       s_e2 = BITMAP_ALLOC (s_obstack);
5801     }
5802   if (e1 == NULL)
5803     e1 = s_e1;
5804   if (e2 == NULL)
5805     e2 = s_e2;
5806
5807   /* Add N1 and N2 to their own set of equivalences to avoid
5808      duplicating the body of the loop just to check N1 and N2
5809      ranges.  */
5810   bitmap_set_bit (e1, SSA_NAME_VERSION (n1));
5811   bitmap_set_bit (e2, SSA_NAME_VERSION (n2));
5812
5813   /* If the equivalence sets have a common intersection, then the two
5814      names can be compared without checking their ranges.  */
5815   if (bitmap_intersect_p (e1, e2))
5816     {
5817       bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
5818       bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
5819
5820       return (comp == EQ_EXPR || comp == GE_EXPR || comp == LE_EXPR)
5821              ? boolean_true_node
5822              : boolean_false_node;
5823     }
5824
5825   /* Start at -1.  Set it to 0 if we do a comparison without relying
5826      on overflow, or 1 if all comparisons rely on overflow.  */
5827   used_strict_overflow = -1;
5828
5829   /* Otherwise, compare all the equivalent ranges.  First, add N1 and
5830      N2 to their own set of equivalences to avoid duplicating the body
5831      of the loop just to check N1 and N2 ranges.  */
5832   EXECUTE_IF_SET_IN_BITMAP (e1, 0, i1, bi1)
5833     {
5834       value_range_t vr1 = get_vr_for_comparison (i1);
5835
5836       t = retval = NULL_TREE;
5837       EXECUTE_IF_SET_IN_BITMAP (e2, 0, i2, bi2)
5838         {
5839           bool sop = false;
5840
5841           value_range_t vr2 = get_vr_for_comparison (i2);
5842
5843           t = compare_ranges (comp, &vr1, &vr2, &sop);
5844           if (t)
5845             {
5846               /* If we get different answers from different members
5847                  of the equivalence set this check must be in a dead
5848                  code region.  Folding it to a trap representation
5849                  would be correct here.  For now just return don't-know.  */
5850               if (retval != NULL
5851                   && t != retval)
5852                 {
5853                   bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
5854                   bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
5855                   return NULL_TREE;
5856                 }
5857               retval = t;
5858
5859               if (!sop)
5860                 used_strict_overflow = 0;
5861               else if (used_strict_overflow < 0)
5862                 used_strict_overflow = 1;
5863             }
5864         }
5865
5866       if (retval)
5867         {
5868           bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
5869           bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
5870           if (used_strict_overflow > 0)
5871             *strict_overflow_p = true;
5872           return retval;
5873         }
5874     }
5875
5876   /* None of the equivalent ranges are useful in computing this
5877      comparison.  */
5878   bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
5879   bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
5880   return NULL_TREE;
5881 }
5882
5883 /* Helper function for vrp_evaluate_conditional_warnv.  */
5884
5885 static tree
5886 vrp_evaluate_conditional_warnv_with_ops_using_ranges (enum tree_code code,
5887                                                       tree op0, tree op1,
5888                                                       bool * strict_overflow_p)
5889 {
5890   value_range_t *vr0, *vr1;
5891
5892   vr0 = (TREE_CODE (op0) == SSA_NAME) ? get_value_range (op0) : NULL;
5893   vr1 = (TREE_CODE (op1) == SSA_NAME) ? get_value_range (op1) : NULL;
5894
5895   if (vr0 && vr1)
5896     return compare_ranges (code, vr0, vr1, strict_overflow_p);
5897   else if (vr0 && vr1 == NULL)
5898     return compare_range_with_value (code, vr0, op1, strict_overflow_p);
5899   else if (vr0 == NULL && vr1)
5900     return (compare_range_with_value
5901             (swap_tree_comparison (code), vr1, op0, strict_overflow_p));
5902   return NULL;
5903 }
5904
5905 /* Helper function for vrp_evaluate_conditional_warnv. */
5906
5907 static tree
5908 vrp_evaluate_conditional_warnv_with_ops (enum tree_code code, tree op0,
5909                                          tree op1, bool use_equiv_p,
5910                                          bool *strict_overflow_p, bool *only_ranges)
5911 {
5912   tree ret;
5913   if (only_ranges)
5914     *only_ranges = true;
5915
5916   /* We only deal with integral and pointer types.  */
5917   if (!INTEGRAL_TYPE_P (TREE_TYPE (op0))
5918       && !POINTER_TYPE_P (TREE_TYPE (op0)))
5919     return NULL_TREE;
5920
5921   if (use_equiv_p)
5922     {
5923       if (only_ranges
5924           && (ret = vrp_evaluate_conditional_warnv_with_ops_using_ranges
5925                       (code, op0, op1, strict_overflow_p)))
5926         return ret;
5927       *only_ranges = false;
5928       if (TREE_CODE (op0) == SSA_NAME && TREE_CODE (op1) == SSA_NAME)
5929         return compare_names (code, op0, op1, strict_overflow_p);
5930       else if (TREE_CODE (op0) == SSA_NAME)
5931         return compare_name_with_value (code, op0, op1, strict_overflow_p);
5932       else if (TREE_CODE (op1) == SSA_NAME)
5933         return (compare_name_with_value
5934                 (swap_tree_comparison (code), op1, op0, strict_overflow_p));
5935     }
5936   else
5937     return vrp_evaluate_conditional_warnv_with_ops_using_ranges (code, op0, op1,
5938                                                                  strict_overflow_p);
5939   return NULL_TREE;
5940 }
5941
5942 /* Given (CODE OP0 OP1) within STMT, try to simplify it based on value range
5943    information.  Return NULL if the conditional can not be evaluated.
5944    The ranges of all the names equivalent with the operands in COND
5945    will be used when trying to compute the value.  If the result is
5946    based on undefined signed overflow, issue a warning if
5947    appropriate.  */
5948
5949 static tree
5950 vrp_evaluate_conditional (enum tree_code code, tree op0, tree op1, gimple stmt)
5951 {
5952   bool sop;
5953   tree ret;
5954   bool only_ranges;
5955
5956   /* Some passes and foldings leak constants with overflow flag set
5957      into the IL.  Avoid doing wrong things with these and bail out.  */
5958   if ((TREE_CODE (op0) == INTEGER_CST
5959        && TREE_OVERFLOW (op0))
5960       || (TREE_CODE (op1) == INTEGER_CST
5961           && TREE_OVERFLOW (op1)))
5962     return NULL_TREE;
5963
5964   sop = false;
5965   ret = vrp_evaluate_conditional_warnv_with_ops (code, op0, op1, true, &sop,
5966                                                  &only_ranges);
5967
5968   if (ret && sop)
5969     {
5970       enum warn_strict_overflow_code wc;
5971       const char* warnmsg;
5972
5973       if (is_gimple_min_invariant (ret))
5974         {
5975           wc = WARN_STRICT_OVERFLOW_CONDITIONAL;
5976           warnmsg = G_("assuming signed overflow does not occur when "
5977                        "simplifying conditional to constant");
5978         }
5979       else
5980         {
5981           wc = WARN_STRICT_OVERFLOW_COMPARISON;
5982           warnmsg = G_("assuming signed overflow does not occur when "
5983                        "simplifying conditional");
5984         }
5985
5986       if (issue_strict_overflow_warning (wc))
5987         {
5988           location_t location;
5989
5990           if (!gimple_has_location (stmt))
5991             location = input_location;
5992           else
5993             location = gimple_location (stmt);
5994           warning_at (location, OPT_Wstrict_overflow, "%s", warnmsg);
5995         }
5996     }
5997
5998   if (warn_type_limits
5999       && ret && only_ranges
6000       && TREE_CODE_CLASS (code) == tcc_comparison
6001       && TREE_CODE (op0) == SSA_NAME)
6002     {
6003       /* If the comparison is being folded and the operand on the LHS
6004          is being compared against a constant value that is outside of
6005          the natural range of OP0's type, then the predicate will
6006          always fold regardless of the value of OP0.  If -Wtype-limits
6007          was specified, emit a warning.  */
6008       tree type = TREE_TYPE (op0);
6009       value_range_t *vr0 = get_value_range (op0);
6010
6011       if (vr0->type != VR_VARYING
6012           && INTEGRAL_TYPE_P (type)
6013           && vrp_val_is_min (vr0->min)
6014           && vrp_val_is_max (vr0->max)
6015           && is_gimple_min_invariant (op1))
6016         {
6017           location_t location;
6018
6019           if (!gimple_has_location (stmt))
6020             location = input_location;
6021           else
6022             location = gimple_location (stmt);
6023
6024           warning_at (location, OPT_Wtype_limits,
6025                       integer_zerop (ret)
6026                       ? G_("comparison always false "
6027                            "due to limited range of data type")
6028                       : G_("comparison always true "
6029                            "due to limited range of data type"));
6030         }
6031     }
6032
6033   return ret;
6034 }
6035
6036
6037 /* Visit conditional statement STMT.  If we can determine which edge
6038    will be taken out of STMT's basic block, record it in
6039    *TAKEN_EDGE_P and return SSA_PROP_INTERESTING.  Otherwise, return
6040    SSA_PROP_VARYING.  */
6041
6042 static enum ssa_prop_result
6043 vrp_visit_cond_stmt (gimple stmt, edge *taken_edge_p)
6044 {
6045   tree val;
6046   bool sop;
6047
6048   *taken_edge_p = NULL;
6049
6050   if (dump_file && (dump_flags & TDF_DETAILS))
6051     {
6052       tree use;
6053       ssa_op_iter i;
6054
6055       fprintf (dump_file, "\nVisiting conditional with predicate: ");
6056       print_gimple_stmt (dump_file, stmt, 0, 0);
6057       fprintf (dump_file, "\nWith known ranges\n");
6058
6059       FOR_EACH_SSA_TREE_OPERAND (use, stmt, i, SSA_OP_USE)
6060         {
6061           fprintf (dump_file, "\t");
6062           print_generic_expr (dump_file, use, 0);
6063           fprintf (dump_file, ": ");
6064           dump_value_range (dump_file, vr_value[SSA_NAME_VERSION (use)]);
6065         }
6066
6067       fprintf (dump_file, "\n");
6068     }
6069
6070   /* Compute the value of the predicate COND by checking the known
6071      ranges of each of its operands.
6072
6073      Note that we cannot evaluate all the equivalent ranges here
6074      because those ranges may not yet be final and with the current
6075      propagation strategy, we cannot determine when the value ranges
6076      of the names in the equivalence set have changed.
6077
6078      For instance, given the following code fragment
6079
6080         i_5 = PHI <8, i_13>
6081         ...
6082         i_14 = ASSERT_EXPR <i_5, i_5 != 0>
6083         if (i_14 == 1)
6084           ...
6085
6086      Assume that on the first visit to i_14, i_5 has the temporary
6087      range [8, 8] because the second argument to the PHI function is
6088      not yet executable.  We derive the range ~[0, 0] for i_14 and the
6089      equivalence set { i_5 }.  So, when we visit 'if (i_14 == 1)' for
6090      the first time, since i_14 is equivalent to the range [8, 8], we
6091      determine that the predicate is always false.
6092
6093      On the next round of propagation, i_13 is determined to be
6094      VARYING, which causes i_5 to drop down to VARYING.  So, another
6095      visit to i_14 is scheduled.  In this second visit, we compute the
6096      exact same range and equivalence set for i_14, namely ~[0, 0] and
6097      { i_5 }.  But we did not have the previous range for i_5
6098      registered, so vrp_visit_assignment thinks that the range for
6099      i_14 has not changed.  Therefore, the predicate 'if (i_14 == 1)'
6100      is not visited again, which stops propagation from visiting
6101      statements in the THEN clause of that if().
6102
6103      To properly fix this we would need to keep the previous range
6104      value for the names in the equivalence set.  This way we would've
6105      discovered that from one visit to the other i_5 changed from
6106      range [8, 8] to VR_VARYING.
6107
6108      However, fixing this apparent limitation may not be worth the
6109      additional checking.  Testing on several code bases (GCC, DLV,
6110      MICO, TRAMP3D and SPEC2000) showed that doing this results in
6111      4 more predicates folded in SPEC.  */
6112   sop = false;
6113
6114   val = vrp_evaluate_conditional_warnv_with_ops (gimple_cond_code (stmt),
6115                                                  gimple_cond_lhs (stmt),
6116                                                  gimple_cond_rhs (stmt),
6117                                                  false, &sop, NULL);
6118   if (val)
6119     {
6120       if (!sop)
6121         *taken_edge_p = find_taken_edge (gimple_bb (stmt), val);
6122       else
6123         {
6124           if (dump_file && (dump_flags & TDF_DETAILS))
6125             fprintf (dump_file,
6126                      "\nIgnoring predicate evaluation because "
6127                      "it assumes that signed overflow is undefined");
6128           val = NULL_TREE;
6129         }
6130     }
6131
6132   if (dump_file && (dump_flags & TDF_DETAILS))
6133     {
6134       fprintf (dump_file, "\nPredicate evaluates to: ");
6135       if (val == NULL_TREE)
6136         fprintf (dump_file, "DON'T KNOW\n");
6137       else
6138         print_generic_stmt (dump_file, val, 0);
6139     }
6140
6141   return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
6142 }
6143
6144 /* Searches the case label vector VEC for the index *IDX of the CASE_LABEL
6145    that includes the value VAL.  The search is restricted to the range
6146    [START_IDX, n - 1] where n is the size of VEC.
6147
6148    If there is a CASE_LABEL for VAL, its index is placed in IDX and true is
6149    returned.
6150
6151    If there is no CASE_LABEL for VAL and there is one that is larger than VAL,
6152    it is placed in IDX and false is returned.
6153
6154    If VAL is larger than any CASE_LABEL, n is placed on IDX and false is
6155    returned. */
6156
6157 static bool
6158 find_case_label_index (gimple stmt, size_t start_idx, tree val, size_t *idx)
6159 {
6160   size_t n = gimple_switch_num_labels (stmt);
6161   size_t low, high;
6162
6163   /* Find case label for minimum of the value range or the next one.
6164      At each iteration we are searching in [low, high - 1]. */
6165
6166   for (low = start_idx, high = n; high != low; )
6167     {
6168       tree t;
6169       int cmp;
6170       /* Note that i != high, so we never ask for n. */
6171       size_t i = (high + low) / 2;
6172       t = gimple_switch_label (stmt, i);
6173
6174       /* Cache the result of comparing CASE_LOW and val.  */
6175       cmp = tree_int_cst_compare (CASE_LOW (t), val);
6176
6177       if (cmp == 0)
6178         {
6179           /* Ranges cannot be empty. */
6180           *idx = i;
6181           return true;
6182         }
6183       else if (cmp > 0)
6184         high = i;
6185       else
6186         {
6187           low = i + 1;
6188           if (CASE_HIGH (t) != NULL
6189               && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
6190             {
6191               *idx = i;
6192               return true;
6193             }
6194         }
6195     }
6196
6197   *idx = high;
6198   return false;
6199 }
6200
6201 /* Searches the case label vector VEC for the range of CASE_LABELs that is used
6202    for values between MIN and MAX. The first index is placed in MIN_IDX. The
6203    last index is placed in MAX_IDX. If the range of CASE_LABELs is empty
6204    then MAX_IDX < MIN_IDX.
6205    Returns true if the default label is not needed. */
6206
6207 static bool
6208 find_case_label_range (gimple stmt, tree min, tree max, size_t *min_idx,
6209                        size_t *max_idx)
6210 {
6211   size_t i, j;
6212   bool min_take_default = !find_case_label_index (stmt, 1, min, &i);
6213   bool max_take_default = !find_case_label_index (stmt, i, max, &j);
6214
6215   if (i == j
6216       && min_take_default
6217       && max_take_default)
6218     {
6219       /* Only the default case label reached.
6220          Return an empty range. */
6221       *min_idx = 1;
6222       *max_idx = 0;
6223       return false;
6224     }
6225   else
6226     {
6227       bool take_default = min_take_default || max_take_default;
6228       tree low, high;
6229       size_t k;
6230
6231       if (max_take_default)
6232         j--;
6233
6234       /* If the case label range is continuous, we do not need
6235          the default case label.  Verify that.  */
6236       high = CASE_LOW (gimple_switch_label (stmt, i));
6237       if (CASE_HIGH (gimple_switch_label (stmt, i)))
6238         high = CASE_HIGH (gimple_switch_label (stmt, i));
6239       for (k = i + 1; k <= j; ++k)
6240         {
6241           low = CASE_LOW (gimple_switch_label (stmt, k));
6242           if (!integer_onep (int_const_binop (MINUS_EXPR, low, high, 0)))
6243             {
6244               take_default = true;
6245               break;
6246             }
6247           high = low;
6248           if (CASE_HIGH (gimple_switch_label (stmt, k)))
6249             high = CASE_HIGH (gimple_switch_label (stmt, k));
6250         }
6251
6252       *min_idx = i;
6253       *max_idx = j;
6254       return !take_default;
6255     }
6256 }
6257
6258 /* Visit switch statement STMT.  If we can determine which edge
6259    will be taken out of STMT's basic block, record it in
6260    *TAKEN_EDGE_P and return SSA_PROP_INTERESTING.  Otherwise, return
6261    SSA_PROP_VARYING.  */
6262
6263 static enum ssa_prop_result
6264 vrp_visit_switch_stmt (gimple stmt, edge *taken_edge_p)
6265 {
6266   tree op, val;
6267   value_range_t *vr;
6268   size_t i = 0, j = 0;
6269   bool take_default;
6270
6271   *taken_edge_p = NULL;
6272   op = gimple_switch_index (stmt);
6273   if (TREE_CODE (op) != SSA_NAME)
6274     return SSA_PROP_VARYING;
6275
6276   vr = get_value_range (op);
6277   if (dump_file && (dump_flags & TDF_DETAILS))
6278     {
6279       fprintf (dump_file, "\nVisiting switch expression with operand ");
6280       print_generic_expr (dump_file, op, 0);
6281       fprintf (dump_file, " with known range ");
6282       dump_value_range (dump_file, vr);
6283       fprintf (dump_file, "\n");
6284     }
6285
6286   if (vr->type != VR_RANGE
6287       || symbolic_range_p (vr))
6288     return SSA_PROP_VARYING;
6289
6290   /* Find the single edge that is taken from the switch expression.  */
6291   take_default = !find_case_label_range (stmt, vr->min, vr->max, &i, &j);
6292
6293   /* Check if the range spans no CASE_LABEL. If so, we only reach the default
6294      label */
6295   if (j < i)
6296     {
6297       gcc_assert (take_default);
6298       val = gimple_switch_default_label (stmt);
6299     }
6300   else
6301     {
6302       /* Check if labels with index i to j and maybe the default label
6303          are all reaching the same label.  */
6304
6305       val = gimple_switch_label (stmt, i);
6306       if (take_default
6307           && CASE_LABEL (gimple_switch_default_label (stmt))
6308           != CASE_LABEL (val))
6309         {
6310           if (dump_file && (dump_flags & TDF_DETAILS))
6311             fprintf (dump_file, "  not a single destination for this "
6312                      "range\n");
6313           return SSA_PROP_VARYING;
6314         }
6315       for (++i; i <= j; ++i)
6316         {
6317           if (CASE_LABEL (gimple_switch_label (stmt, i)) != CASE_LABEL (val))
6318             {
6319               if (dump_file && (dump_flags & TDF_DETAILS))
6320                 fprintf (dump_file, "  not a single destination for this "
6321                          "range\n");
6322               return SSA_PROP_VARYING;
6323             }
6324         }
6325     }
6326
6327   *taken_edge_p = find_edge (gimple_bb (stmt),
6328                              label_to_block (CASE_LABEL (val)));
6329
6330   if (dump_file && (dump_flags & TDF_DETAILS))
6331     {
6332       fprintf (dump_file, "  will take edge to ");
6333       print_generic_stmt (dump_file, CASE_LABEL (val), 0);
6334     }
6335
6336   return SSA_PROP_INTERESTING;
6337 }
6338
6339
6340 /* Evaluate statement STMT.  If the statement produces a useful range,
6341    return SSA_PROP_INTERESTING and record the SSA name with the
6342    interesting range into *OUTPUT_P.
6343
6344    If STMT is a conditional branch and we can determine its truth
6345    value, the taken edge is recorded in *TAKEN_EDGE_P.
6346
6347    If STMT produces a varying value, return SSA_PROP_VARYING.  */
6348
6349 static enum ssa_prop_result
6350 vrp_visit_stmt (gimple stmt, edge *taken_edge_p, tree *output_p)
6351 {
6352   tree def;
6353   ssa_op_iter iter;
6354
6355   if (dump_file && (dump_flags & TDF_DETAILS))
6356     {
6357       fprintf (dump_file, "\nVisiting statement:\n");
6358       print_gimple_stmt (dump_file, stmt, 0, dump_flags);
6359       fprintf (dump_file, "\n");
6360     }
6361
6362   if (!stmt_interesting_for_vrp (stmt))
6363     gcc_assert (stmt_ends_bb_p (stmt));
6364   else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
6365     {
6366       /* In general, assignments with virtual operands are not useful
6367          for deriving ranges, with the obvious exception of calls to
6368          builtin functions.  */
6369
6370       if ((is_gimple_call (stmt)
6371            && gimple_call_fndecl (stmt) != NULL_TREE
6372            && DECL_IS_BUILTIN (gimple_call_fndecl (stmt)))
6373           || !gimple_vuse (stmt))
6374         return vrp_visit_assignment_or_call (stmt, output_p);
6375     }
6376   else if (gimple_code (stmt) == GIMPLE_COND)
6377     return vrp_visit_cond_stmt (stmt, taken_edge_p);
6378   else if (gimple_code (stmt) == GIMPLE_SWITCH)
6379     return vrp_visit_switch_stmt (stmt, taken_edge_p);
6380
6381   /* All other statements produce nothing of interest for VRP, so mark
6382      their outputs varying and prevent further simulation.  */
6383   FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF)
6384     set_value_range_to_varying (get_value_range (def));
6385
6386   return SSA_PROP_VARYING;
6387 }
6388
6389
6390 /* Meet operation for value ranges.  Given two value ranges VR0 and
6391    VR1, store in VR0 a range that contains both VR0 and VR1.  This
6392    may not be the smallest possible such range.  */
6393
6394 static void
6395 vrp_meet (value_range_t *vr0, value_range_t *vr1)
6396 {
6397   if (vr0->type == VR_UNDEFINED)
6398     {
6399       copy_value_range (vr0, vr1);
6400       return;
6401     }
6402
6403   if (vr1->type == VR_UNDEFINED)
6404     {
6405       /* Nothing to do.  VR0 already has the resulting range.  */
6406       return;
6407     }
6408
6409   if (vr0->type == VR_VARYING)
6410     {
6411       /* Nothing to do.  VR0 already has the resulting range.  */
6412       return;
6413     }
6414
6415   if (vr1->type == VR_VARYING)
6416     {
6417       set_value_range_to_varying (vr0);
6418       return;
6419     }
6420
6421   if (vr0->type == VR_RANGE && vr1->type == VR_RANGE)
6422     {
6423       int cmp;
6424       tree min, max;
6425
6426       /* Compute the convex hull of the ranges.  The lower limit of
6427          the new range is the minimum of the two ranges.  If they
6428          cannot be compared, then give up.  */
6429       cmp = compare_values (vr0->min, vr1->min);
6430       if (cmp == 0 || cmp == 1)
6431         min = vr1->min;
6432       else if (cmp == -1)
6433         min = vr0->min;
6434       else
6435         goto give_up;
6436
6437       /* Similarly, the upper limit of the new range is the maximum
6438          of the two ranges.  If they cannot be compared, then
6439          give up.  */
6440       cmp = compare_values (vr0->max, vr1->max);
6441       if (cmp == 0 || cmp == -1)
6442         max = vr1->max;
6443       else if (cmp == 1)
6444         max = vr0->max;
6445       else
6446         goto give_up;
6447
6448       /* Check for useless ranges.  */
6449       if (INTEGRAL_TYPE_P (TREE_TYPE (min))
6450           && ((vrp_val_is_min (min) || is_overflow_infinity (min))
6451               && (vrp_val_is_max (max) || is_overflow_infinity (max))))
6452         goto give_up;
6453
6454       /* The resulting set of equivalences is the intersection of
6455          the two sets.  */
6456       if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
6457         bitmap_and_into (vr0->equiv, vr1->equiv);
6458       else if (vr0->equiv && !vr1->equiv)
6459         bitmap_clear (vr0->equiv);
6460
6461       set_value_range (vr0, vr0->type, min, max, vr0->equiv);
6462     }
6463   else if (vr0->type == VR_ANTI_RANGE && vr1->type == VR_ANTI_RANGE)
6464     {
6465       /* Two anti-ranges meet only if their complements intersect.
6466          Only handle the case of identical ranges.  */
6467       if (compare_values (vr0->min, vr1->min) == 0
6468           && compare_values (vr0->max, vr1->max) == 0
6469           && compare_values (vr0->min, vr0->max) == 0)
6470         {
6471           /* The resulting set of equivalences is the intersection of
6472              the two sets.  */
6473           if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
6474             bitmap_and_into (vr0->equiv, vr1->equiv);
6475           else if (vr0->equiv && !vr1->equiv)
6476             bitmap_clear (vr0->equiv);
6477         }
6478       else
6479         goto give_up;
6480     }
6481   else if (vr0->type == VR_ANTI_RANGE || vr1->type == VR_ANTI_RANGE)
6482     {
6483       /* For a numeric range [VAL1, VAL2] and an anti-range ~[VAL3, VAL4],
6484          only handle the case where the ranges have an empty intersection.
6485          The result of the meet operation is the anti-range.  */
6486       if (!symbolic_range_p (vr0)
6487           && !symbolic_range_p (vr1)
6488           && !value_ranges_intersect_p (vr0, vr1))
6489         {
6490           /* Copy most of VR1 into VR0.  Don't copy VR1's equivalence
6491              set.  We need to compute the intersection of the two
6492              equivalence sets.  */
6493           if (vr1->type == VR_ANTI_RANGE)
6494             set_value_range (vr0, vr1->type, vr1->min, vr1->max, vr0->equiv);
6495
6496           /* The resulting set of equivalences is the intersection of
6497              the two sets.  */
6498           if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
6499             bitmap_and_into (vr0->equiv, vr1->equiv);
6500           else if (vr0->equiv && !vr1->equiv)
6501             bitmap_clear (vr0->equiv);
6502         }
6503       else
6504         goto give_up;
6505     }
6506   else
6507     gcc_unreachable ();
6508
6509   return;
6510
6511 give_up:
6512   /* Failed to find an efficient meet.  Before giving up and setting
6513      the result to VARYING, see if we can at least derive a useful
6514      anti-range.  FIXME, all this nonsense about distinguishing
6515      anti-ranges from ranges is necessary because of the odd
6516      semantics of range_includes_zero_p and friends.  */
6517   if (!symbolic_range_p (vr0)
6518       && ((vr0->type == VR_RANGE && !range_includes_zero_p (vr0))
6519           || (vr0->type == VR_ANTI_RANGE && range_includes_zero_p (vr0)))
6520       && !symbolic_range_p (vr1)
6521       && ((vr1->type == VR_RANGE && !range_includes_zero_p (vr1))
6522           || (vr1->type == VR_ANTI_RANGE && range_includes_zero_p (vr1))))
6523     {
6524       set_value_range_to_nonnull (vr0, TREE_TYPE (vr0->min));
6525
6526       /* Since this meet operation did not result from the meeting of
6527          two equivalent names, VR0 cannot have any equivalences.  */
6528       if (vr0->equiv)
6529         bitmap_clear (vr0->equiv);
6530     }
6531   else
6532     set_value_range_to_varying (vr0);
6533 }
6534
6535
6536 /* Visit all arguments for PHI node PHI that flow through executable
6537    edges.  If a valid value range can be derived from all the incoming
6538    value ranges, set a new range for the LHS of PHI.  */
6539
6540 static enum ssa_prop_result
6541 vrp_visit_phi_node (gimple phi)
6542 {
6543   size_t i;
6544   tree lhs = PHI_RESULT (phi);
6545   value_range_t *lhs_vr = get_value_range (lhs);
6546   value_range_t vr_result = { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL };
6547   int edges, old_edges;
6548   struct loop *l;
6549
6550   if (dump_file && (dump_flags & TDF_DETAILS))
6551     {
6552       fprintf (dump_file, "\nVisiting PHI node: ");
6553       print_gimple_stmt (dump_file, phi, 0, dump_flags);
6554     }
6555
6556   edges = 0;
6557   for (i = 0; i < gimple_phi_num_args (phi); i++)
6558     {
6559       edge e = gimple_phi_arg_edge (phi, i);
6560
6561       if (dump_file && (dump_flags & TDF_DETAILS))
6562         {
6563           fprintf (dump_file,
6564               "\n    Argument #%d (%d -> %d %sexecutable)\n",
6565               (int) i, e->src->index, e->dest->index,
6566               (e->flags & EDGE_EXECUTABLE) ? "" : "not ");
6567         }
6568
6569       if (e->flags & EDGE_EXECUTABLE)
6570         {
6571           tree arg = PHI_ARG_DEF (phi, i);
6572           value_range_t vr_arg;
6573
6574           ++edges;
6575
6576           if (TREE_CODE (arg) == SSA_NAME)
6577             {
6578               vr_arg = *(get_value_range (arg));
6579             }
6580           else
6581             {
6582               if (is_overflow_infinity (arg))
6583                 {
6584                   arg = copy_node (arg);
6585                   TREE_OVERFLOW (arg) = 0;
6586                 }
6587
6588               vr_arg.type = VR_RANGE;
6589               vr_arg.min = arg;
6590               vr_arg.max = arg;
6591               vr_arg.equiv = NULL;
6592             }
6593
6594           if (dump_file && (dump_flags & TDF_DETAILS))
6595             {
6596               fprintf (dump_file, "\t");
6597               print_generic_expr (dump_file, arg, dump_flags);
6598               fprintf (dump_file, "\n\tValue: ");
6599               dump_value_range (dump_file, &vr_arg);
6600               fprintf (dump_file, "\n");
6601             }
6602
6603           vrp_meet (&vr_result, &vr_arg);
6604
6605           if (vr_result.type == VR_VARYING)
6606             break;
6607         }
6608     }
6609
6610   if (vr_result.type == VR_VARYING)
6611     goto varying;
6612
6613   old_edges = vr_phi_edge_counts[SSA_NAME_VERSION (lhs)];
6614   vr_phi_edge_counts[SSA_NAME_VERSION (lhs)] = edges;
6615
6616   /* To prevent infinite iterations in the algorithm, derive ranges
6617      when the new value is slightly bigger or smaller than the
6618      previous one.  We don't do this if we have seen a new executable
6619      edge; this helps us avoid an overflow infinity for conditionals
6620      which are not in a loop.  */
6621   if (edges > 0
6622       && edges == old_edges)
6623     {
6624       int cmp_min = compare_values (lhs_vr->min, vr_result.min);
6625       int cmp_max = compare_values (lhs_vr->max, vr_result.max);
6626
6627       /* For non VR_RANGE or for pointers fall back to varying if
6628          the range changed.  */
6629       if ((lhs_vr->type != VR_RANGE || vr_result.type != VR_RANGE
6630            || POINTER_TYPE_P (TREE_TYPE (lhs)))
6631           && (cmp_min != 0 || cmp_max != 0))
6632         goto varying;
6633
6634       /* If the new minimum is smaller or larger than the previous
6635          one, go all the way to -INF.  In the first case, to avoid
6636          iterating millions of times to reach -INF, and in the
6637          other case to avoid infinite bouncing between different
6638          minimums.  */
6639       if (cmp_min > 0 || cmp_min < 0)
6640         {
6641           if (!needs_overflow_infinity (TREE_TYPE (vr_result.min))
6642               || !vrp_var_may_overflow (lhs, phi))
6643             vr_result.min = TYPE_MIN_VALUE (TREE_TYPE (vr_result.min));
6644           else if (supports_overflow_infinity (TREE_TYPE (vr_result.min)))
6645             vr_result.min =
6646                 negative_overflow_infinity (TREE_TYPE (vr_result.min));
6647         }
6648
6649       /* Similarly, if the new maximum is smaller or larger than
6650          the previous one, go all the way to +INF.  */
6651       if (cmp_max < 0 || cmp_max > 0)
6652         {
6653           if (!needs_overflow_infinity (TREE_TYPE (vr_result.max))
6654               || !vrp_var_may_overflow (lhs, phi))
6655             vr_result.max = TYPE_MAX_VALUE (TREE_TYPE (vr_result.max));
6656           else if (supports_overflow_infinity (TREE_TYPE (vr_result.max)))
6657             vr_result.max =
6658                 positive_overflow_infinity (TREE_TYPE (vr_result.max));
6659         }
6660
6661       /* If we dropped either bound to +-INF then if this is a loop
6662          PHI node SCEV may known more about its value-range.  */
6663       if ((cmp_min > 0 || cmp_min < 0
6664            || cmp_max < 0 || cmp_max > 0)
6665           && current_loops
6666           && (l = loop_containing_stmt (phi))
6667           && l->header == gimple_bb (phi))
6668         adjust_range_with_scev (&vr_result, l, phi, lhs);
6669
6670       /* If we will end up with a (-INF, +INF) range, set it to
6671          VARYING.  Same if the previous max value was invalid for
6672          the type and we end up with vr_result.min > vr_result.max.  */
6673       if ((vrp_val_is_max (vr_result.max)
6674            && vrp_val_is_min (vr_result.min))
6675           || compare_values (vr_result.min,
6676                              vr_result.max) > 0)
6677         goto varying;
6678     }
6679
6680   /* If the new range is different than the previous value, keep
6681      iterating.  */
6682   if (update_value_range (lhs, &vr_result))
6683     {
6684       if (dump_file && (dump_flags & TDF_DETAILS))
6685         {
6686           fprintf (dump_file, "Found new range for ");
6687           print_generic_expr (dump_file, lhs, 0);
6688           fprintf (dump_file, ": ");
6689           dump_value_range (dump_file, &vr_result);
6690           fprintf (dump_file, "\n\n");
6691         }
6692
6693       return SSA_PROP_INTERESTING;
6694     }
6695
6696   /* Nothing changed, don't add outgoing edges.  */
6697   return SSA_PROP_NOT_INTERESTING;
6698
6699   /* No match found.  Set the LHS to VARYING.  */
6700 varying:
6701   set_value_range_to_varying (lhs_vr);
6702   return SSA_PROP_VARYING;
6703 }
6704
6705 /* Simplify boolean operations if the source is known
6706    to be already a boolean.  */
6707 static bool
6708 simplify_truth_ops_using_ranges (gimple_stmt_iterator *gsi, gimple stmt)
6709 {
6710   enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
6711   tree val = NULL;
6712   tree op0, op1;
6713   value_range_t *vr;
6714   bool sop = false;
6715   bool need_conversion;
6716
6717   op0 = gimple_assign_rhs1 (stmt);
6718   if (TYPE_PRECISION (TREE_TYPE (op0)) != 1)
6719     {
6720       if (TREE_CODE (op0) != SSA_NAME)
6721         return false;
6722       vr = get_value_range (op0);
6723
6724       val = compare_range_with_value (GE_EXPR, vr, integer_zero_node, &sop);
6725       if (!val || !integer_onep (val))
6726         return false;
6727
6728       val = compare_range_with_value (LE_EXPR, vr, integer_one_node, &sop);
6729       if (!val || !integer_onep (val))
6730         return false;
6731     }
6732
6733   if (rhs_code == TRUTH_NOT_EXPR)
6734     {
6735       rhs_code = NE_EXPR;
6736       op1 = build_int_cst (TREE_TYPE (op0), 1);
6737     }
6738   else
6739     {
6740       op1 = gimple_assign_rhs2 (stmt);
6741
6742       /* Reduce number of cases to handle.  */
6743       if (is_gimple_min_invariant (op1))
6744         {
6745           /* Exclude anything that should have been already folded.  */
6746           if (rhs_code != EQ_EXPR
6747               && rhs_code != NE_EXPR
6748               && rhs_code != TRUTH_XOR_EXPR)
6749             return false;
6750
6751           if (!integer_zerop (op1)
6752               && !integer_onep (op1)
6753               && !integer_all_onesp (op1))
6754             return false;
6755
6756           /* Limit the number of cases we have to consider.  */
6757           if (rhs_code == EQ_EXPR)
6758             {
6759               rhs_code = NE_EXPR;
6760               op1 = fold_unary (TRUTH_NOT_EXPR, TREE_TYPE (op1), op1);
6761             }
6762         }
6763       else
6764         {
6765           /* Punt on A == B as there is no BIT_XNOR_EXPR.  */
6766           if (rhs_code == EQ_EXPR)
6767             return false;
6768
6769           if (TYPE_PRECISION (TREE_TYPE (op1)) != 1)
6770             {
6771               vr = get_value_range (op1);
6772               val = compare_range_with_value (GE_EXPR, vr, integer_zero_node, &sop);
6773               if (!val || !integer_onep (val))
6774                 return false;
6775
6776               val = compare_range_with_value (LE_EXPR, vr, integer_one_node, &sop);
6777               if (!val || !integer_onep (val))
6778                 return false;
6779             }
6780         }
6781     }
6782
6783   if (sop && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
6784     {
6785       location_t location;
6786
6787       if (!gimple_has_location (stmt))
6788         location = input_location;
6789       else
6790         location = gimple_location (stmt);
6791
6792       if (rhs_code == TRUTH_AND_EXPR || rhs_code == TRUTH_OR_EXPR)
6793         warning_at (location, OPT_Wstrict_overflow,
6794                     _("assuming signed overflow does not occur when "
6795                       "simplifying && or || to & or |"));
6796       else
6797         warning_at (location, OPT_Wstrict_overflow,
6798                     _("assuming signed overflow does not occur when "
6799                       "simplifying ==, != or ! to identity or ^"));
6800     }
6801
6802   need_conversion =
6803     !useless_type_conversion_p (TREE_TYPE (gimple_assign_lhs (stmt)),
6804                                 TREE_TYPE (op0));
6805
6806   /* Make sure to not sign-extend -1 as a boolean value.  */
6807   if (need_conversion
6808       && !TYPE_UNSIGNED (TREE_TYPE (op0))
6809       && TYPE_PRECISION (TREE_TYPE (op0)) == 1)
6810     return false;
6811
6812   switch (rhs_code)
6813     {
6814     case TRUTH_AND_EXPR:
6815       rhs_code = BIT_AND_EXPR;
6816       break;
6817     case TRUTH_OR_EXPR:
6818       rhs_code = BIT_IOR_EXPR;
6819       break;
6820     case TRUTH_XOR_EXPR:
6821     case NE_EXPR:
6822       if (integer_zerop (op1))
6823         {
6824           gimple_assign_set_rhs_with_ops (gsi,
6825                                           need_conversion ? NOP_EXPR : SSA_NAME,
6826                                           op0, NULL);
6827           update_stmt (gsi_stmt (*gsi));
6828           return true;
6829         }
6830
6831       rhs_code = BIT_XOR_EXPR;
6832       break;
6833     default:
6834       gcc_unreachable ();
6835     }
6836
6837   if (need_conversion)
6838     return false;
6839
6840   gimple_assign_set_rhs_with_ops (gsi, rhs_code, op0, op1);
6841   update_stmt (gsi_stmt (*gsi));
6842   return true;
6843 }
6844
6845 /* Simplify a division or modulo operator to a right shift or
6846    bitwise and if the first operand is unsigned or is greater
6847    than zero and the second operand is an exact power of two.  */
6848
6849 static bool
6850 simplify_div_or_mod_using_ranges (gimple stmt)
6851 {
6852   enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
6853   tree val = NULL;
6854   tree op0 = gimple_assign_rhs1 (stmt);
6855   tree op1 = gimple_assign_rhs2 (stmt);
6856   value_range_t *vr = get_value_range (gimple_assign_rhs1 (stmt));
6857
6858   if (TYPE_UNSIGNED (TREE_TYPE (op0)))
6859     {
6860       val = integer_one_node;
6861     }
6862   else
6863     {
6864       bool sop = false;
6865
6866       val = compare_range_with_value (GE_EXPR, vr, integer_zero_node, &sop);
6867
6868       if (val
6869           && sop
6870           && integer_onep (val)
6871           && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
6872         {
6873           location_t location;
6874
6875           if (!gimple_has_location (stmt))
6876             location = input_location;
6877           else
6878             location = gimple_location (stmt);
6879           warning_at (location, OPT_Wstrict_overflow,
6880                       "assuming signed overflow does not occur when "
6881                       "simplifying %</%> or %<%%%> to %<>>%> or %<&%>");
6882         }
6883     }
6884
6885   if (val && integer_onep (val))
6886     {
6887       tree t;
6888
6889       if (rhs_code == TRUNC_DIV_EXPR)
6890         {
6891           t = build_int_cst (NULL_TREE, tree_log2 (op1));
6892           gimple_assign_set_rhs_code (stmt, RSHIFT_EXPR);
6893           gimple_assign_set_rhs1 (stmt, op0);
6894           gimple_assign_set_rhs2 (stmt, t);
6895         }
6896       else
6897         {
6898           t = build_int_cst (TREE_TYPE (op1), 1);
6899           t = int_const_binop (MINUS_EXPR, op1, t, 0);
6900           t = fold_convert (TREE_TYPE (op0), t);
6901
6902           gimple_assign_set_rhs_code (stmt, BIT_AND_EXPR);
6903           gimple_assign_set_rhs1 (stmt, op0);
6904           gimple_assign_set_rhs2 (stmt, t);
6905         }
6906
6907       update_stmt (stmt);
6908       return true;
6909     }
6910
6911   return false;
6912 }
6913
6914 /* If the operand to an ABS_EXPR is >= 0, then eliminate the
6915    ABS_EXPR.  If the operand is <= 0, then simplify the
6916    ABS_EXPR into a NEGATE_EXPR.  */
6917
6918 static bool
6919 simplify_abs_using_ranges (gimple stmt)
6920 {
6921   tree val = NULL;
6922   tree op = gimple_assign_rhs1 (stmt);
6923   tree type = TREE_TYPE (op);
6924   value_range_t *vr = get_value_range (op);
6925
6926   if (TYPE_UNSIGNED (type))
6927     {
6928       val = integer_zero_node;
6929     }
6930   else if (vr)
6931     {
6932       bool sop = false;
6933
6934       val = compare_range_with_value (LE_EXPR, vr, integer_zero_node, &sop);
6935       if (!val)
6936         {
6937           sop = false;
6938           val = compare_range_with_value (GE_EXPR, vr, integer_zero_node,
6939                                           &sop);
6940
6941           if (val)
6942             {
6943               if (integer_zerop (val))
6944                 val = integer_one_node;
6945               else if (integer_onep (val))
6946                 val = integer_zero_node;
6947             }
6948         }
6949
6950       if (val
6951           && (integer_onep (val) || integer_zerop (val)))
6952         {
6953           if (sop && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
6954             {
6955               location_t location;
6956
6957               if (!gimple_has_location (stmt))
6958                 location = input_location;
6959               else
6960                 location = gimple_location (stmt);
6961               warning_at (location, OPT_Wstrict_overflow,
6962                           "assuming signed overflow does not occur when "
6963                           "simplifying %<abs (X)%> to %<X%> or %<-X%>");
6964             }
6965
6966           gimple_assign_set_rhs1 (stmt, op);
6967           if (integer_onep (val))
6968             gimple_assign_set_rhs_code (stmt, NEGATE_EXPR);
6969           else
6970             gimple_assign_set_rhs_code (stmt, SSA_NAME);
6971           update_stmt (stmt);
6972           return true;
6973         }
6974     }
6975
6976   return false;
6977 }
6978
6979 /* Optimize away redundant BIT_AND_EXPR and BIT_IOR_EXPR.
6980    If all the bits that are being cleared by & are already
6981    known to be zero from VR, or all the bits that are being
6982    set by | are already known to be one from VR, the bit
6983    operation is redundant.  */
6984
6985 static bool
6986 simplify_bit_ops_using_ranges (gimple_stmt_iterator *gsi, gimple stmt)
6987 {
6988   tree op0 = gimple_assign_rhs1 (stmt);
6989   tree op1 = gimple_assign_rhs2 (stmt);
6990   tree op = NULL_TREE;
6991   value_range_t vr0 = { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL };
6992   value_range_t vr1 = { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL };
6993   double_int may_be_nonzero0, may_be_nonzero1;
6994   double_int must_be_nonzero0, must_be_nonzero1;
6995   double_int mask;
6996
6997   if (TREE_CODE (op0) == SSA_NAME)
6998     vr0 = *(get_value_range (op0));
6999   else if (is_gimple_min_invariant (op0))
7000     set_value_range_to_value (&vr0, op0, NULL);
7001   else
7002     return false;
7003
7004   if (TREE_CODE (op1) == SSA_NAME)
7005     vr1 = *(get_value_range (op1));
7006   else if (is_gimple_min_invariant (op1))
7007     set_value_range_to_value (&vr1, op1, NULL);
7008   else
7009     return false;
7010
7011   if (!zero_nonzero_bits_from_vr (&vr0, &may_be_nonzero0, &must_be_nonzero0))
7012     return false;
7013   if (!zero_nonzero_bits_from_vr (&vr1, &may_be_nonzero1, &must_be_nonzero1))
7014     return false;
7015
7016   switch (gimple_assign_rhs_code (stmt))
7017     {
7018     case BIT_AND_EXPR:
7019       mask = double_int_and_not (may_be_nonzero0, must_be_nonzero1);
7020       if (double_int_zero_p (mask))
7021         {
7022           op = op0;
7023           break;
7024         }
7025       mask = double_int_and_not (may_be_nonzero1, must_be_nonzero0);
7026       if (double_int_zero_p (mask))
7027         {
7028           op = op1;
7029           break;
7030         }
7031       break;
7032     case BIT_IOR_EXPR:
7033       mask = double_int_and_not (may_be_nonzero0, must_be_nonzero1);
7034       if (double_int_zero_p (mask))
7035         {
7036           op = op1;
7037           break;
7038         }
7039       mask = double_int_and_not (may_be_nonzero1, must_be_nonzero0);
7040       if (double_int_zero_p (mask))
7041         {
7042           op = op0;
7043           break;
7044         }
7045       break;
7046     default:
7047       gcc_unreachable ();
7048     }
7049
7050   if (op == NULL_TREE)
7051     return false;
7052
7053   gimple_assign_set_rhs_with_ops (gsi, TREE_CODE (op), op, NULL);
7054   update_stmt (gsi_stmt (*gsi));
7055   return true;
7056 }
7057
7058 /* We are comparing trees OP0 and OP1 using COND_CODE.  OP0 has
7059    a known value range VR.
7060
7061    If there is one and only one value which will satisfy the
7062    conditional, then return that value.  Else return NULL.  */
7063
7064 static tree
7065 test_for_singularity (enum tree_code cond_code, tree op0,
7066                       tree op1, value_range_t *vr)
7067 {
7068   tree min = NULL;
7069   tree max = NULL;
7070
7071   /* Extract minimum/maximum values which satisfy the
7072      the conditional as it was written.  */
7073   if (cond_code == LE_EXPR || cond_code == LT_EXPR)
7074     {
7075       /* This should not be negative infinity; there is no overflow
7076          here.  */
7077       min = TYPE_MIN_VALUE (TREE_TYPE (op0));
7078
7079       max = op1;
7080       if (cond_code == LT_EXPR && !is_overflow_infinity (max))
7081         {
7082           tree one = build_int_cst (TREE_TYPE (op0), 1);
7083           max = fold_build2 (MINUS_EXPR, TREE_TYPE (op0), max, one);
7084           if (EXPR_P (max))
7085             TREE_NO_WARNING (max) = 1;
7086         }
7087     }
7088   else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
7089     {
7090       /* This should not be positive infinity; there is no overflow
7091          here.  */
7092       max = TYPE_MAX_VALUE (TREE_TYPE (op0));
7093
7094       min = op1;
7095       if (cond_code == GT_EXPR && !is_overflow_infinity (min))
7096         {
7097           tree one = build_int_cst (TREE_TYPE (op0), 1);
7098           min = fold_build2 (PLUS_EXPR, TREE_TYPE (op0), min, one);
7099           if (EXPR_P (min))
7100             TREE_NO_WARNING (min) = 1;
7101         }
7102     }
7103
7104   /* Now refine the minimum and maximum values using any
7105      value range information we have for op0.  */
7106   if (min && max)
7107     {
7108       if (compare_values (vr->min, min) == 1)
7109         min = vr->min;
7110       if (compare_values (vr->max, max) == -1)
7111         max = vr->max;
7112
7113       /* If the new min/max values have converged to a single value,
7114          then there is only one value which can satisfy the condition,
7115          return that value.  */
7116       if (operand_equal_p (min, max, 0) && is_gimple_min_invariant (min))
7117         return min;
7118     }
7119   return NULL;
7120 }
7121
7122 /* Simplify a conditional using a relational operator to an equality
7123    test if the range information indicates only one value can satisfy
7124    the original conditional.  */
7125
7126 static bool
7127 simplify_cond_using_ranges (gimple stmt)
7128 {
7129   tree op0 = gimple_cond_lhs (stmt);
7130   tree op1 = gimple_cond_rhs (stmt);
7131   enum tree_code cond_code = gimple_cond_code (stmt);
7132
7133   if (cond_code != NE_EXPR
7134       && cond_code != EQ_EXPR
7135       && TREE_CODE (op0) == SSA_NAME
7136       && INTEGRAL_TYPE_P (TREE_TYPE (op0))
7137       && is_gimple_min_invariant (op1))
7138     {
7139       value_range_t *vr = get_value_range (op0);
7140
7141       /* If we have range information for OP0, then we might be
7142          able to simplify this conditional. */
7143       if (vr->type == VR_RANGE)
7144         {
7145           tree new_tree = test_for_singularity (cond_code, op0, op1, vr);
7146
7147           if (new_tree)
7148             {
7149               if (dump_file)
7150                 {
7151                   fprintf (dump_file, "Simplified relational ");
7152                   print_gimple_stmt (dump_file, stmt, 0, 0);
7153                   fprintf (dump_file, " into ");
7154                 }
7155
7156               gimple_cond_set_code (stmt, EQ_EXPR);
7157               gimple_cond_set_lhs (stmt, op0);
7158               gimple_cond_set_rhs (stmt, new_tree);
7159
7160               update_stmt (stmt);
7161
7162               if (dump_file)
7163                 {
7164                   print_gimple_stmt (dump_file, stmt, 0, 0);
7165                   fprintf (dump_file, "\n");
7166                 }
7167
7168               return true;
7169             }
7170
7171           /* Try again after inverting the condition.  We only deal
7172              with integral types here, so no need to worry about
7173              issues with inverting FP comparisons.  */
7174           cond_code = invert_tree_comparison (cond_code, false);
7175           new_tree = test_for_singularity (cond_code, op0, op1, vr);
7176
7177           if (new_tree)
7178             {
7179               if (dump_file)
7180                 {
7181                   fprintf (dump_file, "Simplified relational ");
7182                   print_gimple_stmt (dump_file, stmt, 0, 0);
7183                   fprintf (dump_file, " into ");
7184                 }
7185
7186               gimple_cond_set_code (stmt, NE_EXPR);
7187               gimple_cond_set_lhs (stmt, op0);
7188               gimple_cond_set_rhs (stmt, new_tree);
7189
7190               update_stmt (stmt);
7191
7192               if (dump_file)
7193                 {
7194                   print_gimple_stmt (dump_file, stmt, 0, 0);
7195                   fprintf (dump_file, "\n");
7196                 }
7197
7198               return true;
7199             }
7200         }
7201     }
7202
7203   return false;
7204 }
7205
7206 /* Simplify a switch statement using the value range of the switch
7207    argument.  */
7208
7209 static bool
7210 simplify_switch_using_ranges (gimple stmt)
7211 {
7212   tree op = gimple_switch_index (stmt);
7213   value_range_t *vr;
7214   bool take_default;
7215   edge e;
7216   edge_iterator ei;
7217   size_t i = 0, j = 0, n, n2;
7218   tree vec2;
7219   switch_update su;
7220
7221   if (TREE_CODE (op) == SSA_NAME)
7222     {
7223       vr = get_value_range (op);
7224
7225       /* We can only handle integer ranges.  */
7226       if (vr->type != VR_RANGE
7227           || symbolic_range_p (vr))
7228         return false;
7229
7230       /* Find case label for min/max of the value range.  */
7231       take_default = !find_case_label_range (stmt, vr->min, vr->max, &i, &j);
7232     }
7233   else if (TREE_CODE (op) == INTEGER_CST)
7234     {
7235       take_default = !find_case_label_index (stmt, 1, op, &i);
7236       if (take_default)
7237         {
7238           i = 1;
7239           j = 0;
7240         }
7241       else
7242         {
7243           j = i;
7244         }
7245     }
7246   else
7247     return false;
7248
7249   n = gimple_switch_num_labels (stmt);
7250
7251   /* Bail out if this is just all edges taken.  */
7252   if (i == 1
7253       && j == n - 1
7254       && take_default)
7255     return false;
7256
7257   /* Build a new vector of taken case labels.  */
7258   vec2 = make_tree_vec (j - i + 1 + (int)take_default);
7259   n2 = 0;
7260
7261   /* Add the default edge, if necessary.  */
7262   if (take_default)
7263     TREE_VEC_ELT (vec2, n2++) = gimple_switch_default_label (stmt);
7264
7265   for (; i <= j; ++i, ++n2)
7266     TREE_VEC_ELT (vec2, n2) = gimple_switch_label (stmt, i);
7267
7268   /* Mark needed edges.  */
7269   for (i = 0; i < n2; ++i)
7270     {
7271       e = find_edge (gimple_bb (stmt),
7272                      label_to_block (CASE_LABEL (TREE_VEC_ELT (vec2, i))));
7273       e->aux = (void *)-1;
7274     }
7275
7276   /* Queue not needed edges for later removal.  */
7277   FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
7278     {
7279       if (e->aux == (void *)-1)
7280         {
7281           e->aux = NULL;
7282           continue;
7283         }
7284
7285       if (dump_file && (dump_flags & TDF_DETAILS))
7286         {
7287           fprintf (dump_file, "removing unreachable case label\n");
7288         }
7289       VEC_safe_push (edge, heap, to_remove_edges, e);
7290       e->flags &= ~EDGE_EXECUTABLE;
7291     }
7292
7293   /* And queue an update for the stmt.  */
7294   su.stmt = stmt;
7295   su.vec = vec2;
7296   VEC_safe_push (switch_update, heap, to_update_switch_stmts, &su);
7297   return false;
7298 }
7299
7300 /* Simplify STMT using ranges if possible.  */
7301
7302 static bool
7303 simplify_stmt_using_ranges (gimple_stmt_iterator *gsi)
7304 {
7305   gimple stmt = gsi_stmt (*gsi);
7306   if (is_gimple_assign (stmt))
7307     {
7308       enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
7309
7310       switch (rhs_code)
7311         {
7312         case EQ_EXPR:
7313         case NE_EXPR:
7314         case TRUTH_NOT_EXPR:
7315         case TRUTH_AND_EXPR:
7316         case TRUTH_OR_EXPR:
7317         case TRUTH_XOR_EXPR:
7318           /* Transform EQ_EXPR, NE_EXPR, TRUTH_NOT_EXPR into BIT_XOR_EXPR
7319              or identity if the RHS is zero or one, and the LHS are known
7320              to be boolean values.  Transform all TRUTH_*_EXPR into
7321              BIT_*_EXPR if both arguments are known to be boolean values.  */
7322           if (INTEGRAL_TYPE_P (TREE_TYPE (gimple_assign_rhs1 (stmt))))
7323             return simplify_truth_ops_using_ranges (gsi, stmt);
7324           break;
7325
7326       /* Transform TRUNC_DIV_EXPR and TRUNC_MOD_EXPR into RSHIFT_EXPR
7327          and BIT_AND_EXPR respectively if the first operand is greater
7328          than zero and the second operand is an exact power of two.  */
7329         case TRUNC_DIV_EXPR:
7330         case TRUNC_MOD_EXPR:
7331           if (INTEGRAL_TYPE_P (TREE_TYPE (gimple_assign_rhs1 (stmt)))
7332               && integer_pow2p (gimple_assign_rhs2 (stmt)))
7333             return simplify_div_or_mod_using_ranges (stmt);
7334           break;
7335
7336       /* Transform ABS (X) into X or -X as appropriate.  */
7337         case ABS_EXPR:
7338           if (TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME
7339               && INTEGRAL_TYPE_P (TREE_TYPE (gimple_assign_rhs1 (stmt))))
7340             return simplify_abs_using_ranges (stmt);
7341           break;
7342
7343         case BIT_AND_EXPR:
7344         case BIT_IOR_EXPR:
7345           /* Optimize away BIT_AND_EXPR and BIT_IOR_EXPR
7346              if all the bits being cleared are already cleared or
7347              all the bits being set are already set.  */
7348           if (INTEGRAL_TYPE_P (TREE_TYPE (gimple_assign_rhs1 (stmt))))
7349             return simplify_bit_ops_using_ranges (gsi, stmt);
7350           break;
7351
7352         default:
7353           break;
7354         }
7355     }
7356   else if (gimple_code (stmt) == GIMPLE_COND)
7357     return simplify_cond_using_ranges (stmt);
7358   else if (gimple_code (stmt) == GIMPLE_SWITCH)
7359     return simplify_switch_using_ranges (stmt);
7360
7361   return false;
7362 }
7363
7364 /* If the statement pointed by SI has a predicate whose value can be
7365    computed using the value range information computed by VRP, compute
7366    its value and return true.  Otherwise, return false.  */
7367
7368 static bool
7369 fold_predicate_in (gimple_stmt_iterator *si)
7370 {
7371   bool assignment_p = false;
7372   tree val;
7373   gimple stmt = gsi_stmt (*si);
7374
7375   if (is_gimple_assign (stmt)
7376       && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
7377     {
7378       assignment_p = true;
7379       val = vrp_evaluate_conditional (gimple_assign_rhs_code (stmt),
7380                                       gimple_assign_rhs1 (stmt),
7381                                       gimple_assign_rhs2 (stmt),
7382                                       stmt);
7383     }
7384   else if (gimple_code (stmt) == GIMPLE_COND)
7385     val = vrp_evaluate_conditional (gimple_cond_code (stmt),
7386                                     gimple_cond_lhs (stmt),
7387                                     gimple_cond_rhs (stmt),
7388                                     stmt);
7389   else
7390     return false;
7391
7392   if (val)
7393     {
7394       if (assignment_p)
7395         val = fold_convert (gimple_expr_type (stmt), val);
7396
7397       if (dump_file)
7398         {
7399           fprintf (dump_file, "Folding predicate ");
7400           print_gimple_expr (dump_file, stmt, 0, 0);
7401           fprintf (dump_file, " to ");
7402           print_generic_expr (dump_file, val, 0);
7403           fprintf (dump_file, "\n");
7404         }
7405
7406       if (is_gimple_assign (stmt))
7407         gimple_assign_set_rhs_from_tree (si, val);
7408       else
7409         {
7410           gcc_assert (gimple_code (stmt) == GIMPLE_COND);
7411           if (integer_zerop (val))
7412             gimple_cond_make_false (stmt);
7413           else if (integer_onep (val))
7414             gimple_cond_make_true (stmt);
7415           else
7416             gcc_unreachable ();
7417         }
7418
7419       return true;
7420     }
7421
7422   return false;
7423 }
7424
7425 /* Callback for substitute_and_fold folding the stmt at *SI.  */
7426
7427 static bool
7428 vrp_fold_stmt (gimple_stmt_iterator *si)
7429 {
7430   if (fold_predicate_in (si))
7431     return true;
7432
7433   return simplify_stmt_using_ranges (si);
7434 }
7435
7436 /* Stack of dest,src equivalency pairs that need to be restored after
7437    each attempt to thread a block's incoming edge to an outgoing edge.
7438
7439    A NULL entry is used to mark the end of pairs which need to be
7440    restored.  */
7441 static VEC(tree,heap) *stack;
7442
7443 /* A trivial wrapper so that we can present the generic jump threading
7444    code with a simple API for simplifying statements.  STMT is the
7445    statement we want to simplify, WITHIN_STMT provides the location
7446    for any overflow warnings.  */
7447
7448 static tree
7449 simplify_stmt_for_jump_threading (gimple stmt, gimple within_stmt)
7450 {
7451   /* We only use VRP information to simplify conditionals.  This is
7452      overly conservative, but it's unclear if doing more would be
7453      worth the compile time cost.  */
7454   if (gimple_code (stmt) != GIMPLE_COND)
7455     return NULL;
7456
7457   return vrp_evaluate_conditional (gimple_cond_code (stmt),
7458                                    gimple_cond_lhs (stmt),
7459                                    gimple_cond_rhs (stmt), within_stmt);
7460 }
7461
7462 /* Blocks which have more than one predecessor and more than
7463    one successor present jump threading opportunities, i.e.,
7464    when the block is reached from a specific predecessor, we
7465    may be able to determine which of the outgoing edges will
7466    be traversed.  When this optimization applies, we are able
7467    to avoid conditionals at runtime and we may expose secondary
7468    optimization opportunities.
7469
7470    This routine is effectively a driver for the generic jump
7471    threading code.  It basically just presents the generic code
7472    with edges that may be suitable for jump threading.
7473
7474    Unlike DOM, we do not iterate VRP if jump threading was successful.
7475    While iterating may expose new opportunities for VRP, it is expected
7476    those opportunities would be very limited and the compile time cost
7477    to expose those opportunities would be significant.
7478
7479    As jump threading opportunities are discovered, they are registered
7480    for later realization.  */
7481
7482 static void
7483 identify_jump_threads (void)
7484 {
7485   basic_block bb;
7486   gimple dummy;
7487   int i;
7488   edge e;
7489
7490   /* Ugh.  When substituting values earlier in this pass we can
7491      wipe the dominance information.  So rebuild the dominator
7492      information as we need it within the jump threading code.  */
7493   calculate_dominance_info (CDI_DOMINATORS);
7494
7495   /* We do not allow VRP information to be used for jump threading
7496      across a back edge in the CFG.  Otherwise it becomes too
7497      difficult to avoid eliminating loop exit tests.  Of course
7498      EDGE_DFS_BACK is not accurate at this time so we have to
7499      recompute it.  */
7500   mark_dfs_back_edges ();
7501
7502   /* Do not thread across edges we are about to remove.  Just marking
7503      them as EDGE_DFS_BACK will do.  */
7504   FOR_EACH_VEC_ELT (edge, to_remove_edges, i, e)
7505     e->flags |= EDGE_DFS_BACK;
7506
7507   /* Allocate our unwinder stack to unwind any temporary equivalences
7508      that might be recorded.  */
7509   stack = VEC_alloc (tree, heap, 20);
7510
7511   /* To avoid lots of silly node creation, we create a single
7512      conditional and just modify it in-place when attempting to
7513      thread jumps.  */
7514   dummy = gimple_build_cond (EQ_EXPR,
7515                              integer_zero_node, integer_zero_node,
7516                              NULL, NULL);
7517
7518   /* Walk through all the blocks finding those which present a
7519      potential jump threading opportunity.  We could set this up
7520      as a dominator walker and record data during the walk, but
7521      I doubt it's worth the effort for the classes of jump
7522      threading opportunities we are trying to identify at this
7523      point in compilation.  */
7524   FOR_EACH_BB (bb)
7525     {
7526       gimple last;
7527
7528       /* If the generic jump threading code does not find this block
7529          interesting, then there is nothing to do.  */
7530       if (! potentially_threadable_block (bb))
7531         continue;
7532
7533       /* We only care about blocks ending in a COND_EXPR.  While there
7534          may be some value in handling SWITCH_EXPR here, I doubt it's
7535          terribly important.  */
7536       last = gsi_stmt (gsi_last_bb (bb));
7537       if (gimple_code (last) != GIMPLE_COND)
7538         continue;
7539
7540       /* We're basically looking for any kind of conditional with
7541          integral type arguments.  */
7542       if (TREE_CODE (gimple_cond_lhs (last)) == SSA_NAME
7543           && INTEGRAL_TYPE_P (TREE_TYPE (gimple_cond_lhs (last)))
7544           && (TREE_CODE (gimple_cond_rhs (last)) == SSA_NAME
7545               || is_gimple_min_invariant (gimple_cond_rhs (last)))
7546           && INTEGRAL_TYPE_P (TREE_TYPE (gimple_cond_rhs (last))))
7547         {
7548           edge_iterator ei;
7549
7550           /* We've got a block with multiple predecessors and multiple
7551              successors which also ends in a suitable conditional.  For
7552              each predecessor, see if we can thread it to a specific
7553              successor.  */
7554           FOR_EACH_EDGE (e, ei, bb->preds)
7555             {
7556               /* Do not thread across back edges or abnormal edges
7557                  in the CFG.  */
7558               if (e->flags & (EDGE_DFS_BACK | EDGE_COMPLEX))
7559                 continue;
7560
7561               thread_across_edge (dummy, e, true, &stack,
7562                                   simplify_stmt_for_jump_threading);
7563             }
7564         }
7565     }
7566
7567   /* We do not actually update the CFG or SSA graphs at this point as
7568      ASSERT_EXPRs are still in the IL and cfg cleanup code does not yet
7569      handle ASSERT_EXPRs gracefully.  */
7570 }
7571
7572 /* We identified all the jump threading opportunities earlier, but could
7573    not transform the CFG at that time.  This routine transforms the
7574    CFG and arranges for the dominator tree to be rebuilt if necessary.
7575
7576    Note the SSA graph update will occur during the normal TODO
7577    processing by the pass manager.  */
7578 static void
7579 finalize_jump_threads (void)
7580 {
7581   thread_through_all_blocks (false);
7582   VEC_free (tree, heap, stack);
7583 }
7584
7585
7586 /* Traverse all the blocks folding conditionals with known ranges.  */
7587
7588 static void
7589 vrp_finalize (void)
7590 {
7591   size_t i;
7592   unsigned num = num_ssa_names;
7593
7594   if (dump_file)
7595     {
7596       fprintf (dump_file, "\nValue ranges after VRP:\n\n");
7597       dump_all_value_ranges (dump_file);
7598       fprintf (dump_file, "\n");
7599     }
7600
7601   substitute_and_fold (op_with_constant_singleton_value_range,
7602                        vrp_fold_stmt, false);
7603
7604   if (warn_array_bounds)
7605     check_all_array_refs ();
7606
7607   /* We must identify jump threading opportunities before we release
7608      the datastructures built by VRP.  */
7609   identify_jump_threads ();
7610
7611   /* Free allocated memory.  */
7612   for (i = 0; i < num; i++)
7613     if (vr_value[i])
7614       {
7615         BITMAP_FREE (vr_value[i]->equiv);
7616         free (vr_value[i]);
7617       }
7618
7619   free (vr_value);
7620   free (vr_phi_edge_counts);
7621
7622   /* So that we can distinguish between VRP data being available
7623      and not available.  */
7624   vr_value = NULL;
7625   vr_phi_edge_counts = NULL;
7626 }
7627
7628
7629 /* Main entry point to VRP (Value Range Propagation).  This pass is
7630    loosely based on J. R. C. Patterson, ``Accurate Static Branch
7631    Prediction by Value Range Propagation,'' in SIGPLAN Conference on
7632    Programming Language Design and Implementation, pp. 67-78, 1995.
7633    Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
7634
7635    This is essentially an SSA-CCP pass modified to deal with ranges
7636    instead of constants.
7637
7638    While propagating ranges, we may find that two or more SSA name
7639    have equivalent, though distinct ranges.  For instance,
7640
7641      1  x_9 = p_3->a;
7642      2  p_4 = ASSERT_EXPR <p_3, p_3 != 0>
7643      3  if (p_4 == q_2)
7644      4    p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
7645      5  endif
7646      6  if (q_2)
7647
7648    In the code above, pointer p_5 has range [q_2, q_2], but from the
7649    code we can also determine that p_5 cannot be NULL and, if q_2 had
7650    a non-varying range, p_5's range should also be compatible with it.
7651
7652    These equivalences are created by two expressions: ASSERT_EXPR and
7653    copy operations.  Since p_5 is an assertion on p_4, and p_4 was the
7654    result of another assertion, then we can use the fact that p_5 and
7655    p_4 are equivalent when evaluating p_5's range.
7656
7657    Together with value ranges, we also propagate these equivalences
7658    between names so that we can take advantage of information from
7659    multiple ranges when doing final replacement.  Note that this
7660    equivalency relation is transitive but not symmetric.
7661
7662    In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
7663    cannot assert that q_2 is equivalent to p_5 because q_2 may be used
7664    in contexts where that assertion does not hold (e.g., in line 6).
7665
7666    TODO, the main difference between this pass and Patterson's is that
7667    we do not propagate edge probabilities.  We only compute whether
7668    edges can be taken or not.  That is, instead of having a spectrum
7669    of jump probabilities between 0 and 1, we only deal with 0, 1 and
7670    DON'T KNOW.  In the future, it may be worthwhile to propagate
7671    probabilities to aid branch prediction.  */
7672
7673 static unsigned int
7674 execute_vrp (void)
7675 {
7676   int i;
7677   edge e;
7678   switch_update *su;
7679
7680   loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
7681   rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
7682   scev_initialize ();
7683
7684   /* Estimate number of iterations - but do not use undefined behavior
7685      for this.  We can't do this lazily as other functions may compute
7686      this using undefined behavior.  */
7687   free_numbers_of_iterations_estimates ();
7688   estimate_numbers_of_iterations (false);
7689
7690   insert_range_assertions ();
7691
7692   to_remove_edges = VEC_alloc (edge, heap, 10);
7693   to_update_switch_stmts = VEC_alloc (switch_update, heap, 5);
7694   threadedge_initialize_values ();
7695
7696   vrp_initialize ();
7697   ssa_propagate (vrp_visit_stmt, vrp_visit_phi_node);
7698   vrp_finalize ();
7699
7700   /* ASSERT_EXPRs must be removed before finalizing jump threads
7701      as finalizing jump threads calls the CFG cleanup code which
7702      does not properly handle ASSERT_EXPRs.  */
7703   remove_range_assertions ();
7704
7705   /* If we exposed any new variables, go ahead and put them into
7706      SSA form now, before we handle jump threading.  This simplifies
7707      interactions between rewriting of _DECL nodes into SSA form
7708      and rewriting SSA_NAME nodes into SSA form after block
7709      duplication and CFG manipulation.  */
7710   update_ssa (TODO_update_ssa);
7711
7712   finalize_jump_threads ();
7713
7714   /* Remove dead edges from SWITCH_EXPR optimization.  This leaves the
7715      CFG in a broken state and requires a cfg_cleanup run.  */
7716   FOR_EACH_VEC_ELT (edge, to_remove_edges, i, e)
7717     remove_edge (e);
7718   /* Update SWITCH_EXPR case label vector.  */
7719   FOR_EACH_VEC_ELT (switch_update, to_update_switch_stmts, i, su)
7720     {
7721       size_t j;
7722       size_t n = TREE_VEC_LENGTH (su->vec);
7723       tree label;
7724       gimple_switch_set_num_labels (su->stmt, n);
7725       for (j = 0; j < n; j++)
7726         gimple_switch_set_label (su->stmt, j, TREE_VEC_ELT (su->vec, j));
7727       /* As we may have replaced the default label with a regular one
7728          make sure to make it a real default label again.  This ensures
7729          optimal expansion.  */
7730       label = gimple_switch_default_label (su->stmt);
7731       CASE_LOW (label) = NULL_TREE;
7732       CASE_HIGH (label) = NULL_TREE;
7733     }
7734
7735   if (VEC_length (edge, to_remove_edges) > 0)
7736     free_dominance_info (CDI_DOMINATORS);
7737
7738   VEC_free (edge, heap, to_remove_edges);
7739   VEC_free (switch_update, heap, to_update_switch_stmts);
7740   threadedge_finalize_values ();
7741
7742   scev_finalize ();
7743   loop_optimizer_finalize ();
7744   return 0;
7745 }
7746
7747 static bool
7748 gate_vrp (void)
7749 {
7750   return flag_tree_vrp != 0;
7751 }
7752
7753 struct gimple_opt_pass pass_vrp =
7754 {
7755  {
7756   GIMPLE_PASS,
7757   "vrp",                                /* name */
7758   gate_vrp,                             /* gate */
7759   execute_vrp,                          /* execute */
7760   NULL,                                 /* sub */
7761   NULL,                                 /* next */
7762   0,                                    /* static_pass_number */
7763   TV_TREE_VRP,                          /* tv_id */
7764   PROP_ssa,                             /* properties_required */
7765   0,                                    /* properties_provided */
7766   0,                                    /* properties_destroyed */
7767   0,                                    /* todo_flags_start */
7768   TODO_cleanup_cfg
7769     | TODO_update_ssa
7770     | TODO_verify_ssa
7771     | TODO_verify_flow
7772     | TODO_dump_func
7773     | TODO_ggc_collect                  /* todo_flags_finish */
7774  }
7775 };