OSDN Git Service

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