OSDN Git Service

gcc/
[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 maybe_add_assert_expr.  */
42 static sbitmap found;
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 /* Given a conditional predicate COND that has WHICH as one of its
52    operands, return the other operand.  No error checking is done.
53    This helper assumes that COND is a comparison and WHICH is one of
54    its operands.  */
55
56 static inline tree
57 get_opposite_operand (tree cond, tree which)
58 {
59   if (TREE_OPERAND (cond, 0) == which)
60     return TREE_OPERAND (cond, 1);
61   else
62     return TREE_OPERAND (cond, 0);
63 }
64
65
66 /* Given a comparison code, return its opposite.  Note that this is *not*
67    the same as inverting its truth value (invert_tree_comparison).  Here we
68    just want to literally flip the comparison around.
69    
70    So, '<' gets '>', '<=' gets '>='.  Both '==' and '!=' are returned
71    unchanged.  */
72
73 static enum tree_code
74 opposite_comparison (enum tree_code code)
75 {
76   switch (code)
77     {
78     case EQ_EXPR:
79     case NE_EXPR:
80     case ORDERED_EXPR:
81     case UNORDERED_EXPR:
82     case LTGT_EXPR:
83     case UNEQ_EXPR:
84       return code;
85     case GT_EXPR:
86       return LT_EXPR;
87     case GE_EXPR:
88       return LE_EXPR;
89     case LT_EXPR:
90       return GT_EXPR;
91     case LE_EXPR:
92       return GE_EXPR;
93     case UNGT_EXPR:
94       return UNLT_EXPR;
95     case UNGE_EXPR:
96       return UNLE_EXPR;
97     case UNLT_EXPR:
98       return UNGT_EXPR;
99     case UNLE_EXPR:
100       return UNGE_EXPR;
101     default:
102       gcc_unreachable ();
103     }
104 }
105
106
107 /* Set value range VR to {T, MIN, MAX}.  */
108
109 static inline void
110 set_value_range (value_range *vr, enum value_range_type t, tree min, tree max)
111 {
112 #if defined ENABLE_CHECKING
113   if (t == VR_RANGE || t == VR_ANTI_RANGE)
114     {
115       int cmp;
116
117       gcc_assert (min && max);
118
119       if (INTEGRAL_TYPE_P (TREE_TYPE (min)) && t == VR_ANTI_RANGE)
120         gcc_assert (min != TYPE_MIN_VALUE (TREE_TYPE (min))
121                     || max != TYPE_MAX_VALUE (TREE_TYPE (max)));
122
123       cmp = compare_values (min, max);
124       gcc_assert (cmp == 0 || cmp == -1 || cmp == -2);
125     }
126 #endif
127
128   if (t == VR_RANGE
129       && INTEGRAL_TYPE_P (TREE_TYPE (min))
130       && min == TYPE_MIN_VALUE (TREE_TYPE (min))
131       && max == TYPE_MAX_VALUE (TREE_TYPE (max)))
132     {
133       /* Ranges that cover all the possible values for the type decay
134          to VARYING.  */
135       vr->type = VR_VARYING;
136       vr->min = NULL_TREE;
137       vr->max = NULL_TREE;
138       return;
139     }
140
141   vr->type = t;
142   vr->min = min;
143   vr->max = max;
144 }
145
146
147 /* Similar to set_value_range but return true if any field of VR
148    changed from its previous value.  */
149
150 static inline bool
151 update_value_range (value_range *vr, enum value_range_type t, tree min,
152                     tree max)
153 {
154   bool is_new = vr->type != t || vr->min != min || vr->max != max;
155   if (is_new)
156     set_value_range (vr, t, min, max);
157
158   return is_new;
159 }
160
161
162 /* Return value range information for VAR.  Create an empty range if
163    none existed.  */
164
165 value_range *
166 get_value_range (tree var)
167 {
168   value_range *vr;
169   tree sym;
170
171   vr = SSA_NAME_VALUE_RANGE (var);
172   if (vr)
173     return vr;
174
175   /* Create a default value range.  */
176   vr = ggc_alloc (sizeof (*vr));
177   memset ((void *) vr, 0, sizeof (*vr));
178   SSA_NAME_VALUE_RANGE (var) = vr;
179
180   /* If VAR is a default definition for a PARM_DECL, then we have to
181      assume a VARYING range for it.  */
182   sym = SSA_NAME_VAR (var);
183   if (TREE_CODE (sym) == PARM_DECL && var == var_ann (sym)->default_def)
184     set_value_range (vr, VR_VARYING, NULL_TREE, NULL_TREE);
185
186   return vr;
187 }
188
189
190 /* Return true if value range VR involves at least one symbol.  */
191
192 static inline bool
193 symbolic_range_p (value_range *vr)
194 {
195   return (!is_gimple_min_invariant (vr->min)
196           || !is_gimple_min_invariant (vr->max));
197 }
198
199
200 /* Return true if EXPR computes a non-zero value.  */
201
202 bool
203 expr_computes_nonzero (tree expr)
204 {
205   /* Type casts won't change anything, so just strip it.  */
206   STRIP_NOPS (expr);
207
208   /* Calling alloca, guarantees that the value is non-NULL.  */
209   if (alloca_call_p (expr))
210     return true;
211
212   /* The address of a non-weak symbol is never NULL, unless the user
213      has requested not to remove NULL pointer checks.  */
214   if (flag_delete_null_pointer_checks
215       && TREE_CODE (expr) == ADDR_EXPR
216       && DECL_P (TREE_OPERAND (expr, 0))
217       && !DECL_WEAK (TREE_OPERAND (expr, 0)))
218     return true;
219
220   /* IOR of any value with a nonzero value will result in a nonzero
221      value.  */
222   if (TREE_CODE (expr) == BIT_IOR_EXPR
223       && integer_nonzerop (TREE_OPERAND (expr, 1)))
224     return true;
225
226   return false;
227 }
228
229
230 /* Return true if VR is ~[0, 0].  */
231
232 static inline bool
233 range_is_nonnull (value_range *vr)
234 {
235   return vr->type == VR_ANTI_RANGE
236          && integer_zerop (vr->min)
237          && integer_zerop (vr->max);
238 }
239
240
241 /* Return true if VR is [0, 0].  */
242
243 static inline bool
244 range_is_null (value_range *vr)
245 {
246   return vr->type == VR_RANGE
247          && integer_zerop (vr->min)
248          && integer_zerop (vr->max);
249 }
250
251
252 /* Set value range VR to a non-NULL range of type TYPE.  */
253
254 static void
255 set_value_range_to_nonnull (value_range *vr, tree type)
256 {
257   tree zero = build_int_cst (type, 0);
258   set_value_range (vr, VR_ANTI_RANGE, zero, zero);
259 }
260
261
262 /* Set value range VR to a NULL range of type TYPE.  */
263
264 static void
265 set_value_range_to_null (value_range *vr, tree type)
266 {
267   tree zero = build_int_cst (type, 0);
268   set_value_range (vr, VR_RANGE, zero, zero);
269 }
270
271
272 /* Compare two values VAL1 and VAL2.  Return
273    
274         -2 if VAL1 and VAL2 cannot be compared at compile-time,
275         -1 if VAL1 < VAL2,
276          0 if VAL1 == VAL2,
277         +1 if VAL1 > VAL2, and
278         +2 if VAL1 != VAL2
279
280    This is similar to tree_int_cst_compare but supports pointer values
281    and values that cannot be compared at compile time.  */
282
283 static int
284 compare_values (tree val1, tree val2)
285 {
286   if (val1 == val2)
287     return 0;
288
289   /* Do some limited symbolic comparisons.  */
290   if (!POINTER_TYPE_P (TREE_TYPE (val1)))
291     {
292       /* We can determine some comparisons against +INF and -INF even
293          if the other value is an expression.  */
294       if (val1 == TYPE_MAX_VALUE (TREE_TYPE (val1))
295           && TREE_CODE (val2) == MINUS_EXPR)
296         {
297           /* +INF > NAME - CST.  */
298           return 1;
299         }
300       else if (val1 == TYPE_MIN_VALUE (TREE_TYPE (val1))
301                && TREE_CODE (val2) == PLUS_EXPR)
302         {
303           /* -INF < NAME + CST.  */
304           return -1;
305         }
306       else if (TREE_CODE (val1) == MINUS_EXPR
307                && val2 == TYPE_MAX_VALUE (TREE_TYPE (val2)))
308         {
309           /* NAME - CST < +INF.  */
310           return -1;
311         }
312       else if (TREE_CODE (val1) == PLUS_EXPR
313                && val2 == TYPE_MIN_VALUE (TREE_TYPE (val2)))
314         {
315           /* NAME + CST > -INF.  */
316           return 1;
317         }
318     }
319
320   if ((TREE_CODE (val1) == SSA_NAME
321        || TREE_CODE (val1) == PLUS_EXPR
322        || TREE_CODE (val1) == MINUS_EXPR)
323       && (TREE_CODE (val2) == SSA_NAME
324           || TREE_CODE (val2) == PLUS_EXPR
325           || TREE_CODE (val2) == MINUS_EXPR))
326     {
327       tree n1, c1, n2, c2;
328   
329       /* If VAL1 and VAL2 are of the form 'NAME [+-] CST' or 'NAME',
330          return -1 or +1 accordingly.  If VAL1 and VAL2 don't use the
331          same name, return -2.  */
332       if (TREE_CODE (val1) == SSA_NAME)
333         {
334           n1 = val1;
335           c1 = NULL_TREE;
336         }
337       else
338         {
339           n1 = TREE_OPERAND (val1, 0);
340           c1 = TREE_OPERAND (val1, 1);
341         }
342
343       if (TREE_CODE (val2) == SSA_NAME)
344         {
345           n2 = val2;
346           c2 = NULL_TREE;
347         }
348       else
349         {
350           n2 = TREE_OPERAND (val2, 0);
351           c2 = TREE_OPERAND (val2, 1);
352         }
353
354       /* Both values must use the same name.  */
355       if (n1 != n2)
356         return -2;
357
358       if (TREE_CODE (val1) == SSA_NAME)
359         {
360           if (TREE_CODE (val2) == SSA_NAME)
361             /* NAME == NAME  */
362             return 0;
363           else if (TREE_CODE (val2) == PLUS_EXPR)
364             /* NAME < NAME + CST  */
365             return -1;
366           else if (TREE_CODE (val2) == MINUS_EXPR)
367             /* NAME > NAME - CST  */
368             return 1;
369         }
370       else if (TREE_CODE (val1) == PLUS_EXPR)
371         {
372           if (TREE_CODE (val2) == SSA_NAME)
373             /* NAME + CST > NAME  */
374             return 1;
375           else if (TREE_CODE (val2) == PLUS_EXPR)
376             /* NAME + CST1 > NAME + CST2, if CST1 > CST2  */
377             return compare_values (c1, c2);
378           else if (TREE_CODE (val2) == MINUS_EXPR)
379             /* NAME + CST1 > NAME - CST2  */
380             return 1;
381         }
382       else if (TREE_CODE (val1) == MINUS_EXPR)
383         {
384           if (TREE_CODE (val2) == SSA_NAME)
385             /* NAME - CST < NAME  */
386             return -1;
387           else if (TREE_CODE (val2) == PLUS_EXPR)
388             /* NAME - CST1 < NAME + CST2  */
389             return -1;
390           else if (TREE_CODE (val2) == MINUS_EXPR)
391             /* NAME - CST1 > NAME - CST2, if CST1 < CST2.  Notice that
392                C1 and C2 are swapped in the call to compare_values.  */
393             return compare_values (c2, c1);
394         }
395
396       gcc_unreachable ();
397     }
398
399   /* We cannot compare non-constants.  */
400   if (!is_gimple_min_invariant (val1) || !is_gimple_min_invariant (val2))
401     return -2;
402
403   if (!POINTER_TYPE_P (TREE_TYPE (val1)))
404     return tree_int_cst_compare (val1, val2);
405   else
406     {
407       tree t;
408
409       /* First see if VAL1 and VAL2 are not the same.  */
410       if (val1 == val2 || operand_equal_p (val1, val2, 0))
411         return 0;
412       
413       /* If VAL1 is a lower address than VAL2, return -1.  */
414       t = fold (build2 (LT_EXPR, TREE_TYPE (val1), val1, val2));
415       if (t == boolean_true_node)
416         return -1;
417
418       /* If VAL1 is a higher address than VAL2, return +1.  */
419       t = fold (build2 (GT_EXPR, TREE_TYPE (val1), val1, val2));
420       if (t == boolean_true_node)
421         return 1;
422
423       /* If VAL1 is different than VAL2, return +2.  */
424       t = fold (build2 (NE_EXPR, TREE_TYPE (val1), val1, val2));
425       if (t == boolean_true_node)
426         return 2;
427
428       return -2;
429     }
430 }
431
432
433 /* Return 1 if VAL is inside value range VR (VR->MIN <= VAL <= VR->MAX),
434           0 if VAL is not inside VR,
435          -2 if we cannot tell either way.  */
436
437 static inline int
438 value_inside_range (tree val, value_range *vr)
439 {
440   int cmp1, cmp2;
441
442   cmp1 = compare_values (val, vr->min);
443   if (cmp1 == -2 || cmp1 == 2)
444     return -2;
445
446   cmp2 = compare_values (val, vr->max);
447   if (cmp2 == -2 || cmp2 == 2)
448     return -2;
449
450   return (cmp1 == 0 || cmp1 == 1) && (cmp2 == -1 || cmp2 == 0);
451 }
452
453
454 /* Return true if value ranges VR0 and VR1 have a non-empty
455    intersection.  */
456
457 static inline bool
458 value_ranges_intersect_p (value_range *vr0, value_range *vr1)
459 {
460   return (value_inside_range (vr1->min, vr0) == 1
461           || value_inside_range (vr1->max, vr0) == 1
462           || value_inside_range (vr0->min, vr1) == 1
463           || value_inside_range (vr0->max, vr1) == 1);
464 }
465
466
467 /* Extract value range information from an ASSERT_EXPR EXPR and store
468    it in *VR_P.  */
469
470 static void
471 extract_range_from_assert (value_range *vr_p, tree expr)
472 {
473   tree var, cond, limit, type;
474   value_range *var_vr;
475
476   var = ASSERT_EXPR_VAR (expr);
477   cond = ASSERT_EXPR_COND (expr);
478
479   gcc_assert (TREE_CODE_CLASS (TREE_CODE (cond)) == tcc_comparison);
480
481   /* Find VAR in the ASSERT_EXPR conditional.  */
482   limit = get_opposite_operand (cond, var);
483   type = TREE_TYPE (limit);
484
485   gcc_assert (limit != var);
486
487   /* For pointer arithmetic, we only keep track of anti-ranges
488      (NE_EXPR).  Notice that we don't need to handle EQ_EXPR in these
489      cases because assertions with equalities are never generated.
490      The assert pass generates straight assignments in those cases.  */
491   if (POINTER_TYPE_P (type) && TREE_CODE (cond) != NE_EXPR)
492     {
493       set_value_range (vr_p, VR_VARYING, NULL_TREE, NULL_TREE);
494       return;
495     }
496
497   if (TREE_CODE (cond) == NE_EXPR)
498     set_value_range (vr_p, VR_ANTI_RANGE, limit, limit);
499   else if (TREE_CODE (cond) == LE_EXPR)
500     set_value_range (vr_p, VR_RANGE, TYPE_MIN_VALUE (type), limit);
501   else if (TREE_CODE (cond) == LT_EXPR)
502     {
503       tree one = build_int_cst (type, 1);
504       set_value_range (vr_p, VR_RANGE, TYPE_MIN_VALUE (type),
505                        fold (build (MINUS_EXPR, type, limit, one)));
506     }
507   else if (TREE_CODE (cond) == GE_EXPR)
508     set_value_range (vr_p, VR_RANGE, limit, TYPE_MAX_VALUE (type));
509   else if (TREE_CODE (cond) == GT_EXPR)
510     {
511       tree one = build_int_cst (type, 1);
512       set_value_range (vr_p, VR_RANGE,
513                        fold (build (PLUS_EXPR, type, limit, one)),
514                        TYPE_MAX_VALUE (type));
515     }
516   else
517     gcc_unreachable ();
518
519   /* If VAR already has a known range and the two ranges have a
520      non-empty intersection, we can refine the resulting range.
521      Since the assert expression creates an equivalency and at the
522      same time it asserts a predicate, we can take the intersection of
523      the two ranges to get better precision.  */
524   var_vr = get_value_range (var);
525   if (var_vr->type == VR_RANGE
526       && vr_p->type == VR_RANGE
527       && value_ranges_intersect_p (var_vr, vr_p))
528     {
529       tree min, max;
530
531       /* Use the larger of the two minimums.  */
532       if (compare_values (vr_p->min, var_vr->min) == -1)
533         min = var_vr->min;
534       else
535         min = vr_p->min;
536
537       /* Use the smaller of the two maximums.  */
538       if (compare_values (vr_p->max, var_vr->max) == 1)
539         max = var_vr->max;
540       else
541         max = vr_p->max;
542
543       set_value_range (vr_p, vr_p->type, min, max);
544     }
545 }
546
547
548 /* Extract range information from SSA name VAR and store it in VR.  If
549    VAR has an interesting range, use it.  Otherwise, create the
550    range [VAR, VAR] and return it.  This is useful in situations where
551    we may have conditionals testing values of VARYING names.  For
552    instance,
553
554         x_3 = y_5;
555         if (x_3 > y_5)
556           ...
557
558     Even if y_5 is deemed VARYING, we can determine that x_3 > y_5 is
559     always false.  */
560
561 static void
562 extract_range_from_ssa_name (value_range *vr, tree var)
563 {
564   value_range *var_vr = get_value_range (var);
565
566   if (var_vr->type != VR_UNDEFINED && var_vr->type != VR_VARYING)
567     *vr = *var_vr;
568   else
569     set_value_range (vr, VR_RANGE, var, var);
570 }
571
572
573 /* Extract range information from a binary expression EXPR based on
574    the ranges of each of its operands and the expression code.  */
575
576 static void
577 extract_range_from_binary_expr (value_range *vr, tree expr)
578 {
579   enum tree_code code = TREE_CODE (expr);
580   tree op0, op1, min, max;
581   value_range vr0, vr1;
582   int cmp;
583
584   /* Not all binary expressions can be applied to ranges in a
585      meaningful way.  Handle only arithmetic operations.  */
586   if (code != PLUS_EXPR
587       && code != MINUS_EXPR
588       && code != MULT_EXPR
589       && code != TRUNC_DIV_EXPR
590       && code != FLOOR_DIV_EXPR
591       && code != CEIL_DIV_EXPR
592       && code != EXACT_DIV_EXPR
593       && code != ROUND_DIV_EXPR
594       && code != MIN_EXPR
595       && code != MAX_EXPR)
596     {
597       set_value_range (vr, VR_VARYING, NULL_TREE, NULL_TREE);
598       return;
599     }
600
601   /* Get value ranges for each operand.  For constant operands, create
602      a new value range with the operand to simplify processing.  */
603   op0 = TREE_OPERAND (expr, 0);
604   if (TREE_CODE (op0) == SSA_NAME)
605     vr0 = *(get_value_range (op0));
606   else
607     {
608       if (is_gimple_min_invariant (op0))
609         set_value_range (&vr0, VR_RANGE, op0, op0);
610       else
611         set_value_range (&vr0, VR_VARYING, NULL_TREE, NULL_TREE);
612     }
613
614   op1 = TREE_OPERAND (expr, 1);
615   if (TREE_CODE (op1) == SSA_NAME)
616     vr1 = *(get_value_range (op1));
617   else
618     {
619       if (is_gimple_min_invariant (op1))
620         set_value_range (&vr1, VR_RANGE, op1, op1);
621       else
622         set_value_range (&vr1, VR_VARYING, 0, 0);
623     }
624
625   /* If either range is UNDEFINED, so is the result.  */
626   if (vr0.type == VR_UNDEFINED || vr1.type == VR_UNDEFINED)
627     {
628       set_value_range (vr, VR_UNDEFINED, NULL_TREE, NULL_TREE);
629       return;
630     }
631
632   /* If either range is VARYING, so is the result.  */
633   if (vr0.type == VR_VARYING || vr1.type == VR_VARYING)
634     {
635       set_value_range (vr, VR_VARYING, NULL_TREE, NULL_TREE);
636       return;
637     }
638
639   /* If the ranges are of different types, the result is VARYING.  */
640   if (vr0.type != vr1.type)
641     {
642       set_value_range (vr, VR_VARYING, NULL_TREE, NULL_TREE);
643       return;
644     }
645
646   /* TODO.  Refuse to do any symbolic range operations for now.  */
647   if (symbolic_range_p (&vr0) || symbolic_range_p (&vr1))
648     {
649       set_value_range (vr, VR_VARYING, NULL_TREE, NULL_TREE);
650       return;
651     }
652
653   /* Now evaluate the expression to determine the new range.  */
654   if (POINTER_TYPE_P (TREE_TYPE (expr))
655       || POINTER_TYPE_P (TREE_TYPE (op0))
656       || POINTER_TYPE_P (TREE_TYPE (op1)))
657     {
658       /* For pointer types, we are really only interested in asserting
659          whether the expression evaluates to non-NULL.  FIXME.  We
660          used to gcc_assert (code == PLUS_EXPR || code == MINUS_EXPR),
661          but ivopts is generating expressions with pointer
662          multiplication in them.  */
663       if (code == PLUS_EXPR)
664         {
665           /* Assume that pointers can never wrap around.  FIXME, Is
666              this always safe?  */
667           tree zero = build_int_cst (TREE_TYPE (expr), 0);
668           set_value_range (vr, VR_ANTI_RANGE, zero, zero);
669         }
670       else
671         {
672           /* Subtracting from a pointer, may yield 0, so just drop the
673              resulting range to varying.  */
674           set_value_range (vr, VR_VARYING, NULL_TREE, NULL_TREE);
675         }
676
677       return;
678     }
679
680   /* For integer ranges, apply the operation to each end of the
681      range and see what we end up with.  */
682   if (code == PLUS_EXPR
683       || code == MULT_EXPR
684       || code == MIN_EXPR
685       || code == MAX_EXPR)
686     {
687       /* For operations that make the resulting range directly
688          proportional to the original ranges, apply the operation to
689          the same end of each range.  */
690       min = int_const_binop (code, vr0.min, vr1.min, 0);
691       max = int_const_binop (code, vr0.max, vr1.max, 0);
692     }
693   else
694     {
695       /* For operations that make the resulting range inversely
696          proportional to the original ranges (-, /), apply the
697          operation to the opposite ends of each range.  */
698       min = int_const_binop (code, vr0.min, vr1.max, 0);
699       max = int_const_binop (code, vr0.max, vr1.min, 0);
700     }
701
702   cmp = compare_values (min, max);
703   if (cmp == -2 || cmp == 1)
704     {
705       /* If the new range has its limits swapped around (MIN > MAX),
706          then the operation caused one of them to wrap around, mark
707          the new range VARYING.  */
708       set_value_range (vr, VR_VARYING, NULL_TREE, NULL_TREE);
709     }
710   else
711     set_value_range (vr, vr0.type, min, max);
712 }
713
714
715 /* Extract range information from a unary expression EXPR based on
716    the range of its operand and the expression code.  */
717
718 static void
719 extract_range_from_unary_expr (value_range *vr, tree expr)
720 {
721   enum tree_code code = TREE_CODE (expr);
722   tree min, max, op0;
723   value_range vr0;
724   int cmp;
725
726   /* Get value ranges for the operand.  For constant operands, create
727      a new value range with the operand to simplify processing.  */
728   op0 = TREE_OPERAND (expr, 0);
729   if (TREE_CODE (op0) == SSA_NAME)
730     vr0 = *(get_value_range (op0));
731   else
732     {
733       if (is_gimple_min_invariant (op0))
734         set_value_range (&vr0, VR_RANGE, op0, op0);
735       else
736         set_value_range (&vr0, VR_VARYING, NULL_TREE, NULL_TREE);
737     }
738
739   /* If VR0 is UNDEFINED, so is the result.  */
740   if (vr0.type == VR_UNDEFINED)
741     {
742       set_value_range (vr, VR_UNDEFINED, NULL_TREE, NULL_TREE);
743       return;
744     }
745
746   /* If VR0 is VARYING, so is the result.  */
747   if (vr0.type == VR_VARYING)
748     {
749       set_value_range (vr, VR_VARYING, NULL_TREE, NULL_TREE);
750       return;
751     }
752
753   /* TODO.  Refuse to do any symbolic range operations for now.  */
754   if (symbolic_range_p (&vr0))
755     {
756       set_value_range (vr, VR_VARYING, NULL_TREE, NULL_TREE);
757       return;
758     }
759
760   /* If the operand is neither a pointer nor an integral type, set the
761      range to VARYING.  TODO, we may set the range to non-zero.  */
762   if (!INTEGRAL_TYPE_P (TREE_TYPE (op0))
763       && !POINTER_TYPE_P (TREE_TYPE (op0)))
764     {
765       set_value_range (vr, VR_VARYING, NULL_TREE, NULL_TREE);
766       return;
767     }
768
769   /* If the expression involves pointers, we are only interested in
770      determining if it evaluates to NULL [0, 0] or non-NULL (~[0, 0]).  */
771   if (POINTER_TYPE_P (TREE_TYPE (expr)) || POINTER_TYPE_P (TREE_TYPE (op0)))
772     {
773       if (range_is_nonnull (&vr0) || expr_computes_nonzero (expr))
774         set_value_range_to_nonnull (vr, TREE_TYPE (expr));
775       else if (range_is_null (&vr0))
776         set_value_range_to_null (vr, TREE_TYPE (expr));
777       else
778         set_value_range (vr, VR_VARYING, NULL_TREE, NULL_TREE);
779
780       return;
781     }
782
783   /* Handle unary expressions on integer ranges.  */
784   if ((code == NOP_EXPR || code == CONVERT_EXPR)
785       && (TYPE_SIZE (TREE_TYPE (vr0.min)) != TYPE_SIZE (TREE_TYPE (expr))))
786     {
787       /* When converting types of different sizes, set the result to
788          VARYING.  Things like sign extensions and precision loss may
789          change the range.  For instance, if x_3 is of type 'long long
790          int' and 'y_5 = (unsigned short) x_3', if x_3 is ~[0, 0], it
791          is impossible to know at compile time whether y_5 will be
792          ~[0, 0].  */
793       set_value_range (vr, VR_VARYING, NULL_TREE, NULL_TREE);
794       return;
795     }
796
797   /* Apply the operation to each end of the range and see what we end
798      up with.  */
799   min = fold_unary_to_constant (code, TREE_TYPE (expr), vr0.min);
800   max = fold_unary_to_constant (code, TREE_TYPE (expr), vr0.max);
801
802   cmp = compare_values (min, max);
803   if (cmp == -2 || cmp == 1)
804     {
805       /* If the new range has its limits swapped around (MIN > MAX),
806          then the operation caused one of them to wrap around, mark
807          the new range VARYING.  */
808       set_value_range (vr, VR_VARYING, NULL_TREE, NULL_TREE);
809     }
810   else
811     set_value_range (vr, vr0.type, min, max);
812 }
813
814
815 /* Try to compute a useful range out of expression EXPR and store it
816    in *VR_P.  */
817
818 static void
819 extract_range_from_expr (value_range *vr, tree expr)
820 {
821   enum tree_code code = TREE_CODE (expr);
822
823   if (code == ASSERT_EXPR)
824     extract_range_from_assert (vr, expr);
825   else if (code == SSA_NAME)
826     extract_range_from_ssa_name (vr, expr);
827   else if (TREE_CODE_CLASS (code) == tcc_binary)
828     extract_range_from_binary_expr (vr, expr);
829   else if (TREE_CODE_CLASS (code) == tcc_unary)
830     extract_range_from_unary_expr (vr, expr);
831   else if (expr_computes_nonzero (expr))
832     set_value_range_to_nonnull (vr, TREE_TYPE (expr));
833   else if (TREE_CODE (expr) == INTEGER_CST)
834     set_value_range (vr, VR_RANGE, expr, expr);
835   else
836     set_value_range (vr, VR_VARYING, NULL_TREE, NULL_TREE);
837 }
838
839
840 /* Given a range VR, a loop L and a variable VAR, determine whether it
841    would be profitable to adjust VR using scalar evolution information
842    for VAR.  If so, update VR with the new limits.  */
843
844 static void
845 adjust_range_with_scev (value_range *vr, struct loop *l, tree var)
846 {
847   tree init, step, chrec;
848   bool init_is_max;
849
850   /* TODO.  Don't adjust anti-ranges.  An anti-range may provide
851      better opportunities than a regular range, but I'm not sure.  */
852   if (vr->type == VR_ANTI_RANGE)
853     return;
854
855   chrec = analyze_scalar_evolution (l, var);
856   if (TREE_CODE (chrec) != POLYNOMIAL_CHREC)
857     return;
858
859   init = CHREC_LEFT (chrec);
860   step = CHREC_RIGHT (chrec);
861
862   /* If STEP is symbolic, we can't know whether INIT will be the
863      minimum or maximum value in the range.  */
864   if (!is_gimple_min_invariant (step))
865     return;
866
867   /* FIXME.  When dealing with unsigned types,
868      analyze_scalar_evolution sets STEP to very large unsigned values
869      when the evolution goes backwards.  This confuses this analysis
870      because we think that INIT is the smallest value that the range
871      can take, instead of the largest.  Ignore these chrecs for now.  */
872   if (INTEGRAL_TYPE_P (TREE_TYPE (step)) && TYPE_UNSIGNED (TREE_TYPE (step)))
873     return;
874
875   /* If STEP is negative, then INIT is the maximum value the range
876      will take.  Otherwise, INIT is the minimum value.  */
877   init_is_max = (tree_int_cst_sgn (step) < 0);
878
879   if (!POINTER_TYPE_P (TREE_TYPE (init))
880       && (vr->type == VR_VARYING || vr->type == VR_UNDEFINED))
881     {
882       /* For VARYING or UNDEFINED ranges, just about anything we get
883          from scalar evolutions should be better.  */
884       if (init_is_max)
885         set_value_range (vr, VR_RANGE, TYPE_MIN_VALUE (TREE_TYPE (init)), init);
886       else
887         set_value_range (vr, VR_RANGE, init, TYPE_MAX_VALUE (TREE_TYPE (init)));
888     }
889   else if (vr->type == VR_RANGE)
890     {
891       if (init_is_max)
892         {
893           /* INIT is the maximum value.  If INIT is lower than
894              VR->MAX, set VR->MAX to INIT.  */
895           if (compare_values (init, vr->max) == -1)
896             set_value_range (vr, VR_RANGE, vr->min, init);
897         }
898       else
899         {
900           /* If INIT is bigger than VR->MIN, set VR->MIN to INIT.  */
901           if (compare_values (init, vr->min) == 1)
902             set_value_range (vr, VR_RANGE, init, vr->max);
903         }
904     }
905 }
906
907
908 /* Given two numeric value ranges VR0, VR1 and a comparison code COMP:
909    
910    - Return BOOLEAN_TRUE_NODE if VR0 COMP VR1 always returns true for all the
911      values in the ranges.
912
913    - Return BOOLEAN_FALSE_NODE if the comparison always returns false.
914
915    - Return NULL_TREE if it is not always possible to determine the value of
916      the comparison.  */
917
918 static tree
919 compare_ranges (enum tree_code comp, value_range *vr0, value_range *vr1)
920 {
921   /* VARYING or UNDEFINED ranges cannot be compared.  */
922   if (vr0->type == VR_VARYING
923       || vr0->type == VR_UNDEFINED
924       || vr1->type == VR_VARYING
925       || vr1->type == VR_UNDEFINED)
926     return NULL_TREE;
927
928   /* Anti-ranges need to be handled separately.  */
929   if (vr0->type == VR_ANTI_RANGE || vr1->type == VR_ANTI_RANGE)
930     {
931       /* If both are anti-ranges, then we cannot compute any
932          comparison.  */
933       if (vr0->type == VR_ANTI_RANGE && vr1->type == VR_ANTI_RANGE)
934         return NULL_TREE;
935
936       /* These comparisons are never statically computable.  */
937       if (comp == GT_EXPR
938           || comp == GE_EXPR
939           || comp == LT_EXPR
940           || comp == LE_EXPR)
941         return NULL_TREE;
942
943       /* Equality can be computed only between a range and an
944          anti-range.  ~[VAL1, VAL2] == [VAL1, VAL2] is always false.  */
945       if (vr0->type == VR_RANGE)
946         {
947           /* To simplify processing, make VR0 the anti-range.  */
948           value_range *tmp = vr0;
949           vr0 = vr1;
950           vr1 = tmp;
951         }
952
953       gcc_assert (comp == NE_EXPR || comp == EQ_EXPR);
954
955       if (compare_values (vr0->min, vr1->min) == 0
956           && compare_values (vr0->max, vr1->max) == 0)
957         return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
958
959       return NULL_TREE;
960     }
961
962   /* Simplify processing.  If COMP is GT_EXPR or GE_EXPR, switch the
963      operands around and change the comparison code.  */
964   if (comp == GT_EXPR || comp == GE_EXPR)
965     {
966       value_range *tmp;
967       comp = (comp == GT_EXPR) ? LT_EXPR : LE_EXPR;
968       tmp = vr0;
969       vr0 = vr1;
970       vr1 = tmp;
971     }
972
973   if (comp == EQ_EXPR)
974     {
975       /* Equality may only be computed if both ranges represent
976          exactly one value.  */
977       if (compare_values (vr0->min, vr0->max) == 0
978           && compare_values (vr1->min, vr1->max) == 0)
979         {
980           int cmp_min = compare_values (vr0->min, vr1->min);
981           int cmp_max = compare_values (vr0->max, vr1->max);
982           if (cmp_min == 0 && cmp_max == 0)
983             return boolean_true_node;
984           else if (cmp_min != -2 && cmp_max != -2)
985             return boolean_false_node;
986         }
987
988       return NULL_TREE;
989     }
990   else if (comp == NE_EXPR)
991     {
992       int cmp1, cmp2;
993
994       /* If VR0 is completely to the left or completely to the right
995          of VR1, they are always different.  Notice that we need to
996          make sure that both comparisons yield similar results to
997          avoid comparing values that cannot be compared at
998          compile-time.  */
999       cmp1 = compare_values (vr0->max, vr1->min);
1000       cmp2 = compare_values (vr0->min, vr1->max);
1001       if ((cmp1 == -1 && cmp2 == -1) || (cmp1 == 1 && cmp2 == 1))
1002         return boolean_true_node;
1003
1004       /* If VR0 and VR1 represent a single value and are identical,
1005          return false.  */
1006       else if (compare_values (vr0->min, vr0->max) == 0
1007                && compare_values (vr1->min, vr1->max) == 0
1008                && compare_values (vr0->min, vr1->min) == 0
1009                && compare_values (vr0->max, vr1->max) == 0)
1010         return boolean_false_node;
1011
1012       /* Otherwise, they may or may not be different.  */
1013       else
1014         return NULL_TREE;
1015     }
1016   else if (comp == LT_EXPR || comp == LE_EXPR)
1017     {
1018       int tst;
1019
1020       /* If VR0 is to the left of VR1, return true.  */
1021       tst = compare_values (vr0->max, vr1->min);
1022       if ((comp == LT_EXPR && tst == -1)
1023           || (comp == LE_EXPR && (tst == -1 || tst == 0)))
1024         return boolean_true_node;
1025
1026       /* If VR0 is to the right of VR1, return false.  */
1027       tst = compare_values (vr0->min, vr1->max);
1028       if ((comp == LT_EXPR && (tst == 0 || tst == 1))
1029           || (comp == LE_EXPR && tst == 1))
1030         return boolean_false_node;
1031
1032       /* Otherwise, we don't know.  */
1033       return NULL_TREE;
1034     }
1035     
1036   gcc_unreachable ();
1037 }
1038
1039
1040 /* Given a value range VR, a value VAL and a comparison code COMP, return
1041    BOOLEAN_TRUE_NODE if VR COMP VR1 always returns true for all the
1042    values in VR.  Return BOOLEAN_FALSE_NODE if the comparison
1043    always returns false.  Return NULL_TREE if it is not always
1044    possible to determine the value of the comparison.  */
1045
1046 static tree
1047 compare_range_with_value (enum tree_code comp, value_range *vr, tree val)
1048 {
1049   if (vr->type == VR_VARYING || vr->type == VR_UNDEFINED)
1050     return NULL_TREE;
1051
1052   /* Anti-ranges need to be handled separately.  */
1053   if (vr->type == VR_ANTI_RANGE)
1054     {
1055       /* For anti-ranges, the only predicates that we can compute at
1056          compile time are equality and inequality.  */
1057       if (comp == GT_EXPR
1058           || comp == GE_EXPR
1059           || comp == LT_EXPR
1060           || comp == LE_EXPR)
1061         return NULL_TREE;
1062
1063       /* ~[VAL, VAL] == VAL is always false.  */
1064       if (compare_values (vr->min, val) == 0
1065           && compare_values (vr->max, val) == 0)
1066         return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
1067
1068       return NULL_TREE;
1069     }
1070
1071   if (comp == EQ_EXPR)
1072     {
1073       /* EQ_EXPR may only be computed if VR represents exactly
1074          one value.  */
1075       if (compare_values (vr->min, vr->max) == 0)
1076         {
1077           int cmp = compare_values (vr->min, val);
1078           if (cmp == 0)
1079             return boolean_true_node;
1080           else if (cmp == -1 || cmp == 1 || cmp == 2)
1081             return boolean_false_node;
1082         }
1083
1084       return NULL_TREE;
1085     }
1086   else if (comp == NE_EXPR)
1087     {
1088       /* If VAL is not inside VR, then they are always different.  */
1089       if (compare_values (vr->max, val) == -1
1090           || compare_values (vr->min, val) == 1)
1091         return boolean_true_node;
1092
1093       /* If VR represents exactly one value equal to VAL, then return
1094          false.  */
1095       if (compare_values (vr->min, vr->max) == 0
1096           && compare_values (vr->min, val) == 0)
1097         return boolean_false_node;
1098
1099       /* Otherwise, they may or may not be different.  */
1100       return NULL_TREE;
1101     }
1102   else if (comp == LT_EXPR || comp == LE_EXPR)
1103     {
1104       int tst;
1105
1106       /* If VR is to the left of VAL, return true.  */
1107       tst = compare_values (vr->max, val);
1108       if ((comp == LT_EXPR && tst == -1)
1109           || (comp == LE_EXPR && (tst == -1 || tst == 0)))
1110         return boolean_true_node;
1111
1112       /* If VR is to the right of VAL, return false.  */
1113       tst = compare_values (vr->min, val);
1114       if ((comp == LT_EXPR && (tst == 0 || tst == 1))
1115           || (comp == LE_EXPR && tst == 1))
1116         return boolean_false_node;
1117
1118       /* Otherwise, we don't know.  */
1119       return NULL_TREE;
1120     }
1121   else if (comp == GT_EXPR || comp == GE_EXPR)
1122     {
1123       int tst;
1124
1125       /* If VR is to the right of VAL, return true.  */
1126       tst = compare_values (vr->min, val);
1127       if ((comp == GT_EXPR && tst == 1)
1128           || (comp == GE_EXPR && (tst == 0 || tst == 1)))
1129         return boolean_true_node;
1130
1131       /* If VR is to the left of VAL, return false.  */
1132       tst = compare_values (vr->max, val);
1133       if ((comp == GT_EXPR && (tst == -1 || tst == 0))
1134           || (comp == GE_EXPR && tst == -1))
1135         return boolean_false_node;
1136
1137       /* Otherwise, we don't know.  */
1138       return NULL_TREE;
1139     }
1140
1141   gcc_unreachable ();
1142 }
1143
1144
1145 /* Debugging dumps.  */
1146
1147 void
1148 dump_value_range (FILE *file, value_range *vr)
1149 {
1150   if (vr == NULL)
1151     fprintf (file, "[]");
1152   else if (vr->type == VR_UNDEFINED)
1153     fprintf (file, "UNDEFINED");
1154   else if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
1155     {
1156       fprintf (file, "%s[", (vr->type == VR_ANTI_RANGE) ? "~" : "");
1157       print_generic_expr (file, vr->min, 0);
1158       fprintf (file, ", ");
1159       print_generic_expr (file, vr->max, 0);
1160       fprintf (file, "]");
1161     }
1162   else if (vr->type == VR_VARYING)
1163     fprintf (file, "VARYING");
1164   else
1165     fprintf (file, "INVALID RANGE");
1166 }
1167
1168
1169 /* Dump value range VR to stderr.  */
1170
1171 void
1172 debug_value_range (value_range *vr)
1173 {
1174   dump_value_range (stderr, vr);
1175 }
1176
1177
1178 /* Dump value ranges of all SSA_NAMEs to FILE.  */
1179
1180 void
1181 dump_all_value_ranges (FILE *file)
1182 {
1183   size_t i;
1184
1185   for (i = 0; i < num_ssa_names; i++)
1186     {
1187       tree var = ssa_name (i);
1188       if (var && SSA_NAME_VALUE_RANGE (var))
1189         {
1190           print_generic_expr (file, var, 0);
1191           fprintf (file, ": ");
1192           dump_value_range (file, SSA_NAME_VALUE_RANGE (var));
1193           fprintf (file, "\n");
1194         }
1195     }
1196
1197   fprintf (file, "\n");
1198 }
1199
1200
1201 /* Dump all value ranges to stderr.  */
1202
1203 void
1204 debug_all_value_ranges (void)
1205 {
1206   dump_all_value_ranges (stderr);
1207 }
1208
1209
1210 /*---------------------------------------------------------------------------
1211                             Value Range Propagation
1212 ---------------------------------------------------------------------------*/
1213
1214 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
1215    create a new SSA name N and return the assertion assignment
1216    'V = ASSERT_EXPR <V, V OP W>'.  */
1217
1218 static tree
1219 build_assert_expr_for (tree cond, tree v)
1220 {
1221   tree n, assertion;
1222
1223   gcc_assert (TREE_CODE (v) == SSA_NAME);
1224   n = duplicate_ssa_name (v, NULL_TREE);
1225
1226   if (TREE_CODE_CLASS (TREE_CODE (cond)) == tcc_comparison)
1227     {
1228       /* Build N = ASSERT_EXPR <V, COND>.  As a special case, if the
1229          conditional is an EQ_EXPR (V == Z), just build the assignment
1230          N = Z.  */
1231       if (TREE_CODE (cond) == EQ_EXPR)
1232         {
1233           tree other = get_opposite_operand (cond, v);
1234           assertion = build (MODIFY_EXPR, TREE_TYPE (v), n, other);
1235         }
1236       else
1237         assertion = build (MODIFY_EXPR, TREE_TYPE (v), n,
1238                            build (ASSERT_EXPR, TREE_TYPE (v), v, cond));
1239     }
1240   else if (TREE_CODE (cond) == TRUTH_NOT_EXPR)
1241     {
1242       /* Given !V, build the assignment N = false.  */
1243       tree op0 = TREE_OPERAND (cond, 0);
1244       gcc_assert (op0 == v);
1245       assertion = build (MODIFY_EXPR, TREE_TYPE (v), n, boolean_false_node);
1246     }
1247   else if (TREE_CODE (cond) == SSA_NAME)
1248     {
1249       /* Given V, build the assignment N = true.  */
1250       gcc_assert (v == cond);
1251       assertion = build (MODIFY_EXPR, TREE_TYPE (v), n, boolean_true_node);
1252     }
1253   else
1254     gcc_unreachable ();
1255
1256   SSA_NAME_DEF_STMT (n) = assertion;
1257
1258   /* The new ASSERT_EXPR, creates a new SSA name that replaces the
1259      operand of the ASSERT_EXPR. Register the new name and the old one
1260      in the replacement table so that we can fix the SSA web after
1261      adding all the ASSERT_EXPRs.  */
1262   register_new_name_mapping (n, v);
1263
1264   return assertion;
1265 }
1266
1267
1268 /* Return false if EXPR is a predicate expression involving floating
1269    point values.  */
1270
1271 static inline bool
1272 fp_predicate (tree expr)
1273 {
1274   return TREE_CODE_CLASS (TREE_CODE (expr)) == tcc_comparison
1275          && FLOAT_TYPE_P (TREE_TYPE (TREE_OPERAND (expr, 0)));
1276 }
1277
1278
1279 /* Return an expression predicate that represents the range of values
1280    that can be taken by operand OP after STMT executes.  */
1281
1282 static tree
1283 infer_value_range (tree stmt, tree op)
1284 {
1285   /* Do not attempt to infer anything in names that flow through
1286      abnormal edges.  */
1287   if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
1288     return NULL_TREE;
1289
1290   if (POINTER_TYPE_P (TREE_TYPE (op)))
1291     {
1292       bool is_store;
1293       unsigned num_uses, num_derefs;
1294
1295       count_uses_and_derefs (op, stmt, &num_uses, &num_derefs, &is_store);
1296       if (num_derefs > 0 && flag_delete_null_pointer_checks)
1297         {
1298           /* We can only assume that a pointer dereference will yield
1299              non-NULL if -fdelete-null-pointer-checks is enabled.  */
1300           tree null = build_int_cst (TREE_TYPE (op), 0);
1301           tree t = build (NE_EXPR, boolean_type_node, op, null);
1302           return t;
1303         }
1304     }
1305
1306   return NULL_TREE;
1307 }
1308
1309
1310 /* Return true if OP is the result of an ASSERT_EXPR that tests the
1311    same condition as COND.  */
1312
1313 static bool
1314 has_assert_expr (tree op, tree cond)
1315 {
1316   tree def_stmt = SSA_NAME_DEF_STMT (op);
1317   tree assert_expr, other_cond, other_op;
1318
1319   /* If OP was not generated by an ASSERT_EXPR, return false.  */
1320   if (TREE_CODE (def_stmt) != MODIFY_EXPR
1321       || TREE_CODE (TREE_OPERAND (def_stmt, 1)) != ASSERT_EXPR)
1322     return false;
1323
1324   assert_expr = TREE_OPERAND (def_stmt, 1);
1325   other_cond = ASSERT_EXPR_COND (assert_expr);
1326   other_op = ASSERT_EXPR_VAR (assert_expr);
1327
1328   if (TREE_CODE (cond) == TREE_CODE (other_cond))
1329     {
1330       tree t1, t2;
1331
1332       /* If COND is not a comparison predicate, something is wrong.  */
1333       gcc_assert (TREE_CODE_CLASS (TREE_CODE (cond)) == tcc_comparison);
1334
1335       /* Note that we only need to compare against one of the operands
1336          of OTHER_COND.  
1337          
1338          Suppose that we are about to insert the assertion ASSERT_EXPR
1339          <x_4, x_4 != 0> and the defining statement for x_4 is x_4 =
1340          ASSERT_EXPR <x_3, x_3 != 0>.
1341
1342          In this case, we don't really want to insert a new
1343          ASSERT_EXPR for x_4 because that would be redundant.  We
1344          already know that x_4 is not 0.  So, when comparing the
1345          conditionals 'x_3 != 0' and 'x_4 != 0', we don't want to
1346          compare x_3 and x_4, we just want to compare the predicate's
1347          code (!=) and the other operand (0).  */
1348       if (TREE_OPERAND (cond, 0) == op)
1349         t1 = TREE_OPERAND (cond, 1);
1350       else
1351         t1 = TREE_OPERAND (cond, 0);
1352
1353       if (TREE_OPERAND (other_cond, 0) == other_op)
1354         t2 = TREE_OPERAND (other_cond, 1);
1355       else
1356         t2 = TREE_OPERAND (other_cond, 0);
1357
1358       return (t1 == t2 || operand_equal_p (t1, t2, 0));
1359     }
1360
1361   return false;
1362 }
1363
1364
1365 /* Traverse all the statements in block BB looking for used variables.
1366    Variables used in BB are added to bitmap FOUND.  The algorithm
1367    works in three main parts:
1368
1369    1- For every statement S in BB, all the variables used by S are
1370       added to bitmap FOUND.
1371
1372    2- If statement S uses an operand N in a way that exposes a known
1373       value range for N, then if N was not already generated by an
1374       ASSERT_EXPR, create a new ASSERT_EXPR for N.  For instance, if N
1375       is a pointer and the statement dereferences it, we can assume
1376       that N is not NULL.
1377
1378    3- COND_EXPRs are a special case of #2.  We can derive range
1379       information from the predicate but need to insert different
1380       ASSERT_EXPRs for each of the sub-graphs rooted at the
1381       conditional block.  If the last statement of BB is a conditional
1382       expression of the form 'X op Y', then
1383
1384       a) Remove X and Y from the set FOUND.
1385
1386       b) If the conditional dominates its THEN_CLAUSE sub-graph,
1387          recurse into it.  On return, if X and/or Y are marked in
1388          FOUND, then an ASSERT_EXPR is added for the corresponding
1389          variable.
1390
1391       c) Repeat step (b) on the ELSE_CLAUSE.
1392
1393       d) Mark X and Y in FOUND.
1394
1395    4- If BB does not end in a conditional expression, then we recurse
1396       into BB's dominator children.
1397    
1398    At the end of the recursive traversal, ASSERT_EXPRs will have been
1399    added to the edges of COND_EXPR blocks that have sub-graphs using
1400    one or both predicate operands.  For instance,
1401
1402         if (a == 9)
1403           b = a;
1404         else
1405           b = c + 1;
1406
1407    In this case, an assertion on the THEN clause is useful to
1408    determine that 'a' is always 9 on that edge.  However, an assertion
1409    on the ELSE clause would be unnecessary.
1410
1411    On exit from this function, all the names created by the newly
1412    inserted ASSERT_EXPRs need to be added to the SSA web by rewriting
1413    the SSA names that they replace.
1414    
1415    TODO.  Handle SWITCH_EXPR.  */
1416
1417 static bool
1418 maybe_add_assert_expr (basic_block bb)
1419 {
1420   block_stmt_iterator si;
1421   tree last;
1422   bool added;
1423   use_optype uses;
1424
1425   /* Step 1.  Mark all the SSA names used in BB in bitmap FOUND.  */
1426   added = false;
1427   last = NULL_TREE;
1428   for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
1429     {
1430       tree stmt, op;
1431       ssa_op_iter i;
1432       
1433       stmt = bsi_stmt (si);
1434       get_stmt_operands (stmt);
1435
1436       /* Mark all the SSA names used by STMT in bitmap FOUND.  If STMT
1437          is inside the sub-graph of a conditional block, when we
1438          return from this recursive walk, our parent will use the
1439          FOUND bitset to determine if one of the operands it was
1440          looking for was present in the sub-graph.  */
1441       FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
1442         {
1443           tree cond;
1444
1445           SET_BIT (found, SSA_NAME_VERSION (op));
1446
1447           cond = infer_value_range (stmt, op);
1448           if (!cond)
1449             continue;
1450
1451           /* Step 2.  If OP is used in such a way that we can infer a
1452              value range for it, create a new ASSERT_EXPR for OP
1453              (unless OP already has an ASSERT_EXPR).  */
1454           gcc_assert (!is_ctrl_stmt (stmt));
1455
1456           if (has_assert_expr (op, cond))
1457             continue;
1458
1459           if (!stmt_ends_bb_p (stmt))
1460             {
1461               /* If STMT does not end the block, we can insert the new
1462                  assertion right after it.  */
1463               tree t = build_assert_expr_for (cond, op);
1464               bsi_insert_after (&si, t, BSI_NEW_STMT);
1465               added = true;
1466             }
1467           else
1468             {
1469               /* STMT must be the last statement in BB.  We can only
1470                  insert new assertions on the non-abnormal edge out of
1471                  BB.  Note that since STMT is not control flow, there
1472                  may only be one non-abnormal edge out of BB.  */
1473               edge_iterator ei;
1474               edge e;
1475
1476               FOR_EACH_EDGE (e, ei, bb->succs)
1477                 if (!(e->flags & EDGE_ABNORMAL))
1478                   {
1479                     tree t = build_assert_expr_for (cond, op);
1480                     bsi_insert_on_edge (e, t);
1481                     added = true;
1482                     break;
1483                   }
1484             }
1485         }
1486
1487       /* Remember the last statement of the block.  */
1488       last = stmt;
1489     }
1490
1491   /* Step 3.  If BB's last statement is a conditional expression
1492      involving integer operands, recurse into each of the sub-graphs
1493      rooted at BB to determine if we need to add ASSERT_EXPRs.
1494      Notice that we only care about the first operand of the
1495      conditional.  Adding assertions for both operands may actually 
1496      hinder VRP.  FIXME, add example.  */
1497   if (last
1498       && TREE_CODE (last) == COND_EXPR
1499       && !fp_predicate (COND_EXPR_COND (last))
1500       && NUM_USES (uses = STMT_USE_OPS (last)) > 0)
1501     {
1502       edge e;
1503       edge_iterator ei;
1504       tree op, cond;
1505       basic_block son;
1506       
1507       cond = COND_EXPR_COND (last);
1508
1509       op = USE_OP (uses, 0);
1510
1511       /* Do not attempt to infer anything in names that flow through
1512          abnormal edges.  */
1513       if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
1514         return false;
1515
1516       /* Remove the COND_EXPR operand from the FOUND bitmap.
1517          Otherwise, when we finish traversing each of the sub-graphs,
1518          we won't know whether the variables were found in the
1519          sub-graphs or if they had been found in a block upstream from
1520          BB.  */
1521       RESET_BIT (found, SSA_NAME_VERSION (op));
1522
1523       /* Look for uses of the operands in each of the sub-graphs
1524          rooted at BB.  We need to check each of the outgoing edges
1525          separately, so that we know what kind of ASSERT_EXPR to
1526          insert.  */
1527       FOR_EACH_EDGE (e, ei, bb->succs)
1528         {
1529           /* If BB strictly dominates the sub-graph at E->DEST,
1530              recurse into it.  */
1531           if (e->dest != bb
1532               && dominated_by_p (CDI_DOMINATORS, e->dest, bb))
1533             added |= maybe_add_assert_expr (e->dest);
1534
1535           /* Once we traversed the sub-graph, check if any block inside
1536              used either of the predicate's operands.  If so, add the
1537              appropriate ASSERT_EXPR.  */
1538           if (TEST_BIT (found, SSA_NAME_VERSION (op)))
1539             {
1540               /* We found a use of OP in the sub-graph rooted at
1541                  E->DEST.  Add an ASSERT_EXPR according to whether
1542                  E goes to THEN_CLAUSE or ELSE_CLAUSE.  */
1543               tree c, t;
1544
1545               if (e->flags & EDGE_TRUE_VALUE)
1546                 c = unshare_expr (cond);
1547               else if (e->flags & EDGE_FALSE_VALUE)
1548                 c = invert_truthvalue (cond);
1549               else
1550                 gcc_unreachable ();
1551
1552               t = build_assert_expr_for (c, op);
1553               bsi_insert_on_edge (e, t);
1554               added = true;
1555             }
1556         }
1557
1558       /* Finally, mark all the COND_EXPR operands as found.  */
1559       SET_BIT (found, SSA_NAME_VERSION (op));
1560
1561       /* Recurse into the dominator children of BB that are not BB's
1562          immediate successors.  Note that we have already visited BB's
1563          other dominator children above.  */
1564       for (son = first_dom_son (CDI_DOMINATORS, bb);
1565            son;
1566            son = next_dom_son (CDI_DOMINATORS, son))
1567         {
1568           if (find_edge (bb, son) == NULL)
1569             added |= maybe_add_assert_expr (son);
1570         }
1571     }
1572   else
1573     {
1574       /* Step 4.  Recurse into the dominator children of BB.  */
1575       basic_block son;
1576
1577       for (son = first_dom_son (CDI_DOMINATORS, bb);
1578            son;
1579            son = next_dom_son (CDI_DOMINATORS, son))
1580         added |= maybe_add_assert_expr (son);
1581     }
1582
1583   return added;
1584 }
1585
1586
1587 /* Traverse the flowgraph looking for conditional jumps to insert range
1588    expressions.  These range expressions are meant to provide information
1589    to optimizations that need to reason in terms of value ranges.  They
1590    will not be expanded into RTL.  For instance, given:
1591
1592    x = ...
1593    y = ...
1594    if (x < y)
1595      y = x - 2;
1596    else
1597      x = y + 3;
1598
1599    this pass will transform the code into:
1600
1601    x = ...
1602    y = ...
1603    if (x < y)
1604     {
1605       x = ASSERT_EXPR <x, x < y>
1606       y = x - 2
1607     }
1608    else
1609     {
1610       y = ASSERT_EXPR <y, x <= y>
1611       x = y + 3
1612     }
1613
1614    The idea is that once copy and constant propagation have run, other
1615    optimizations will be able to determine what ranges of values can 'x'
1616    take in different paths of the code, simply by checking the reaching
1617    definition of 'x'.  */
1618
1619 static void
1620 insert_range_assertions (void)
1621 {
1622   edge e;
1623   edge_iterator ei;
1624   bool update_ssa_p;
1625   
1626   found = sbitmap_alloc (num_ssa_names);
1627   sbitmap_zero (found);
1628
1629   calculate_dominance_info (CDI_DOMINATORS);
1630
1631   update_ssa_p = false;
1632   FOR_EACH_EDGE (e, ei, ENTRY_BLOCK_PTR->succs)
1633     if (maybe_add_assert_expr (e->dest))
1634       update_ssa_p = true;
1635
1636   if (update_ssa_p)
1637     {
1638       bsi_commit_edge_inserts ();
1639       update_ssa (TODO_update_ssa_no_phi);
1640     }
1641
1642   if (dump_file && (dump_flags & TDF_DETAILS))
1643     {
1644       fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
1645       dump_function_to_file (current_function_decl, dump_file, dump_flags);
1646     }
1647
1648   sbitmap_free (found);
1649 }
1650
1651
1652 /* Convert range assertion expressions into copies.  FIXME, explain why.  */
1653
1654 static void
1655 remove_range_assertions (void)
1656 {
1657   basic_block bb;
1658   block_stmt_iterator si;
1659
1660   FOR_EACH_BB (bb)
1661     for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
1662       {
1663         tree stmt = bsi_stmt (si);
1664
1665         if (TREE_CODE (stmt) == MODIFY_EXPR
1666             && TREE_CODE (TREE_OPERAND (stmt, 1)) == ASSERT_EXPR)
1667           {
1668             tree rhs = TREE_OPERAND (stmt, 1);
1669             tree cond = fold (ASSERT_EXPR_COND (rhs));
1670             gcc_assert (cond != boolean_false_node);
1671             TREE_OPERAND (stmt, 1) = ASSERT_EXPR_VAR (rhs);
1672             update_stmt (stmt);
1673           }
1674       }
1675 }
1676
1677
1678 /* Return true if STMT is interesting for VRP.  */
1679
1680 static bool
1681 stmt_interesting_for_vrp (tree stmt)
1682 {
1683   if (TREE_CODE (stmt) == PHI_NODE
1684       && is_gimple_reg (PHI_RESULT (stmt))
1685       && (INTEGRAL_TYPE_P (TREE_TYPE (PHI_RESULT (stmt)))
1686           || POINTER_TYPE_P (TREE_TYPE (PHI_RESULT (stmt)))))
1687     return true;
1688   else if (TREE_CODE (stmt) == MODIFY_EXPR)
1689     {
1690       tree lhs = TREE_OPERAND (stmt, 0);
1691       stmt_ann_t ann = stmt_ann (stmt);
1692
1693       if (TREE_CODE (lhs) == SSA_NAME
1694           && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
1695               || POINTER_TYPE_P (TREE_TYPE (lhs)))
1696           && NUM_V_MAY_DEFS (V_MAY_DEF_OPS (ann)) == 0
1697           && NUM_VUSES (VUSE_OPS (ann)) == 0
1698           && NUM_V_MUST_DEFS (V_MUST_DEF_OPS (ann)) == 0)
1699         return true;
1700     }
1701   else if (TREE_CODE (stmt) == COND_EXPR || TREE_CODE (stmt) == SWITCH_EXPR)
1702     return true;
1703
1704   return false;
1705 }
1706
1707
1708 /* Initialize local data structures for VRP.  Return true if VRP
1709    is worth running (i.e. if we found any statements that could
1710    benefit from range information).  */
1711
1712 static bool
1713 vrp_initialize (void)
1714 {
1715   basic_block bb;
1716   bool do_vrp;
1717
1718   /* If we don't find any ASSERT_EXPRs in the code, there's no point
1719      running VRP.  */
1720   do_vrp = false;
1721
1722   FOR_EACH_BB (bb)
1723     {
1724       block_stmt_iterator si;
1725       tree phi;
1726
1727       for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
1728         {
1729           if (!stmt_interesting_for_vrp (phi))
1730             {
1731               tree lhs = PHI_RESULT (phi);
1732               set_value_range (get_value_range (lhs), VR_VARYING, 0, 0);
1733               DONT_SIMULATE_AGAIN (phi) = true;
1734             }
1735           else
1736             DONT_SIMULATE_AGAIN (phi) = false;
1737         }
1738
1739       for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
1740         {
1741           tree stmt = bsi_stmt (si);
1742
1743           if (!stmt_interesting_for_vrp (stmt))
1744             {
1745               ssa_op_iter i;
1746               tree def;
1747               FOR_EACH_SSA_TREE_OPERAND (def, stmt, i, SSA_OP_DEF)
1748                 set_value_range (get_value_range (def), VR_VARYING, 0, 0);
1749               DONT_SIMULATE_AGAIN (stmt) = true;
1750             }
1751           else
1752             {
1753               if (TREE_CODE (stmt) == MODIFY_EXPR
1754                    && TREE_CODE (TREE_OPERAND (stmt, 1)) == ASSERT_EXPR)
1755                 do_vrp = true;
1756
1757               DONT_SIMULATE_AGAIN (stmt) = false;
1758             }
1759         }
1760     }
1761
1762   return do_vrp;
1763 }
1764
1765
1766 /* Visit assignment STMT.  If it produces an interesting range, record
1767    the SSA name in *OUTPUT_P.  */
1768
1769 static enum ssa_prop_result
1770 vrp_visit_assignment (tree stmt, tree *output_p)
1771 {
1772   tree lhs, rhs, def;
1773   ssa_op_iter iter;
1774
1775   lhs = TREE_OPERAND (stmt, 0);
1776   rhs = TREE_OPERAND (stmt, 1);
1777
1778   /* We only keep track of ranges in integral and pointer types.  */
1779   if (TREE_CODE (lhs) == SSA_NAME
1780       && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
1781           || POINTER_TYPE_P (TREE_TYPE (lhs))))
1782     {
1783       value_range *vr, new_vr;
1784       struct loop *l;
1785       
1786       vr = get_value_range (lhs);
1787       extract_range_from_expr (&new_vr, rhs);
1788
1789       /* If STMT is inside a loop, we may be able to know something
1790          else about the range of LHS by examining scalar evolution
1791          information.  */
1792       if (cfg_loops && (l = loop_containing_stmt (stmt)))
1793         adjust_range_with_scev (&new_vr, l, lhs);
1794
1795       if (update_value_range (vr, new_vr.type, new_vr.min, new_vr.max))
1796         {
1797           *output_p = lhs;
1798
1799           if (dump_file && (dump_flags & TDF_DETAILS))
1800             {
1801               fprintf (dump_file, "Found new range ");
1802               dump_value_range (dump_file, &new_vr);
1803               fprintf (dump_file, " for ");
1804               print_generic_expr (dump_file, lhs, 0);
1805               fprintf (dump_file, "\n\n");
1806             }
1807
1808           if (new_vr.type == VR_VARYING)
1809             return SSA_PROP_VARYING;
1810
1811           return SSA_PROP_INTERESTING;
1812         }
1813
1814       return SSA_PROP_NOT_INTERESTING;
1815     }
1816   
1817   /* Every other statements produces no useful ranges.  */
1818   FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF)
1819     set_value_range (get_value_range (def), VR_VARYING, 0, 0);
1820
1821   return SSA_PROP_VARYING;
1822 }
1823
1824
1825 /* Given a conditional predicate COND, try to determine if COND yields
1826    true or false based on the value ranges of its operands.  */
1827
1828 static tree
1829 vrp_evaluate_conditional (tree cond)
1830 {
1831   gcc_assert (TREE_CODE (cond) == SSA_NAME
1832               || TREE_CODE_CLASS (TREE_CODE (cond)) == tcc_comparison);
1833
1834   if (TREE_CODE (cond) == SSA_NAME)
1835     {
1836       /* For SSA names, only return a truth value if the range is
1837          known and contains exactly one value.  */
1838       value_range *vr = SSA_NAME_VALUE_RANGE (cond);
1839       if (vr && vr->type == VR_RANGE && vr->min == vr->max)
1840         return vr->min;
1841     }
1842   else
1843     {
1844       /* For comparisons, evaluate each operand and compare their
1845          ranges.  */
1846       tree op0, op1;
1847       value_range *vr0, *vr1;
1848
1849       op0 = TREE_OPERAND (cond, 0);
1850       vr0 = (TREE_CODE (op0) == SSA_NAME) ? get_value_range (op0) : NULL;
1851
1852       op1 = TREE_OPERAND (cond, 1);
1853       vr1 = (TREE_CODE (op1) == SSA_NAME) ? get_value_range (op1) : NULL;
1854
1855       if (vr0 && vr1)
1856         return compare_ranges (TREE_CODE (cond), vr0, vr1);
1857       else if (vr0 && vr1 == NULL)
1858         return compare_range_with_value (TREE_CODE (cond), vr0, op1);
1859       else if (vr0 == NULL && vr1)
1860         return compare_range_with_value (opposite_comparison (TREE_CODE (cond)),
1861                                          vr1, op0);
1862     }
1863
1864   /* Anything else cannot be computed statically.  */
1865   return NULL_TREE;
1866 }
1867
1868
1869 /* Visit conditional statement STMT.  If we can determine which edge
1870    will be taken out of STMT's basic block, record it in
1871    *TAKEN_EDGE_P and return SSA_PROP_INTERESTING.  Otherwise, return
1872    SSA_PROP_VARYING.  */
1873
1874 static enum ssa_prop_result
1875 vrp_visit_cond_stmt (tree stmt, edge *taken_edge_p)
1876 {
1877   tree cond, val;
1878
1879   *taken_edge_p = NULL;
1880
1881   /* FIXME.  Handle SWITCH_EXPRs.  But first, the assert pass needs to
1882      add ASSERT_EXPRs for them.  */
1883   if (TREE_CODE (stmt) == SWITCH_EXPR)
1884     return SSA_PROP_VARYING;
1885
1886   cond = COND_EXPR_COND (stmt);
1887
1888   if (dump_file && (dump_flags & TDF_DETAILS))
1889     {
1890       tree use;
1891       ssa_op_iter i;
1892
1893       fprintf (dump_file, "\nVisiting conditional with predicate: ");
1894       print_generic_expr (dump_file, cond, 0);
1895       fprintf (dump_file, "\nWith known ranges\n");
1896       
1897       FOR_EACH_SSA_TREE_OPERAND (use, stmt, i, SSA_OP_USE)
1898         {
1899           fprintf (dump_file, "\t");
1900           print_generic_expr (dump_file, use, 0);
1901           fprintf (dump_file, ": ");
1902           dump_value_range (dump_file, SSA_NAME_VALUE_RANGE (use));
1903         }
1904
1905       fprintf (dump_file, "\n");
1906     }
1907
1908   /* Compute the value of the predicate COND by checking the known
1909      ranges of each of its operands.  */
1910   val = vrp_evaluate_conditional (cond);
1911   if (val)
1912     *taken_edge_p = find_taken_edge (bb_for_stmt (stmt), val);
1913
1914   if (dump_file && (dump_flags & TDF_DETAILS))
1915     {
1916       fprintf (dump_file, "\nPredicate evaluates to: ");
1917       if (val == NULL_TREE)
1918         fprintf (dump_file, "DON'T KNOW\n");
1919       else
1920         print_generic_stmt (dump_file, val, 0);
1921     }
1922
1923   return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
1924 }
1925
1926
1927 /* Evaluate statement STMT.  If the statement produces a useful range,
1928    return SSA_PROP_INTERESTING and record the SSA name with the
1929    interesting range into *OUTPUT_P.
1930
1931    If STMT is a conditional branch and we can determine its truth
1932    value, the taken edge is recorded in *TAKEN_EDGE_P.
1933
1934    If STMT produces a varying value, return SSA_PROP_VARYING.  */
1935
1936 static enum ssa_prop_result
1937 vrp_visit_stmt (tree stmt, edge *taken_edge_p, tree *output_p)
1938 {
1939   tree def;
1940   ssa_op_iter iter;
1941   stmt_ann_t ann;
1942
1943   if (dump_file && (dump_flags & TDF_DETAILS))
1944     {
1945       fprintf (dump_file, "\nVisiting statement:\n");
1946       print_generic_stmt (dump_file, stmt, dump_flags);
1947       fprintf (dump_file, "\n");
1948     }
1949
1950   ann = stmt_ann (stmt);
1951   if (TREE_CODE (stmt) == MODIFY_EXPR
1952       && NUM_V_MAY_DEFS (V_MAY_DEF_OPS (ann)) == 0
1953       && NUM_VUSES (VUSE_OPS (ann)) == 0
1954       && NUM_V_MUST_DEFS (V_MUST_DEF_OPS (ann)) == 0)
1955     return vrp_visit_assignment (stmt, output_p);
1956   else if (TREE_CODE (stmt) == COND_EXPR || TREE_CODE (stmt) == SWITCH_EXPR)
1957     return vrp_visit_cond_stmt (stmt, taken_edge_p);
1958
1959   /* All other statements produce nothing of interest for VRP, so mark
1960      their outputs varying and prevent further simulation.  */
1961   FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF)
1962     set_value_range (get_value_range (def), VR_VARYING, 0, 0);
1963
1964   return SSA_PROP_VARYING;
1965 }
1966
1967
1968 /* Meet operation for value ranges.  Given two value ranges VR0 and
1969    VR1, store in VR0 the result of meeting VR0 and VR1.
1970    
1971    The meeting rules are as follows:
1972
1973    1- If VR0 and VR1 have an empty intersection, set VR0 to VR_VARYING.
1974
1975    2- If VR0 and VR1 have a non-empty intersection, set VR0 to the
1976       union of VR0 and VR1.  */
1977
1978 static void
1979 vrp_meet (value_range *vr0, value_range *vr1)
1980 {
1981   if (vr0->type == VR_UNDEFINED)
1982     {
1983       *vr0 = *vr1;
1984       return;
1985     }
1986
1987   if (vr1->type == VR_UNDEFINED)
1988     {
1989       /* Nothing to do.  VR0 already has the resulting range.  */
1990       return;
1991     }
1992
1993   if (vr0->type == VR_VARYING)
1994     {
1995       /* Nothing to do.  VR0 already has the resulting range.  */
1996       return;
1997     }
1998
1999   if (vr1->type == VR_VARYING)
2000     {
2001       *vr0 = *vr1;
2002       return;
2003     }
2004
2005   /* If either is a symbolic range, drop to VARYING.  */
2006   if (symbolic_range_p (vr0) || symbolic_range_p (vr1))
2007     {
2008       set_value_range (vr0, VR_VARYING, NULL_TREE, NULL_TREE);
2009       return;
2010     }
2011
2012   if (vr0->type == VR_RANGE && vr1->type == VR_RANGE)
2013     {
2014       /* If VR0 and VR1 have a non-empty intersection, compute the
2015          union of both ranges.  */
2016       if (value_ranges_intersect_p (vr0, vr1))
2017         {
2018           tree min, max;
2019
2020           min = vr0->min;
2021           max = vr0->max;
2022
2023           /* The lower limit of the new range is the minimum of the
2024              two ranges.  */
2025           if (compare_values (vr0->min, vr1->min) == 1)
2026             min = vr1->min;
2027
2028           /* The upper limit of the new range is the maximum of the
2029              two ranges.  */
2030           if (compare_values (vr0->max, vr1->max) == -1)
2031             max = vr1->max;
2032
2033           set_value_range (vr0, vr0->type, min, max);
2034         }
2035       else
2036         {
2037           /* The two ranges don't intersect, set the result to VR_VARYING.  */
2038           set_value_range (vr0, VR_VARYING, NULL_TREE, NULL_TREE);
2039         }
2040     }
2041   else if (vr0->type == VR_ANTI_RANGE && vr1->type == VR_ANTI_RANGE)
2042     {
2043       /* Two anti-ranges meet only if they are both identical.  */
2044       if (compare_values (vr0->min, vr1->min) == 0
2045           && compare_values (vr0->max, vr1->max) == 0
2046           && compare_values (vr0->min, vr0->max) == 0)
2047         /* Nothing to do.  */ ;
2048       else
2049         set_value_range (vr0, VR_VARYING, NULL_TREE, NULL_TREE);
2050     }
2051   else if (vr0->type == VR_ANTI_RANGE || vr1->type == VR_ANTI_RANGE)
2052     {
2053       /* A range [VAL1, VAL2] and an anti-range ~[VAL3, VAL4] meet
2054          only if the ranges have an empty intersection.  The result of
2055          the meet operation is the anti-range.  */
2056       if (!value_ranges_intersect_p (vr0, vr1))
2057         {
2058           if (vr1->type == VR_ANTI_RANGE)
2059             *vr0 = *vr1;
2060         }
2061       else
2062         set_value_range (vr0, VR_VARYING, NULL_TREE, NULL_TREE);
2063     }
2064   else
2065     gcc_unreachable ();
2066 }
2067
2068       
2069 /* Visit all arguments for PHI node PHI that flow through executable
2070    edges.  If a valid value range can be derived from all the incoming
2071    value ranges, set a new range for the LHS of PHI.  */
2072
2073 static enum ssa_prop_result
2074 vrp_visit_phi_node (tree phi)
2075 {
2076   int i;
2077   tree lhs = PHI_RESULT (phi);
2078   value_range *lhs_vr = get_value_range (lhs);
2079   value_range vr_result = *lhs_vr;
2080
2081   if (dump_file && (dump_flags & TDF_DETAILS))
2082     {
2083       fprintf (dump_file, "\nVisiting PHI node: ");
2084       print_generic_expr (dump_file, phi, dump_flags);
2085     }
2086
2087   for (i = 0; i < PHI_NUM_ARGS (phi); i++)
2088     {
2089       edge e = PHI_ARG_EDGE (phi, i);
2090
2091       if (dump_file && (dump_flags & TDF_DETAILS))
2092         {
2093           fprintf (dump_file,
2094               "\n    Argument #%d (%d -> %d %sexecutable)\n",
2095               i, e->src->index, e->dest->index,
2096               (e->flags & EDGE_EXECUTABLE) ? "" : "not ");
2097         }
2098
2099       if (e->flags & EDGE_EXECUTABLE)
2100         {
2101           tree arg = PHI_ARG_DEF (phi, i);
2102           value_range vr_arg;
2103
2104           if (TREE_CODE (arg) == SSA_NAME)
2105             vr_arg = *(get_value_range (arg));
2106           else
2107             {
2108               vr_arg.type = VR_RANGE;
2109               vr_arg.min = arg;
2110               vr_arg.max = arg;
2111             }
2112
2113           if (dump_file && (dump_flags & TDF_DETAILS))
2114             {
2115               fprintf (dump_file, "\t");
2116               print_generic_expr (dump_file, arg, dump_flags);
2117               fprintf (dump_file, "\n\tValue: ");
2118               dump_value_range (dump_file, &vr_arg);
2119               fprintf (dump_file, "\n");
2120             }
2121
2122           vrp_meet (&vr_result, &vr_arg);
2123
2124           if (vr_result.type == VR_VARYING)
2125             break;
2126         }
2127     }
2128
2129   if (vr_result.type == VR_VARYING)
2130     {
2131       set_value_range (lhs_vr, VR_VARYING, 0, 0);
2132       return SSA_PROP_VARYING;
2133     }
2134
2135   /* To prevent infinite iterations in the algorithm, derive ranges
2136      when the new value is slightly bigger or smaller than the
2137      previous one.  */
2138   if (lhs_vr->type == VR_RANGE)
2139     {
2140       if (!POINTER_TYPE_P (TREE_TYPE (lhs)))
2141         {
2142           int cmp_min = compare_values (lhs_vr->min, vr_result.min);
2143           int cmp_max = compare_values (lhs_vr->max, vr_result.max);
2144
2145           /* If the new minimum is smaller or larger than the previous
2146              one, go all the way to -INF.  In the first case, to avoid
2147              iterating millions of times to reach -INF, and in the
2148              other case to avoid infinite bouncing between different
2149              minimums.  */
2150           if (cmp_min > 0 || cmp_min < 0)
2151             vr_result.min = TYPE_MIN_VALUE (TREE_TYPE (vr_result.min));
2152
2153           /* Similarly, if the new maximum is smaller or larger than
2154              the previous one, go all the way to +INF.  */
2155           if (cmp_max < 0 || cmp_max > 0)
2156             vr_result.max = TYPE_MAX_VALUE (TREE_TYPE (vr_result.max));
2157
2158           /* If we ended up with a (-INF, +INF) range, set it to
2159              VARYING.  */
2160           if (vr_result.min == TYPE_MIN_VALUE (TREE_TYPE (vr_result.min))
2161               && vr_result.max == TYPE_MAX_VALUE (TREE_TYPE (vr_result.max)))
2162             {
2163               set_value_range (lhs_vr, VR_VARYING, 0, 0);
2164               return SSA_PROP_VARYING;
2165             }
2166         }
2167     }
2168
2169   /* If the new range is different than the previous value, keep
2170      iterating.  */
2171   if (update_value_range (lhs_vr, vr_result.type, vr_result.min, vr_result.max))
2172     return SSA_PROP_INTERESTING;
2173
2174   /* Nothing changed, don't add outgoing edges.  */
2175   return SSA_PROP_NOT_INTERESTING;
2176 }
2177
2178
2179 /* Traverse all the blocks folding conditionals with known ranges.  */
2180
2181 static void
2182 vrp_finalize (void)
2183 {
2184   basic_block bb;
2185   int num_pred_folded = 0;
2186
2187   if (dump_file)
2188     {
2189       fprintf (dump_file, "\nValue ranges after VRP:\n\n");
2190       dump_all_value_ranges (dump_file);
2191       fprintf (dump_file, "\n");
2192     }
2193
2194   FOR_EACH_BB (bb)
2195     {
2196       tree last = last_stmt (bb);
2197       if (last && TREE_CODE (last) == COND_EXPR)
2198         {
2199           tree val = vrp_evaluate_conditional (COND_EXPR_COND (last));
2200           if (val)
2201             {
2202               if (dump_file)
2203                 {
2204                   fprintf (dump_file, "Folding predicate ");
2205                   print_generic_expr (dump_file, COND_EXPR_COND (last), 0);
2206                   fprintf (dump_file, " to ");
2207                   print_generic_expr (dump_file, val, 0);
2208                   fprintf (dump_file, "\n");
2209                 }
2210
2211               num_pred_folded++;
2212               COND_EXPR_COND (last) = val;
2213               update_stmt (last);
2214             }
2215         }
2216     }
2217
2218   if (dump_file && (dump_flags & TDF_STATS))
2219     fprintf (dump_file, "\nNumber of predicates folded: %d\n\n",
2220              num_pred_folded);
2221 }
2222
2223
2224 /* Main entry point to VRP (Value Range Propagation).  This pass is
2225    loosely based on J. R. C. Patterson, ``Accurate Static Branch
2226    Prediction by Value Range Propagation,'' in SIGPLAN Conference on
2227    Programming Language Design and Implementation, pp. 67-78, 1995.
2228    Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
2229
2230    This is essentially an SSA-CCP pass modified to deal with ranges
2231    instead of constants.
2232
2233    TODO, the main difference between this pass and Patterson's is that
2234    we do not propagate edge probabilities.  We only compute whether
2235    edges can be taken or not.  That is, instead of having a spectrum
2236    of jump probabilities between 0 and 1, we only deal with 0, 1 and
2237    DON'T KNOW.  In the future, it may be worthwhile to propagate
2238    probabilities to aid branch prediction.  */
2239
2240 static void
2241 execute_vrp (void)
2242 {
2243   insert_range_assertions ();
2244
2245   cfg_loops = loop_optimizer_init (NULL);
2246   if (cfg_loops)
2247     scev_initialize (cfg_loops);
2248
2249   if (vrp_initialize ())
2250     {
2251       ssa_propagate (vrp_visit_stmt, vrp_visit_phi_node);
2252       vrp_finalize ();
2253     }
2254
2255   if (cfg_loops)
2256     {
2257       scev_finalize ();
2258       loop_optimizer_finalize (cfg_loops, NULL);
2259       current_loops = NULL;
2260     }
2261
2262   remove_range_assertions ();
2263 }
2264
2265 static bool
2266 gate_vrp (void)
2267 {
2268   return flag_tree_vrp != 0;
2269 }
2270
2271 struct tree_opt_pass pass_vrp =
2272 {
2273   "vrp",                                /* name */
2274   gate_vrp,                             /* gate */
2275   execute_vrp,                          /* execute */
2276   NULL,                                 /* sub */
2277   NULL,                                 /* next */
2278   0,                                    /* static_pass_number */
2279   TV_TREE_VRP,                          /* tv_id */
2280   PROP_ssa | PROP_alias,                /* properties_required */
2281   0,                                    /* properties_provided */
2282   0,                                    /* properties_destroyed */
2283   0,                                    /* todo_flags_start */
2284   TODO_cleanup_cfg
2285     | TODO_ggc_collect
2286     | TODO_verify_ssa
2287     | TODO_dump_func
2288     | TODO_update_ssa,                  /* todo_flags_finish */
2289   0                                     /* letter */
2290 };