OSDN Git Service

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