OSDN Git Service

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