OSDN Git Service

e55ef37616260fe3415eb2d508355d5dfb0d3f9c
[pf3gnuchains/gcc-fork.git] / gcc / tree-vrp.c
1 /* Support routines for Value Range Propagation (VRP).
2    Copyright (C) 2005 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 2, 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 COPYING.  If not, write to
19 the Free Software Foundation, 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA.  */
21
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "ggc.h"
27 #include "flags.h"
28 #include "tree.h"
29 #include "basic-block.h"
30 #include "tree-flow.h"
31 #include "tree-pass.h"
32 #include "tree-dump.h"
33 #include "timevar.h"
34 #include "diagnostic.h"
35 #include "cfgloop.h"
36 #include "tree-scalar-evolution.h"
37 #include "tree-ssa-propagate.h"
38 #include "tree-chrec.h"
39
40 /* Set of SSA names found during the dominator traversal of a
41    sub-graph in find_assert_locations.  */
42 static sbitmap found_in_subgraph;
43
44 /* Loop structure of the program.  Used to analyze scalar evolutions
45    inside adjust_range_with_scev.  */
46 static struct loops *cfg_loops;
47
48 /* Local functions.  */
49 static int compare_values (tree val1, tree val2);
50
51 /* Location information for ASSERT_EXPRs.  Each instance of this
52    structure describes an ASSERT_EXPR for an SSA name.  Since a single
53    SSA name may have more than one assertion associated with it, these
54    locations are kept in a linked list attached to the corresponding
55    SSA name.  */
56 struct assert_locus_d
57 {
58   /* Basic block where the assertion would be inserted.  */
59   basic_block bb;
60
61   /* Some assertions need to be inserted on an edge (e.g., assertions
62      generated by COND_EXPRs).  In those cases, BB will be NULL.  */
63   edge e;
64
65   /* Pointer to the statement that generated this assertion.  */
66   block_stmt_iterator si;
67
68   /* Predicate code for the ASSERT_EXPR.  Must be COMPARISON_CLASS_P.  */
69   enum tree_code comp_code;
70
71   /* Value being compared against.  */
72   tree val;
73
74   /* Next node in the linked list.  */
75   struct assert_locus_d *next;
76 };
77
78 typedef struct assert_locus_d *assert_locus_t;
79
80 /* If bit I is present, it means that SSA name N_i has a list of
81    assertions that should be inserted in the IL.  */
82 static bitmap need_assert_for;
83
84 /* Array of locations lists where to insert assertions.  ASSERTS_FOR[I]
85    holds a list of ASSERT_LOCUS_T nodes that describe where
86    ASSERT_EXPRs for SSA name N_I should be inserted.  */
87 static assert_locus_t *asserts_for;
88
89 /* Set of blocks visited in find_assert_locations.  Used to avoid
90    visiting the same block more than once.  */
91 static sbitmap blocks_visited;
92
93 /* Value range array.  After propagation, VR_VALUE[I] holds the range
94    of values that SSA name N_I may take.  */
95 static value_range_t **vr_value;
96
97 /* Given a comparison code, return its opposite.  Note that this is *not*
98    the same as inverting its truth value (invert_tree_comparison).  Here we
99    just want to literally flip the comparison around.
100    
101    So, '<' gets '>', '<=' gets '>='.  Both '==' and '!=' are returned
102    unchanged.  */
103
104 static enum tree_code
105 opposite_comparison (enum tree_code code)
106 {
107   switch (code)
108     {
109     case EQ_EXPR:
110     case NE_EXPR:
111     case ORDERED_EXPR:
112     case UNORDERED_EXPR:
113     case LTGT_EXPR:
114     case UNEQ_EXPR:
115       return code;
116     case GT_EXPR:
117       return LT_EXPR;
118     case GE_EXPR:
119       return LE_EXPR;
120     case LT_EXPR:
121       return GT_EXPR;
122     case LE_EXPR:
123       return GE_EXPR;
124     case UNGT_EXPR:
125       return UNLT_EXPR;
126     case UNGE_EXPR:
127       return UNLE_EXPR;
128     case UNLT_EXPR:
129       return UNGT_EXPR;
130     case UNLE_EXPR:
131       return UNGE_EXPR;
132     default:
133       gcc_unreachable ();
134     }
135 }
136
137
138 /* Return true if EXPR computes a non-zero value.  */
139
140 bool
141 expr_computes_nonzero (tree expr)
142 {
143   /* Type casts won't change anything, so just strip them.  */
144   STRIP_NOPS (expr);
145
146   /* Calling alloca, guarantees that the value is non-NULL.  */
147   if (alloca_call_p (expr))
148     return true;
149
150   /* The address of a non-weak symbol is never NULL, unless the user
151      has requested not to remove NULL pointer checks.  */
152   if (flag_delete_null_pointer_checks
153       && TREE_CODE (expr) == ADDR_EXPR
154       && DECL_P (TREE_OPERAND (expr, 0))
155       && !DECL_WEAK (TREE_OPERAND (expr, 0)))
156     return true;
157
158   /* IOR of any value with a nonzero value will result in a nonzero
159      value.  */
160   if (TREE_CODE (expr) == BIT_IOR_EXPR
161       && integer_nonzerop (TREE_OPERAND (expr, 1)))
162     return true;
163
164   return false;
165 }
166
167
168 /* Set value range VR to {T, MIN, MAX, EQUIV}.  */
169
170 static void
171 set_value_range (value_range_t *vr, enum value_range_type t, tree min,
172                  tree max, bitmap equiv)
173 {
174 #if defined ENABLE_CHECKING
175   /* Check the validity of the range.  */
176   if (t == VR_RANGE || t == VR_ANTI_RANGE)
177     {
178       int cmp;
179
180       gcc_assert (min && max);
181
182       if (INTEGRAL_TYPE_P (TREE_TYPE (min)) && t == VR_ANTI_RANGE)
183         gcc_assert (min != TYPE_MIN_VALUE (TREE_TYPE (min))
184                     || max != TYPE_MAX_VALUE (TREE_TYPE (max)));
185
186       cmp = compare_values (min, max);
187       gcc_assert (cmp == 0 || cmp == -1 || cmp == -2);
188     }
189
190   if (t == VR_UNDEFINED || t == VR_VARYING)
191     gcc_assert (min == NULL_TREE && max == NULL_TREE);
192
193   if (t == VR_UNDEFINED || t == VR_VARYING)
194     gcc_assert (equiv == NULL || bitmap_empty_p (equiv));
195 #endif
196
197   vr->type = t;
198   vr->min = min;
199   vr->max = max;
200
201   /* Since updating the equivalence set involves deep copying the
202      bitmaps, only do it if absolutely necessary.  */
203   if (vr->equiv == NULL)
204     vr->equiv = BITMAP_ALLOC (NULL);
205
206   if (equiv != vr->equiv)
207     {
208       if (equiv && !bitmap_empty_p (equiv))
209         bitmap_copy (vr->equiv, equiv);
210       else
211         bitmap_clear (vr->equiv);
212     }
213 }
214
215
216 /* Copy value range FROM into value range TO.  */
217
218 static inline void
219 copy_value_range (value_range_t *to, value_range_t *from)
220 {
221   set_value_range (to, from->type, from->min, from->max, from->equiv);
222 }
223
224
225 /* Set value range VR to a non-NULL range of type TYPE.  */
226
227 static inline void
228 set_value_range_to_nonnull (value_range_t *vr, tree type)
229 {
230   tree zero = build_int_cst (type, 0);
231   set_value_range (vr, VR_ANTI_RANGE, zero, zero, vr->equiv);
232 }
233
234
235 /* Set value range VR to a NULL range of type TYPE.  */
236
237 static inline void
238 set_value_range_to_null (value_range_t *vr, tree type)
239 {
240   tree zero = build_int_cst (type, 0);
241   set_value_range (vr, VR_RANGE, zero, zero, vr->equiv);
242 }
243
244
245 /* Set value range VR to VR_VARYING.  */
246
247 static inline void
248 set_value_range_to_varying (value_range_t *vr)
249 {
250   vr->type = VR_VARYING;
251   vr->min = vr->max = NULL_TREE;
252   if (vr->equiv)
253     bitmap_clear (vr->equiv);
254 }
255
256
257 /* Set value range VR to VR_UNDEFINED.  */
258
259 static inline void
260 set_value_range_to_undefined (value_range_t *vr)
261 {
262   vr->type = VR_UNDEFINED;
263   vr->min = vr->max = NULL_TREE;
264   if (vr->equiv)
265     bitmap_clear (vr->equiv);
266 }
267
268
269 /* Return value range information for VAR.  Create an empty range
270    if none existed.  */
271
272 static value_range_t *
273 get_value_range (tree var)
274 {
275   value_range_t *vr;
276   tree sym;
277   unsigned ver = SSA_NAME_VERSION (var);
278
279   vr = vr_value[ver];
280   if (vr)
281     return vr;
282
283   /* Create a default value range.  */
284   vr_value[ver] = vr = xmalloc (sizeof (*vr));
285   memset (vr, 0, sizeof (*vr));
286
287   /* Allocate an equivalence set.  */
288   vr->equiv = BITMAP_ALLOC (NULL);
289
290   /* If VAR is a default definition, the variable can take any value
291      in VAR's type.  */
292   sym = SSA_NAME_VAR (var);
293   if (var == var_ann (sym)->default_def)
294     set_value_range_to_varying (vr);
295
296   return vr;
297 }
298
299
300 /* Update the value range and equivalence set for variable VAR to
301    NEW_VR.  Return true if NEW_VR is different from VAR's previous
302    value.
303
304    NOTE: This function assumes that NEW_VR is a temporary value range
305    object created for the sole purpose of updating VAR's range.  The
306    storage used by the equivalence set from NEW_VR will be freed by
307    this function.  Do not call update_value_range when NEW_VR
308    is the range object associated with another SSA name.  */
309
310 static inline bool
311 update_value_range (tree var, value_range_t *new_vr)
312 {
313   value_range_t *old_vr;
314   bool is_new;
315
316   /* Update the value range, if necessary.  */
317   old_vr = get_value_range (var);
318   is_new = old_vr->type != new_vr->type
319            || old_vr->min != new_vr->min
320            || old_vr->max != new_vr->max
321            || (old_vr->equiv == NULL && new_vr->equiv)
322            || (old_vr->equiv && new_vr->equiv == NULL)
323            || (!bitmap_equal_p (old_vr->equiv, new_vr->equiv));
324
325   if (is_new)
326     set_value_range (old_vr, new_vr->type, new_vr->min, new_vr->max,
327                      new_vr->equiv);
328
329   BITMAP_FREE (new_vr->equiv);
330   new_vr->equiv = NULL;
331
332   return is_new;
333 }
334
335
336 /* Add VAR and VAR's equivalence set to EQUIV.  */
337
338 static void
339 add_equivalence (bitmap equiv, tree var)
340 {
341   unsigned ver = SSA_NAME_VERSION (var);
342   value_range_t *vr = vr_value[ver];
343
344   bitmap_set_bit (equiv, ver);
345   if (vr && vr->equiv)
346     bitmap_ior_into (equiv, vr->equiv);
347 }
348
349
350 /* Return true if VR is ~[0, 0].  */
351
352 static inline bool
353 range_is_nonnull (value_range_t *vr)
354 {
355   return vr->type == VR_ANTI_RANGE
356          && integer_zerop (vr->min)
357          && integer_zerop (vr->max);
358 }
359
360
361 /* Return true if VR is [0, 0].  */
362
363 static inline bool
364 range_is_null (value_range_t *vr)
365 {
366   return vr->type == VR_RANGE
367          && integer_zerop (vr->min)
368          && integer_zerop (vr->max);
369 }
370
371
372 /* Return true if value range VR involves at least one symbol.  */
373
374 static inline bool
375 symbolic_range_p (value_range_t *vr)
376 {
377   return (!is_gimple_min_invariant (vr->min)
378           || !is_gimple_min_invariant (vr->max));
379 }
380
381
382 /* Like expr_computes_nonzero, but this function uses value ranges
383    obtained so far.  */
384
385 static bool
386 vrp_expr_computes_nonzero (tree expr)
387 {
388   if (expr_computes_nonzero (expr))
389     return true;
390
391   /* If we have an expression of the form &X->a, then the expression
392      is nonnull if X is nonnull.  */
393   if (TREE_CODE (expr) == ADDR_EXPR)
394     {
395       tree base = get_base_address (TREE_OPERAND (expr, 0));
396
397       if (base != NULL_TREE
398           && TREE_CODE (base) == INDIRECT_REF
399           && TREE_CODE (TREE_OPERAND (base, 0)) == SSA_NAME)
400         {
401           value_range_t *vr = get_value_range (TREE_OPERAND (base, 0));
402           if (range_is_nonnull (vr))
403             return true;
404         }
405     }
406
407   return false;
408 }
409
410
411 /* Compare two values VAL1 and VAL2.  Return
412    
413         -2 if VAL1 and VAL2 cannot be compared at compile-time,
414         -1 if VAL1 < VAL2,
415          0 if VAL1 == VAL2,
416         +1 if VAL1 > VAL2, and
417         +2 if VAL1 != VAL2
418
419    This is similar to tree_int_cst_compare but supports pointer values
420    and values that cannot be compared at compile time.  */
421
422 static int
423 compare_values (tree val1, tree val2)
424 {
425   if (val1 == val2)
426     return 0;
427
428   /* Below we rely on the fact that VAL1 and VAL2 are both pointers or
429      both integers.  */
430   gcc_assert (POINTER_TYPE_P (TREE_TYPE (val1))
431               == POINTER_TYPE_P (TREE_TYPE (val2)));
432
433   /* Do some limited symbolic comparisons.  */
434   if (!POINTER_TYPE_P (TREE_TYPE (val1)))
435     {
436       /* We can determine some comparisons against +INF and -INF even
437          if the other value is an expression.  */
438       if (val1 == TYPE_MAX_VALUE (TREE_TYPE (val1))
439           && TREE_CODE (val2) == MINUS_EXPR)
440         {
441           /* +INF > NAME - CST.  */
442           return 1;
443         }
444       else if (val1 == TYPE_MIN_VALUE (TREE_TYPE (val1))
445                && TREE_CODE (val2) == PLUS_EXPR)
446         {
447           /* -INF < NAME + CST.  */
448           return -1;
449         }
450       else if (TREE_CODE (val1) == MINUS_EXPR
451                && val2 == TYPE_MAX_VALUE (TREE_TYPE (val2)))
452         {
453           /* NAME - CST < +INF.  */
454           return -1;
455         }
456       else if (TREE_CODE (val1) == PLUS_EXPR
457                && val2 == TYPE_MIN_VALUE (TREE_TYPE (val2)))
458         {
459           /* NAME + CST > -INF.  */
460           return 1;
461         }
462     }
463
464   if ((TREE_CODE (val1) == SSA_NAME
465        || TREE_CODE (val1) == PLUS_EXPR
466        || TREE_CODE (val1) == MINUS_EXPR)
467       && (TREE_CODE (val2) == SSA_NAME
468           || TREE_CODE (val2) == PLUS_EXPR
469           || TREE_CODE (val2) == MINUS_EXPR))
470     {
471       tree n1, c1, n2, c2;
472   
473       /* If VAL1 and VAL2 are of the form 'NAME [+-] CST' or 'NAME',
474          return -1 or +1 accordingly.  If VAL1 and VAL2 don't use the
475          same name, return -2.  */
476       if (TREE_CODE (val1) == SSA_NAME)
477         {
478           n1 = val1;
479           c1 = NULL_TREE;
480         }
481       else
482         {
483           n1 = TREE_OPERAND (val1, 0);
484           c1 = TREE_OPERAND (val1, 1);
485         }
486
487       if (TREE_CODE (val2) == SSA_NAME)
488         {
489           n2 = val2;
490           c2 = NULL_TREE;
491         }
492       else
493         {
494           n2 = TREE_OPERAND (val2, 0);
495           c2 = TREE_OPERAND (val2, 1);
496         }
497
498       /* Both values must use the same name.  */
499       if (n1 != n2)
500         return -2;
501
502       if (TREE_CODE (val1) == SSA_NAME)
503         {
504           if (TREE_CODE (val2) == SSA_NAME)
505             /* NAME == NAME  */
506             return 0;
507           else if (TREE_CODE (val2) == PLUS_EXPR)
508             /* NAME < NAME + CST  */
509             return -1;
510           else if (TREE_CODE (val2) == MINUS_EXPR)
511             /* NAME > NAME - CST  */
512             return 1;
513         }
514       else if (TREE_CODE (val1) == PLUS_EXPR)
515         {
516           if (TREE_CODE (val2) == SSA_NAME)
517             /* NAME + CST > NAME  */
518             return 1;
519           else if (TREE_CODE (val2) == PLUS_EXPR)
520             /* NAME + CST1 > NAME + CST2, if CST1 > CST2  */
521             return compare_values (c1, c2);
522           else if (TREE_CODE (val2) == MINUS_EXPR)
523             /* NAME + CST1 > NAME - CST2  */
524             return 1;
525         }
526       else if (TREE_CODE (val1) == MINUS_EXPR)
527         {
528           if (TREE_CODE (val2) == SSA_NAME)
529             /* NAME - CST < NAME  */
530             return -1;
531           else if (TREE_CODE (val2) == PLUS_EXPR)
532             /* NAME - CST1 < NAME + CST2  */
533             return -1;
534           else if (TREE_CODE (val2) == MINUS_EXPR)
535             /* NAME - CST1 > NAME - CST2, if CST1 < CST2.  Notice that
536                C1 and C2 are swapped in the call to compare_values.  */
537             return compare_values (c2, c1);
538         }
539
540       gcc_unreachable ();
541     }
542
543   /* We cannot compare non-constants.  */
544   if (!is_gimple_min_invariant (val1) || !is_gimple_min_invariant (val2))
545     return -2;
546
547   /* We cannot compare overflowed values.  */
548   if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
549     return -2;
550
551   if (!POINTER_TYPE_P (TREE_TYPE (val1)))
552     return tree_int_cst_compare (val1, val2);
553   else
554     {
555       tree t;
556
557       /* First see if VAL1 and VAL2 are not the same.  */
558       if (val1 == val2 || operand_equal_p (val1, val2, 0))
559         return 0;
560       
561       /* If VAL1 is a lower address than VAL2, return -1.  */
562       t = fold_binary (LT_EXPR, boolean_type_node, val1, val2);
563       if (t == boolean_true_node)
564         return -1;
565
566       /* If VAL1 is a higher address than VAL2, return +1.  */
567       t = fold_binary (GT_EXPR, boolean_type_node, val1, val2);
568       if (t == boolean_true_node)
569         return 1;
570
571       /* If VAL1 is different than VAL2, return +2.  */
572       t = fold_binary (NE_EXPR, boolean_type_node, val1, val2);
573       if (t == boolean_true_node)
574         return 2;
575
576       return -2;
577     }
578 }
579
580
581 /* Return 1 if VAL is inside value range VR (VR->MIN <= VAL <= VR->MAX),
582           0 if VAL is not inside VR,
583          -2 if we cannot tell either way.  */
584
585 static inline int
586 value_inside_range (tree val, value_range_t *vr)
587 {
588   int cmp1, cmp2;
589
590   cmp1 = compare_values (val, vr->min);
591   if (cmp1 == -2 || cmp1 == 2)
592     return -2;
593
594   cmp2 = compare_values (val, vr->max);
595   if (cmp2 == -2 || cmp2 == 2)
596     return -2;
597
598   return (cmp1 == 0 || cmp1 == 1) && (cmp2 == -1 || cmp2 == 0);
599 }
600
601
602 /* Return true if value ranges VR0 and VR1 have a non-empty
603    intersection.  */
604
605 static inline bool
606 value_ranges_intersect_p (value_range_t *vr0, value_range_t *vr1)
607 {
608   return (value_inside_range (vr1->min, vr0) == 1
609           || value_inside_range (vr1->max, vr0) == 1
610           || value_inside_range (vr0->min, vr1) == 1
611           || value_inside_range (vr0->max, vr1) == 1);
612 }
613
614
615 /* Return true if VR includes the value zero, false otheriwse.  */
616
617 static inline bool
618 range_includes_zero_p (value_range_t *vr)
619 {
620   tree zero;
621
622   gcc_assert (vr->type != VR_UNDEFINED
623               && vr->type != VR_VARYING
624               && !symbolic_range_p (vr));
625
626   zero = build_int_cst (TREE_TYPE (vr->min), 0);
627   return (value_inside_range (zero, vr) == 1);
628 }
629
630
631 /* Extract value range information from an ASSERT_EXPR EXPR and store
632    it in *VR_P.  */
633
634 static void
635 extract_range_from_assert (value_range_t *vr_p, tree expr)
636 {
637   tree var, cond, limit, min, max, type;
638   value_range_t *var_vr, *limit_vr;
639   enum tree_code cond_code;
640
641   var = ASSERT_EXPR_VAR (expr);
642   cond = ASSERT_EXPR_COND (expr);
643
644   gcc_assert (COMPARISON_CLASS_P (cond));
645
646   /* Find VAR in the ASSERT_EXPR conditional.  */
647   if (var == TREE_OPERAND (cond, 0))
648     {
649       /* If the predicate is of the form VAR COMP LIMIT, then we just
650          take LIMIT from the RHS and use the same comparison code.  */
651       limit = TREE_OPERAND (cond, 1);
652       cond_code = TREE_CODE (cond);
653     }
654   else
655     {
656       /* If the predicate is of the form LIMIT COMP VAR, then we need
657          to flip around the comparison code to create the proper range
658          for VAR.  */
659       limit = TREE_OPERAND (cond, 0);
660       cond_code = opposite_comparison (TREE_CODE (cond));
661     }
662
663   type = TREE_TYPE (limit);
664   gcc_assert (limit != var);
665
666   /* For pointer arithmetic, we only keep track of pointer equality
667      and inequality.  */
668   if (POINTER_TYPE_P (type) && cond_code != NE_EXPR && cond_code != EQ_EXPR)
669     {
670       set_value_range_to_varying (vr_p);
671       return;
672     }
673
674   /* If LIMIT is another SSA name and LIMIT has a range of its own,
675      try to use LIMIT's range to avoid creating symbolic ranges
676      unnecessarily. */
677   limit_vr = (TREE_CODE (limit) == SSA_NAME) ? get_value_range (limit) : NULL;
678
679   /* LIMIT's range is only interesting if it has any useful information.  */
680   if (limit_vr
681       && (limit_vr->type == VR_UNDEFINED
682           || limit_vr->type == VR_VARYING
683           || symbolic_range_p (limit_vr)))
684     limit_vr = NULL;
685
686   /* Special handling for integral types with super-types.  Some FEs
687      construct integral types derived from other types and restrict
688      the range of values these new types may take.
689
690      It may happen that LIMIT is actually smaller than TYPE's minimum
691      value.  For instance, the Ada FE is generating code like this
692      during bootstrap:
693
694             D.1480_32 = nam_30 - 300000361;
695             if (D.1480_32 <= 1) goto <L112>; else goto <L52>;
696             <L112>:;
697             D.1480_94 = ASSERT_EXPR <D.1480_32, D.1480_32 <= 1>;
698
699      All the names are of type types__name_id___XDLU_300000000__399999999
700      which has min == 300000000 and max == 399999999.  This means that
701      the ASSERT_EXPR would try to create the range [3000000, 1] which
702      is invalid.
703
704      The fact that the type specifies MIN and MAX values does not
705      automatically mean that every variable of that type will always
706      be within that range, so the predicate may well be true at run
707      time.  If we had symbolic -INF and +INF values, we could
708      represent this range, but we currently represent -INF and +INF
709      using the type's min and max values.
710          
711      So, the only sensible thing we can do for now is set the
712      resulting range to VR_VARYING.  TODO, would having symbolic -INF
713      and +INF values be worth the trouble?  */
714   if (TREE_CODE (limit) != SSA_NAME
715       && INTEGRAL_TYPE_P (type)
716       && TREE_TYPE (type))
717     {
718       if (cond_code == LE_EXPR || cond_code == LT_EXPR)
719         {
720           tree type_min = TYPE_MIN_VALUE (type);
721           int cmp = compare_values (limit, type_min);
722
723           /* For < or <= comparisons, if LIMIT is smaller than
724              TYPE_MIN, set the range to VR_VARYING.  */
725           if (cmp == -1 || cmp == 0)
726             {
727               set_value_range_to_varying (vr_p);
728               return;
729             }
730         }
731       else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
732         {
733           tree type_max = TYPE_MIN_VALUE (type);
734           int cmp = compare_values (limit, type_max);
735
736           /* For > or >= comparisons, if LIMIT is bigger than
737              TYPE_MAX, set the range to VR_VARYING.  */
738           if (cmp == 1 || cmp == 0)
739             {
740               set_value_range_to_varying (vr_p);
741               return;
742             }
743         }
744     }
745
746   /* The new range has the same set of equivalences of VAR's range.  */
747   gcc_assert (vr_p->equiv == NULL);
748   vr_p->equiv = BITMAP_ALLOC (NULL);
749   add_equivalence (vr_p->equiv, var);
750
751   /* Extract a new range based on the asserted comparison for VAR and
752      LIMIT's value range.  Notice that if LIMIT has an anti-range, we
753      will only use it for equality comparisons (EQ_EXPR).  For any
754      other kind of assertion, we cannot derive a range from LIMIT's
755      anti-range that can be used to describe the new range.  For
756      instance, ASSERT_EXPR <x_2, x_2 <= b_4>.  If b_4 is ~[2, 10],
757      then b_4 takes on the ranges [-INF, 1] and [11, +INF].  There is
758      no single range for x_2 that could describe LE_EXPR, so we might
759      as well build the range [b_4, +INF] for it.  */
760   if (cond_code == EQ_EXPR)
761     {
762       enum value_range_type range_type;
763
764       if (limit_vr)
765         {
766           range_type = limit_vr->type;
767           min = limit_vr->min;
768           max = limit_vr->max;
769         }
770       else
771         {
772           range_type = VR_RANGE;
773           min = limit;
774           max = limit;
775         }
776
777       set_value_range (vr_p, range_type, min, max, vr_p->equiv);
778
779       /* When asserting the equality VAR == LIMIT and LIMIT is another
780          SSA name, the new range will also inherit the equivalence set
781          from LIMIT.  */
782       if (TREE_CODE (limit) == SSA_NAME)
783         add_equivalence (vr_p->equiv, limit);
784     }
785   else if (cond_code == NE_EXPR)
786     {
787       /* As described above, when LIMIT's range is an anti-range and
788          this assertion is an inequality (NE_EXPR), then we cannot
789          derive anything from the anti-range.  For instance, if
790          LIMIT's range was ~[0, 0], the assertion 'VAR != LIMIT' does
791          not imply that VAR's range is [0, 0].  So, in the case of
792          anti-ranges, we just assert the inequality using LIMIT and
793          not its anti-range.  */
794       if (limit_vr == NULL
795           || limit_vr->type == VR_ANTI_RANGE)
796         {
797           min = limit;
798           max = limit;
799         }
800       else
801         {
802           min = limit_vr->min;
803           max = limit_vr->max;
804         }
805
806       /* If MIN and MAX cover the whole range for their type, then
807          just use the original LIMIT.  */
808       if (INTEGRAL_TYPE_P (type)
809           && min == TYPE_MIN_VALUE (type)
810           && max == TYPE_MAX_VALUE (type))
811         min = max = limit;
812
813       set_value_range (vr_p, VR_ANTI_RANGE, min, max, vr_p->equiv);
814     }
815   else if (cond_code == LE_EXPR || cond_code == LT_EXPR)
816     {
817       min = TYPE_MIN_VALUE (type);
818
819       if (limit_vr == NULL || limit_vr->type == VR_ANTI_RANGE)
820         max = limit;
821       else
822         {
823           /* If LIMIT_VR is of the form [N1, N2], we need to build the
824              range [MIN, N2] for LE_EXPR and [MIN, N2 - 1] for
825              LT_EXPR.  */
826           max = limit_vr->max;
827         }
828
829       /* For LT_EXPR, we create the range [MIN, MAX - 1].  */
830       if (cond_code == LT_EXPR)
831         {
832           tree one = build_int_cst (type, 1);
833           max = fold (build (MINUS_EXPR, type, max, one));
834         }
835
836       set_value_range (vr_p, VR_RANGE, min, max, vr_p->equiv);
837     }
838   else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
839     {
840       max = TYPE_MAX_VALUE (type);
841
842       if (limit_vr == NULL || limit_vr->type == VR_ANTI_RANGE)
843         min = limit;
844       else
845         {
846           /* If LIMIT_VR is of the form [N1, N2], we need to build the
847              range [N1, MAX] for GE_EXPR and [N1 + 1, MAX] for
848              GT_EXPR.  */
849           min = limit_vr->min;
850         }
851
852       /* For GT_EXPR, we create the range [MIN + 1, MAX].  */
853       if (cond_code == GT_EXPR)
854         {
855           tree one = build_int_cst (type, 1);
856           min = fold (build (PLUS_EXPR, type, min, one));
857         }
858
859       set_value_range (vr_p, VR_RANGE, min, max, vr_p->equiv);
860     }
861   else
862     gcc_unreachable ();
863
864   /* If VAR already had a known range and the two ranges have a
865      non-empty intersection, we can refine the resulting range.
866      Since the assert expression creates an equivalency and at the
867      same time it asserts a predicate, we can take the intersection of
868      the two ranges to get better precision.  */
869   var_vr = get_value_range (var);
870   if (var_vr->type == VR_RANGE
871       && vr_p->type == VR_RANGE
872       && value_ranges_intersect_p (var_vr, vr_p))
873     {
874       /* Use the larger of the two minimums.  */
875       if (compare_values (vr_p->min, var_vr->min) == -1)
876         min = var_vr->min;
877       else
878         min = vr_p->min;
879
880       /* Use the smaller of the two maximums.  */
881       if (compare_values (vr_p->max, var_vr->max) == 1)
882         max = var_vr->max;
883       else
884         max = vr_p->max;
885
886       set_value_range (vr_p, vr_p->type, min, max, vr_p->equiv);
887     }
888 }
889
890
891 /* Extract range information from SSA name VAR and store it in VR.  If
892    VAR has an interesting range, use it.  Otherwise, create the
893    range [VAR, VAR] and return it.  This is useful in situations where
894    we may have conditionals testing values of VARYING names.  For
895    instance,
896
897         x_3 = y_5;
898         if (x_3 > y_5)
899           ...
900
901     Even if y_5 is deemed VARYING, we can determine that x_3 > y_5 is
902     always false.  */
903
904 static void
905 extract_range_from_ssa_name (value_range_t *vr, tree var)
906 {
907   value_range_t *var_vr = get_value_range (var);
908
909   if (var_vr->type != VR_UNDEFINED && var_vr->type != VR_VARYING)
910     copy_value_range (vr, var_vr);
911   else
912     set_value_range (vr, VR_RANGE, var, var, NULL);
913
914   add_equivalence (vr->equiv, var);
915 }
916
917
918 /* Extract range information from a binary expression EXPR based on
919    the ranges of each of its operands and the expression code.  */
920
921 static void
922 extract_range_from_binary_expr (value_range_t *vr, tree expr)
923 {
924   enum tree_code code = TREE_CODE (expr);
925   tree op0, op1, min, max;
926   int cmp;
927   value_range_t vr0 = { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL };
928   value_range_t vr1 = { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL };
929
930   /* Not all binary expressions can be applied to ranges in a
931      meaningful way.  Handle only arithmetic operations.  */
932   if (code != PLUS_EXPR
933       && code != MINUS_EXPR
934       && code != MULT_EXPR
935       && code != TRUNC_DIV_EXPR
936       && code != FLOOR_DIV_EXPR
937       && code != CEIL_DIV_EXPR
938       && code != EXACT_DIV_EXPR
939       && code != ROUND_DIV_EXPR
940       && code != MIN_EXPR
941       && code != MAX_EXPR
942       && code != TRUTH_ANDIF_EXPR
943       && code != TRUTH_ORIF_EXPR
944       && code != TRUTH_AND_EXPR
945       && code != TRUTH_OR_EXPR
946       && code != TRUTH_XOR_EXPR)
947     {
948       set_value_range_to_varying (vr);
949       return;
950     }
951
952   /* Get value ranges for each operand.  For constant operands, create
953      a new value range with the operand to simplify processing.  */
954   op0 = TREE_OPERAND (expr, 0);
955   if (TREE_CODE (op0) == SSA_NAME)
956     vr0 = *(get_value_range (op0));
957   else if (is_gimple_min_invariant (op0))
958     set_value_range (&vr0, VR_RANGE, op0, op0, NULL);
959   else
960     set_value_range_to_varying (&vr0);
961
962   op1 = TREE_OPERAND (expr, 1);
963   if (TREE_CODE (op1) == SSA_NAME)
964     vr1 = *(get_value_range (op1));
965   else if (is_gimple_min_invariant (op1))
966     set_value_range (&vr1, VR_RANGE, op1, op1, NULL);
967   else
968     set_value_range_to_varying (&vr1);
969
970   /* If either range is UNDEFINED, so is the result.  */
971   if (vr0.type == VR_UNDEFINED || vr1.type == VR_UNDEFINED)
972     {
973       set_value_range_to_undefined (vr);
974       return;
975     }
976
977   /* Refuse to operate on VARYING ranges, ranges of different kinds
978      and symbolic ranges.  TODO, we may be able to derive anti-ranges
979      in some cases.  */
980   if (vr0.type == VR_VARYING
981       || vr1.type == VR_VARYING
982       || vr0.type != vr1.type
983       || symbolic_range_p (&vr0)
984       || symbolic_range_p (&vr1))
985     {
986       set_value_range_to_varying (vr);
987       return;
988     }
989
990   /* Now evaluate the expression to determine the new range.  */
991   if (POINTER_TYPE_P (TREE_TYPE (expr))
992       || POINTER_TYPE_P (TREE_TYPE (op0))
993       || POINTER_TYPE_P (TREE_TYPE (op1)))
994     {
995       /* For pointer types, we are really only interested in asserting
996          whether the expression evaluates to non-NULL.  FIXME, we used
997          to gcc_assert (code == PLUS_EXPR || code == MINUS_EXPR), but
998          ivopts is generating expressions with pointer multiplication
999          in them.  */
1000       if (code == PLUS_EXPR)
1001         set_value_range_to_nonnull (vr, TREE_TYPE (expr));
1002       else
1003         {
1004           /* Subtracting from a pointer, may yield 0, so just drop the
1005              resulting range to varying.  */
1006           set_value_range_to_varying (vr);
1007         }
1008
1009       return;
1010     }
1011
1012   /* For integer ranges, apply the operation to each end of the
1013      range and see what we end up with.  */
1014   if (code == TRUTH_ANDIF_EXPR
1015       || code == TRUTH_ORIF_EXPR
1016       || code == TRUTH_AND_EXPR
1017       || code == TRUTH_OR_EXPR
1018       || code == TRUTH_XOR_EXPR)
1019     {
1020       /* Boolean expressions cannot be folded with int_const_binop.  */
1021       min = fold_binary (code, TREE_TYPE (expr), vr0.min, vr1.min);
1022       max = fold_binary (code, TREE_TYPE (expr), vr0.max, vr1.max);
1023     }
1024   else if (code == PLUS_EXPR
1025            || code == MULT_EXPR
1026            || code == MIN_EXPR
1027            || code == MAX_EXPR)
1028     {
1029       /* For operations that make the resulting range directly
1030          proportional to the original ranges, apply the operation to
1031          the same end of each range.  */
1032       min = int_const_binop (code, vr0.min, vr1.min, 0);
1033       max = int_const_binop (code, vr0.max, vr1.max, 0);
1034     }
1035   else if (code == TRUNC_DIV_EXPR
1036            || code == FLOOR_DIV_EXPR
1037            || code == CEIL_DIV_EXPR
1038            || code == EXACT_DIV_EXPR
1039            || code == ROUND_DIV_EXPR)
1040     {
1041       tree zero;
1042
1043       /* Divisions are a bit tricky to handle, depending on the mix of
1044          signs we have in the two range, we will need to divide
1045          different values to get the minimum and maximum values for
1046          the new range.  If VR1 includes zero, the result is VARYING.  */
1047       if (range_includes_zero_p (&vr1))
1048         {
1049           set_value_range_to_varying (vr);
1050           return;
1051         }
1052
1053       /* We have three main variations to handle for VR0: all negative
1054          values, all positive values and a mix of negative and
1055          positive.  For each of these, we need to consider if VR1 is
1056          all negative or all positive.  In total, there are 6
1057          combinations to handle.  */
1058       zero = build_int_cst (TREE_TYPE (expr), 0);
1059       if (compare_values (vr0.max, zero) == -1)
1060         {
1061           /* VR0 is all negative.  */
1062           if (compare_values (vr1.min, zero) == 1)
1063             {
1064               /* If VR1 is all positive, the new range is obtained
1065                  with [VR0.MIN / VR1.MIN, VR0.MAX / VR1.MAX].  */
1066               min = int_const_binop (code, vr0.min, vr1.min, 0);
1067               max = int_const_binop (code, vr0.max, vr1.max, 0);
1068             }
1069           else
1070             {
1071               /* If VR1 is all negative, the new range is obtained
1072                  with [VR0.MAX / VR1.MIN, VR0.MIN / VR1.MAX].  */
1073               gcc_assert (compare_values (vr1.max, zero) == -1);
1074               min = int_const_binop (code, vr0.max, vr1.min, 0);
1075               max = int_const_binop (code, vr0.min, vr1.max, 0);
1076             }
1077         }
1078       else if (range_includes_zero_p (&vr0))
1079         {
1080           /* VR0 is a mix of negative and positive values.  */
1081           if (compare_values (vr1.min, zero) == 1)
1082             {
1083               /* If VR1 is all positive, the new range is obtained
1084                  with [VR0.MIN / VR1.MIN, VR0.MAX / VR1.MIN].  */
1085               min = int_const_binop (code, vr0.min, vr1.min, 0);
1086               max = int_const_binop (code, vr0.max, vr1.min, 0);
1087             }
1088           else
1089             {
1090               /* If VR1 is all negative, the new range is obtained
1091                  with [VR0.MAX / VR1.MAX, VR0.MIN / VR1.MAX].  */
1092               gcc_assert (compare_values (vr1.max, zero) == -1);
1093               min = int_const_binop (code, vr0.max, vr1.max, 0);
1094               max = int_const_binop (code, vr0.min, vr1.max, 0);
1095             }
1096         }
1097       else
1098         {
1099           /* VR0 is all positive.  */
1100           gcc_assert (compare_values (vr0.min, zero) == 1);
1101           if (compare_values (vr1.min, zero) == 1)
1102             {
1103               /* If VR1 is all positive, the new range is obtained
1104                  with [VR0.MIN / VR1.MAX, VR0.MAX / VR1.MIN].  */
1105               min = int_const_binop (code, vr0.min, vr1.max, 0);
1106               max = int_const_binop (code, vr0.max, vr1.min, 0);
1107             }
1108           else
1109             {
1110               /* If VR1 is all negative, the new range is obtained
1111                  with [VR0.MAX / VR1.MAX, VR0.MIN / VR1.MIN].  */
1112               gcc_assert (compare_values (vr1.max, zero) == -1);
1113               min = int_const_binop (code, vr0.max, vr1.max, 0);
1114               max = int_const_binop (code, vr0.min, vr1.min, 0);
1115             }
1116         }
1117     }
1118   else if (code == MINUS_EXPR)
1119     {
1120       /* For MINUS_EXPR, apply the operation to the opposite ends of
1121          each range.  */
1122       min = int_const_binop (code, vr0.min, vr1.max, 0);
1123       max = int_const_binop (code, vr0.max, vr1.min, 0);
1124     }
1125   else
1126     gcc_unreachable ();
1127
1128   /* If MAX overflowed, then the result depends on whether we are
1129      using wrapping arithmetic or not.  */
1130   if (TREE_OVERFLOW (max))
1131     {
1132       /* If we are using wrapping arithmetic, set the result to
1133          VARYING.  */
1134       if (flag_wrapv)
1135         {
1136           set_value_range_to_varying (vr);
1137           return;
1138         }
1139
1140       /* Otherwise, set MAX to +INF.  */
1141       max = TYPE_MAX_VALUE (TREE_TYPE (expr));
1142     }
1143
1144   /* If MIN overflowed, then the result depends on whether we are
1145      using wrapping arithmetic or not.  */
1146   if (TREE_OVERFLOW (min))
1147     {
1148       /* If we are using wrapping arithmetic, set the result to
1149          VARYING.  */
1150       if (flag_wrapv)
1151         {
1152           set_value_range_to_varying (vr);
1153           return;
1154         }
1155
1156       /* Otherwise, set MIN to -INF.  */
1157       min = TYPE_MIN_VALUE (TREE_TYPE (expr));
1158     }
1159
1160   cmp = compare_values (min, max);
1161   if (cmp == -2 || cmp == 1)
1162     {
1163       /* If the new range has its limits swapped around (MIN > MAX),
1164          then the operation caused one of them to wrap around, mark
1165          the new range VARYING.  */
1166       set_value_range_to_varying (vr);
1167     }
1168   else
1169     set_value_range (vr, vr0.type, min, max, NULL);
1170 }
1171
1172
1173 /* Extract range information from a unary expression EXPR based on
1174    the range of its operand and the expression code.  */
1175
1176 static void
1177 extract_range_from_unary_expr (value_range_t *vr, tree expr)
1178 {
1179   enum tree_code code = TREE_CODE (expr);
1180   tree min, max, op0;
1181   int cmp;
1182   value_range_t vr0 = { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL };
1183
1184   /* Refuse to operate on certain unary expressions for which we
1185      cannot easily determine a resulting range.  */
1186   if (code == FIX_TRUNC_EXPR
1187       || code == FIX_CEIL_EXPR
1188       || code == FIX_FLOOR_EXPR
1189       || code == FIX_ROUND_EXPR
1190       || code == FLOAT_EXPR
1191       || code == BIT_NOT_EXPR
1192       || code == NON_LVALUE_EXPR
1193       || code == CONJ_EXPR)
1194     {
1195       set_value_range_to_varying (vr);
1196       return;
1197     }
1198
1199   /* Get value ranges for the operand.  For constant operands, create
1200      a new value range with the operand to simplify processing.  */
1201   op0 = TREE_OPERAND (expr, 0);
1202   if (TREE_CODE (op0) == SSA_NAME)
1203     vr0 = *(get_value_range (op0));
1204   else if (is_gimple_min_invariant (op0))
1205     set_value_range (&vr0, VR_RANGE, op0, op0, NULL);
1206   else
1207     set_value_range_to_varying (&vr0);
1208
1209   /* If VR0 is UNDEFINED, so is the result.  */
1210   if (vr0.type == VR_UNDEFINED)
1211     {
1212       set_value_range_to_undefined (vr);
1213       return;
1214     }
1215
1216   /* Refuse to operate on varying and symbolic ranges.  Also, if the
1217      operand is neither a pointer nor an integral type, set the
1218      resulting range to VARYING.  TODO, in some cases we may be able
1219      to derive anti-ranges (like non-zero values).  */
1220   if (vr0.type == VR_VARYING
1221       || (!INTEGRAL_TYPE_P (TREE_TYPE (op0))
1222           && !POINTER_TYPE_P (TREE_TYPE (op0)))
1223       || symbolic_range_p (&vr0))
1224     {
1225       set_value_range_to_varying (vr);
1226       return;
1227     }
1228
1229   /* If the expression involves pointers, we are only interested in
1230      determining if it evaluates to NULL [0, 0] or non-NULL (~[0, 0]).  */
1231   if (POINTER_TYPE_P (TREE_TYPE (expr)) || POINTER_TYPE_P (TREE_TYPE (op0)))
1232     {
1233       if (range_is_nonnull (&vr0) || expr_computes_nonzero (expr))
1234         set_value_range_to_nonnull (vr, TREE_TYPE (expr));
1235       else if (range_is_null (&vr0))
1236         set_value_range_to_null (vr, TREE_TYPE (expr));
1237       else
1238         set_value_range_to_varying (vr);
1239
1240       return;
1241     }
1242
1243   /* Handle unary expressions on integer ranges.  */
1244   if ((code == NOP_EXPR || code == CONVERT_EXPR)
1245       && (TYPE_SIZE (TREE_TYPE (vr0.min)) != TYPE_SIZE (TREE_TYPE (expr))))
1246     {
1247       /* When converting types of different sizes, set the result to
1248          VARYING.  Things like sign extensions and precision loss may
1249          change the range.  For instance, if x_3 is of type 'long long
1250          int' and 'y_5 = (unsigned short) x_3', if x_3 is ~[0, 0], it
1251          is impossible to know at compile time whether y_5 will be
1252          ~[0, 0].  */
1253       set_value_range_to_varying (vr);
1254       return;
1255     }
1256
1257   /* Apply the operation to each end of the range and see what we end
1258      up with.  */
1259   if (code == NEGATE_EXPR
1260       && !TYPE_UNSIGNED (TREE_TYPE (expr)))
1261     {
1262       /* Negating an anti-range doesn't really do anything to it.  The
1263          new range will also not take on the same range of values
1264          excluded by the original anti-range.  */
1265       if (vr0.type == VR_ANTI_RANGE)
1266         {
1267           copy_value_range (vr, &vr0);
1268           return;
1269         }
1270
1271       /* NEGATE_EXPR flips the range around.  */
1272       min = (vr0.max == TYPE_MAX_VALUE (TREE_TYPE (expr)))
1273             ? TYPE_MIN_VALUE (TREE_TYPE (expr))
1274             : fold_unary_to_constant (code, TREE_TYPE (expr), vr0.max);
1275
1276       max = (vr0.min == TYPE_MIN_VALUE (TREE_TYPE (expr)))
1277             ? TYPE_MAX_VALUE (TREE_TYPE (expr))
1278             : fold_unary_to_constant (code, TREE_TYPE (expr), vr0.min);
1279     }
1280   else if (code == ABS_EXPR
1281            && !TYPE_UNSIGNED (TREE_TYPE (expr)))
1282     {
1283       /* ABS_EXPR may flip the range around, if the original range
1284          included negative values.  */
1285       min = (vr0.min == TYPE_MIN_VALUE (TREE_TYPE (expr)))
1286             ? TYPE_MAX_VALUE (TREE_TYPE (expr))
1287             : fold_unary_to_constant (code, TREE_TYPE (expr), vr0.min);
1288
1289       max = fold_unary_to_constant (code, TREE_TYPE (expr), vr0.max);
1290
1291       /* If the range was reversed, swap MIN and MAX.  */
1292       if (compare_values (min, max) == 1)
1293         {
1294           tree t = min;
1295           min = max;
1296           max = t;
1297         }
1298     }
1299   else
1300     {
1301       /* Otherwise, operate on each end of the range.  */
1302       min = fold_unary_to_constant (code, TREE_TYPE (expr), vr0.min);
1303       max = fold_unary_to_constant (code, TREE_TYPE (expr), vr0.max);
1304     }
1305
1306   cmp = compare_values (min, max);
1307   if (cmp == -2 || cmp == 1)
1308     {
1309       /* If the new range has its limits swapped around (MIN > MAX),
1310          then the operation caused one of them to wrap around, mark
1311          the new range VARYING.  */
1312       set_value_range_to_varying (vr);
1313     }
1314   else
1315     set_value_range (vr, vr0.type, min, max, NULL);
1316 }
1317
1318
1319 /* Extract range information from a comparison expression EXPR based
1320    on the range of its operand and the expression code.  */
1321
1322 static void
1323 extract_range_from_comparison (value_range_t *vr, tree expr)
1324 {
1325   tree val = vrp_evaluate_conditional (expr, false);
1326   if (val)
1327     {
1328       /* Since this expression was found on the RHS of an assignment,
1329          its type may be different from _Bool.  Convert VAL to EXPR's
1330          type.  */
1331       val = fold_convert (TREE_TYPE (expr), val);
1332       set_value_range (vr, VR_RANGE, val, val, vr->equiv);
1333     }
1334   else
1335     set_value_range_to_varying (vr);
1336 }
1337
1338
1339 /* Try to compute a useful range out of expression EXPR and store it
1340    in *VR.  */
1341
1342 static void
1343 extract_range_from_expr (value_range_t *vr, tree expr)
1344 {
1345   enum tree_code code = TREE_CODE (expr);
1346
1347   if (code == ASSERT_EXPR)
1348     extract_range_from_assert (vr, expr);
1349   else if (code == SSA_NAME)
1350     extract_range_from_ssa_name (vr, expr);
1351   else if (TREE_CODE_CLASS (code) == tcc_binary
1352            || code == TRUTH_ANDIF_EXPR
1353            || code == TRUTH_ORIF_EXPR
1354            || code == TRUTH_AND_EXPR
1355            || code == TRUTH_OR_EXPR
1356            || code == TRUTH_XOR_EXPR)
1357     extract_range_from_binary_expr (vr, expr);
1358   else if (TREE_CODE_CLASS (code) == tcc_unary)
1359     extract_range_from_unary_expr (vr, expr);
1360   else if (TREE_CODE_CLASS (code) == tcc_comparison)
1361     extract_range_from_comparison (vr, expr);
1362   else if (vrp_expr_computes_nonzero (expr))
1363     set_value_range_to_nonnull (vr, TREE_TYPE (expr));
1364   else if (is_gimple_min_invariant (expr))
1365     set_value_range (vr, VR_RANGE, expr, expr, NULL);
1366   else
1367     set_value_range_to_varying (vr);
1368 }
1369
1370
1371 /* Given a range VR, a loop L and a variable VAR, determine whether it
1372    would be profitable to adjust VR using scalar evolution information
1373    for VAR.  If so, update VR with the new limits.  */
1374
1375 static void
1376 adjust_range_with_scev (value_range_t *vr, struct loop *l, tree var)
1377 {
1378   tree init, step, chrec;
1379   bool init_is_max;
1380
1381   /* TODO.  Don't adjust anti-ranges.  An anti-range may provide
1382      better opportunities than a regular range, but I'm not sure.  */
1383   if (vr->type == VR_ANTI_RANGE)
1384     return;
1385
1386   chrec = analyze_scalar_evolution (l, var);
1387   if (TREE_CODE (chrec) != POLYNOMIAL_CHREC)
1388     return;
1389
1390   init = CHREC_LEFT (chrec);
1391   step = CHREC_RIGHT (chrec);
1392
1393   /* If STEP is symbolic, we can't know whether INIT will be the
1394      minimum or maximum value in the range.  */
1395   if (!is_gimple_min_invariant (step))
1396     return;
1397
1398   /* FIXME.  When dealing with unsigned types,
1399      analyze_scalar_evolution sets STEP to very large unsigned values
1400      when the evolution goes backwards.  This confuses this analysis
1401      because we think that INIT is the smallest value that the range
1402      can take, instead of the largest.  Ignore these chrecs for now.  */
1403   if (INTEGRAL_TYPE_P (TREE_TYPE (step)) && TYPE_UNSIGNED (TREE_TYPE (step)))
1404     return;
1405
1406   /* Do not adjust ranges when using wrapping arithmetic.  */
1407   if (flag_wrapv)
1408     return;
1409
1410   /* If STEP is negative, then INIT is the maximum value the range
1411      will take.  Otherwise, INIT is the minimum value.  */
1412   init_is_max = (tree_int_cst_sgn (step) < 0);
1413
1414   if (!POINTER_TYPE_P (TREE_TYPE (init))
1415       && (vr->type == VR_VARYING || vr->type == VR_UNDEFINED))
1416     {
1417       /* For VARYING or UNDEFINED ranges, just about anything we get
1418          from scalar evolutions should be better.  */
1419       if (init_is_max)
1420         set_value_range (vr, VR_RANGE, TYPE_MIN_VALUE (TREE_TYPE (init)),
1421                          init, vr->equiv);
1422       else
1423         set_value_range (vr, VR_RANGE, init, TYPE_MAX_VALUE (TREE_TYPE (init)),
1424                          vr->equiv);
1425     }
1426   else if (vr->type == VR_RANGE)
1427     {
1428       tree min = vr->min;
1429       tree max = vr->max;
1430
1431       if (init_is_max)
1432         {
1433           /* INIT is the maximum value.  If INIT is lower than VR->MAX
1434              but no smaller than VR->MIN, set VR->MAX to INIT.  */
1435           if (compare_values (init, max) == -1)
1436             {
1437               max = init;
1438
1439               /* If we just created an invalid range with the minimum
1440                  greater than the maximum, take the minimum all the
1441                  way to -INF.  */
1442               if (compare_values (min, max) == 1)
1443                 min = TYPE_MIN_VALUE (TREE_TYPE (min));
1444             }
1445         }
1446       else
1447         {
1448           /* If INIT is bigger than VR->MIN, set VR->MIN to INIT.  */
1449           if (compare_values (init, min) == 1)
1450             {
1451               min = init;
1452
1453               /* If we just created an invalid range with the minimum
1454                  greater than the maximum, take the maximum all the
1455                  way to +INF.  */
1456               if (compare_values (min, max) == 1)
1457                 max = TYPE_MAX_VALUE (TREE_TYPE (max));
1458             }
1459         }
1460
1461       set_value_range (vr, VR_RANGE, min, max, vr->equiv);
1462     }
1463 }
1464
1465
1466 /* Given two numeric value ranges VR0, VR1 and a comparison code COMP:
1467    
1468    - Return BOOLEAN_TRUE_NODE if VR0 COMP VR1 always returns true for
1469      all the values in the ranges.
1470
1471    - Return BOOLEAN_FALSE_NODE if the comparison always returns false.
1472
1473    - Return NULL_TREE if it is not always possible to determine the
1474      value of the comparison.  */
1475
1476
1477 static tree
1478 compare_ranges (enum tree_code comp, value_range_t *vr0, value_range_t *vr1)
1479 {
1480   /* VARYING or UNDEFINED ranges cannot be compared.  */
1481   if (vr0->type == VR_VARYING
1482       || vr0->type == VR_UNDEFINED
1483       || vr1->type == VR_VARYING
1484       || vr1->type == VR_UNDEFINED)
1485     return NULL_TREE;
1486
1487   /* Anti-ranges need to be handled separately.  */
1488   if (vr0->type == VR_ANTI_RANGE || vr1->type == VR_ANTI_RANGE)
1489     {
1490       /* If both are anti-ranges, then we cannot compute any
1491          comparison.  */
1492       if (vr0->type == VR_ANTI_RANGE && vr1->type == VR_ANTI_RANGE)
1493         return NULL_TREE;
1494
1495       /* These comparisons are never statically computable.  */
1496       if (comp == GT_EXPR
1497           || comp == GE_EXPR
1498           || comp == LT_EXPR
1499           || comp == LE_EXPR)
1500         return NULL_TREE;
1501
1502       /* Equality can be computed only between a range and an
1503          anti-range.  ~[VAL1, VAL2] == [VAL1, VAL2] is always false.  */
1504       if (vr0->type == VR_RANGE)
1505         {
1506           /* To simplify processing, make VR0 the anti-range.  */
1507           value_range_t *tmp = vr0;
1508           vr0 = vr1;
1509           vr1 = tmp;
1510         }
1511
1512       gcc_assert (comp == NE_EXPR || comp == EQ_EXPR);
1513
1514       if (compare_values (vr0->min, vr1->min) == 0
1515           && compare_values (vr0->max, vr1->max) == 0)
1516         return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
1517
1518       return NULL_TREE;
1519     }
1520
1521   /* Simplify processing.  If COMP is GT_EXPR or GE_EXPR, switch the
1522      operands around and change the comparison code.  */
1523   if (comp == GT_EXPR || comp == GE_EXPR)
1524     {
1525       value_range_t *tmp;
1526       comp = (comp == GT_EXPR) ? LT_EXPR : LE_EXPR;
1527       tmp = vr0;
1528       vr0 = vr1;
1529       vr1 = tmp;
1530     }
1531
1532   if (comp == EQ_EXPR)
1533     {
1534       /* Equality may only be computed if both ranges represent
1535          exactly one value.  */
1536       if (compare_values (vr0->min, vr0->max) == 0
1537           && compare_values (vr1->min, vr1->max) == 0)
1538         {
1539           int cmp_min = compare_values (vr0->min, vr1->min);
1540           int cmp_max = compare_values (vr0->max, vr1->max);
1541           if (cmp_min == 0 && cmp_max == 0)
1542             return boolean_true_node;
1543           else if (cmp_min != -2 && cmp_max != -2)
1544             return boolean_false_node;
1545         }
1546
1547       return NULL_TREE;
1548     }
1549   else if (comp == NE_EXPR)
1550     {
1551       int cmp1, cmp2;
1552
1553       /* If VR0 is completely to the left or completely to the right
1554          of VR1, they are always different.  Notice that we need to
1555          make sure that both comparisons yield similar results to
1556          avoid comparing values that cannot be compared at
1557          compile-time.  */
1558       cmp1 = compare_values (vr0->max, vr1->min);
1559       cmp2 = compare_values (vr0->min, vr1->max);
1560       if ((cmp1 == -1 && cmp2 == -1) || (cmp1 == 1 && cmp2 == 1))
1561         return boolean_true_node;
1562
1563       /* If VR0 and VR1 represent a single value and are identical,
1564          return false.  */
1565       else if (compare_values (vr0->min, vr0->max) == 0
1566                && compare_values (vr1->min, vr1->max) == 0
1567                && compare_values (vr0->min, vr1->min) == 0
1568                && compare_values (vr0->max, vr1->max) == 0)
1569         return boolean_false_node;
1570
1571       /* Otherwise, they may or may not be different.  */
1572       else
1573         return NULL_TREE;
1574     }
1575   else if (comp == LT_EXPR || comp == LE_EXPR)
1576     {
1577       int tst;
1578
1579       /* If VR0 is to the left of VR1, return true.  */
1580       tst = compare_values (vr0->max, vr1->min);
1581       if ((comp == LT_EXPR && tst == -1)
1582           || (comp == LE_EXPR && (tst == -1 || tst == 0)))
1583         return boolean_true_node;
1584
1585       /* If VR0 is to the right of VR1, return false.  */
1586       tst = compare_values (vr0->min, vr1->max);
1587       if ((comp == LT_EXPR && (tst == 0 || tst == 1))
1588           || (comp == LE_EXPR && tst == 1))
1589         return boolean_false_node;
1590
1591       /* Otherwise, we don't know.  */
1592       return NULL_TREE;
1593     }
1594     
1595   gcc_unreachable ();
1596 }
1597
1598
1599 /* Given a value range VR, a value VAL and a comparison code COMP, return
1600    BOOLEAN_TRUE_NODE if VR COMP VAL always returns true for all the
1601    values in VR.  Return BOOLEAN_FALSE_NODE if the comparison
1602    always returns false.  Return NULL_TREE if it is not always
1603    possible to determine the value of the comparison.  */
1604
1605 static tree
1606 compare_range_with_value (enum tree_code comp, value_range_t *vr, tree val)
1607 {
1608   if (vr->type == VR_VARYING || vr->type == VR_UNDEFINED)
1609     return NULL_TREE;
1610
1611   /* Anti-ranges need to be handled separately.  */
1612   if (vr->type == VR_ANTI_RANGE)
1613     {
1614       /* For anti-ranges, the only predicates that we can compute at
1615          compile time are equality and inequality.  */
1616       if (comp == GT_EXPR
1617           || comp == GE_EXPR
1618           || comp == LT_EXPR
1619           || comp == LE_EXPR)
1620         return NULL_TREE;
1621
1622       /* ~[VAL, VAL] == VAL is always false.  */
1623       if (compare_values (vr->min, val) == 0
1624           && compare_values (vr->max, val) == 0)
1625         return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
1626
1627       return NULL_TREE;
1628     }
1629
1630   if (comp == EQ_EXPR)
1631     {
1632       /* EQ_EXPR may only be computed if VR represents exactly
1633          one value.  */
1634       if (compare_values (vr->min, vr->max) == 0)
1635         {
1636           int cmp = compare_values (vr->min, val);
1637           if (cmp == 0)
1638             return boolean_true_node;
1639           else if (cmp == -1 || cmp == 1 || cmp == 2)
1640             return boolean_false_node;
1641         }
1642       else if (compare_values (val, vr->min) == -1
1643                || compare_values (vr->max, val) == -1)
1644         return boolean_false_node;
1645
1646       return NULL_TREE;
1647     }
1648   else if (comp == NE_EXPR)
1649     {
1650       /* If VAL is not inside VR, then they are always different.  */
1651       if (compare_values (vr->max, val) == -1
1652           || compare_values (vr->min, val) == 1)
1653         return boolean_true_node;
1654
1655       /* If VR represents exactly one value equal to VAL, then return
1656          false.  */
1657       if (compare_values (vr->min, vr->max) == 0
1658           && compare_values (vr->min, val) == 0)
1659         return boolean_false_node;
1660
1661       /* Otherwise, they may or may not be different.  */
1662       return NULL_TREE;
1663     }
1664   else if (comp == LT_EXPR || comp == LE_EXPR)
1665     {
1666       int tst;
1667
1668       /* If VR is to the left of VAL, return true.  */
1669       tst = compare_values (vr->max, val);
1670       if ((comp == LT_EXPR && tst == -1)
1671           || (comp == LE_EXPR && (tst == -1 || tst == 0)))
1672         return boolean_true_node;
1673
1674       /* If VR is to the right of VAL, return false.  */
1675       tst = compare_values (vr->min, val);
1676       if ((comp == LT_EXPR && (tst == 0 || tst == 1))
1677           || (comp == LE_EXPR && tst == 1))
1678         return boolean_false_node;
1679
1680       /* Otherwise, we don't know.  */
1681       return NULL_TREE;
1682     }
1683   else if (comp == GT_EXPR || comp == GE_EXPR)
1684     {
1685       int tst;
1686
1687       /* If VR is to the right of VAL, return true.  */
1688       tst = compare_values (vr->min, val);
1689       if ((comp == GT_EXPR && tst == 1)
1690           || (comp == GE_EXPR && (tst == 0 || tst == 1)))
1691         return boolean_true_node;
1692
1693       /* If VR is to the left of VAL, return false.  */
1694       tst = compare_values (vr->max, val);
1695       if ((comp == GT_EXPR && (tst == -1 || tst == 0))
1696           || (comp == GE_EXPR && tst == -1))
1697         return boolean_false_node;
1698
1699       /* Otherwise, we don't know.  */
1700       return NULL_TREE;
1701     }
1702
1703   gcc_unreachable ();
1704 }
1705
1706
1707 /* Debugging dumps.  */
1708
1709 void dump_value_range (FILE *, value_range_t *);
1710 void debug_value_range (value_range_t *);
1711 void dump_all_value_ranges (FILE *);
1712 void debug_all_value_ranges (void);
1713 void dump_vr_equiv (FILE *, bitmap);
1714 void debug_vr_equiv (bitmap);
1715
1716
1717 /* Dump value range VR to FILE.  */
1718
1719 void
1720 dump_value_range (FILE *file, value_range_t *vr)
1721 {
1722   if (vr == NULL)
1723     fprintf (file, "[]");
1724   else if (vr->type == VR_UNDEFINED)
1725     fprintf (file, "UNDEFINED");
1726   else if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
1727     {
1728       tree type = TREE_TYPE (vr->min);
1729
1730       fprintf (file, "%s[", (vr->type == VR_ANTI_RANGE) ? "~" : "");
1731
1732       if (INTEGRAL_TYPE_P (type)
1733           && !TYPE_UNSIGNED (type)
1734           && vr->min == TYPE_MIN_VALUE (type))
1735         fprintf (file, "-INF");
1736       else
1737         print_generic_expr (file, vr->min, 0);
1738
1739       fprintf (file, ", ");
1740
1741       if (INTEGRAL_TYPE_P (type)
1742           && vr->max == TYPE_MAX_VALUE (type))
1743         fprintf (file, "+INF");
1744       else
1745         print_generic_expr (file, vr->max, 0);
1746
1747       fprintf (file, "]");
1748
1749       if (vr->equiv)
1750         {
1751           bitmap_iterator bi;
1752           unsigned i, c = 0;
1753
1754           fprintf (file, "  EQUIVALENCES: { ");
1755
1756           EXECUTE_IF_SET_IN_BITMAP (vr->equiv, 0, i, bi)
1757             {
1758               print_generic_expr (file, ssa_name (i), 0);
1759               fprintf (file, " ");
1760               c++;
1761             }
1762
1763           fprintf (file, "} (%u elements)", c);
1764         }
1765     }
1766   else if (vr->type == VR_VARYING)
1767     fprintf (file, "VARYING");
1768   else
1769     fprintf (file, "INVALID RANGE");
1770 }
1771
1772
1773 /* Dump value range VR to stderr.  */
1774
1775 void
1776 debug_value_range (value_range_t *vr)
1777 {
1778   dump_value_range (stderr, vr);
1779 }
1780
1781
1782 /* Dump value ranges of all SSA_NAMEs to FILE.  */
1783
1784 void
1785 dump_all_value_ranges (FILE *file)
1786 {
1787   size_t i;
1788
1789   for (i = 0; i < num_ssa_names; i++)
1790     {
1791       if (vr_value[i])
1792         {
1793           print_generic_expr (file, ssa_name (i), 0);
1794           fprintf (file, ": ");
1795           dump_value_range (file, vr_value[i]);
1796           fprintf (file, "\n");
1797         }
1798     }
1799
1800   fprintf (file, "\n");
1801 }
1802
1803
1804 /* Dump all value ranges to stderr.  */
1805
1806 void
1807 debug_all_value_ranges (void)
1808 {
1809   dump_all_value_ranges (stderr);
1810 }
1811
1812
1813 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
1814    create a new SSA name N and return the assertion assignment
1815    'V = ASSERT_EXPR <V, V OP W>'.  */
1816
1817 static tree
1818 build_assert_expr_for (tree cond, tree v)
1819 {
1820   tree n, assertion;
1821
1822   gcc_assert (TREE_CODE (v) == SSA_NAME);
1823   n = duplicate_ssa_name (v, NULL_TREE);
1824
1825   if (COMPARISON_CLASS_P (cond))
1826     {
1827       tree a = build (ASSERT_EXPR, TREE_TYPE (v), v, cond); 
1828       assertion = build (MODIFY_EXPR, TREE_TYPE (v), n, a);
1829     }
1830   else if (TREE_CODE (cond) == TRUTH_NOT_EXPR)
1831     {
1832       /* Given !V, build the assignment N = false.  */
1833       tree op0 = TREE_OPERAND (cond, 0);
1834       gcc_assert (op0 == v);
1835       assertion = build (MODIFY_EXPR, TREE_TYPE (v), n, boolean_false_node);
1836     }
1837   else if (TREE_CODE (cond) == SSA_NAME)
1838     {
1839       /* Given V, build the assignment N = true.  */
1840       gcc_assert (v == cond);
1841       assertion = build (MODIFY_EXPR, TREE_TYPE (v), n, boolean_true_node);
1842     }
1843   else
1844     gcc_unreachable ();
1845
1846   SSA_NAME_DEF_STMT (n) = assertion;
1847
1848   /* The new ASSERT_EXPR, creates a new SSA name that replaces the
1849      operand of the ASSERT_EXPR. Register the new name and the old one
1850      in the replacement table so that we can fix the SSA web after
1851      adding all the ASSERT_EXPRs.  */
1852   register_new_name_mapping (n, v);
1853
1854   return assertion;
1855 }
1856
1857
1858 /* Return false if EXPR is a predicate expression involving floating
1859    point values.  */
1860
1861 static inline bool
1862 fp_predicate (tree expr)
1863 {
1864   return (COMPARISON_CLASS_P (expr)
1865           && FLOAT_TYPE_P (TREE_TYPE (TREE_OPERAND (expr, 0))));
1866 }
1867
1868
1869 /* If the range of values taken by OP can be inferred after STMT executes,
1870    return the comparison code (COMP_CODE_P) and value (VAL_P) that
1871    describes the inferred range.  Return true if a range could be
1872    inferred.  */
1873
1874 static bool
1875 infer_value_range (tree stmt, tree op, enum tree_code *comp_code_p, tree *val_p)
1876 {
1877   *val_p = NULL_TREE;
1878   *comp_code_p = ERROR_MARK;
1879
1880   /* Do not attempt to infer anything in names that flow through
1881      abnormal edges.  */
1882   if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
1883     return false;
1884
1885   /* Similarly, don't infer anything from statements that may throw
1886      exceptions.  */
1887   if (tree_could_throw_p (stmt))
1888     return false;
1889
1890   if (POINTER_TYPE_P (TREE_TYPE (op)))
1891     {
1892       bool is_store;
1893       unsigned num_uses, num_derefs;
1894
1895       count_uses_and_derefs (op, stmt, &num_uses, &num_derefs, &is_store);
1896       if (num_derefs > 0 && flag_delete_null_pointer_checks)
1897         {
1898           /* We can only assume that a pointer dereference will yield
1899              non-NULL if -fdelete-null-pointer-checks is enabled.  */
1900           *val_p = build_int_cst (TREE_TYPE (op), 0);
1901           *comp_code_p = NE_EXPR;
1902           return true;
1903         }
1904     }
1905
1906   return false;
1907 }
1908
1909
1910 #if 0
1911 /* Return true if OP is the result of an ASSERT_EXPR that tests the
1912    same condition as COND.  */
1913
1914 static bool
1915 has_assert_expr (tree op, tree cond)
1916 {
1917   tree def_stmt = SSA_NAME_DEF_STMT (op);
1918   tree assert_expr, other_cond, other_op;
1919
1920   /* If OP was not generated by an ASSERT_EXPR, return false.  */
1921   if (TREE_CODE (def_stmt) != MODIFY_EXPR
1922       || TREE_CODE (TREE_OPERAND (def_stmt, 1)) != ASSERT_EXPR)
1923     return false;
1924
1925   assert_expr = TREE_OPERAND (def_stmt, 1);
1926   other_cond = ASSERT_EXPR_COND (assert_expr);
1927   other_op = ASSERT_EXPR_VAR (assert_expr);
1928
1929   if (TREE_CODE (cond) == TREE_CODE (other_cond))
1930     {
1931       tree t1, t2;
1932
1933       /* If COND is not a comparison predicate, something is wrong.  */
1934       gcc_assert (COMPARISON_CLASS_P (cond));
1935
1936       /* Note that we only need to compare against one of the operands
1937          of OTHER_COND.  
1938          
1939          Suppose that we are about to insert the assertion ASSERT_EXPR
1940          <x_4, x_4 != 0> and the defining statement for x_4 is x_4 =
1941          ASSERT_EXPR <x_3, x_3 != 0>.
1942
1943          In this case, we don't really want to insert a new
1944          ASSERT_EXPR for x_4 because that would be redundant.  We
1945          already know that x_4 is not 0.  So, when comparing the
1946          conditionals 'x_3 != 0' and 'x_4 != 0', we don't want to
1947          compare x_3 and x_4, we just want to compare the predicate's
1948          code (!=) and the other operand (0).  */
1949       if (TREE_OPERAND (cond, 0) == op)
1950         t1 = TREE_OPERAND (cond, 1);
1951       else
1952         t1 = TREE_OPERAND (cond, 0);
1953
1954       if (TREE_OPERAND (other_cond, 0) == other_op)
1955         t2 = TREE_OPERAND (other_cond, 1);
1956       else
1957         t2 = TREE_OPERAND (other_cond, 0);
1958
1959       return (t1 == t2 || operand_equal_p (t1, t2, 0));
1960     }
1961
1962   return false;
1963 }
1964
1965
1966 /* Traverse all the statements in block BB looking for used variables.
1967    Variables used in BB are added to bitmap FOUND.  The algorithm
1968    works in three main parts:
1969
1970    1- For every statement S in BB, all the variables used by S are
1971       added to bitmap FOUND.
1972
1973    2- If statement S uses an operand N in a way that exposes a known
1974       value range for N, then if N was not already generated by an
1975       ASSERT_EXPR, create a new ASSERT_EXPR for N.  For instance, if N
1976       is a pointer and the statement dereferences it, we can assume
1977       that N is not NULL.
1978
1979    3- COND_EXPRs are a special case of #2.  We can derive range
1980       information from the predicate but need to insert different
1981       ASSERT_EXPRs for each of the sub-graphs rooted at the
1982       conditional block.  If the last statement of BB is a conditional
1983       expression of the form 'X op Y', then
1984
1985       a) Remove X and Y from the set FOUND.
1986
1987       b) If the conditional dominates its THEN_CLAUSE sub-graph,
1988          recurse into it.  On return, if X and/or Y are marked in
1989          FOUND, then an ASSERT_EXPR is added for the corresponding
1990          variable.
1991
1992       c) Repeat step (b) on the ELSE_CLAUSE.
1993
1994       d) Mark X and Y in FOUND.
1995
1996    4- If BB does not end in a conditional expression, then we recurse
1997       into BB's dominator children.
1998    
1999    At the end of the recursive traversal, ASSERT_EXPRs will have been
2000    added to the edges of COND_EXPR blocks that have sub-graphs using
2001    one or both predicate operands.  For instance,
2002
2003         if (a == 9)
2004           b = a;
2005         else
2006           b = c + 1;
2007
2008    In this case, an assertion on the THEN clause is useful to
2009    determine that 'a' is always 9 on that edge.  However, an assertion
2010    on the ELSE clause would be unnecessary.
2011
2012    On exit from this function, all the names created by the newly
2013    inserted ASSERT_EXPRs need to be added to the SSA web by rewriting
2014    the SSA names that they replace.
2015    
2016    TODO.  Handle SWITCH_EXPR.  */
2017
2018 static bool
2019 maybe_add_assert_expr (basic_block bb)
2020 {
2021   block_stmt_iterator si;
2022   tree last;
2023   bool added;
2024
2025   /* Step 1.  Mark all the SSA names used in BB in bitmap FOUND.  */
2026   added = false;
2027   last = NULL_TREE;
2028   for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
2029     {
2030       tree stmt, op;
2031       ssa_op_iter i;
2032       
2033       stmt = bsi_stmt (si);
2034
2035       /* Mark all the SSA names used by STMT in bitmap FOUND.  If STMT
2036          is inside the sub-graph of a conditional block, when we
2037          return from this recursive walk, our parent will use the
2038          FOUND bitset to determine if one of the operands it was
2039          looking for was present in the sub-graph.  */
2040       FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
2041         {
2042           tree cond;
2043
2044           /* If OP is used only once, namely in this STMT, don't
2045              bother inserting an ASSERT_EXPR for it.  Such an
2046              ASSERT_EXPR would do nothing but increase compile time.
2047              Experiments show that with this simple check, we can save
2048              more than 20% of ASSERT_EXPRs.  */
2049           if (has_single_use (op))
2050             continue;
2051
2052           SET_BIT (found, SSA_NAME_VERSION (op));
2053
2054           cond = infer_value_range (stmt, op);
2055           if (!cond)
2056             continue;
2057
2058           /* Step 2.  If OP is used in such a way that we can infer a
2059              value range for it, create a new ASSERT_EXPR for OP
2060              (unless OP already has an ASSERT_EXPR).  */
2061           gcc_assert (!is_ctrl_stmt (stmt));
2062
2063           if (has_assert_expr (op, cond))
2064             continue;
2065
2066           if (!stmt_ends_bb_p (stmt))
2067             {
2068               /* If STMT does not end the block, we can insert the new
2069                  assertion right after it.  */
2070               tree t = build_assert_expr_for (cond, op);
2071               bsi_insert_after (&si, t, BSI_NEW_STMT);
2072               added = true;
2073             }
2074           else
2075             {
2076               /* STMT must be the last statement in BB.  We can only
2077                  insert new assertions on the non-abnormal edge out of
2078                  BB.  Note that since STMT is not control flow, there
2079                  may only be one non-abnormal edge out of BB.  */
2080               edge_iterator ei;
2081               edge e;
2082
2083               FOR_EACH_EDGE (e, ei, bb->succs)
2084                 if (!(e->flags & EDGE_ABNORMAL))
2085                   {
2086                     tree t = build_assert_expr_for (cond, op);
2087                     bsi_insert_on_edge (e, t);
2088                     added = true;
2089                     break;
2090                   }
2091             }
2092         }
2093
2094       /* Remember the last statement of the block.  */
2095       last = stmt;
2096     }
2097
2098   /* Step 3.  If BB's last statement is a conditional expression
2099      involving integer operands, recurse into each of the sub-graphs
2100      rooted at BB to determine if we need to add ASSERT_EXPRs.
2101      Notice that we only care about the first operand of the
2102      conditional.  Adding assertions for both operands may actually 
2103      hinder VRP.  FIXME, add example.  */
2104   if (last
2105       && TREE_CODE (last) == COND_EXPR
2106       && !fp_predicate (COND_EXPR_COND (last))
2107       && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
2108     {
2109       edge e;
2110       edge_iterator ei;
2111       tree op, cond;
2112       basic_block son;
2113       ssa_op_iter iter;
2114       
2115       cond = COND_EXPR_COND (last);
2116
2117       /* Get just the first use operand.  */
2118       FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
2119         break;
2120       gcc_assert (op != NULL);
2121
2122       /* Do not attempt to infer anything in names that flow through
2123          abnormal edges.  */
2124       if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
2125         return false;
2126
2127       /* Remove the COND_EXPR operand from the FOUND bitmap.
2128          Otherwise, when we finish traversing each of the sub-graphs,
2129          we won't know whether the variables were found in the
2130          sub-graphs or if they had been found in a block upstream from
2131          BB.  */
2132       RESET_BIT (found, SSA_NAME_VERSION (op));
2133
2134       /* Look for uses of the operands in each of the sub-graphs
2135          rooted at BB.  We need to check each of the outgoing edges
2136          separately, so that we know what kind of ASSERT_EXPR to
2137          insert.  */
2138       FOR_EACH_EDGE (e, ei, bb->succs)
2139         {
2140           /* If BB strictly dominates the sub-graph at E->DEST,
2141              recurse into it.  */
2142           if (e->dest != bb
2143               && dominated_by_p (CDI_DOMINATORS, e->dest, bb))
2144             added |= maybe_add_assert_expr (e->dest);
2145
2146           /* Once we traversed the sub-graph, check if any block inside
2147              used either of the predicate's operands.  If so, add the
2148              appropriate ASSERT_EXPR.  */
2149           if (TEST_BIT (found, SSA_NAME_VERSION (op)))
2150             {
2151               /* We found a use of OP in the sub-graph rooted at
2152                  E->DEST.  Add an ASSERT_EXPR according to whether
2153                  E goes to THEN_CLAUSE or ELSE_CLAUSE.  */
2154               tree c, t;
2155
2156               if (e->flags & EDGE_TRUE_VALUE)
2157                 c = unshare_expr (cond);
2158               else if (e->flags & EDGE_FALSE_VALUE)
2159                 c = invert_truthvalue (cond);
2160               else
2161                 gcc_unreachable ();
2162
2163               t = build_assert_expr_for (c, op);
2164               bsi_insert_on_edge (e, t);
2165               added = true;
2166             }
2167         }
2168
2169       /* Finally, mark all the COND_EXPR operands as found.  */
2170       SET_BIT (found, SSA_NAME_VERSION (op));
2171
2172       /* Recurse into the dominator children of BB that are not BB's
2173          immediate successors.  Note that we have already visited BB's
2174          other dominator children above.  */
2175       for (son = first_dom_son (CDI_DOMINATORS, bb);
2176            son;
2177            son = next_dom_son (CDI_DOMINATORS, son))
2178         {
2179           if (find_edge (bb, son) == NULL)
2180             added |= maybe_add_assert_expr (son);
2181         }
2182     }
2183   else
2184     {
2185       /* Step 4.  Recurse into the dominator children of BB.  */
2186       basic_block son;
2187
2188       for (son = first_dom_son (CDI_DOMINATORS, bb);
2189            son;
2190            son = next_dom_son (CDI_DOMINATORS, son))
2191         added |= maybe_add_assert_expr (son);
2192     }
2193
2194   return added;
2195 }
2196 #endif
2197
2198
2199 void dump_asserts_for (FILE *, tree);
2200 void debug_asserts_for (tree);
2201 void dump_all_asserts (FILE *);
2202 void debug_all_asserts (void);
2203
2204 /* Dump all the registered assertions for NAME to FILE.  */
2205
2206 void
2207 dump_asserts_for (FILE *file, tree name)
2208 {
2209   assert_locus_t loc;
2210
2211   fprintf (file, "Assertions to be inserted for ");
2212   print_generic_expr (file, name, 0);
2213   fprintf (file, "\n");
2214
2215   loc = asserts_for[SSA_NAME_VERSION (name)];
2216   while (loc)
2217     {
2218       fprintf (file, "\t");
2219       print_generic_expr (file, bsi_stmt (loc->si), 0);
2220       fprintf (file, "\n\tBB #%d", loc->bb->index);
2221       if (loc->e)
2222         {
2223           fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
2224                    loc->e->dest->index);
2225           dump_edge_info (file, loc->e, 0);
2226         }
2227       fprintf (file, "\n\tPREDICATE: ");
2228       print_generic_expr (file, name, 0);
2229       fprintf (file, " %s ", tree_code_name[(int)loc->comp_code]);
2230       print_generic_expr (file, loc->val, 0);
2231       fprintf (file, "\n\n");
2232       loc = loc->next;
2233     }
2234
2235   fprintf (file, "\n");
2236 }
2237
2238
2239 /* Dump all the registered assertions for NAME to stderr.  */
2240
2241 void
2242 debug_asserts_for (tree name)
2243 {
2244   dump_asserts_for (stderr, name);
2245 }
2246
2247
2248 /* Dump all the registered assertions for all the names to FILE.  */
2249
2250 void
2251 dump_all_asserts (FILE *file)
2252 {
2253   unsigned i;
2254   bitmap_iterator bi;
2255
2256   fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
2257   EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
2258     dump_asserts_for (file, ssa_name (i));
2259   fprintf (file, "\n");
2260 }
2261
2262
2263 /* Dump all the registered assertions for all the names to stderr.  */
2264
2265 void
2266 debug_all_asserts (void)
2267 {
2268   dump_all_asserts (stderr);
2269 }
2270
2271
2272 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
2273    'NAME COMP_CODE VAL' at a location that dominates block BB or
2274    E->DEST, then register this location as a possible insertion point
2275    for ASSERT_EXPR <NAME, NAME COMP_CODE VAL>.
2276
2277    BB, E and SI provide the exact insertion point for the new
2278    ASSERT_EXPR.  If BB is NULL, then the ASSERT_EXPR is to be inserted
2279    on edge E.  Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
2280    BB.  If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
2281    must not be NULL.  */
2282
2283 static void
2284 register_new_assert_for (tree name,
2285                          enum tree_code comp_code,
2286                          tree val,
2287                          basic_block bb,
2288                          edge e,
2289                          block_stmt_iterator si)
2290 {
2291   assert_locus_t n, loc, last_loc;
2292   bool found;
2293   basic_block dest_bb;
2294
2295 #if defined ENABLE_CHECKING
2296   gcc_assert (bb == NULL || e == NULL);
2297
2298   if (e == NULL)
2299     gcc_assert (TREE_CODE (bsi_stmt (si)) != COND_EXPR
2300                 && TREE_CODE (bsi_stmt (si)) != SWITCH_EXPR);
2301 #endif
2302
2303   /* The new assertion A will be inserted at BB or E.  We need to
2304      determine if the new location is dominated by a previously
2305      registered location for A.  If we are doing an edge insertion,
2306      assume that A will be inserted at E->DEST.  Note that this is not
2307      necessarily true.
2308      
2309      If E is a critical edge, it will be split.  But even if E is
2310      split, the new block will dominate the same set of blocks that
2311      E->DEST dominates.
2312      
2313      The reverse, however, is not true, blocks dominated by E->DEST
2314      will not be dominated by the new block created to split E.  So,
2315      if the insertion location is on a critical edge, we will not use
2316      the new location to move another assertion previously registered
2317      at a block dominated by E->DEST.  */
2318   dest_bb = (bb) ? bb : e->dest;
2319
2320   /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
2321      VAL at a block dominating DEST_BB, then we don't need to insert a new
2322      one.  Similarly, if the same assertion already exists at a block
2323      dominated by DEST_BB and the new location is not on a critical
2324      edge, then update the existing location for the assertion (i.e.,
2325      move the assertion up in the dominance tree).
2326
2327      Note, this is implemented as a simple linked list because there
2328      should not be more than a handful of assertions registered per
2329      name.  If this becomes a performance problem, a table hashed by
2330      COMP_CODE and VAL could be implemented.  */
2331   loc = asserts_for[SSA_NAME_VERSION (name)];
2332   last_loc = loc;
2333   found = false;
2334   while (loc)
2335     {
2336       if (loc->comp_code == comp_code
2337           && (loc->val == val
2338               || operand_equal_p (loc->val, val, 0)))
2339         {
2340           /* If the assertion NAME COMP_CODE VAL has already been
2341              registered at a basic block that dominates DEST_BB, then
2342              we don't need to insert the same assertion again.  Note
2343              that we don't check strict dominance here to avoid
2344              replicating the same assertion inside the same basic
2345              block more than once (e.g., when a pointer is
2346              dereferenced several times inside a block).
2347
2348              An exception to this rule are edge insertions.  If the
2349              new assertion is to be inserted on edge E, then it will
2350              dominate all the other insertions that we may want to
2351              insert in DEST_BB.  So, if we are doing an edge
2352              insertion, don't do this dominance check.  */
2353           if (e == NULL
2354               && dominated_by_p (CDI_DOMINATORS, dest_bb, loc->bb))
2355             return;
2356
2357           /* Otherwise, if E is not a critical edge and DEST_BB
2358              dominates the existing location for the assertion, move
2359              the assertion up in the dominance tree by updating its
2360              location information.  */
2361           if ((e == NULL || !EDGE_CRITICAL_P (e))
2362               && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
2363             {
2364               loc->bb = dest_bb;
2365               loc->e = e;
2366               loc->si = si;
2367               return;
2368             }
2369         }
2370
2371       /* Update the last node of the list and move to the next one.  */
2372       last_loc = loc;
2373       loc = loc->next;
2374     }
2375
2376   /* If we didn't find an assertion already registered for
2377      NAME COMP_CODE VAL, add a new one at the end of the list of
2378      assertions associated with NAME.  */
2379   n = xmalloc (sizeof (*n));
2380   n->bb = dest_bb;
2381   n->e = e;
2382   n->si = si;
2383   n->comp_code = comp_code;
2384   n->val = val;
2385   n->next = NULL;
2386
2387   if (last_loc)
2388     last_loc->next = n;
2389   else
2390     asserts_for[SSA_NAME_VERSION (name)] = n;
2391
2392   bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
2393 }
2394
2395
2396 /* Try to register an edge assertion for SSA name NAME on edge E for
2397    the conditional jump pointed by SI.  Return true if an assertion
2398    for NAME could be registered.  */
2399
2400 static bool
2401 register_edge_assert_for (tree name, edge e, block_stmt_iterator si)
2402 {
2403   tree val, stmt;
2404   enum tree_code comp_code;
2405
2406   stmt = bsi_stmt (si);
2407
2408   /* Do not attempt to infer anything in names that flow through
2409      abnormal edges.  */
2410   if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
2411     return false;
2412
2413   /* If NAME was not found in the sub-graph reachable from E, then
2414      there's nothing to do.  */
2415   if (!TEST_BIT (found_in_subgraph, SSA_NAME_VERSION (name)))
2416     return false;
2417
2418   /* We found a use of NAME in the sub-graph rooted at E->DEST.
2419      Register an assertion for NAME according to the value that NAME
2420      takes on edge E.  */
2421   if (TREE_CODE (stmt) == COND_EXPR)
2422     {
2423       /* If BB ends in a COND_EXPR then NAME then we should insert
2424          the original predicate on EDGE_TRUE_VALUE and the
2425          opposite predicate on EDGE_FALSE_VALUE.  */
2426       tree cond = COND_EXPR_COND (stmt);
2427       bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
2428
2429       /* Predicates may be a single SSA name or NAME OP VAL.  */
2430       if (cond == name)
2431         {
2432           /* If the predicate is a name, it must be NAME, in which
2433              case we create the predicate NAME == true or
2434              NAME == false accordingly.  */
2435           comp_code = EQ_EXPR;
2436           val = (is_else_edge) ? boolean_false_node : boolean_true_node;
2437         }
2438       else
2439         {
2440           /* Otherwise, we have a comparison of the form NAME COMP VAL
2441              or VAL COMP NAME.  */
2442           if (name == TREE_OPERAND (cond, 1))
2443             {
2444               /* If the predicate is of the form VAL COMP NAME, flip
2445                  COMP around because we need to register NAME as the
2446                  first operand in the predicate.  */
2447               comp_code = opposite_comparison (TREE_CODE (cond));
2448               val = TREE_OPERAND (cond, 0);
2449             }
2450           else
2451             {
2452               /* The comparison is of the form NAME COMP VAL, so the
2453                  comparison code remains unchanged.  */
2454               comp_code = TREE_CODE (cond);
2455               val = TREE_OPERAND (cond, 1);
2456             }
2457
2458           /* If we are inserting the assertion on the ELSE edge, we
2459              need to invert the sign comparison.  */
2460           if (is_else_edge)
2461             comp_code = invert_tree_comparison (comp_code, 0);
2462         }
2463     }
2464   else
2465     {
2466       /* FIXME.  Handle SWITCH_EXPR.  */
2467       gcc_unreachable ();
2468     }
2469
2470   register_new_assert_for (name, comp_code, val, NULL, e, si);
2471   return true;
2472 }
2473
2474
2475 static bool find_assert_locations (basic_block bb);
2476
2477 /* Determine whether the outgoing edges of BB should receive an
2478    ASSERT_EXPR for each of the operands of BB's last statement.  The
2479    last statement of BB must be a COND_EXPR or a SWITCH_EXPR.
2480
2481    If any of the sub-graphs rooted at BB have an interesting use of
2482    the predicate operands, an assert location node is added to the
2483    list of assertions for the corresponding operands.  */
2484
2485 static bool
2486 find_conditional_asserts (basic_block bb)
2487 {
2488   bool need_assert;
2489   block_stmt_iterator last_si;
2490   tree op, last;
2491   edge_iterator ei;
2492   edge e;
2493   ssa_op_iter iter;
2494
2495   need_assert = false;
2496   last_si = bsi_last (bb);
2497   last = bsi_stmt (last_si);
2498
2499   /* Look for uses of the operands in each of the sub-graphs
2500      rooted at BB.  We need to check each of the outgoing edges
2501      separately, so that we know what kind of ASSERT_EXPR to
2502      insert.  */
2503   FOR_EACH_EDGE (e, ei, bb->succs)
2504     {
2505       if (e->dest == bb)
2506         continue;
2507
2508       /* Remove the COND_EXPR operands from the FOUND_IN_SUBGRAPH bitmap.
2509          Otherwise, when we finish traversing each of the sub-graphs, we
2510          won't know whether the variables were found in the sub-graphs or
2511          if they had been found in a block upstream from BB.  */
2512       FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
2513         RESET_BIT (found_in_subgraph, SSA_NAME_VERSION (op));
2514
2515       /* Traverse the strictly dominated sub-graph rooted at E->DEST
2516          to determine if any of the operands in the conditional
2517          predicate are used.  */
2518       if (e->dest != bb)
2519         need_assert |= find_assert_locations (e->dest);
2520
2521       /* Register the necessary assertions for each operand in the
2522          conditional predicate.  */
2523       FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
2524         need_assert |= register_edge_assert_for (op, e, last_si);
2525     }
2526
2527   /* Finally, indicate that we have found the operands in the
2528      conditional.  */
2529   FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
2530     SET_BIT (found_in_subgraph, SSA_NAME_VERSION (op));
2531
2532   return need_assert;
2533 }
2534
2535
2536 /* Traverse all the statements in block BB looking for statements that
2537    may generate useful assertions for the SSA names in their operand.
2538    If a statement produces a useful assertion A for name N_i, then the
2539    list of assertions already generated for N_i is scanned to
2540    determine if A is actually needed.
2541    
2542    If N_i already had the assertion A at a location dominating the
2543    current location, then nothing needs to be done.  Otherwise, the
2544    new location for A is recorded instead.
2545
2546    1- For every statement S in BB, all the variables used by S are
2547       added to bitmap FOUND_IN_SUBGRAPH.
2548
2549    2- If statement S uses an operand N in a way that exposes a known
2550       value range for N, then if N was not already generated by an
2551       ASSERT_EXPR, create a new assert location for N.  For instance,
2552       if N is a pointer and the statement dereferences it, we can
2553       assume that N is not NULL.
2554
2555    3- COND_EXPRs are a special case of #2.  We can derive range
2556       information from the predicate but need to insert different
2557       ASSERT_EXPRs for each of the sub-graphs rooted at the
2558       conditional block.  If the last statement of BB is a conditional
2559       expression of the form 'X op Y', then
2560
2561       a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
2562
2563       b) If the conditional is the only entry point to the sub-graph
2564          corresponding to the THEN_CLAUSE, recurse into it.  On
2565          return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
2566          an ASSERT_EXPR is added for the corresponding variable.
2567
2568       c) Repeat step (b) on the ELSE_CLAUSE.
2569
2570       d) Mark X and Y in FOUND_IN_SUBGRAPH.
2571
2572       For instance,
2573
2574             if (a == 9)
2575               b = a;
2576             else
2577               b = c + 1;
2578
2579       In this case, an assertion on the THEN clause is useful to
2580       determine that 'a' is always 9 on that edge.  However, an assertion
2581       on the ELSE clause would be unnecessary.
2582
2583    4- If BB does not end in a conditional expression, then we recurse
2584       into BB's dominator children.
2585    
2586    At the end of the recursive traversal, every SSA name will have a
2587    list of locations where ASSERT_EXPRs should be added.  When a new
2588    location for name N is found, it is registered by calling
2589    register_new_assert_for.  That function keeps track of all the
2590    registered assertions to prevent adding unnecessary assertions.
2591    For instance, if a pointer P_4 is dereferenced more than once in a
2592    dominator tree, only the location dominating all the dereference of
2593    P_4 will receive an ASSERT_EXPR.
2594
2595    If this function returns true, then it means that there are names
2596    for which we need to generate ASSERT_EXPRs.  Those assertions are
2597    inserted by process_assert_insertions.
2598
2599    TODO.  Handle SWITCH_EXPR.  */
2600
2601 static bool
2602 find_assert_locations (basic_block bb)
2603 {
2604   block_stmt_iterator si;
2605   tree last, phi;
2606   bool need_assert;
2607   basic_block son;
2608
2609   if (TEST_BIT (blocks_visited, bb->index))
2610     return false;
2611
2612   SET_BIT (blocks_visited, bb->index);
2613
2614   need_assert = false;
2615
2616   /* Traverse all PHI nodes in BB marking used operands.  */
2617   for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
2618     {
2619       use_operand_p arg_p;
2620       ssa_op_iter i;
2621
2622       FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
2623         {
2624           tree arg = USE_FROM_PTR (arg_p);
2625           if (TREE_CODE (arg) == SSA_NAME)
2626             {
2627               gcc_assert (is_gimple_reg (PHI_RESULT (phi)));
2628               SET_BIT (found_in_subgraph, SSA_NAME_VERSION (arg));
2629             }
2630         }
2631     }
2632
2633   /* Traverse all the statements in BB marking used names and looking
2634      for statements that may infer assertions for their used operands.  */
2635   last = NULL_TREE;
2636   for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
2637     {
2638       tree stmt, op;
2639       ssa_op_iter i;
2640
2641       stmt = bsi_stmt (si);
2642
2643       /* See if we can derive an assertion for any of STMT's operands.  */
2644       FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
2645         {
2646           tree value;
2647           enum tree_code comp_code;
2648
2649           /* Mark OP in bitmap FOUND_IN_SUBGRAPH.  If STMT is inside
2650              the sub-graph of a conditional block, when we return from
2651              this recursive walk, our parent will use the
2652              FOUND_IN_SUBGRAPH bitset to determine if one of the
2653              operands it was looking for was present in the sub-graph.  */
2654           SET_BIT (found_in_subgraph, SSA_NAME_VERSION (op));
2655
2656           /* If OP is used only once, namely in this STMT, don't
2657              bother creating an ASSERT_EXPR for it.  Such an
2658              ASSERT_EXPR would do nothing but increase compile time.
2659              Experiments show that with this simple check, we can save
2660              more than 20% of ASSERT_EXPRs.  */
2661           if (has_single_use (op))
2662             continue;
2663
2664           /* If OP is used in such a way that we can infer a value
2665              range for it, and we don't find a previous assertion for
2666              it, create a new assertion location node for OP.  */
2667           if (infer_value_range (stmt, op, &comp_code, &value))
2668             {
2669               register_new_assert_for (op, comp_code, value, bb, NULL, si);
2670               need_assert = true;
2671             }
2672         }
2673
2674       /* Remember the last statement of the block.  */
2675       last = stmt;
2676     }
2677
2678   /* If BB's last statement is a conditional expression
2679      involving integer operands, recurse into each of the sub-graphs
2680      rooted at BB to determine if we need to add ASSERT_EXPRs.  */
2681   if (last
2682       && TREE_CODE (last) == COND_EXPR
2683       && !fp_predicate (COND_EXPR_COND (last))
2684       && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
2685     need_assert |= find_conditional_asserts (bb);
2686
2687   /* Recurse into the dominator children of BB.  */
2688   for (son = first_dom_son (CDI_DOMINATORS, bb);
2689        son;
2690        son = next_dom_son (CDI_DOMINATORS, son))
2691     need_assert |= find_assert_locations (son);
2692
2693   return need_assert;
2694 }
2695
2696
2697 /* Create an ASSERT_EXPR for NAME and insert it in the location
2698    indicated by LOC.  Return true if we made any edge insertions.  */
2699
2700 static bool
2701 process_assert_insertions_for (tree name, assert_locus_t loc)
2702 {
2703   /* Build the comparison expression NAME_i COMP_CODE VAL.  */
2704   tree stmt, cond, assert_expr;
2705   edge_iterator ei;
2706   edge e;
2707
2708   cond = build (loc->comp_code, boolean_type_node, name, loc->val);
2709   assert_expr = build_assert_expr_for (cond, name);
2710
2711   if (loc->e)
2712     {
2713       /* We have been asked to insert the assertion on an edge.  This
2714          is used only by COND_EXPR and SWITCH_EXPR assertions.  */
2715 #if defined ENABLE_CHECKING
2716       gcc_assert (TREE_CODE (bsi_stmt (loc->si)) == COND_EXPR
2717           || TREE_CODE (bsi_stmt (loc->si)) == SWITCH_EXPR);
2718 #endif
2719
2720       bsi_insert_on_edge (loc->e, assert_expr);
2721       return true;
2722     }
2723
2724   /* Otherwise, we can insert right after LOC->SI iff the
2725      statement must not be the last statement in the block.  */
2726   stmt = bsi_stmt (loc->si);
2727   if (!stmt_ends_bb_p (stmt))
2728     {
2729       bsi_insert_after (&loc->si, assert_expr, BSI_SAME_STMT);
2730       return false;
2731     }
2732
2733   /* If STMT must be the last statement in BB, we can only insert new
2734      assertions on the non-abnormal edge out of BB.  Note that since
2735      STMT is not control flow, there may only be one non-abnormal edge
2736      out of BB.  */
2737   FOR_EACH_EDGE (e, ei, loc->bb->succs)
2738     if (!(e->flags & EDGE_ABNORMAL))
2739       {
2740         bsi_insert_on_edge (e, assert_expr);
2741         return true;
2742       }
2743
2744   gcc_unreachable ();
2745 }
2746
2747
2748 /* Process all the insertions registered for every name N_i registered
2749    in NEED_ASSERT_FOR.  The list of assertions to be inserted are
2750    found in ASSERTS_FOR[i].  */
2751
2752 static void
2753 process_assert_insertions (void)
2754 {
2755   unsigned i;
2756   bitmap_iterator bi;
2757   bool update_edges_p = false;
2758   int num_asserts = 0;
2759
2760   if (dump_file && (dump_flags & TDF_DETAILS))
2761     dump_all_asserts (dump_file);
2762
2763   EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
2764     {
2765       assert_locus_t loc = asserts_for[i];
2766       gcc_assert (loc);
2767
2768       while (loc)
2769         {
2770           assert_locus_t next = loc->next;
2771           update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
2772           free (loc);
2773           loc = next;
2774           num_asserts++;
2775         }
2776     }
2777
2778   if (update_edges_p)
2779     bsi_commit_edge_inserts ();
2780
2781   if (dump_file && (dump_flags & TDF_STATS))
2782     fprintf (dump_file, "\nNumber of ASSERT_EXPR expressions inserted: %d\n\n",
2783              num_asserts);
2784 }
2785
2786
2787 /* Traverse the flowgraph looking for conditional jumps to insert range
2788    expressions.  These range expressions are meant to provide information
2789    to optimizations that need to reason in terms of value ranges.  They
2790    will not be expanded into RTL.  For instance, given:
2791
2792    x = ...
2793    y = ...
2794    if (x < y)
2795      y = x - 2;
2796    else
2797      x = y + 3;
2798
2799    this pass will transform the code into:
2800
2801    x = ...
2802    y = ...
2803    if (x < y)
2804     {
2805       x = ASSERT_EXPR <x, x < y>
2806       y = x - 2
2807     }
2808    else
2809     {
2810       y = ASSERT_EXPR <y, x <= y>
2811       x = y + 3
2812     }
2813
2814    The idea is that once copy and constant propagation have run, other
2815    optimizations will be able to determine what ranges of values can 'x'
2816    take in different paths of the code, simply by checking the reaching
2817    definition of 'x'.  */
2818
2819 static void
2820 insert_range_assertions (void)
2821 {
2822   edge e;
2823   edge_iterator ei;
2824   bool update_ssa_p;
2825   
2826   found_in_subgraph = sbitmap_alloc (num_ssa_names);
2827   sbitmap_zero (found_in_subgraph);
2828
2829   blocks_visited = sbitmap_alloc (last_basic_block);
2830   sbitmap_zero (blocks_visited);
2831
2832   need_assert_for = BITMAP_ALLOC (NULL);
2833   asserts_for = xmalloc (num_ssa_names * sizeof (assert_locus_t));
2834   memset (asserts_for, 0, num_ssa_names * sizeof (assert_locus_t));
2835
2836   calculate_dominance_info (CDI_DOMINATORS);
2837
2838   update_ssa_p = false;
2839   FOR_EACH_EDGE (e, ei, ENTRY_BLOCK_PTR->succs)
2840     if (find_assert_locations (e->dest))
2841       update_ssa_p = true;
2842
2843   if (update_ssa_p)
2844     {
2845       process_assert_insertions ();
2846       update_ssa (TODO_update_ssa_no_phi);
2847     }
2848
2849   if (dump_file && (dump_flags & TDF_DETAILS))
2850     {
2851       fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
2852       dump_function_to_file (current_function_decl, dump_file, dump_flags);
2853     }
2854
2855   sbitmap_free (found_in_subgraph);
2856   free (asserts_for);
2857   BITMAP_FREE (need_assert_for);
2858 }
2859
2860
2861 /* Convert range assertion expressions into the implied copies.
2862    
2863    FIXME, this will eventually lead to copy propagation removing the
2864    names that had useful range information attached to them.  For
2865    instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
2866    then N_i will have the range [3, +INF].
2867    
2868    However, by converting the assertion into the implied copy
2869    operation N_i = N_j, we will then copy-propagate N_j into the uses
2870    of N_i and lose the range information.  We may want to hold on to
2871    ASSERT_EXPRs a little while longer as the ranges could be used in
2872    things like jump threading.
2873    
2874    The problem with keeping ASSERT_EXPRs around is that passes after
2875    VRP need to handle them appropriately.  */
2876
2877 static void
2878 remove_range_assertions (void)
2879 {
2880   basic_block bb;
2881   block_stmt_iterator si;
2882
2883   FOR_EACH_BB (bb)
2884     for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
2885       {
2886         tree stmt = bsi_stmt (si);
2887
2888         if (TREE_CODE (stmt) == MODIFY_EXPR
2889             && TREE_CODE (TREE_OPERAND (stmt, 1)) == ASSERT_EXPR)
2890           {
2891             tree rhs = TREE_OPERAND (stmt, 1);
2892             tree cond = fold (ASSERT_EXPR_COND (rhs));
2893             gcc_assert (cond != boolean_false_node);
2894             TREE_OPERAND (stmt, 1) = ASSERT_EXPR_VAR (rhs);
2895             update_stmt (stmt);
2896           }
2897       }
2898 }
2899
2900
2901 /* Return true if STMT is interesting for VRP.  */
2902
2903 static bool
2904 stmt_interesting_for_vrp (tree stmt)
2905 {
2906   if (TREE_CODE (stmt) == PHI_NODE
2907       && is_gimple_reg (PHI_RESULT (stmt))
2908       && (INTEGRAL_TYPE_P (TREE_TYPE (PHI_RESULT (stmt)))
2909           || POINTER_TYPE_P (TREE_TYPE (PHI_RESULT (stmt)))))
2910     return true;
2911   else if (TREE_CODE (stmt) == MODIFY_EXPR)
2912     {
2913       tree lhs = TREE_OPERAND (stmt, 0);
2914
2915       if (TREE_CODE (lhs) == SSA_NAME
2916           && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
2917               || POINTER_TYPE_P (TREE_TYPE (lhs)))
2918           && ZERO_SSA_OPERANDS (stmt, SSA_OP_ALL_VIRTUALS))
2919         return true;
2920     }
2921   else if (TREE_CODE (stmt) == COND_EXPR || TREE_CODE (stmt) == SWITCH_EXPR)
2922     return true;
2923
2924   return false;
2925 }
2926
2927
2928 /* Initialize local data structures for VRP.  Return true if VRP
2929    is worth running (i.e. if we found any statements that could
2930    benefit from range information).  */
2931
2932 static void
2933 vrp_initialize (void)
2934 {
2935   basic_block bb;
2936
2937   vr_value = xmalloc (num_ssa_names * sizeof (value_range_t *));
2938   memset (vr_value, 0, num_ssa_names * sizeof (value_range_t *));
2939
2940   FOR_EACH_BB (bb)
2941     {
2942       block_stmt_iterator si;
2943       tree phi;
2944
2945       for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
2946         {
2947           if (!stmt_interesting_for_vrp (phi))
2948             {
2949               tree lhs = PHI_RESULT (phi);
2950               set_value_range_to_varying (get_value_range (lhs));
2951               DONT_SIMULATE_AGAIN (phi) = true;
2952             }
2953           else
2954             DONT_SIMULATE_AGAIN (phi) = false;
2955         }
2956
2957       for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
2958         {
2959           tree stmt = bsi_stmt (si);
2960
2961           if (!stmt_interesting_for_vrp (stmt))
2962             {
2963               ssa_op_iter i;
2964               tree def;
2965               FOR_EACH_SSA_TREE_OPERAND (def, stmt, i, SSA_OP_DEF)
2966                 set_value_range_to_varying (get_value_range (def));
2967               DONT_SIMULATE_AGAIN (stmt) = true;
2968             }
2969           else
2970             {
2971               DONT_SIMULATE_AGAIN (stmt) = false;
2972             }
2973         }
2974     }
2975 }
2976
2977
2978 /* Visit assignment STMT.  If it produces an interesting range, record
2979    the SSA name in *OUTPUT_P.  */
2980
2981 static enum ssa_prop_result
2982 vrp_visit_assignment (tree stmt, tree *output_p)
2983 {
2984   tree lhs, rhs, def;
2985   ssa_op_iter iter;
2986
2987   lhs = TREE_OPERAND (stmt, 0);
2988   rhs = TREE_OPERAND (stmt, 1);
2989
2990   /* We only keep track of ranges in integral and pointer types.  */
2991   if (TREE_CODE (lhs) == SSA_NAME
2992       && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
2993           || POINTER_TYPE_P (TREE_TYPE (lhs))))
2994     {
2995       struct loop *l;
2996       value_range_t new_vr = { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL };
2997
2998       extract_range_from_expr (&new_vr, rhs);
2999
3000       /* If STMT is inside a loop, we may be able to know something
3001          else about the range of LHS by examining scalar evolution
3002          information.  */
3003       if (cfg_loops && (l = loop_containing_stmt (stmt)))
3004         adjust_range_with_scev (&new_vr, l, lhs);
3005
3006       if (update_value_range (lhs, &new_vr))
3007         {
3008           *output_p = lhs;
3009
3010           if (dump_file && (dump_flags & TDF_DETAILS))
3011             {
3012               fprintf (dump_file, "Found new range for ");
3013               print_generic_expr (dump_file, lhs, 0);
3014               fprintf (dump_file, ": ");
3015               dump_value_range (dump_file, &new_vr);
3016               fprintf (dump_file, "\n\n");
3017             }
3018
3019           if (new_vr.type == VR_VARYING)
3020             return SSA_PROP_VARYING;
3021
3022           return SSA_PROP_INTERESTING;
3023         }
3024
3025       return SSA_PROP_NOT_INTERESTING;
3026     }
3027   
3028   /* Every other statement produces no useful ranges.  */
3029   FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF)
3030     set_value_range_to_varying (get_value_range (def));
3031
3032   return SSA_PROP_VARYING;
3033 }
3034
3035
3036 /* Compare all the value ranges for names equivalent to VAR with VAL
3037    using comparison code COMP.  Return the same value returned by
3038    compare_range_with_value.  */
3039
3040 static tree
3041 compare_name_with_value (enum tree_code comp, tree var, tree val)
3042 {
3043   bitmap_iterator bi;
3044   unsigned i;
3045   bitmap e;
3046   tree retval, t;
3047   
3048   t = retval = NULL_TREE;
3049
3050   /* Get the set of equivalences for VAR.  */
3051   e = get_value_range (var)->equiv;
3052
3053   /* Add VAR to its own set of equivalences so that VAR's value range
3054      is processed by this loop (otherwise, we would have to replicate
3055      the body of the loop just to check VAR's value range).  */
3056   bitmap_set_bit (e, SSA_NAME_VERSION (var));
3057
3058   EXECUTE_IF_SET_IN_BITMAP (e, 0, i, bi)
3059     {
3060       value_range_t equiv_vr = *(vr_value[i]);
3061
3062       /* If name N_i does not have a valid range, use N_i as its own
3063          range.  This allows us to compare against names that may
3064          have N_i in their ranges.  */
3065       if (equiv_vr.type == VR_VARYING || equiv_vr.type == VR_UNDEFINED)
3066         {
3067           equiv_vr.type = VR_RANGE;
3068           equiv_vr.min = ssa_name (i);
3069           equiv_vr.max = ssa_name (i);
3070         }
3071
3072       t = compare_range_with_value (comp, &equiv_vr, val);
3073       if (t)
3074         {
3075           /* All the ranges should compare the same against VAL.  */
3076           gcc_assert (retval == NULL || t == retval);
3077           retval = t;
3078         }
3079     }
3080
3081   /* Remove VAR from its own equivalence set.  */
3082   bitmap_clear_bit (e, SSA_NAME_VERSION (var));
3083
3084   if (retval)
3085     return retval;
3086
3087   /* We couldn't find a non-NULL value for the predicate.  */
3088   return NULL_TREE;
3089 }
3090
3091
3092 /* Given a comparison code COMP and names N1 and N2, compare all the
3093    ranges equivalent to N1 against all the ranges equivalente to N2
3094    to determine the value of N1 COMP N2.  Return the same value
3095    returned by compare_ranges.  */
3096
3097 static tree
3098 compare_names (enum tree_code comp, tree n1, tree n2)
3099 {
3100   tree t, retval;
3101   bitmap e1, e2;
3102   bitmap_iterator bi1, bi2;
3103   unsigned i1, i2;
3104
3105   /* Compare the ranges of every name equivalent to N1 against the
3106      ranges of every name equivalent to N2.  */
3107   e1 = get_value_range (n1)->equiv;
3108   e2 = get_value_range (n2)->equiv;
3109
3110   /* Add N1 and N2 to their own set of equivalences to avoid
3111      duplicating the body of the loop just to check N1 and N2
3112      ranges.  */
3113   bitmap_set_bit (e1, SSA_NAME_VERSION (n1));
3114   bitmap_set_bit (e2, SSA_NAME_VERSION (n2));
3115
3116   /* If the equivalence sets have a common intersection, then the two
3117      names can be compared without checking their ranges.  */
3118   if (bitmap_intersect_p (e1, e2))
3119     {
3120       bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
3121       bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
3122
3123       return (comp == EQ_EXPR || comp == GE_EXPR || comp == LE_EXPR)
3124              ? boolean_true_node
3125              : boolean_false_node;
3126     }
3127
3128   /* Otherwise, compare all the equivalent ranges.  First, add N1 and
3129      N2 to their own set of equivalences to avoid duplicating the body
3130      of the loop just to check N1 and N2 ranges.  */
3131   EXECUTE_IF_SET_IN_BITMAP (e1, 0, i1, bi1)
3132     {
3133       value_range_t vr1 = *(vr_value[i1]);
3134
3135       /* If the range is VARYING or UNDEFINED, use the name itself.  */
3136       if (vr1.type == VR_VARYING || vr1.type == VR_UNDEFINED)
3137         {
3138           vr1.type = VR_RANGE;
3139           vr1.min = ssa_name (i1);
3140           vr1.max = ssa_name (i1);
3141         }
3142
3143       t = retval = NULL_TREE;
3144       EXECUTE_IF_SET_IN_BITMAP (e2, 0, i2, bi2)
3145         {
3146           value_range_t vr2 = *(vr_value[i2]);
3147
3148           if (vr2.type == VR_VARYING || vr2.type == VR_UNDEFINED)
3149             {
3150               vr2.type = VR_RANGE;
3151               vr2.min = ssa_name (i2);
3152               vr2.max = ssa_name (i2);
3153             }
3154
3155           t = compare_ranges (comp, &vr1, &vr2);
3156           if (t)
3157             {
3158               /* All the ranges in the equivalent sets should compare
3159                  the same.  */
3160               gcc_assert (retval == NULL || t == retval);
3161               retval = t;
3162             }
3163         }
3164
3165       if (retval)
3166         {
3167           bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
3168           bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
3169           return retval;
3170         }
3171     }
3172
3173   /* None of the equivalent ranges are useful in computing this
3174      comparison.  */
3175   bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
3176   bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
3177   return NULL_TREE;
3178 }
3179
3180
3181 /* Given a conditional predicate COND, try to determine if COND yields
3182    true or false based on the value ranges of its operands.  Return
3183    BOOLEAN_TRUE_NODE if the conditional always evaluates to true,
3184    BOOLEAN_FALSE_NODE if the conditional always evaluates to false, and,
3185    NULL if the conditional cannot be evaluated at compile time.
3186
3187    If USE_EQUIV_P is true, the ranges of all the names equivalent with
3188    the operands in COND are used when trying to compute its value.
3189    This is only used during final substitution.  During propagation,
3190    we only check the range of each variable and not its equivalents.  */
3191
3192 tree
3193 vrp_evaluate_conditional (tree cond, bool use_equiv_p)
3194 {
3195   gcc_assert (TREE_CODE (cond) == SSA_NAME
3196               || TREE_CODE_CLASS (TREE_CODE (cond)) == tcc_comparison);
3197
3198   if (TREE_CODE (cond) == SSA_NAME)
3199     {
3200       value_range_t *vr;
3201       tree retval;
3202
3203       if (use_equiv_p)
3204         retval = compare_name_with_value (NE_EXPR, cond, boolean_false_node);
3205       else
3206         {
3207           value_range_t *vr = get_value_range (cond);
3208           retval = compare_range_with_value (NE_EXPR, vr, boolean_false_node);
3209         }
3210
3211       /* If COND has a known boolean range, return it.  */
3212       if (retval)
3213         return retval;
3214
3215       /* Otherwise, if COND has a symbolic range of exactly one value,
3216          return it.  */
3217       vr = get_value_range (cond);
3218       if (vr->type == VR_RANGE && vr->min == vr->max)
3219         return vr->min;
3220     }
3221   else
3222     {
3223       tree op0 = TREE_OPERAND (cond, 0);
3224       tree op1 = TREE_OPERAND (cond, 1);
3225
3226       /* We only deal with integral and pointer types.  */
3227       if (!INTEGRAL_TYPE_P (TREE_TYPE (op0))
3228           && !POINTER_TYPE_P (TREE_TYPE (op0)))
3229         return NULL_TREE;
3230
3231       if (use_equiv_p)
3232         {
3233           if (TREE_CODE (op0) == SSA_NAME && TREE_CODE (op1) == SSA_NAME)
3234             return compare_names (TREE_CODE (cond), op0, op1);
3235           else if (TREE_CODE (op0) == SSA_NAME)
3236             return compare_name_with_value (TREE_CODE (cond), op0, op1);
3237           else if (TREE_CODE (op1) == SSA_NAME)
3238             return compare_name_with_value (
3239                     opposite_comparison (TREE_CODE (cond)), op1, op0);
3240         }
3241       else
3242         {
3243           value_range_t *vr0, *vr1;
3244
3245           vr0 = (TREE_CODE (op0) == SSA_NAME) ? get_value_range (op0) : NULL;
3246           vr1 = (TREE_CODE (op1) == SSA_NAME) ? get_value_range (op1) : NULL;
3247
3248           if (vr0 && vr1)
3249             return compare_ranges (TREE_CODE (cond), vr0, vr1);
3250           else if (vr0 && vr1 == NULL)
3251             return compare_range_with_value (TREE_CODE (cond), vr0, op1);
3252           else if (vr0 == NULL && vr1)
3253             return compare_range_with_value (
3254                     opposite_comparison (TREE_CODE (cond)), vr1, op0);
3255         }
3256     }
3257
3258   /* Anything else cannot be computed statically.  */
3259   return NULL_TREE;
3260 }
3261
3262
3263 /* Visit conditional statement STMT.  If we can determine which edge
3264    will be taken out of STMT's basic block, record it in
3265    *TAKEN_EDGE_P and return SSA_PROP_INTERESTING.  Otherwise, return
3266    SSA_PROP_VARYING.  */
3267
3268 static enum ssa_prop_result
3269 vrp_visit_cond_stmt (tree stmt, edge *taken_edge_p)
3270 {
3271   tree cond, val;
3272
3273   *taken_edge_p = NULL;
3274
3275   /* FIXME.  Handle SWITCH_EXPRs.  But first, the assert pass needs to
3276      add ASSERT_EXPRs for them.  */
3277   if (TREE_CODE (stmt) == SWITCH_EXPR)
3278     return SSA_PROP_VARYING;
3279
3280   cond = COND_EXPR_COND (stmt);
3281
3282   if (dump_file && (dump_flags & TDF_DETAILS))
3283     {
3284       tree use;
3285       ssa_op_iter i;
3286
3287       fprintf (dump_file, "\nVisiting conditional with predicate: ");
3288       print_generic_expr (dump_file, cond, 0);
3289       fprintf (dump_file, "\nWith known ranges\n");
3290       
3291       FOR_EACH_SSA_TREE_OPERAND (use, stmt, i, SSA_OP_USE)
3292         {
3293           fprintf (dump_file, "\t");
3294           print_generic_expr (dump_file, use, 0);
3295           fprintf (dump_file, ": ");
3296           dump_value_range (dump_file, vr_value[SSA_NAME_VERSION (use)]);
3297         }
3298
3299       fprintf (dump_file, "\n");
3300     }
3301
3302   /* Compute the value of the predicate COND by checking the known
3303      ranges of each of its operands.
3304      
3305      Note that we cannot evaluate all the equivalent ranges here
3306      because those ranges may not yet be final and with the current
3307      propagation strategy, we cannot determine when the value ranges
3308      of the names in the equivalence set have changed.
3309
3310      For instance, given the following code fragment
3311
3312         i_5 = PHI <8, i_13>
3313         ...
3314         i_14 = ASSERT_EXPR <i_5, i_5 != 0>
3315         if (i_14 == 1)
3316           ...
3317
3318      Assume that on the first visit to i_14, i_5 has the temporary
3319      range [8, 8] because the second argument to the PHI function is
3320      not yet executable.  We derive the range ~[0, 0] for i_14 and the
3321      equivalence set { i_5 }.  So, when we visit 'if (i_14 == 1)' for
3322      the first time, since i_14 is equivalent to the range [8, 8], we
3323      determine that the predicate is always false.
3324
3325      On the next round of propagation, i_13 is determined to be
3326      VARYING, which causes i_5 to drop down to VARYING.  So, another
3327      visit to i_14 is scheduled.  In this second visit, we compute the
3328      exact same range and equivalence set for i_14, namely ~[0, 0] and
3329      { i_5 }.  But we did not have the previous range for i_5
3330      registered, so vrp_visit_assignment thinks that the range for
3331      i_14 has not changed.  Therefore, the predicate 'if (i_14 == 1)'
3332      is not visited again, which stops propagation from visiting
3333      statements in the THEN clause of that if().
3334
3335      To properly fix this we would need to keep the previous range
3336      value for the names in the equivalence set.  This way we would've
3337      discovered that from one visit to the other i_5 changed from
3338      range [8, 8] to VR_VARYING.
3339
3340      However, fixing this apparent limitation may not be worth the
3341      additional checking.  Testing on several code bases (GCC, DLV,
3342      MICO, TRAMP3D and SPEC2000) showed that doing this results in
3343      4 more predicates folded in SPEC.  */
3344   val = vrp_evaluate_conditional (cond, false);
3345   if (val)
3346     *taken_edge_p = find_taken_edge (bb_for_stmt (stmt), val);
3347
3348   if (dump_file && (dump_flags & TDF_DETAILS))
3349     {
3350       fprintf (dump_file, "\nPredicate evaluates to: ");
3351       if (val == NULL_TREE)
3352         fprintf (dump_file, "DON'T KNOW\n");
3353       else
3354         print_generic_stmt (dump_file, val, 0);
3355     }
3356
3357   return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
3358 }
3359
3360
3361 /* Evaluate statement STMT.  If the statement produces a useful range,
3362    return SSA_PROP_INTERESTING and record the SSA name with the
3363    interesting range into *OUTPUT_P.
3364
3365    If STMT is a conditional branch and we can determine its truth
3366    value, the taken edge is recorded in *TAKEN_EDGE_P.
3367
3368    If STMT produces a varying value, return SSA_PROP_VARYING.  */
3369
3370 static enum ssa_prop_result
3371 vrp_visit_stmt (tree stmt, edge *taken_edge_p, tree *output_p)
3372 {
3373   tree def;
3374   ssa_op_iter iter;
3375   stmt_ann_t ann;
3376
3377   if (dump_file && (dump_flags & TDF_DETAILS))
3378     {
3379       fprintf (dump_file, "\nVisiting statement:\n");
3380       print_generic_stmt (dump_file, stmt, dump_flags);
3381       fprintf (dump_file, "\n");
3382     }
3383
3384   ann = stmt_ann (stmt);
3385   if (TREE_CODE (stmt) == MODIFY_EXPR
3386       && ZERO_SSA_OPERANDS (stmt, SSA_OP_ALL_VIRTUALS))
3387     return vrp_visit_assignment (stmt, output_p);
3388   else if (TREE_CODE (stmt) == COND_EXPR || TREE_CODE (stmt) == SWITCH_EXPR)
3389     return vrp_visit_cond_stmt (stmt, taken_edge_p);
3390
3391   /* All other statements produce nothing of interest for VRP, so mark
3392      their outputs varying and prevent further simulation.  */
3393   FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF)
3394     set_value_range_to_varying (get_value_range (def));
3395
3396   return SSA_PROP_VARYING;
3397 }
3398
3399
3400 /* Meet operation for value ranges.  Given two value ranges VR0 and
3401    VR1, store in VR0 the result of meeting VR0 and VR1.
3402    
3403    The meeting rules are as follows:
3404
3405    1- If VR0 and VR1 have an empty intersection, set VR0 to VR_VARYING.
3406
3407    2- If VR0 and VR1 have a non-empty intersection, set VR0 to the
3408       union of VR0 and VR1.  */
3409
3410 static void
3411 vrp_meet (value_range_t *vr0, value_range_t *vr1)
3412 {
3413   if (vr0->type == VR_UNDEFINED)
3414     {
3415       copy_value_range (vr0, vr1);
3416       return;
3417     }
3418
3419   if (vr1->type == VR_UNDEFINED)
3420     {
3421       /* Nothing to do.  VR0 already has the resulting range.  */
3422       return;
3423     }
3424
3425   if (vr0->type == VR_VARYING)
3426     {
3427       /* Nothing to do.  VR0 already has the resulting range.  */
3428       return;
3429     }
3430
3431   if (vr1->type == VR_VARYING)
3432     {
3433       set_value_range_to_varying (vr0);
3434       return;
3435     }
3436
3437   if (vr0->type == VR_RANGE && vr1->type == VR_RANGE)
3438     {
3439       /* If VR0 and VR1 have a non-empty intersection, compute the
3440          union of both ranges.  */
3441       if (value_ranges_intersect_p (vr0, vr1))
3442         {
3443           int cmp;
3444           tree min, max;
3445
3446           /* The lower limit of the new range is the minimum of the
3447              two ranges.  If they cannot be compared, the result is
3448              VARYING.  */
3449           cmp = compare_values (vr0->min, vr1->min);
3450           if (cmp == 0 || cmp == 1)
3451             min = vr1->min;
3452           else if (cmp == -1)
3453             min = vr0->min;
3454           else
3455             {
3456               set_value_range_to_varying (vr0);
3457               return;
3458             }
3459
3460           /* Similarly, the upper limit of the new range is the
3461              maximum of the two ranges.  If they cannot be compared,
3462              the result is VARYING.  */
3463           cmp = compare_values (vr0->max, vr1->max);
3464           if (cmp == 0 || cmp == -1)
3465             max = vr1->max;
3466           else if (cmp == 1)
3467             max = vr0->max;
3468           else
3469             {
3470               set_value_range_to_varying (vr0);
3471               return;
3472             }
3473
3474           /* The resulting set of equivalencies is the intersection of
3475              the two sets.  */
3476           if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
3477             bitmap_and_into (vr0->equiv, vr1->equiv);
3478
3479           set_value_range (vr0, vr0->type, min, max, vr0->equiv);
3480         }
3481       else
3482         goto no_meet;
3483     }
3484   else if (vr0->type == VR_ANTI_RANGE && vr1->type == VR_ANTI_RANGE)
3485     {
3486       /* Two anti-ranges meet only if they are both identical.  */
3487       if (compare_values (vr0->min, vr1->min) == 0
3488           && compare_values (vr0->max, vr1->max) == 0
3489           && compare_values (vr0->min, vr0->max) == 0)
3490         {
3491           /* The resulting set of equivalencies is the intersection of
3492              the two sets.  */
3493           if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
3494             bitmap_and_into (vr0->equiv, vr1->equiv);
3495         }
3496       else
3497         goto no_meet;
3498     }
3499   else if (vr0->type == VR_ANTI_RANGE || vr1->type == VR_ANTI_RANGE)
3500     {
3501       /* A numeric range [VAL1, VAL2] and an anti-range ~[VAL3, VAL4]
3502          meet only if the ranges have an empty intersection.  The
3503          result of the meet operation is the anti-range.  */
3504       if (!symbolic_range_p (vr0)
3505           && !symbolic_range_p (vr1)
3506           && !value_ranges_intersect_p (vr0, vr1))
3507         {
3508           if (vr1->type == VR_ANTI_RANGE)
3509             copy_value_range (vr0, vr1);
3510         }
3511       else
3512         goto no_meet;
3513     }
3514   else
3515     gcc_unreachable ();
3516
3517   return;
3518
3519 no_meet:
3520   /* The two range VR0 and VR1 do not meet.  Before giving up and
3521      setting the result to VARYING, see if we can at least derive a
3522      useful anti-range.  */
3523   if (!symbolic_range_p (vr0)
3524       && !range_includes_zero_p (vr0)
3525       && !symbolic_range_p (vr1)
3526       && !range_includes_zero_p (vr1))
3527     set_value_range_to_nonnull (vr0, TREE_TYPE (vr0->min));
3528   else
3529     set_value_range_to_varying (vr0);
3530 }
3531
3532
3533 /* Visit all arguments for PHI node PHI that flow through executable
3534    edges.  If a valid value range can be derived from all the incoming
3535    value ranges, set a new range for the LHS of PHI.  */
3536
3537 static enum ssa_prop_result
3538 vrp_visit_phi_node (tree phi)
3539 {
3540   int i;
3541   tree lhs = PHI_RESULT (phi);
3542   value_range_t *lhs_vr = get_value_range (lhs);
3543   value_range_t vr_result = { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL };
3544
3545   copy_value_range (&vr_result, lhs_vr);
3546
3547   if (dump_file && (dump_flags & TDF_DETAILS))
3548     {
3549       fprintf (dump_file, "\nVisiting PHI node: ");
3550       print_generic_expr (dump_file, phi, dump_flags);
3551     }
3552
3553   for (i = 0; i < PHI_NUM_ARGS (phi); i++)
3554     {
3555       edge e = PHI_ARG_EDGE (phi, i);
3556
3557       if (dump_file && (dump_flags & TDF_DETAILS))
3558         {
3559           fprintf (dump_file,
3560               "\n    Argument #%d (%d -> %d %sexecutable)\n",
3561               i, e->src->index, e->dest->index,
3562               (e->flags & EDGE_EXECUTABLE) ? "" : "not ");
3563         }
3564
3565       if (e->flags & EDGE_EXECUTABLE)
3566         {
3567           tree arg = PHI_ARG_DEF (phi, i);
3568           value_range_t vr_arg;
3569
3570           if (TREE_CODE (arg) == SSA_NAME)
3571             vr_arg = *(get_value_range (arg));
3572           else
3573             {
3574               vr_arg.type = VR_RANGE;
3575               vr_arg.min = arg;
3576               vr_arg.max = arg;
3577               vr_arg.equiv = NULL;
3578             }
3579
3580           if (dump_file && (dump_flags & TDF_DETAILS))
3581             {
3582               fprintf (dump_file, "\t");
3583               print_generic_expr (dump_file, arg, dump_flags);
3584               fprintf (dump_file, "\n\tValue: ");
3585               dump_value_range (dump_file, &vr_arg);
3586               fprintf (dump_file, "\n");
3587             }
3588
3589           vrp_meet (&vr_result, &vr_arg);
3590
3591           if (vr_result.type == VR_VARYING)
3592             break;
3593         }
3594     }
3595
3596   if (vr_result.type == VR_VARYING)
3597     goto varying;
3598
3599   /* To prevent infinite iterations in the algorithm, derive ranges
3600      when the new value is slightly bigger or smaller than the
3601      previous one.  */
3602   if (lhs_vr->type == VR_RANGE)
3603     {
3604       if (!POINTER_TYPE_P (TREE_TYPE (lhs)))
3605         {
3606           int cmp_min = compare_values (lhs_vr->min, vr_result.min);
3607           int cmp_max = compare_values (lhs_vr->max, vr_result.max);
3608
3609           /* If the new minimum is smaller or larger than the previous
3610              one, go all the way to -INF.  In the first case, to avoid
3611              iterating millions of times to reach -INF, and in the
3612              other case to avoid infinite bouncing between different
3613              minimums.  */
3614           if (cmp_min > 0 || cmp_min < 0)
3615             vr_result.min = TYPE_MIN_VALUE (TREE_TYPE (vr_result.min));
3616
3617           /* Similarly, if the new maximum is smaller or larger than
3618              the previous one, go all the way to +INF.  */
3619           if (cmp_max < 0 || cmp_max > 0)
3620             vr_result.max = TYPE_MAX_VALUE (TREE_TYPE (vr_result.max));
3621
3622           /* If we ended up with a (-INF, +INF) range, set it to
3623              VARYING.  */
3624           if (vr_result.min == TYPE_MIN_VALUE (TREE_TYPE (vr_result.min))
3625               && vr_result.max == TYPE_MAX_VALUE (TREE_TYPE (vr_result.max)))
3626             goto varying;
3627         }
3628     }
3629
3630   /* If the new range is different than the previous value, keep
3631      iterating.  */
3632   if (update_value_range (lhs, &vr_result))
3633     return SSA_PROP_INTERESTING;
3634
3635   /* Nothing changed, don't add outgoing edges.  */
3636   return SSA_PROP_NOT_INTERESTING;
3637
3638   /* No match found.  Set the LHS to VARYING.  */
3639 varying:
3640   set_value_range_to_varying (lhs_vr);
3641   return SSA_PROP_VARYING;
3642 }
3643
3644
3645 /* Traverse all the blocks folding conditionals with known ranges.  */
3646
3647 static void
3648 vrp_finalize (void)
3649 {
3650   size_t i;
3651   prop_value_t *single_val_range;
3652   bool do_value_subst_p;
3653
3654   if (dump_file)
3655     {
3656       fprintf (dump_file, "\nValue ranges after VRP:\n\n");
3657       dump_all_value_ranges (dump_file);
3658       fprintf (dump_file, "\n");
3659     }
3660
3661   /* We may have ended with ranges that have exactly one value.  Those
3662      values can be substituted as any other copy/const propagated
3663      value using substitute_and_fold.  */
3664   single_val_range = xmalloc (num_ssa_names * sizeof (*single_val_range));
3665   memset (single_val_range, 0, num_ssa_names * sizeof (*single_val_range));
3666
3667   do_value_subst_p = false;
3668   for (i = 0; i < num_ssa_names; i++)
3669     if (vr_value[i]
3670         && vr_value[i]->type == VR_RANGE
3671         && vr_value[i]->min == vr_value[i]->max)
3672       {
3673         single_val_range[i].value = vr_value[i]->min;
3674         do_value_subst_p = true;
3675       }
3676
3677   if (!do_value_subst_p)
3678     {
3679       /* We found no single-valued ranges, don't waste time trying to
3680          do single value substitution in substitute_and_fold.  */
3681       free (single_val_range);
3682       single_val_range = NULL;
3683     }
3684
3685   substitute_and_fold (single_val_range, true);
3686
3687   /* Free allocated memory.  */
3688   for (i = 0; i < num_ssa_names; i++)
3689     if (vr_value[i])
3690       {
3691         BITMAP_FREE (vr_value[i]->equiv);
3692         free (vr_value[i]);
3693       }
3694
3695   free (single_val_range);
3696   free (vr_value);
3697 }
3698
3699
3700 /* Main entry point to VRP (Value Range Propagation).  This pass is
3701    loosely based on J. R. C. Patterson, ``Accurate Static Branch
3702    Prediction by Value Range Propagation,'' in SIGPLAN Conference on
3703    Programming Language Design and Implementation, pp. 67-78, 1995.
3704    Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
3705
3706    This is essentially an SSA-CCP pass modified to deal with ranges
3707    instead of constants.
3708
3709    While propagating ranges, we may find that two or more SSA name
3710    have equivalent, though distinct ranges.  For instance,
3711
3712      1  x_9 = p_3->a;
3713      2  p_4 = ASSERT_EXPR <p_3, p_3 != 0>
3714      3  if (p_4 == q_2)
3715      4    p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
3716      5  endif
3717      6  if (q_2)
3718         
3719    In the code above, pointer p_5 has range [q_2, q_2], but from the
3720    code we can also determine that p_5 cannot be NULL and, if q_2 had
3721    a non-varying range, p_5's range should also be compatible with it.
3722
3723    These equivalencies are created by two expressions: ASSERT_EXPR and
3724    copy operations.  Since p_5 is an assertion on p_4, and p_4 was the
3725    result of another assertion, then we can use the fact that p_5 and
3726    p_4 are equivalent when evaluating p_5's range.
3727
3728    Together with value ranges, we also propagate these equivalencies
3729    between names so that we can take advantage of information from
3730    multiple ranges when doing final replacement.  Note that this
3731    equivalency relation is transitive but not symmetric.
3732    
3733    In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
3734    cannot assert that q_2 is equivalent to p_5 because q_2 may be used
3735    in contexts where that assertion does not hold (e.g., in line 6).
3736
3737    TODO, the main difference between this pass and Patterson's is that
3738    we do not propagate edge probabilities.  We only compute whether
3739    edges can be taken or not.  That is, instead of having a spectrum
3740    of jump probabilities between 0 and 1, we only deal with 0, 1 and
3741    DON'T KNOW.  In the future, it may be worthwhile to propagate
3742    probabilities to aid branch prediction.  */
3743
3744 static void
3745 execute_vrp (void)
3746 {
3747   insert_range_assertions ();
3748
3749   cfg_loops = loop_optimizer_init (NULL);
3750   if (cfg_loops)
3751     scev_initialize (cfg_loops);
3752
3753   vrp_initialize ();
3754   ssa_propagate (vrp_visit_stmt, vrp_visit_phi_node);
3755   vrp_finalize ();
3756
3757   if (cfg_loops)
3758     {
3759       scev_finalize ();
3760       loop_optimizer_finalize (cfg_loops, NULL);
3761       current_loops = NULL;
3762     }
3763
3764   remove_range_assertions ();
3765 }
3766
3767 static bool
3768 gate_vrp (void)
3769 {
3770   return flag_tree_vrp != 0;
3771 }
3772
3773 struct tree_opt_pass pass_vrp =
3774 {
3775   "vrp",                                /* name */
3776   gate_vrp,                             /* gate */
3777   execute_vrp,                          /* execute */
3778   NULL,                                 /* sub */
3779   NULL,                                 /* next */
3780   0,                                    /* static_pass_number */
3781   TV_TREE_VRP,                          /* tv_id */
3782   PROP_ssa | PROP_alias,                /* properties_required */
3783   0,                                    /* properties_provided */
3784   0,                                    /* properties_destroyed */
3785   0,                                    /* todo_flags_start */
3786   TODO_cleanup_cfg
3787     | TODO_ggc_collect
3788     | TODO_verify_ssa
3789     | TODO_dump_func
3790     | TODO_update_ssa,                  /* todo_flags_finish */
3791   0                                     /* letter */
3792 };