Import pre-release gcc-5.0 to new vendor branch
[dragonfly.git] / contrib / gcc-5.0 / gcc / tree-vrp.c
1 /* Support routines for Value Range Propagation (VRP).
2    Copyright (C) 2005-2015 Free Software Foundation, Inc.
3    Contributed by Diego Novillo <dnovillo@redhat.com>.
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
11
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "flags.h"
26 #include "hash-set.h"
27 #include "machmode.h"
28 #include "vec.h"
29 #include "double-int.h"
30 #include "input.h"
31 #include "alias.h"
32 #include "symtab.h"
33 #include "wide-int.h"
34 #include "inchash.h"
35 #include "tree.h"
36 #include "fold-const.h"
37 #include "stor-layout.h"
38 #include "calls.h"
39 #include "predict.h"
40 #include "hard-reg-set.h"
41 #include "function.h"
42 #include "dominance.h"
43 #include "cfg.h"
44 #include "cfganal.h"
45 #include "basic-block.h"
46 #include "tree-ssa-alias.h"
47 #include "internal-fn.h"
48 #include "gimple-fold.h"
49 #include "tree-eh.h"
50 #include "gimple-expr.h"
51 #include "is-a.h"
52 #include "gimple.h"
53 #include "gimple-iterator.h"
54 #include "gimple-walk.h"
55 #include "gimple-ssa.h"
56 #include "tree-cfg.h"
57 #include "tree-phinodes.h"
58 #include "ssa-iterators.h"
59 #include "stringpool.h"
60 #include "tree-ssanames.h"
61 #include "tree-ssa-loop-manip.h"
62 #include "tree-ssa-loop-niter.h"
63 #include "tree-ssa-loop.h"
64 #include "tree-into-ssa.h"
65 #include "tree-ssa.h"
66 #include "tree-pass.h"
67 #include "tree-dump.h"
68 #include "gimple-pretty-print.h"
69 #include "diagnostic-core.h"
70 #include "intl.h"
71 #include "cfgloop.h"
72 #include "tree-scalar-evolution.h"
73 #include "tree-ssa-propagate.h"
74 #include "tree-chrec.h"
75 #include "tree-ssa-threadupdate.h"
76 #include "hashtab.h"
77 #include "rtl.h"
78 #include "statistics.h"
79 #include "real.h"
80 #include "fixed-value.h"
81 #include "insn-config.h"
82 #include "expmed.h"
83 #include "dojump.h"
84 #include "explow.h"
85 #include "emit-rtl.h"
86 #include "varasm.h"
87 #include "stmt.h"
88 #include "expr.h"
89 #include "insn-codes.h"
90 #include "optabs.h"
91 #include "tree-ssa-threadedge.h"
92
93
94
95 /* Range of values that can be associated with an SSA_NAME after VRP
96    has executed.  */
97 struct value_range_d
98 {
99   /* Lattice value represented by this range.  */
100   enum value_range_type type;
101
102   /* Minimum and maximum values represented by this range.  These
103      values should be interpreted as follows:
104
105         - If TYPE is VR_UNDEFINED or VR_VARYING then MIN and MAX must
106           be NULL.
107
108         - If TYPE == VR_RANGE then MIN holds the minimum value and
109           MAX holds the maximum value of the range [MIN, MAX].
110
111         - If TYPE == ANTI_RANGE the variable is known to NOT
112           take any values in the range [MIN, MAX].  */
113   tree min;
114   tree max;
115
116   /* Set of SSA names whose value ranges are equivalent to this one.
117      This set is only valid when TYPE is VR_RANGE or VR_ANTI_RANGE.  */
118   bitmap equiv;
119 };
120
121 typedef struct value_range_d value_range_t;
122
123 #define VR_INITIALIZER { VR_UNDEFINED, NULL_TREE, NULL_TREE, NULL }
124
125 /* Set of SSA names found live during the RPO traversal of the function
126    for still active basic-blocks.  */
127 static sbitmap *live;
128
129 /* Return true if the SSA name NAME is live on the edge E.  */
130
131 static bool
132 live_on_edge (edge e, tree name)
133 {
134   return (live[e->dest->index]
135           && bitmap_bit_p (live[e->dest->index], SSA_NAME_VERSION (name)));
136 }
137
138 /* Local functions.  */
139 static int compare_values (tree val1, tree val2);
140 static int compare_values_warnv (tree val1, tree val2, bool *);
141 static void vrp_meet (value_range_t *, value_range_t *);
142 static void vrp_intersect_ranges (value_range_t *, value_range_t *);
143 static tree vrp_evaluate_conditional_warnv_with_ops (enum tree_code,
144                                                      tree, tree, bool, bool *,
145                                                      bool *);
146
147 /* Location information for ASSERT_EXPRs.  Each instance of this
148    structure describes an ASSERT_EXPR for an SSA name.  Since a single
149    SSA name may have more than one assertion associated with it, these
150    locations are kept in a linked list attached to the corresponding
151    SSA name.  */
152 struct assert_locus_d
153 {
154   /* Basic block where the assertion would be inserted.  */
155   basic_block bb;
156
157   /* Some assertions need to be inserted on an edge (e.g., assertions
158      generated by COND_EXPRs).  In those cases, BB will be NULL.  */
159   edge e;
160
161   /* Pointer to the statement that generated this assertion.  */
162   gimple_stmt_iterator si;
163
164   /* Predicate code for the ASSERT_EXPR.  Must be COMPARISON_CLASS_P.  */
165   enum tree_code comp_code;
166
167   /* Value being compared against.  */
168   tree val;
169
170   /* Expression to compare.  */
171   tree expr;
172
173   /* Next node in the linked list.  */
174   struct assert_locus_d *next;
175 };
176
177 typedef struct assert_locus_d *assert_locus_t;
178
179 /* If bit I is present, it means that SSA name N_i has a list of
180    assertions that should be inserted in the IL.  */
181 static bitmap need_assert_for;
182
183 /* Array of locations lists where to insert assertions.  ASSERTS_FOR[I]
184    holds a list of ASSERT_LOCUS_T nodes that describe where
185    ASSERT_EXPRs for SSA name N_I should be inserted.  */
186 static assert_locus_t *asserts_for;
187
188 /* Value range array.  After propagation, VR_VALUE[I] holds the range
189    of values that SSA name N_I may take.  */
190 static unsigned num_vr_values;
191 static value_range_t **vr_value;
192 static bool values_propagated;
193
194 /* For a PHI node which sets SSA name N_I, VR_COUNTS[I] holds the
195    number of executable edges we saw the last time we visited the
196    node.  */
197 static int *vr_phi_edge_counts;
198
199 typedef struct {
200   gswitch *stmt;
201   tree vec;
202 } switch_update;
203
204 static vec<edge> to_remove_edges;
205 static vec<switch_update> to_update_switch_stmts;
206
207
208 /* Return the maximum value for TYPE.  */
209
210 static inline tree
211 vrp_val_max (const_tree type)
212 {
213   if (!INTEGRAL_TYPE_P (type))
214     return NULL_TREE;
215
216   return TYPE_MAX_VALUE (type);
217 }
218
219 /* Return the minimum value for TYPE.  */
220
221 static inline tree
222 vrp_val_min (const_tree type)
223 {
224   if (!INTEGRAL_TYPE_P (type))
225     return NULL_TREE;
226
227   return TYPE_MIN_VALUE (type);
228 }
229
230 /* Return whether VAL is equal to the maximum value of its type.  This
231    will be true for a positive overflow infinity.  We can't do a
232    simple equality comparison with TYPE_MAX_VALUE because C typedefs
233    and Ada subtypes can produce types whose TYPE_MAX_VALUE is not ==
234    to the integer constant with the same value in the type.  */
235
236 static inline bool
237 vrp_val_is_max (const_tree val)
238 {
239   tree type_max = vrp_val_max (TREE_TYPE (val));
240   return (val == type_max
241           || (type_max != NULL_TREE
242               && operand_equal_p (val, type_max, 0)));
243 }
244
245 /* Return whether VAL is equal to the minimum value of its type.  This
246    will be true for a negative overflow infinity.  */
247
248 static inline bool
249 vrp_val_is_min (const_tree val)
250 {
251   tree type_min = vrp_val_min (TREE_TYPE (val));
252   return (val == type_min
253           || (type_min != NULL_TREE
254               && operand_equal_p (val, type_min, 0)));
255 }
256
257
258 /* Return whether TYPE should use an overflow infinity distinct from
259    TYPE_{MIN,MAX}_VALUE.  We use an overflow infinity value to
260    represent a signed overflow during VRP computations.  An infinity
261    is distinct from a half-range, which will go from some number to
262    TYPE_{MIN,MAX}_VALUE.  */
263
264 static inline bool
265 needs_overflow_infinity (const_tree type)
266 {
267   return INTEGRAL_TYPE_P (type) && !TYPE_OVERFLOW_WRAPS (type);
268 }
269
270 /* Return whether TYPE can support our overflow infinity
271    representation: we use the TREE_OVERFLOW flag, which only exists
272    for constants.  If TYPE doesn't support this, we don't optimize
273    cases which would require signed overflow--we drop them to
274    VARYING.  */
275
276 static inline bool
277 supports_overflow_infinity (const_tree type)
278 {
279   tree min = vrp_val_min (type), max = vrp_val_max (type);
280 #ifdef ENABLE_CHECKING
281   gcc_assert (needs_overflow_infinity (type));
282 #endif
283   return (min != NULL_TREE
284           && CONSTANT_CLASS_P (min)
285           && max != NULL_TREE
286           && CONSTANT_CLASS_P (max));
287 }
288
289 /* VAL is the maximum or minimum value of a type.  Return a
290    corresponding overflow infinity.  */
291
292 static inline tree
293 make_overflow_infinity (tree val)
294 {
295   gcc_checking_assert (val != NULL_TREE && CONSTANT_CLASS_P (val));
296   val = copy_node (val);
297   TREE_OVERFLOW (val) = 1;
298   return val;
299 }
300
301 /* Return a negative overflow infinity for TYPE.  */
302
303 static inline tree
304 negative_overflow_infinity (tree type)
305 {
306   gcc_checking_assert (supports_overflow_infinity (type));
307   return make_overflow_infinity (vrp_val_min (type));
308 }
309
310 /* Return a positive overflow infinity for TYPE.  */
311
312 static inline tree
313 positive_overflow_infinity (tree type)
314 {
315   gcc_checking_assert (supports_overflow_infinity (type));
316   return make_overflow_infinity (vrp_val_max (type));
317 }
318
319 /* Return whether VAL is a negative overflow infinity.  */
320
321 static inline bool
322 is_negative_overflow_infinity (const_tree val)
323 {
324   return (TREE_OVERFLOW_P (val)
325           && needs_overflow_infinity (TREE_TYPE (val))
326           && vrp_val_is_min (val));
327 }
328
329 /* Return whether VAL is a positive overflow infinity.  */
330
331 static inline bool
332 is_positive_overflow_infinity (const_tree val)
333 {
334   return (TREE_OVERFLOW_P (val)
335           && needs_overflow_infinity (TREE_TYPE (val))
336           && vrp_val_is_max (val));
337 }
338
339 /* Return whether VAL is a positive or negative overflow infinity.  */
340
341 static inline bool
342 is_overflow_infinity (const_tree val)
343 {
344   return (TREE_OVERFLOW_P (val)
345           && needs_overflow_infinity (TREE_TYPE (val))
346           && (vrp_val_is_min (val) || vrp_val_is_max (val)));
347 }
348
349 /* Return whether STMT has a constant rhs that is_overflow_infinity. */
350
351 static inline bool
352 stmt_overflow_infinity (gimple stmt)
353 {
354   if (is_gimple_assign (stmt)
355       && get_gimple_rhs_class (gimple_assign_rhs_code (stmt)) ==
356       GIMPLE_SINGLE_RHS)
357     return is_overflow_infinity (gimple_assign_rhs1 (stmt));
358   return false;
359 }
360
361 /* If VAL is now an overflow infinity, return VAL.  Otherwise, return
362    the same value with TREE_OVERFLOW clear.  This can be used to avoid
363    confusing a regular value with an overflow value.  */
364
365 static inline tree
366 avoid_overflow_infinity (tree val)
367 {
368   if (!is_overflow_infinity (val))
369     return val;
370
371   if (vrp_val_is_max (val))
372     return vrp_val_max (TREE_TYPE (val));
373   else
374     {
375       gcc_checking_assert (vrp_val_is_min (val));
376       return vrp_val_min (TREE_TYPE (val));
377     }
378 }
379
380
381 /* Return true if ARG is marked with the nonnull attribute in the
382    current function signature.  */
383
384 static bool
385 nonnull_arg_p (const_tree arg)
386 {
387   tree t, attrs, fntype;
388   unsigned HOST_WIDE_INT arg_num;
389
390   gcc_assert (TREE_CODE (arg) == PARM_DECL && POINTER_TYPE_P (TREE_TYPE (arg)));
391
392   /* The static chain decl is always non null.  */
393   if (arg == cfun->static_chain_decl)
394     return true;
395
396   fntype = TREE_TYPE (current_function_decl);
397   for (attrs = TYPE_ATTRIBUTES (fntype); attrs; attrs = TREE_CHAIN (attrs))
398     {
399       attrs = lookup_attribute ("nonnull", attrs);
400
401       /* If "nonnull" wasn't specified, we know nothing about the argument.  */
402       if (attrs == NULL_TREE)
403         return false;
404
405       /* If "nonnull" applies to all the arguments, then ARG is non-null.  */
406       if (TREE_VALUE (attrs) == NULL_TREE)
407         return true;
408
409       /* Get the position number for ARG in the function signature.  */
410       for (arg_num = 1, t = DECL_ARGUMENTS (current_function_decl);
411            t;
412            t = DECL_CHAIN (t), arg_num++)
413         {
414           if (t == arg)
415             break;
416         }
417
418       gcc_assert (t == arg);
419
420       /* Now see if ARG_NUM is mentioned in the nonnull list.  */
421       for (t = TREE_VALUE (attrs); t; t = TREE_CHAIN (t))
422         {
423           if (compare_tree_int (TREE_VALUE (t), arg_num) == 0)
424             return true;
425         }
426     }
427
428   return false;
429 }
430
431
432 /* Set value range VR to VR_UNDEFINED.  */
433
434 static inline void
435 set_value_range_to_undefined (value_range_t *vr)
436 {
437   vr->type = VR_UNDEFINED;
438   vr->min = vr->max = NULL_TREE;
439   if (vr->equiv)
440     bitmap_clear (vr->equiv);
441 }
442
443
444 /* Set value range VR to VR_VARYING.  */
445
446 static inline void
447 set_value_range_to_varying (value_range_t *vr)
448 {
449   vr->type = VR_VARYING;
450   vr->min = vr->max = NULL_TREE;
451   if (vr->equiv)
452     bitmap_clear (vr->equiv);
453 }
454
455
456 /* Set value range VR to {T, MIN, MAX, EQUIV}.  */
457
458 static void
459 set_value_range (value_range_t *vr, enum value_range_type t, tree min,
460                  tree max, bitmap equiv)
461 {
462 #if defined ENABLE_CHECKING
463   /* Check the validity of the range.  */
464   if (t == VR_RANGE || t == VR_ANTI_RANGE)
465     {
466       int cmp;
467
468       gcc_assert (min && max);
469
470       gcc_assert ((!TREE_OVERFLOW_P (min) || is_overflow_infinity (min))
471                   && (!TREE_OVERFLOW_P (max) || is_overflow_infinity (max)));
472
473       if (INTEGRAL_TYPE_P (TREE_TYPE (min)) && t == VR_ANTI_RANGE)
474         gcc_assert (!vrp_val_is_min (min) || !vrp_val_is_max (max));
475
476       cmp = compare_values (min, max);
477       gcc_assert (cmp == 0 || cmp == -1 || cmp == -2);
478
479       if (needs_overflow_infinity (TREE_TYPE (min)))
480         gcc_assert (!is_overflow_infinity (min)
481                     || !is_overflow_infinity (max));
482     }
483
484   if (t == VR_UNDEFINED || t == VR_VARYING)
485     gcc_assert (min == NULL_TREE && max == NULL_TREE);
486
487   if (t == VR_UNDEFINED || t == VR_VARYING)
488     gcc_assert (equiv == NULL || bitmap_empty_p (equiv));
489 #endif
490
491   vr->type = t;
492   vr->min = min;
493   vr->max = max;
494
495   /* Since updating the equivalence set involves deep copying the
496      bitmaps, only do it if absolutely necessary.  */
497   if (vr->equiv == NULL
498       && equiv != NULL)
499     vr->equiv = BITMAP_ALLOC (NULL);
500
501   if (equiv != vr->equiv)
502     {
503       if (equiv && !bitmap_empty_p (equiv))
504         bitmap_copy (vr->equiv, equiv);
505       else
506         bitmap_clear (vr->equiv);
507     }
508 }
509
510
511 /* Set value range VR to the canonical form of {T, MIN, MAX, EQUIV}.
512    This means adjusting T, MIN and MAX representing the case of a
513    wrapping range with MAX < MIN covering [MIN, type_max] U [type_min, MAX]
514    as anti-rage ~[MAX+1, MIN-1].  Likewise for wrapping anti-ranges.
515    In corner cases where MAX+1 or MIN-1 wraps this will fall back
516    to varying.
517    This routine exists to ease canonicalization in the case where we
518    extract ranges from var + CST op limit.  */
519
520 static void
521 set_and_canonicalize_value_range (value_range_t *vr, enum value_range_type t,
522                                   tree min, tree max, bitmap equiv)
523 {
524   /* Use the canonical setters for VR_UNDEFINED and VR_VARYING.  */
525   if (t == VR_UNDEFINED)
526     {
527       set_value_range_to_undefined (vr);
528       return;
529     }
530   else if (t == VR_VARYING)
531     {
532       set_value_range_to_varying (vr);
533       return;
534     }
535
536   /* Nothing to canonicalize for symbolic ranges.  */
537   if (TREE_CODE (min) != INTEGER_CST
538       || TREE_CODE (max) != INTEGER_CST)
539     {
540       set_value_range (vr, t, min, max, equiv);
541       return;
542     }
543
544   /* Wrong order for min and max, to swap them and the VR type we need
545      to adjust them.  */
546   if (tree_int_cst_lt (max, min))
547     {
548       tree one, tmp;
549
550       /* For one bit precision if max < min, then the swapped
551          range covers all values, so for VR_RANGE it is varying and
552          for VR_ANTI_RANGE empty range, so drop to varying as well.  */
553       if (TYPE_PRECISION (TREE_TYPE (min)) == 1)
554         {
555           set_value_range_to_varying (vr);
556           return;
557         }
558
559       one = build_int_cst (TREE_TYPE (min), 1);
560       tmp = int_const_binop (PLUS_EXPR, max, one);
561       max = int_const_binop (MINUS_EXPR, min, one);
562       min = tmp;
563
564       /* There's one corner case, if we had [C+1, C] before we now have
565          that again.  But this represents an empty value range, so drop
566          to varying in this case.  */
567       if (tree_int_cst_lt (max, min))
568         {
569           set_value_range_to_varying (vr);
570           return;
571         }
572
573       t = t == VR_RANGE ? VR_ANTI_RANGE : VR_RANGE;
574     }
575
576   /* Anti-ranges that can be represented as ranges should be so.  */
577   if (t == VR_ANTI_RANGE)
578     {
579       bool is_min = vrp_val_is_min (min);
580       bool is_max = vrp_val_is_max (max);
581
582       if (is_min && is_max)
583         {
584           /* We cannot deal with empty ranges, drop to varying.
585              ???  This could be VR_UNDEFINED instead.  */
586           set_value_range_to_varying (vr);
587           return;
588         }
589       else if (TYPE_PRECISION (TREE_TYPE (min)) == 1
590                && (is_min || is_max))
591         {
592           /* Non-empty boolean ranges can always be represented
593              as a singleton range.  */
594           if (is_min)
595             min = max = vrp_val_max (TREE_TYPE (min));
596           else
597             min = max = vrp_val_min (TREE_TYPE (min));
598           t = VR_RANGE;
599         }
600       else if (is_min
601                /* As a special exception preserve non-null ranges.  */
602                && !(TYPE_UNSIGNED (TREE_TYPE (min))
603                     && integer_zerop (max)))
604         {
605           tree one = build_int_cst (TREE_TYPE (max), 1);
606           min = int_const_binop (PLUS_EXPR, max, one);
607           max = vrp_val_max (TREE_TYPE (max));
608           t = VR_RANGE;
609         }
610       else if (is_max)
611         {
612           tree one = build_int_cst (TREE_TYPE (min), 1);
613           max = int_const_binop (MINUS_EXPR, min, one);
614           min = vrp_val_min (TREE_TYPE (min));
615           t = VR_RANGE;
616         }
617     }
618
619   /* Drop [-INF(OVF), +INF(OVF)] to varying.  */
620   if (needs_overflow_infinity (TREE_TYPE (min))
621       && is_overflow_infinity (min)
622       && is_overflow_infinity (max))
623     {
624       set_value_range_to_varying (vr);
625       return;
626     }
627
628   set_value_range (vr, t, min, max, equiv);
629 }
630
631 /* Copy value range FROM into value range TO.  */
632
633 static inline void
634 copy_value_range (value_range_t *to, value_range_t *from)
635 {
636   set_value_range (to, from->type, from->min, from->max, from->equiv);
637 }
638
639 /* Set value range VR to a single value.  This function is only called
640    with values we get from statements, and exists to clear the
641    TREE_OVERFLOW flag so that we don't think we have an overflow
642    infinity when we shouldn't.  */
643
644 static inline void
645 set_value_range_to_value (value_range_t *vr, tree val, bitmap equiv)
646 {
647   gcc_assert (is_gimple_min_invariant (val));
648   if (TREE_OVERFLOW_P (val))
649     val = drop_tree_overflow (val);
650   set_value_range (vr, VR_RANGE, val, val, equiv);
651 }
652
653 /* Set value range VR to a non-negative range of type TYPE.
654    OVERFLOW_INFINITY indicates whether to use an overflow infinity
655    rather than TYPE_MAX_VALUE; this should be true if we determine
656    that the range is nonnegative based on the assumption that signed
657    overflow does not occur.  */
658
659 static inline void
660 set_value_range_to_nonnegative (value_range_t *vr, tree type,
661                                 bool overflow_infinity)
662 {
663   tree zero;
664
665   if (overflow_infinity && !supports_overflow_infinity (type))
666     {
667       set_value_range_to_varying (vr);
668       return;
669     }
670
671   zero = build_int_cst (type, 0);
672   set_value_range (vr, VR_RANGE, zero,
673                    (overflow_infinity
674                     ? positive_overflow_infinity (type)
675                     : TYPE_MAX_VALUE (type)),
676                    vr->equiv);
677 }
678
679 /* Set value range VR to a non-NULL range of type TYPE.  */
680
681 static inline void
682 set_value_range_to_nonnull (value_range_t *vr, tree type)
683 {
684   tree zero = build_int_cst (type, 0);
685   set_value_range (vr, VR_ANTI_RANGE, zero, zero, vr->equiv);
686 }
687
688
689 /* Set value range VR to a NULL range of type TYPE.  */
690
691 static inline void
692 set_value_range_to_null (value_range_t *vr, tree type)
693 {
694   set_value_range_to_value (vr, build_int_cst (type, 0), vr->equiv);
695 }
696
697
698 /* Set value range VR to a range of a truthvalue of type TYPE.  */
699
700 static inline void
701 set_value_range_to_truthvalue (value_range_t *vr, tree type)
702 {
703   if (TYPE_PRECISION (type) == 1)
704     set_value_range_to_varying (vr);
705   else
706     set_value_range (vr, VR_RANGE,
707                      build_int_cst (type, 0), build_int_cst (type, 1),
708                      vr->equiv);
709 }
710
711
712 /* If abs (min) < abs (max), set VR to [-max, max], if
713    abs (min) >= abs (max), set VR to [-min, min].  */
714
715 static void
716 abs_extent_range (value_range_t *vr, tree min, tree max)
717 {
718   int cmp;
719
720   gcc_assert (TREE_CODE (min) == INTEGER_CST);
721   gcc_assert (TREE_CODE (max) == INTEGER_CST);
722   gcc_assert (INTEGRAL_TYPE_P (TREE_TYPE (min)));
723   gcc_assert (!TYPE_UNSIGNED (TREE_TYPE (min)));
724   min = fold_unary (ABS_EXPR, TREE_TYPE (min), min);
725   max = fold_unary (ABS_EXPR, TREE_TYPE (max), max);
726   if (TREE_OVERFLOW (min) || TREE_OVERFLOW (max))
727     {
728       set_value_range_to_varying (vr);
729       return;
730     }
731   cmp = compare_values (min, max);
732   if (cmp == -1)
733     min = fold_unary (NEGATE_EXPR, TREE_TYPE (min), max);
734   else if (cmp == 0 || cmp == 1)
735     {
736       max = min;
737       min = fold_unary (NEGATE_EXPR, TREE_TYPE (min), min);
738     }
739   else
740     {
741       set_value_range_to_varying (vr);
742       return;
743     }
744   set_and_canonicalize_value_range (vr, VR_RANGE, min, max, NULL);
745 }
746
747
748 /* Return value range information for VAR.
749
750    If we have no values ranges recorded (ie, VRP is not running), then
751    return NULL.  Otherwise create an empty range if none existed for VAR.  */
752
753 static value_range_t *
754 get_value_range (const_tree var)
755 {
756   static const struct value_range_d vr_const_varying
757     = { VR_VARYING, NULL_TREE, NULL_TREE, NULL };
758   value_range_t *vr;
759   tree sym;
760   unsigned ver = SSA_NAME_VERSION (var);
761
762   /* If we have no recorded ranges, then return NULL.  */
763   if (! vr_value)
764     return NULL;
765
766   /* If we query the range for a new SSA name return an unmodifiable VARYING.
767      We should get here at most from the substitute-and-fold stage which
768      will never try to change values.  */
769   if (ver >= num_vr_values)
770     return CONST_CAST (value_range_t *, &vr_const_varying);
771
772   vr = vr_value[ver];
773   if (vr)
774     return vr;
775
776   /* After propagation finished do not allocate new value-ranges.  */
777   if (values_propagated)
778     return CONST_CAST (value_range_t *, &vr_const_varying);
779
780   /* Create a default value range.  */
781   vr_value[ver] = vr = XCNEW (value_range_t);
782
783   /* Defer allocating the equivalence set.  */
784   vr->equiv = NULL;
785
786   /* If VAR is a default definition of a parameter, the variable can
787      take any value in VAR's type.  */
788   if (SSA_NAME_IS_DEFAULT_DEF (var))
789     {
790       sym = SSA_NAME_VAR (var);
791       if (TREE_CODE (sym) == PARM_DECL)
792         {
793           /* Try to use the "nonnull" attribute to create ~[0, 0]
794              anti-ranges for pointers.  Note that this is only valid with
795              default definitions of PARM_DECLs.  */
796           if (POINTER_TYPE_P (TREE_TYPE (sym))
797               && nonnull_arg_p (sym))
798             set_value_range_to_nonnull (vr, TREE_TYPE (sym));
799           else
800             set_value_range_to_varying (vr);
801         }
802       else if (TREE_CODE (sym) == RESULT_DECL
803                && DECL_BY_REFERENCE (sym))
804         set_value_range_to_nonnull (vr, TREE_TYPE (sym));
805     }
806
807   return vr;
808 }
809
810 /* Return true, if VAL1 and VAL2 are equal values for VRP purposes.  */
811
812 static inline bool
813 vrp_operand_equal_p (const_tree val1, const_tree val2)
814 {
815   if (val1 == val2)
816     return true;
817   if (!val1 || !val2 || !operand_equal_p (val1, val2, 0))
818     return false;
819   return is_overflow_infinity (val1) == is_overflow_infinity (val2);
820 }
821
822 /* Return true, if the bitmaps B1 and B2 are equal.  */
823
824 static inline bool
825 vrp_bitmap_equal_p (const_bitmap b1, const_bitmap b2)
826 {
827   return (b1 == b2
828           || ((!b1 || bitmap_empty_p (b1))
829               && (!b2 || bitmap_empty_p (b2)))
830           || (b1 && b2
831               && bitmap_equal_p (b1, b2)));
832 }
833
834 /* Update the value range and equivalence set for variable VAR to
835    NEW_VR.  Return true if NEW_VR is different from VAR's previous
836    value.
837
838    NOTE: This function assumes that NEW_VR is a temporary value range
839    object created for the sole purpose of updating VAR's range.  The
840    storage used by the equivalence set from NEW_VR will be freed by
841    this function.  Do not call update_value_range when NEW_VR
842    is the range object associated with another SSA name.  */
843
844 static inline bool
845 update_value_range (const_tree var, value_range_t *new_vr)
846 {
847   value_range_t *old_vr;
848   bool is_new;
849
850   /* If there is a value-range on the SSA name from earlier analysis
851      factor that in.  */
852   if (INTEGRAL_TYPE_P (TREE_TYPE (var)))
853     {
854       wide_int min, max;
855       value_range_type rtype = get_range_info (var, &min, &max);
856       if (rtype == VR_RANGE || rtype == VR_ANTI_RANGE)
857         {
858           value_range_d nr;
859           nr.type = rtype;
860           nr.min = wide_int_to_tree (TREE_TYPE (var), min);
861           nr.max = wide_int_to_tree (TREE_TYPE (var), max);
862           nr.equiv = NULL;
863           vrp_intersect_ranges (new_vr, &nr);
864         }
865     }
866
867   /* Update the value range, if necessary.  */
868   old_vr = get_value_range (var);
869   is_new = old_vr->type != new_vr->type
870            || !vrp_operand_equal_p (old_vr->min, new_vr->min)
871            || !vrp_operand_equal_p (old_vr->max, new_vr->max)
872            || !vrp_bitmap_equal_p (old_vr->equiv, new_vr->equiv);
873
874   if (is_new)
875     {
876       /* Do not allow transitions up the lattice.  The following
877          is slightly more awkward than just new_vr->type < old_vr->type
878          because VR_RANGE and VR_ANTI_RANGE need to be considered
879          the same.  We may not have is_new when transitioning to
880          UNDEFINED or from VARYING.  */
881       if (new_vr->type == VR_UNDEFINED
882           || old_vr->type == VR_VARYING)
883         set_value_range_to_varying (old_vr);
884       else
885         set_value_range (old_vr, new_vr->type, new_vr->min, new_vr->max,
886                          new_vr->equiv);
887     }
888
889   BITMAP_FREE (new_vr->equiv);
890
891   return is_new;
892 }
893
894
895 /* Add VAR and VAR's equivalence set to EQUIV.  This is the central
896    point where equivalence processing can be turned on/off.  */
897
898 static void
899 add_equivalence (bitmap *equiv, const_tree var)
900 {
901   unsigned ver = SSA_NAME_VERSION (var);
902   value_range_t *vr = vr_value[ver];
903
904   if (*equiv == NULL)
905     *equiv = BITMAP_ALLOC (NULL);
906   bitmap_set_bit (*equiv, ver);
907   if (vr && vr->equiv)
908     bitmap_ior_into (*equiv, vr->equiv);
909 }
910
911
912 /* Return true if VR is ~[0, 0].  */
913
914 static inline bool
915 range_is_nonnull (value_range_t *vr)
916 {
917   return vr->type == VR_ANTI_RANGE
918          && integer_zerop (vr->min)
919          && integer_zerop (vr->max);
920 }
921
922
923 /* Return true if VR is [0, 0].  */
924
925 static inline bool
926 range_is_null (value_range_t *vr)
927 {
928   return vr->type == VR_RANGE
929          && integer_zerop (vr->min)
930          && integer_zerop (vr->max);
931 }
932
933 /* Return true if max and min of VR are INTEGER_CST.  It's not necessary
934    a singleton.  */
935
936 static inline bool
937 range_int_cst_p (value_range_t *vr)
938 {
939   return (vr->type == VR_RANGE
940           && TREE_CODE (vr->max) == INTEGER_CST
941           && TREE_CODE (vr->min) == INTEGER_CST);
942 }
943
944 /* Return true if VR is a INTEGER_CST singleton.  */
945
946 static inline bool
947 range_int_cst_singleton_p (value_range_t *vr)
948 {
949   return (range_int_cst_p (vr)
950           && !is_overflow_infinity (vr->min)
951           && !is_overflow_infinity (vr->max)
952           && tree_int_cst_equal (vr->min, vr->max));
953 }
954
955 /* Return true if value range VR involves at least one symbol.  */
956
957 static inline bool
958 symbolic_range_p (value_range_t *vr)
959 {
960   return (!is_gimple_min_invariant (vr->min)
961           || !is_gimple_min_invariant (vr->max));
962 }
963
964 /* Return the single symbol (an SSA_NAME) contained in T if any, or NULL_TREE
965    otherwise.  We only handle additive operations and set NEG to true if the
966    symbol is negated and INV to the invariant part, if any.  */
967
968 static tree
969 get_single_symbol (tree t, bool *neg, tree *inv)
970 {
971   bool neg_;
972   tree inv_;
973
974   if (TREE_CODE (t) == PLUS_EXPR
975       || TREE_CODE (t) == POINTER_PLUS_EXPR
976       || TREE_CODE (t) == MINUS_EXPR)
977     {
978       if (is_gimple_min_invariant (TREE_OPERAND (t, 0)))
979         {
980           neg_ = (TREE_CODE (t) == MINUS_EXPR);
981           inv_ = TREE_OPERAND (t, 0);
982           t = TREE_OPERAND (t, 1);
983         }
984       else if (is_gimple_min_invariant (TREE_OPERAND (t, 1)))
985         {
986           neg_ = false;
987           inv_ = TREE_OPERAND (t, 1);
988           t = TREE_OPERAND (t, 0);
989         }
990       else
991         return NULL_TREE;
992     }
993   else
994     {
995       neg_ = false;
996       inv_ = NULL_TREE;
997     }
998
999   if (TREE_CODE (t) == NEGATE_EXPR)
1000     {
1001       t = TREE_OPERAND (t, 0);
1002       neg_ = !neg_;
1003     }
1004
1005   if (TREE_CODE (t) != SSA_NAME)
1006     return NULL_TREE;
1007
1008   *neg = neg_;
1009   *inv = inv_;
1010   return t;
1011 }
1012
1013 /* The reverse operation: build a symbolic expression with TYPE
1014    from symbol SYM, negated according to NEG, and invariant INV.  */
1015
1016 static tree
1017 build_symbolic_expr (tree type, tree sym, bool neg, tree inv)
1018 {
1019   const bool pointer_p = POINTER_TYPE_P (type);
1020   tree t = sym;
1021
1022   if (neg)
1023     t = build1 (NEGATE_EXPR, type, t);
1024
1025   if (integer_zerop (inv))
1026     return t;
1027
1028   return build2 (pointer_p ? POINTER_PLUS_EXPR : PLUS_EXPR, type, t, inv);
1029 }
1030
1031 /* Return true if value range VR involves exactly one symbol SYM.  */
1032
1033 static bool
1034 symbolic_range_based_on_p (value_range_t *vr, const_tree sym)
1035 {
1036   bool neg, min_has_symbol, max_has_symbol;
1037   tree inv;
1038
1039   if (is_gimple_min_invariant (vr->min))
1040     min_has_symbol = false;
1041   else if (get_single_symbol (vr->min, &neg, &inv) == sym)
1042     min_has_symbol = true;
1043   else
1044     return false;
1045
1046   if (is_gimple_min_invariant (vr->max))
1047     max_has_symbol = false;
1048   else if (get_single_symbol (vr->max, &neg, &inv) == sym)
1049     max_has_symbol = true;
1050   else
1051     return false;
1052
1053   return (min_has_symbol || max_has_symbol);
1054 }
1055
1056 /* Return true if value range VR uses an overflow infinity.  */
1057
1058 static inline bool
1059 overflow_infinity_range_p (value_range_t *vr)
1060 {
1061   return (vr->type == VR_RANGE
1062           && (is_overflow_infinity (vr->min)
1063               || is_overflow_infinity (vr->max)));
1064 }
1065
1066 /* Return false if we can not make a valid comparison based on VR;
1067    this will be the case if it uses an overflow infinity and overflow
1068    is not undefined (i.e., -fno-strict-overflow is in effect).
1069    Otherwise return true, and set *STRICT_OVERFLOW_P to true if VR
1070    uses an overflow infinity.  */
1071
1072 static bool
1073 usable_range_p (value_range_t *vr, bool *strict_overflow_p)
1074 {
1075   gcc_assert (vr->type == VR_RANGE);
1076   if (is_overflow_infinity (vr->min))
1077     {
1078       *strict_overflow_p = true;
1079       if (!TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (vr->min)))
1080         return false;
1081     }
1082   if (is_overflow_infinity (vr->max))
1083     {
1084       *strict_overflow_p = true;
1085       if (!TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (vr->max)))
1086         return false;
1087     }
1088   return true;
1089 }
1090
1091
1092 /* Return true if the result of assignment STMT is know to be non-negative.
1093    If the return value is based on the assumption that signed overflow is
1094    undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
1095    *STRICT_OVERFLOW_P.*/
1096
1097 static bool
1098 gimple_assign_nonnegative_warnv_p (gimple stmt, bool *strict_overflow_p)
1099 {
1100   enum tree_code code = gimple_assign_rhs_code (stmt);
1101   switch (get_gimple_rhs_class (code))
1102     {
1103     case GIMPLE_UNARY_RHS:
1104       return tree_unary_nonnegative_warnv_p (gimple_assign_rhs_code (stmt),
1105                                              gimple_expr_type (stmt),
1106                                              gimple_assign_rhs1 (stmt),
1107                                              strict_overflow_p);
1108     case GIMPLE_BINARY_RHS:
1109       return tree_binary_nonnegative_warnv_p (gimple_assign_rhs_code (stmt),
1110                                               gimple_expr_type (stmt),
1111                                               gimple_assign_rhs1 (stmt),
1112                                               gimple_assign_rhs2 (stmt),
1113                                               strict_overflow_p);
1114     case GIMPLE_TERNARY_RHS:
1115       return false;
1116     case GIMPLE_SINGLE_RHS:
1117       return tree_single_nonnegative_warnv_p (gimple_assign_rhs1 (stmt),
1118                                               strict_overflow_p);
1119     case GIMPLE_INVALID_RHS:
1120       gcc_unreachable ();
1121     default:
1122       gcc_unreachable ();
1123     }
1124 }
1125
1126 /* Return true if return value of call STMT is know to be non-negative.
1127    If the return value is based on the assumption that signed overflow is
1128    undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
1129    *STRICT_OVERFLOW_P.*/
1130
1131 static bool
1132 gimple_call_nonnegative_warnv_p (gimple stmt, bool *strict_overflow_p)
1133 {
1134   tree arg0 = gimple_call_num_args (stmt) > 0 ?
1135     gimple_call_arg (stmt, 0) : NULL_TREE;
1136   tree arg1 = gimple_call_num_args (stmt) > 1 ?
1137     gimple_call_arg (stmt, 1) : NULL_TREE;
1138
1139   return tree_call_nonnegative_warnv_p (gimple_expr_type (stmt),
1140                                         gimple_call_fndecl (stmt),
1141                                         arg0,
1142                                         arg1,
1143                                         strict_overflow_p);
1144 }
1145
1146 /* Return true if STMT is know to to compute a non-negative value.
1147    If the return value is based on the assumption that signed overflow is
1148    undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
1149    *STRICT_OVERFLOW_P.*/
1150
1151 static bool
1152 gimple_stmt_nonnegative_warnv_p (gimple stmt, bool *strict_overflow_p)
1153 {
1154   switch (gimple_code (stmt))
1155     {
1156     case GIMPLE_ASSIGN:
1157       return gimple_assign_nonnegative_warnv_p (stmt, strict_overflow_p);
1158     case GIMPLE_CALL:
1159       return gimple_call_nonnegative_warnv_p (stmt, strict_overflow_p);
1160     default:
1161       gcc_unreachable ();
1162     }
1163 }
1164
1165 /* Return true if the result of assignment STMT is know to be non-zero.
1166    If the return value is based on the assumption that signed overflow is
1167    undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
1168    *STRICT_OVERFLOW_P.*/
1169
1170 static bool
1171 gimple_assign_nonzero_warnv_p (gimple stmt, bool *strict_overflow_p)
1172 {
1173   enum tree_code code = gimple_assign_rhs_code (stmt);
1174   switch (get_gimple_rhs_class (code))
1175     {
1176     case GIMPLE_UNARY_RHS:
1177       return tree_unary_nonzero_warnv_p (gimple_assign_rhs_code (stmt),
1178                                          gimple_expr_type (stmt),
1179                                          gimple_assign_rhs1 (stmt),
1180                                          strict_overflow_p);
1181     case GIMPLE_BINARY_RHS:
1182       return tree_binary_nonzero_warnv_p (gimple_assign_rhs_code (stmt),
1183                                           gimple_expr_type (stmt),
1184                                           gimple_assign_rhs1 (stmt),
1185                                           gimple_assign_rhs2 (stmt),
1186                                           strict_overflow_p);
1187     case GIMPLE_TERNARY_RHS:
1188       return false;
1189     case GIMPLE_SINGLE_RHS:
1190       return tree_single_nonzero_warnv_p (gimple_assign_rhs1 (stmt),
1191                                           strict_overflow_p);
1192     case GIMPLE_INVALID_RHS:
1193       gcc_unreachable ();
1194     default:
1195       gcc_unreachable ();
1196     }
1197 }
1198
1199 /* Return true if STMT is known to compute a non-zero value.
1200    If the return value is based on the assumption that signed overflow is
1201    undefined, set *STRICT_OVERFLOW_P to true; otherwise, don't change
1202    *STRICT_OVERFLOW_P.*/
1203
1204 static bool
1205 gimple_stmt_nonzero_warnv_p (gimple stmt, bool *strict_overflow_p)
1206 {
1207   switch (gimple_code (stmt))
1208     {
1209     case GIMPLE_ASSIGN:
1210       return gimple_assign_nonzero_warnv_p (stmt, strict_overflow_p);
1211     case GIMPLE_CALL:
1212       {
1213         tree fndecl = gimple_call_fndecl (stmt);
1214         if (!fndecl) return false;
1215         if (flag_delete_null_pointer_checks && !flag_check_new
1216             && DECL_IS_OPERATOR_NEW (fndecl)
1217             && !TREE_NOTHROW (fndecl))
1218           return true;
1219         if (flag_delete_null_pointer_checks && 
1220             lookup_attribute ("returns_nonnull",
1221                               TYPE_ATTRIBUTES (gimple_call_fntype (stmt))))
1222           return true;
1223         return gimple_alloca_call_p (stmt);
1224       }
1225     default:
1226       gcc_unreachable ();
1227     }
1228 }
1229
1230 /* Like tree_expr_nonzero_warnv_p, but this function uses value ranges
1231    obtained so far.  */
1232
1233 static bool
1234 vrp_stmt_computes_nonzero (gimple stmt, bool *strict_overflow_p)
1235 {
1236   if (gimple_stmt_nonzero_warnv_p (stmt, strict_overflow_p))
1237     return true;
1238
1239   /* If we have an expression of the form &X->a, then the expression
1240      is nonnull if X is nonnull.  */
1241   if (is_gimple_assign (stmt)
1242       && gimple_assign_rhs_code (stmt) == ADDR_EXPR)
1243     {
1244       tree expr = gimple_assign_rhs1 (stmt);
1245       tree base = get_base_address (TREE_OPERAND (expr, 0));
1246
1247       if (base != NULL_TREE
1248           && TREE_CODE (base) == MEM_REF
1249           && TREE_CODE (TREE_OPERAND (base, 0)) == SSA_NAME)
1250         {
1251           value_range_t *vr = get_value_range (TREE_OPERAND (base, 0));
1252           if (range_is_nonnull (vr))
1253             return true;
1254         }
1255     }
1256
1257   return false;
1258 }
1259
1260 /* Returns true if EXPR is a valid value (as expected by compare_values) --
1261    a gimple invariant, or SSA_NAME +- CST.  */
1262
1263 static bool
1264 valid_value_p (tree expr)
1265 {
1266   if (TREE_CODE (expr) == SSA_NAME)
1267     return true;
1268
1269   if (TREE_CODE (expr) == PLUS_EXPR
1270       || TREE_CODE (expr) == MINUS_EXPR)
1271     return (TREE_CODE (TREE_OPERAND (expr, 0)) == SSA_NAME
1272             && TREE_CODE (TREE_OPERAND (expr, 1)) == INTEGER_CST);
1273
1274   return is_gimple_min_invariant (expr);
1275 }
1276
1277 /* Return
1278    1 if VAL < VAL2
1279    0 if !(VAL < VAL2)
1280    -2 if those are incomparable.  */
1281 static inline int
1282 operand_less_p (tree val, tree val2)
1283 {
1284   /* LT is folded faster than GE and others.  Inline the common case.  */
1285   if (TREE_CODE (val) == INTEGER_CST && TREE_CODE (val2) == INTEGER_CST)
1286     return tree_int_cst_lt (val, val2);
1287   else
1288     {
1289       tree tcmp;
1290
1291       fold_defer_overflow_warnings ();
1292
1293       tcmp = fold_binary_to_constant (LT_EXPR, boolean_type_node, val, val2);
1294
1295       fold_undefer_and_ignore_overflow_warnings ();
1296
1297       if (!tcmp
1298           || TREE_CODE (tcmp) != INTEGER_CST)
1299         return -2;
1300
1301       if (!integer_zerop (tcmp))
1302         return 1;
1303     }
1304
1305   /* val >= val2, not considering overflow infinity.  */
1306   if (is_negative_overflow_infinity (val))
1307     return is_negative_overflow_infinity (val2) ? 0 : 1;
1308   else if (is_positive_overflow_infinity (val2))
1309     return is_positive_overflow_infinity (val) ? 0 : 1;
1310
1311   return 0;
1312 }
1313
1314 /* Compare two values VAL1 and VAL2.  Return
1315
1316         -2 if VAL1 and VAL2 cannot be compared at compile-time,
1317         -1 if VAL1 < VAL2,
1318          0 if VAL1 == VAL2,
1319         +1 if VAL1 > VAL2, and
1320         +2 if VAL1 != VAL2
1321
1322    This is similar to tree_int_cst_compare but supports pointer values
1323    and values that cannot be compared at compile time.
1324
1325    If STRICT_OVERFLOW_P is not NULL, then set *STRICT_OVERFLOW_P to
1326    true if the return value is only valid if we assume that signed
1327    overflow is undefined.  */
1328
1329 static int
1330 compare_values_warnv (tree val1, tree val2, bool *strict_overflow_p)
1331 {
1332   if (val1 == val2)
1333     return 0;
1334
1335   /* Below we rely on the fact that VAL1 and VAL2 are both pointers or
1336      both integers.  */
1337   gcc_assert (POINTER_TYPE_P (TREE_TYPE (val1))
1338               == POINTER_TYPE_P (TREE_TYPE (val2)));
1339
1340   /* Convert the two values into the same type.  This is needed because
1341      sizetype causes sign extension even for unsigned types.  */
1342   val2 = fold_convert (TREE_TYPE (val1), val2);
1343   STRIP_USELESS_TYPE_CONVERSION (val2);
1344
1345   if ((TREE_CODE (val1) == SSA_NAME
1346        || (TREE_CODE (val1) == NEGATE_EXPR
1347            && TREE_CODE (TREE_OPERAND (val1, 0)) == SSA_NAME)
1348        || TREE_CODE (val1) == PLUS_EXPR
1349        || TREE_CODE (val1) == MINUS_EXPR)
1350       && (TREE_CODE (val2) == SSA_NAME
1351           || (TREE_CODE (val2) == NEGATE_EXPR
1352               && TREE_CODE (TREE_OPERAND (val2, 0)) == SSA_NAME)
1353           || TREE_CODE (val2) == PLUS_EXPR
1354           || TREE_CODE (val2) == MINUS_EXPR))
1355     {
1356       tree n1, c1, n2, c2;
1357       enum tree_code code1, code2;
1358
1359       /* If VAL1 and VAL2 are of the form '[-]NAME [+-] CST' or 'NAME',
1360          return -1 or +1 accordingly.  If VAL1 and VAL2 don't use the
1361          same name, return -2.  */
1362       if (TREE_CODE (val1) == SSA_NAME || TREE_CODE (val1) == NEGATE_EXPR)
1363         {
1364           code1 = SSA_NAME;
1365           n1 = val1;
1366           c1 = NULL_TREE;
1367         }
1368       else
1369         {
1370           code1 = TREE_CODE (val1);
1371           n1 = TREE_OPERAND (val1, 0);
1372           c1 = TREE_OPERAND (val1, 1);
1373           if (tree_int_cst_sgn (c1) == -1)
1374             {
1375               if (is_negative_overflow_infinity (c1))
1376                 return -2;
1377               c1 = fold_unary_to_constant (NEGATE_EXPR, TREE_TYPE (c1), c1);
1378               if (!c1)
1379                 return -2;
1380               code1 = code1 == MINUS_EXPR ? PLUS_EXPR : MINUS_EXPR;
1381             }
1382         }
1383
1384       if (TREE_CODE (val2) == SSA_NAME || TREE_CODE (val2) == NEGATE_EXPR)
1385         {
1386           code2 = SSA_NAME;
1387           n2 = val2;
1388           c2 = NULL_TREE;
1389         }
1390       else
1391         {
1392           code2 = TREE_CODE (val2);
1393           n2 = TREE_OPERAND (val2, 0);
1394           c2 = TREE_OPERAND (val2, 1);
1395           if (tree_int_cst_sgn (c2) == -1)
1396             {
1397               if (is_negative_overflow_infinity (c2))
1398                 return -2;
1399               c2 = fold_unary_to_constant (NEGATE_EXPR, TREE_TYPE (c2), c2);
1400               if (!c2)
1401                 return -2;
1402               code2 = code2 == MINUS_EXPR ? PLUS_EXPR : MINUS_EXPR;
1403             }
1404         }
1405
1406       /* Both values must use the same name.  */
1407       if (TREE_CODE (n1) == NEGATE_EXPR && TREE_CODE (n2) == NEGATE_EXPR)
1408         {
1409           n1 = TREE_OPERAND (n1, 0);
1410           n2 = TREE_OPERAND (n2, 0);
1411         }
1412       if (n1 != n2)
1413         return -2;
1414
1415       if (code1 == SSA_NAME && code2 == SSA_NAME)
1416         /* NAME == NAME  */
1417         return 0;
1418
1419       /* If overflow is defined we cannot simplify more.  */
1420       if (!TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1)))
1421         return -2;
1422
1423       if (strict_overflow_p != NULL
1424           && (code1 == SSA_NAME || !TREE_NO_WARNING (val1))
1425           && (code2 == SSA_NAME || !TREE_NO_WARNING (val2)))
1426         *strict_overflow_p = true;
1427
1428       if (code1 == SSA_NAME)
1429         {
1430           if (code2 == PLUS_EXPR)
1431             /* NAME < NAME + CST  */
1432             return -1;
1433           else if (code2 == MINUS_EXPR)
1434             /* NAME > NAME - CST  */
1435             return 1;
1436         }
1437       else if (code1 == PLUS_EXPR)
1438         {
1439           if (code2 == SSA_NAME)
1440             /* NAME + CST > NAME  */
1441             return 1;
1442           else if (code2 == PLUS_EXPR)
1443             /* NAME + CST1 > NAME + CST2, if CST1 > CST2  */
1444             return compare_values_warnv (c1, c2, strict_overflow_p);
1445           else if (code2 == MINUS_EXPR)
1446             /* NAME + CST1 > NAME - CST2  */
1447             return 1;
1448         }
1449       else if (code1 == MINUS_EXPR)
1450         {
1451           if (code2 == SSA_NAME)
1452             /* NAME - CST < NAME  */
1453             return -1;
1454           else if (code2 == PLUS_EXPR)
1455             /* NAME - CST1 < NAME + CST2  */
1456             return -1;
1457           else if (code2 == MINUS_EXPR)
1458             /* NAME - CST1 > NAME - CST2, if CST1 < CST2.  Notice that
1459                C1 and C2 are swapped in the call to compare_values.  */
1460             return compare_values_warnv (c2, c1, strict_overflow_p);
1461         }
1462
1463       gcc_unreachable ();
1464     }
1465
1466   /* We cannot compare non-constants.  */
1467   if (!is_gimple_min_invariant (val1) || !is_gimple_min_invariant (val2))
1468     return -2;
1469
1470   if (!POINTER_TYPE_P (TREE_TYPE (val1)))
1471     {
1472       /* We cannot compare overflowed values, except for overflow
1473          infinities.  */
1474       if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
1475         {
1476           if (strict_overflow_p != NULL)
1477             *strict_overflow_p = true;
1478           if (is_negative_overflow_infinity (val1))
1479             return is_negative_overflow_infinity (val2) ? 0 : -1;
1480           else if (is_negative_overflow_infinity (val2))
1481             return 1;
1482           else if (is_positive_overflow_infinity (val1))
1483             return is_positive_overflow_infinity (val2) ? 0 : 1;
1484           else if (is_positive_overflow_infinity (val2))
1485             return -1;
1486           return -2;
1487         }
1488
1489       return tree_int_cst_compare (val1, val2);
1490     }
1491   else
1492     {
1493       tree t;
1494
1495       /* First see if VAL1 and VAL2 are not the same.  */
1496       if (val1 == val2 || operand_equal_p (val1, val2, 0))
1497         return 0;
1498
1499       /* If VAL1 is a lower address than VAL2, return -1.  */
1500       if (operand_less_p (val1, val2) == 1)
1501         return -1;
1502
1503       /* If VAL1 is a higher address than VAL2, return +1.  */
1504       if (operand_less_p (val2, val1) == 1)
1505         return 1;
1506
1507       /* If VAL1 is different than VAL2, return +2.
1508          For integer constants we either have already returned -1 or 1
1509          or they are equivalent.  We still might succeed in proving
1510          something about non-trivial operands.  */
1511       if (TREE_CODE (val1) != INTEGER_CST
1512           || TREE_CODE (val2) != INTEGER_CST)
1513         {
1514           t = fold_binary_to_constant (NE_EXPR, boolean_type_node, val1, val2);
1515           if (t && integer_onep (t))
1516             return 2;
1517         }
1518
1519       return -2;
1520     }
1521 }
1522
1523 /* Compare values like compare_values_warnv, but treat comparisons of
1524    nonconstants which rely on undefined overflow as incomparable.  */
1525
1526 static int
1527 compare_values (tree val1, tree val2)
1528 {
1529   bool sop;
1530   int ret;
1531
1532   sop = false;
1533   ret = compare_values_warnv (val1, val2, &sop);
1534   if (sop
1535       && (!is_gimple_min_invariant (val1) || !is_gimple_min_invariant (val2)))
1536     ret = -2;
1537   return ret;
1538 }
1539
1540
1541 /* Return 1 if VAL is inside value range MIN <= VAL <= MAX,
1542           0 if VAL is not inside [MIN, MAX],
1543          -2 if we cannot tell either way.
1544
1545    Benchmark compile/20001226-1.c compilation time after changing this
1546    function.  */
1547
1548 static inline int
1549 value_inside_range (tree val, tree min, tree max)
1550 {
1551   int cmp1, cmp2;
1552
1553   cmp1 = operand_less_p (val, min);
1554   if (cmp1 == -2)
1555     return -2;
1556   if (cmp1 == 1)
1557     return 0;
1558
1559   cmp2 = operand_less_p (max, val);
1560   if (cmp2 == -2)
1561     return -2;
1562
1563   return !cmp2;
1564 }
1565
1566
1567 /* Return true if value ranges VR0 and VR1 have a non-empty
1568    intersection.
1569
1570    Benchmark compile/20001226-1.c compilation time after changing this
1571    function.
1572    */
1573
1574 static inline bool
1575 value_ranges_intersect_p (value_range_t *vr0, value_range_t *vr1)
1576 {
1577   /* The value ranges do not intersect if the maximum of the first range is
1578      less than the minimum of the second range or vice versa.
1579      When those relations are unknown, we can't do any better.  */
1580   if (operand_less_p (vr0->max, vr1->min) != 0)
1581     return false;
1582   if (operand_less_p (vr1->max, vr0->min) != 0)
1583     return false;
1584   return true;
1585 }
1586
1587
1588 /* Return 1 if [MIN, MAX] includes the value zero, 0 if it does not
1589    include the value zero, -2 if we cannot tell.  */
1590
1591 static inline int
1592 range_includes_zero_p (tree min, tree max)
1593 {
1594   tree zero = build_int_cst (TREE_TYPE (min), 0);
1595   return value_inside_range (zero, min, max);
1596 }
1597
1598 /* Return true if *VR is know to only contain nonnegative values.  */
1599
1600 static inline bool
1601 value_range_nonnegative_p (value_range_t *vr)
1602 {
1603   /* Testing for VR_ANTI_RANGE is not useful here as any anti-range
1604      which would return a useful value should be encoded as a 
1605      VR_RANGE.  */
1606   if (vr->type == VR_RANGE)
1607     {
1608       int result = compare_values (vr->min, integer_zero_node);
1609       return (result == 0 || result == 1);
1610     }
1611
1612   return false;
1613 }
1614
1615 /* If *VR has a value rante that is a single constant value return that,
1616    otherwise return NULL_TREE.  */
1617
1618 static tree
1619 value_range_constant_singleton (value_range_t *vr)
1620 {
1621   if (vr->type == VR_RANGE
1622       && operand_equal_p (vr->min, vr->max, 0)
1623       && is_gimple_min_invariant (vr->min))
1624     return vr->min;
1625
1626   return NULL_TREE;
1627 }
1628
1629 /* If OP has a value range with a single constant value return that,
1630    otherwise return NULL_TREE.  This returns OP itself if OP is a
1631    constant.  */
1632
1633 static tree
1634 op_with_constant_singleton_value_range (tree op)
1635 {
1636   if (is_gimple_min_invariant (op))
1637     return op;
1638
1639   if (TREE_CODE (op) != SSA_NAME)
1640     return NULL_TREE;
1641
1642   return value_range_constant_singleton (get_value_range (op));
1643 }
1644
1645 /* Return true if op is in a boolean [0, 1] value-range.  */
1646
1647 static bool
1648 op_with_boolean_value_range_p (tree op)
1649 {
1650   value_range_t *vr;
1651
1652   if (TYPE_PRECISION (TREE_TYPE (op)) == 1)
1653     return true;
1654
1655   if (integer_zerop (op)
1656       || integer_onep (op))
1657     return true;
1658
1659   if (TREE_CODE (op) != SSA_NAME)
1660     return false;
1661
1662   vr = get_value_range (op);
1663   return (vr->type == VR_RANGE
1664           && integer_zerop (vr->min)
1665           && integer_onep (vr->max));
1666 }
1667
1668 /* Extract value range information from an ASSERT_EXPR EXPR and store
1669    it in *VR_P.  */
1670
1671 static void
1672 extract_range_from_assert (value_range_t *vr_p, tree expr)
1673 {
1674   tree var, cond, limit, min, max, type;
1675   value_range_t *limit_vr;
1676   enum tree_code cond_code;
1677
1678   var = ASSERT_EXPR_VAR (expr);
1679   cond = ASSERT_EXPR_COND (expr);
1680
1681   gcc_assert (COMPARISON_CLASS_P (cond));
1682
1683   /* Find VAR in the ASSERT_EXPR conditional.  */
1684   if (var == TREE_OPERAND (cond, 0)
1685       || TREE_CODE (TREE_OPERAND (cond, 0)) == PLUS_EXPR
1686       || TREE_CODE (TREE_OPERAND (cond, 0)) == NOP_EXPR)
1687     {
1688       /* If the predicate is of the form VAR COMP LIMIT, then we just
1689          take LIMIT from the RHS and use the same comparison code.  */
1690       cond_code = TREE_CODE (cond);
1691       limit = TREE_OPERAND (cond, 1);
1692       cond = TREE_OPERAND (cond, 0);
1693     }
1694   else
1695     {
1696       /* If the predicate is of the form LIMIT COMP VAR, then we need
1697          to flip around the comparison code to create the proper range
1698          for VAR.  */
1699       cond_code = swap_tree_comparison (TREE_CODE (cond));
1700       limit = TREE_OPERAND (cond, 0);
1701       cond = TREE_OPERAND (cond, 1);
1702     }
1703
1704   limit = avoid_overflow_infinity (limit);
1705
1706   type = TREE_TYPE (var);
1707   gcc_assert (limit != var);
1708
1709   /* For pointer arithmetic, we only keep track of pointer equality
1710      and inequality.  */
1711   if (POINTER_TYPE_P (type) && cond_code != NE_EXPR && cond_code != EQ_EXPR)
1712     {
1713       set_value_range_to_varying (vr_p);
1714       return;
1715     }
1716
1717   /* If LIMIT is another SSA name and LIMIT has a range of its own,
1718      try to use LIMIT's range to avoid creating symbolic ranges
1719      unnecessarily. */
1720   limit_vr = (TREE_CODE (limit) == SSA_NAME) ? get_value_range (limit) : NULL;
1721
1722   /* LIMIT's range is only interesting if it has any useful information.  */
1723   if (limit_vr
1724       && (limit_vr->type == VR_UNDEFINED
1725           || limit_vr->type == VR_VARYING
1726           || symbolic_range_p (limit_vr)))
1727     limit_vr = NULL;
1728
1729   /* Initially, the new range has the same set of equivalences of
1730      VAR's range.  This will be revised before returning the final
1731      value.  Since assertions may be chained via mutually exclusive
1732      predicates, we will need to trim the set of equivalences before
1733      we are done.  */
1734   gcc_assert (vr_p->equiv == NULL);
1735   add_equivalence (&vr_p->equiv, var);
1736
1737   /* Extract a new range based on the asserted comparison for VAR and
1738      LIMIT's value range.  Notice that if LIMIT has an anti-range, we
1739      will only use it for equality comparisons (EQ_EXPR).  For any
1740      other kind of assertion, we cannot derive a range from LIMIT's
1741      anti-range that can be used to describe the new range.  For
1742      instance, ASSERT_EXPR <x_2, x_2 <= b_4>.  If b_4 is ~[2, 10],
1743      then b_4 takes on the ranges [-INF, 1] and [11, +INF].  There is
1744      no single range for x_2 that could describe LE_EXPR, so we might
1745      as well build the range [b_4, +INF] for it.
1746      One special case we handle is extracting a range from a
1747      range test encoded as (unsigned)var + CST <= limit.  */
1748   if (TREE_CODE (cond) == NOP_EXPR
1749       || TREE_CODE (cond) == PLUS_EXPR)
1750     {
1751       if (TREE_CODE (cond) == PLUS_EXPR)
1752         {
1753           min = fold_build1 (NEGATE_EXPR, TREE_TYPE (TREE_OPERAND (cond, 1)),
1754                              TREE_OPERAND (cond, 1));
1755           max = int_const_binop (PLUS_EXPR, limit, min);
1756           cond = TREE_OPERAND (cond, 0);
1757         }
1758       else
1759         {
1760           min = build_int_cst (TREE_TYPE (var), 0);
1761           max = limit;
1762         }
1763
1764       /* Make sure to not set TREE_OVERFLOW on the final type
1765          conversion.  We are willingly interpreting large positive
1766          unsigned values as negative signed values here.  */
1767       min = force_fit_type (TREE_TYPE (var), wi::to_widest (min), 0, false);
1768       max = force_fit_type (TREE_TYPE (var), wi::to_widest (max), 0, false);
1769
1770       /* We can transform a max, min range to an anti-range or
1771          vice-versa.  Use set_and_canonicalize_value_range which does
1772          this for us.  */
1773       if (cond_code == LE_EXPR)
1774         set_and_canonicalize_value_range (vr_p, VR_RANGE,
1775                                           min, max, vr_p->equiv);
1776       else if (cond_code == GT_EXPR)
1777         set_and_canonicalize_value_range (vr_p, VR_ANTI_RANGE,
1778                                           min, max, vr_p->equiv);
1779       else
1780         gcc_unreachable ();
1781     }
1782   else if (cond_code == EQ_EXPR)
1783     {
1784       enum value_range_type range_type;
1785
1786       if (limit_vr)
1787         {
1788           range_type = limit_vr->type;
1789           min = limit_vr->min;
1790           max = limit_vr->max;
1791         }
1792       else
1793         {
1794           range_type = VR_RANGE;
1795           min = limit;
1796           max = limit;
1797         }
1798
1799       set_value_range (vr_p, range_type, min, max, vr_p->equiv);
1800
1801       /* When asserting the equality VAR == LIMIT and LIMIT is another
1802          SSA name, the new range will also inherit the equivalence set
1803          from LIMIT.  */
1804       if (TREE_CODE (limit) == SSA_NAME)
1805         add_equivalence (&vr_p->equiv, limit);
1806     }
1807   else if (cond_code == NE_EXPR)
1808     {
1809       /* As described above, when LIMIT's range is an anti-range and
1810          this assertion is an inequality (NE_EXPR), then we cannot
1811          derive anything from the anti-range.  For instance, if
1812          LIMIT's range was ~[0, 0], the assertion 'VAR != LIMIT' does
1813          not imply that VAR's range is [0, 0].  So, in the case of
1814          anti-ranges, we just assert the inequality using LIMIT and
1815          not its anti-range.
1816
1817          If LIMIT_VR is a range, we can only use it to build a new
1818          anti-range if LIMIT_VR is a single-valued range.  For
1819          instance, if LIMIT_VR is [0, 1], the predicate
1820          VAR != [0, 1] does not mean that VAR's range is ~[0, 1].
1821          Rather, it means that for value 0 VAR should be ~[0, 0]
1822          and for value 1, VAR should be ~[1, 1].  We cannot
1823          represent these ranges.
1824
1825          The only situation in which we can build a valid
1826          anti-range is when LIMIT_VR is a single-valued range
1827          (i.e., LIMIT_VR->MIN == LIMIT_VR->MAX).  In that case,
1828          build the anti-range ~[LIMIT_VR->MIN, LIMIT_VR->MAX].  */
1829       if (limit_vr
1830           && limit_vr->type == VR_RANGE
1831           && compare_values (limit_vr->min, limit_vr->max) == 0)
1832         {
1833           min = limit_vr->min;
1834           max = limit_vr->max;
1835         }
1836       else
1837         {
1838           /* In any other case, we cannot use LIMIT's range to build a
1839              valid anti-range.  */
1840           min = max = limit;
1841         }
1842
1843       /* If MIN and MAX cover the whole range for their type, then
1844          just use the original LIMIT.  */
1845       if (INTEGRAL_TYPE_P (type)
1846           && vrp_val_is_min (min)
1847           && vrp_val_is_max (max))
1848         min = max = limit;
1849
1850       set_and_canonicalize_value_range (vr_p, VR_ANTI_RANGE,
1851                                         min, max, vr_p->equiv);
1852     }
1853   else if (cond_code == LE_EXPR || cond_code == LT_EXPR)
1854     {
1855       min = TYPE_MIN_VALUE (type);
1856
1857       if (limit_vr == NULL || limit_vr->type == VR_ANTI_RANGE)
1858         max = limit;
1859       else
1860         {
1861           /* If LIMIT_VR is of the form [N1, N2], we need to build the
1862              range [MIN, N2] for LE_EXPR and [MIN, N2 - 1] for
1863              LT_EXPR.  */
1864           max = limit_vr->max;
1865         }
1866
1867       /* If the maximum value forces us to be out of bounds, simply punt.
1868          It would be pointless to try and do anything more since this
1869          all should be optimized away above us.  */
1870       if ((cond_code == LT_EXPR
1871            && compare_values (max, min) == 0)
1872           || is_overflow_infinity (max))
1873         set_value_range_to_varying (vr_p);
1874       else
1875         {
1876           /* For LT_EXPR, we create the range [MIN, MAX - 1].  */
1877           if (cond_code == LT_EXPR)
1878             {
1879               if (TYPE_PRECISION (TREE_TYPE (max)) == 1
1880                   && !TYPE_UNSIGNED (TREE_TYPE (max)))
1881                 max = fold_build2 (PLUS_EXPR, TREE_TYPE (max), max,
1882                                    build_int_cst (TREE_TYPE (max), -1));
1883               else
1884                 max = fold_build2 (MINUS_EXPR, TREE_TYPE (max), max,
1885                                    build_int_cst (TREE_TYPE (max), 1));
1886               if (EXPR_P (max))
1887                 TREE_NO_WARNING (max) = 1;
1888             }
1889
1890           set_value_range (vr_p, VR_RANGE, min, max, vr_p->equiv);
1891         }
1892     }
1893   else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
1894     {
1895       max = TYPE_MAX_VALUE (type);
1896
1897       if (limit_vr == NULL || limit_vr->type == VR_ANTI_RANGE)
1898         min = limit;
1899       else
1900         {
1901           /* If LIMIT_VR is of the form [N1, N2], we need to build the
1902              range [N1, MAX] for GE_EXPR and [N1 + 1, MAX] for
1903              GT_EXPR.  */
1904           min = limit_vr->min;
1905         }
1906
1907       /* If the minimum value forces us to be out of bounds, simply punt.
1908          It would be pointless to try and do anything more since this
1909          all should be optimized away above us.  */
1910       if ((cond_code == GT_EXPR
1911            && compare_values (min, max) == 0)
1912           || is_overflow_infinity (min))
1913         set_value_range_to_varying (vr_p);
1914       else
1915         {
1916           /* For GT_EXPR, we create the range [MIN + 1, MAX].  */
1917           if (cond_code == GT_EXPR)
1918             {
1919               if (TYPE_PRECISION (TREE_TYPE (min)) == 1
1920                   && !TYPE_UNSIGNED (TREE_TYPE (min)))
1921                 min = fold_build2 (MINUS_EXPR, TREE_TYPE (min), min,
1922                                    build_int_cst (TREE_TYPE (min), -1));
1923               else
1924                 min = fold_build2 (PLUS_EXPR, TREE_TYPE (min), min,
1925                                    build_int_cst (TREE_TYPE (min), 1));
1926               if (EXPR_P (min))
1927                 TREE_NO_WARNING (min) = 1;
1928             }
1929
1930           set_value_range (vr_p, VR_RANGE, min, max, vr_p->equiv);
1931         }
1932     }
1933   else
1934     gcc_unreachable ();
1935
1936   /* Finally intersect the new range with what we already know about var.  */
1937   vrp_intersect_ranges (vr_p, get_value_range (var));
1938 }
1939
1940
1941 /* Extract range information from SSA name VAR and store it in VR.  If
1942    VAR has an interesting range, use it.  Otherwise, create the
1943    range [VAR, VAR] and return it.  This is useful in situations where
1944    we may have conditionals testing values of VARYING names.  For
1945    instance,
1946
1947         x_3 = y_5;
1948         if (x_3 > y_5)
1949           ...
1950
1951     Even if y_5 is deemed VARYING, we can determine that x_3 > y_5 is
1952     always false.  */
1953
1954 static void
1955 extract_range_from_ssa_name (value_range_t *vr, tree var)
1956 {
1957   value_range_t *var_vr = get_value_range (var);
1958
1959   if (var_vr->type != VR_VARYING)
1960     copy_value_range (vr, var_vr);
1961   else
1962     set_value_range (vr, VR_RANGE, var, var, NULL);
1963
1964   add_equivalence (&vr->equiv, var);
1965 }
1966
1967
1968 /* Wrapper around int_const_binop.  If the operation overflows and we
1969    are not using wrapping arithmetic, then adjust the result to be
1970    -INF or +INF depending on CODE, VAL1 and VAL2.  This can return
1971    NULL_TREE if we need to use an overflow infinity representation but
1972    the type does not support it.  */
1973
1974 static tree
1975 vrp_int_const_binop (enum tree_code code, tree val1, tree val2)
1976 {
1977   tree res;
1978
1979   res = int_const_binop (code, val1, val2);
1980
1981   /* If we are using unsigned arithmetic, operate symbolically
1982      on -INF and +INF as int_const_binop only handles signed overflow.  */
1983   if (TYPE_UNSIGNED (TREE_TYPE (val1)))
1984     {
1985       int checkz = compare_values (res, val1);
1986       bool overflow = false;
1987
1988       /* Ensure that res = val1 [+*] val2 >= val1
1989          or that res = val1 - val2 <= val1.  */
1990       if ((code == PLUS_EXPR
1991            && !(checkz == 1 || checkz == 0))
1992           || (code == MINUS_EXPR
1993               && !(checkz == 0 || checkz == -1)))
1994         {
1995           overflow = true;
1996         }
1997       /* Checking for multiplication overflow is done by dividing the
1998          output of the multiplication by the first input of the
1999          multiplication.  If the result of that division operation is
2000          not equal to the second input of the multiplication, then the
2001          multiplication overflowed.  */
2002       else if (code == MULT_EXPR && !integer_zerop (val1))
2003         {
2004           tree tmp = int_const_binop (TRUNC_DIV_EXPR,
2005                                       res,
2006                                       val1);
2007           int check = compare_values (tmp, val2);
2008
2009           if (check != 0)
2010             overflow = true;
2011         }
2012
2013       if (overflow)
2014         {
2015           res = copy_node (res);
2016           TREE_OVERFLOW (res) = 1;
2017         }
2018
2019     }
2020   else if (TYPE_OVERFLOW_WRAPS (TREE_TYPE (val1)))
2021     /* If the singed operation wraps then int_const_binop has done
2022        everything we want.  */
2023     ;
2024   /* Signed division of -1/0 overflows and by the time it gets here
2025      returns NULL_TREE.  */
2026   else if (!res)
2027     return NULL_TREE;
2028   else if ((TREE_OVERFLOW (res)
2029             && !TREE_OVERFLOW (val1)
2030             && !TREE_OVERFLOW (val2))
2031            || is_overflow_infinity (val1)
2032            || is_overflow_infinity (val2))
2033     {
2034       /* If the operation overflowed but neither VAL1 nor VAL2 are
2035          overflown, return -INF or +INF depending on the operation
2036          and the combination of signs of the operands.  */
2037       int sgn1 = tree_int_cst_sgn (val1);
2038       int sgn2 = tree_int_cst_sgn (val2);
2039
2040       if (needs_overflow_infinity (TREE_TYPE (res))
2041           && !supports_overflow_infinity (TREE_TYPE (res)))
2042         return NULL_TREE;
2043
2044       /* We have to punt on adding infinities of different signs,
2045          since we can't tell what the sign of the result should be.
2046          Likewise for subtracting infinities of the same sign.  */
2047       if (((code == PLUS_EXPR && sgn1 != sgn2)
2048            || (code == MINUS_EXPR && sgn1 == sgn2))
2049           && is_overflow_infinity (val1)
2050           && is_overflow_infinity (val2))
2051         return NULL_TREE;
2052
2053       /* Don't try to handle division or shifting of infinities.  */
2054       if ((code == TRUNC_DIV_EXPR
2055            || code == FLOOR_DIV_EXPR
2056            || code == CEIL_DIV_EXPR
2057            || code == EXACT_DIV_EXPR
2058            || code == ROUND_DIV_EXPR
2059            || code == RSHIFT_EXPR)
2060           && (is_overflow_infinity (val1)
2061               || is_overflow_infinity (val2)))
2062         return NULL_TREE;
2063
2064       /* Notice that we only need to handle the restricted set of
2065          operations handled by extract_range_from_binary_expr.
2066          Among them, only multiplication, addition and subtraction
2067          can yield overflow without overflown operands because we
2068          are working with integral types only... except in the
2069          case VAL1 = -INF and VAL2 = -1 which overflows to +INF
2070          for division too.  */
2071
2072       /* For multiplication, the sign of the overflow is given
2073          by the comparison of the signs of the operands.  */
2074       if ((code == MULT_EXPR && sgn1 == sgn2)
2075           /* For addition, the operands must be of the same sign
2076              to yield an overflow.  Its sign is therefore that
2077              of one of the operands, for example the first.  For
2078              infinite operands X + -INF is negative, not positive.  */
2079           || (code == PLUS_EXPR
2080               && (sgn1 >= 0
2081                   ? !is_negative_overflow_infinity (val2)
2082                   : is_positive_overflow_infinity (val2)))
2083           /* For subtraction, non-infinite operands must be of
2084              different signs to yield an overflow.  Its sign is
2085              therefore that of the first operand or the opposite of
2086              that of the second operand.  A first operand of 0 counts
2087              as positive here, for the corner case 0 - (-INF), which
2088              overflows, but must yield +INF.  For infinite operands 0
2089              - INF is negative, not positive.  */
2090           || (code == MINUS_EXPR
2091               && (sgn1 >= 0
2092                   ? !is_positive_overflow_infinity (val2)
2093                   : is_negative_overflow_infinity (val2)))
2094           /* We only get in here with positive shift count, so the
2095              overflow direction is the same as the sign of val1.
2096              Actually rshift does not overflow at all, but we only
2097              handle the case of shifting overflowed -INF and +INF.  */
2098           || (code == RSHIFT_EXPR
2099               && sgn1 >= 0)
2100           /* For division, the only case is -INF / -1 = +INF.  */
2101           || code == TRUNC_DIV_EXPR
2102           || code == FLOOR_DIV_EXPR
2103           || code == CEIL_DIV_EXPR
2104           || code == EXACT_DIV_EXPR
2105           || code == ROUND_DIV_EXPR)
2106         return (needs_overflow_infinity (TREE_TYPE (res))
2107                 ? positive_overflow_infinity (TREE_TYPE (res))
2108                 : TYPE_MAX_VALUE (TREE_TYPE (res)));
2109       else
2110         return (needs_overflow_infinity (TREE_TYPE (res))
2111                 ? negative_overflow_infinity (TREE_TYPE (res))
2112                 : TYPE_MIN_VALUE (TREE_TYPE (res)));
2113     }
2114
2115   return res;
2116 }
2117
2118
2119 /* For range VR compute two wide_int bitmasks.  In *MAY_BE_NONZERO
2120    bitmask if some bit is unset, it means for all numbers in the range
2121    the bit is 0, otherwise it might be 0 or 1.  In *MUST_BE_NONZERO
2122    bitmask if some bit is set, it means for all numbers in the range
2123    the bit is 1, otherwise it might be 0 or 1.  */
2124
2125 static bool
2126 zero_nonzero_bits_from_vr (const tree expr_type,
2127                            value_range_t *vr,
2128                            wide_int *may_be_nonzero,
2129                            wide_int *must_be_nonzero)
2130 {
2131   *may_be_nonzero = wi::minus_one (TYPE_PRECISION (expr_type));
2132   *must_be_nonzero = wi::zero (TYPE_PRECISION (expr_type));
2133   if (!range_int_cst_p (vr)
2134       || is_overflow_infinity (vr->min)
2135       || is_overflow_infinity (vr->max))
2136     return false;
2137
2138   if (range_int_cst_singleton_p (vr))
2139     {
2140       *may_be_nonzero = vr->min;
2141       *must_be_nonzero = *may_be_nonzero;
2142     }
2143   else if (tree_int_cst_sgn (vr->min) >= 0
2144            || tree_int_cst_sgn (vr->max) < 0)
2145     {
2146       wide_int xor_mask = wi::bit_xor (vr->min, vr->max);
2147       *may_be_nonzero = wi::bit_or (vr->min, vr->max);
2148       *must_be_nonzero = wi::bit_and (vr->min, vr->max);
2149       if (xor_mask != 0)
2150         {
2151           wide_int mask = wi::mask (wi::floor_log2 (xor_mask), false,
2152                                     may_be_nonzero->get_precision ());
2153           *may_be_nonzero = *may_be_nonzero | mask;
2154           *must_be_nonzero = must_be_nonzero->and_not (mask);
2155         }
2156     }
2157
2158   return true;
2159 }
2160
2161 /* Create two value-ranges in *VR0 and *VR1 from the anti-range *AR
2162    so that *VR0 U *VR1 == *AR.  Returns true if that is possible,
2163    false otherwise.  If *AR can be represented with a single range
2164    *VR1 will be VR_UNDEFINED.  */
2165
2166 static bool
2167 ranges_from_anti_range (value_range_t *ar,
2168                         value_range_t *vr0, value_range_t *vr1)
2169 {
2170   tree type = TREE_TYPE (ar->min);
2171
2172   vr0->type = VR_UNDEFINED;
2173   vr1->type = VR_UNDEFINED;
2174
2175   if (ar->type != VR_ANTI_RANGE
2176       || TREE_CODE (ar->min) != INTEGER_CST
2177       || TREE_CODE (ar->max) != INTEGER_CST
2178       || !vrp_val_min (type)
2179       || !vrp_val_max (type))
2180     return false;
2181
2182   if (!vrp_val_is_min (ar->min))
2183     {
2184       vr0->type = VR_RANGE;
2185       vr0->min = vrp_val_min (type);
2186       vr0->max = wide_int_to_tree (type, wi::sub (ar->min, 1));
2187     }
2188   if (!vrp_val_is_max (ar->max))
2189     {
2190       vr1->type = VR_RANGE;
2191       vr1->min = wide_int_to_tree (type, wi::add (ar->max, 1));
2192       vr1->max = vrp_val_max (type);
2193     }
2194   if (vr0->type == VR_UNDEFINED)
2195     {
2196       *vr0 = *vr1;
2197       vr1->type = VR_UNDEFINED;
2198     }
2199
2200   return vr0->type != VR_UNDEFINED;
2201 }
2202
2203 /* Helper to extract a value-range *VR for a multiplicative operation
2204    *VR0 CODE *VR1.  */
2205
2206 static void
2207 extract_range_from_multiplicative_op_1 (value_range_t *vr,
2208                                         enum tree_code code,
2209                                         value_range_t *vr0, value_range_t *vr1)
2210 {
2211   enum value_range_type type;
2212   tree val[4];
2213   size_t i;
2214   tree min, max;
2215   bool sop;
2216   int cmp;
2217
2218   /* Multiplications, divisions and shifts are a bit tricky to handle,
2219      depending on the mix of signs we have in the two ranges, we
2220      need to operate on different values to get the minimum and
2221      maximum values for the new range.  One approach is to figure
2222      out all the variations of range combinations and do the
2223      operations.
2224
2225      However, this involves several calls to compare_values and it
2226      is pretty convoluted.  It's simpler to do the 4 operations
2227      (MIN0 OP MIN1, MIN0 OP MAX1, MAX0 OP MIN1 and MAX0 OP MAX0 OP
2228      MAX1) and then figure the smallest and largest values to form
2229      the new range.  */
2230   gcc_assert (code == MULT_EXPR
2231               || code == TRUNC_DIV_EXPR
2232               || code == FLOOR_DIV_EXPR
2233               || code == CEIL_DIV_EXPR
2234               || code == EXACT_DIV_EXPR
2235               || code == ROUND_DIV_EXPR
2236               || code == RSHIFT_EXPR
2237               || code == LSHIFT_EXPR);
2238   gcc_assert ((vr0->type == VR_RANGE
2239                || (code == MULT_EXPR && vr0->type == VR_ANTI_RANGE))
2240               && vr0->type == vr1->type);
2241
2242   type = vr0->type;
2243
2244   /* Compute the 4 cross operations.  */
2245   sop = false;
2246   val[0] = vrp_int_const_binop (code, vr0->min, vr1->min);
2247   if (val[0] == NULL_TREE)
2248     sop = true;
2249
2250   if (vr1->max == vr1->min)
2251     val[1] = NULL_TREE;
2252   else
2253     {
2254       val[1] = vrp_int_const_binop (code, vr0->min, vr1->max);
2255       if (val[1] == NULL_TREE)
2256         sop = true;
2257     }
2258
2259   if (vr0->max == vr0->min)
2260     val[2] = NULL_TREE;
2261   else
2262     {
2263       val[2] = vrp_int_const_binop (code, vr0->max, vr1->min);
2264       if (val[2] == NULL_TREE)
2265         sop = true;
2266     }
2267
2268   if (vr0->min == vr0->max || vr1->min == vr1->max)
2269     val[3] = NULL_TREE;
2270   else
2271     {
2272       val[3] = vrp_int_const_binop (code, vr0->max, vr1->max);
2273       if (val[3] == NULL_TREE)
2274         sop = true;
2275     }
2276
2277   if (sop)
2278     {
2279       set_value_range_to_varying (vr);
2280       return;
2281     }
2282
2283   /* Set MIN to the minimum of VAL[i] and MAX to the maximum
2284      of VAL[i].  */
2285   min = val[0];
2286   max = val[0];
2287   for (i = 1; i < 4; i++)
2288     {
2289       if (!is_gimple_min_invariant (min)
2290           || (TREE_OVERFLOW (min) && !is_overflow_infinity (min))
2291           || !is_gimple_min_invariant (max)
2292           || (TREE_OVERFLOW (max) && !is_overflow_infinity (max)))
2293         break;
2294
2295       if (val[i])
2296         {
2297           if (!is_gimple_min_invariant (val[i])
2298               || (TREE_OVERFLOW (val[i])
2299                   && !is_overflow_infinity (val[i])))
2300             {
2301               /* If we found an overflowed value, set MIN and MAX
2302                  to it so that we set the resulting range to
2303                  VARYING.  */
2304               min = max = val[i];
2305               break;
2306             }
2307
2308           if (compare_values (val[i], min) == -1)
2309             min = val[i];
2310
2311           if (compare_values (val[i], max) == 1)
2312             max = val[i];
2313         }
2314     }
2315
2316   /* If either MIN or MAX overflowed, then set the resulting range to
2317      VARYING.  But we do accept an overflow infinity
2318      representation.  */
2319   if (min == NULL_TREE
2320       || !is_gimple_min_invariant (min)
2321       || (TREE_OVERFLOW (min) && !is_overflow_infinity (min))
2322       || max == NULL_TREE
2323       || !is_gimple_min_invariant (max)
2324       || (TREE_OVERFLOW (max) && !is_overflow_infinity (max)))
2325     {
2326       set_value_range_to_varying (vr);
2327       return;
2328     }
2329
2330   /* We punt if:
2331      1) [-INF, +INF]
2332      2) [-INF, +-INF(OVF)]
2333      3) [+-INF(OVF), +INF]
2334      4) [+-INF(OVF), +-INF(OVF)]
2335      We learn nothing when we have INF and INF(OVF) on both sides.
2336      Note that we do accept [-INF, -INF] and [+INF, +INF] without
2337      overflow.  */
2338   if ((vrp_val_is_min (min) || is_overflow_infinity (min))
2339       && (vrp_val_is_max (max) || is_overflow_infinity (max)))
2340     {
2341       set_value_range_to_varying (vr);
2342       return;
2343     }
2344
2345   cmp = compare_values (min, max);
2346   if (cmp == -2 || cmp == 1)
2347     {
2348       /* If the new range has its limits swapped around (MIN > MAX),
2349          then the operation caused one of them to wrap around, mark
2350          the new range VARYING.  */
2351       set_value_range_to_varying (vr);
2352     }
2353   else
2354     set_value_range (vr, type, min, max, NULL);
2355 }
2356
2357 /* Extract range information from a binary operation CODE based on
2358    the ranges of each of its operands *VR0 and *VR1 with resulting
2359    type EXPR_TYPE.  The resulting range is stored in *VR.  */
2360
2361 static void
2362 extract_range_from_binary_expr_1 (value_range_t *vr,
2363                                   enum tree_code code, tree expr_type,
2364                                   value_range_t *vr0_, value_range_t *vr1_)
2365 {
2366   value_range_t vr0 = *vr0_, vr1 = *vr1_;
2367   value_range_t vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
2368   enum value_range_type type;
2369   tree min = NULL_TREE, max = NULL_TREE;
2370   int cmp;
2371
2372   if (!INTEGRAL_TYPE_P (expr_type)
2373       && !POINTER_TYPE_P (expr_type))
2374     {
2375       set_value_range_to_varying (vr);
2376       return;
2377     }
2378
2379   /* Not all binary expressions can be applied to ranges in a
2380      meaningful way.  Handle only arithmetic operations.  */
2381   if (code != PLUS_EXPR
2382       && code != MINUS_EXPR
2383       && code != POINTER_PLUS_EXPR
2384       && code != MULT_EXPR
2385       && code != TRUNC_DIV_EXPR
2386       && code != FLOOR_DIV_EXPR
2387       && code != CEIL_DIV_EXPR
2388       && code != EXACT_DIV_EXPR
2389       && code != ROUND_DIV_EXPR
2390       && code != TRUNC_MOD_EXPR
2391       && code != RSHIFT_EXPR
2392       && code != LSHIFT_EXPR
2393       && code != MIN_EXPR
2394       && code != MAX_EXPR
2395       && code != BIT_AND_EXPR
2396       && code != BIT_IOR_EXPR
2397       && code != BIT_XOR_EXPR)
2398     {
2399       set_value_range_to_varying (vr);
2400       return;
2401     }
2402
2403   /* If both ranges are UNDEFINED, so is the result.  */
2404   if (vr0.type == VR_UNDEFINED && vr1.type == VR_UNDEFINED)
2405     {
2406       set_value_range_to_undefined (vr);
2407       return;
2408     }
2409   /* If one of the ranges is UNDEFINED drop it to VARYING for the following
2410      code.  At some point we may want to special-case operations that
2411      have UNDEFINED result for all or some value-ranges of the not UNDEFINED
2412      operand.  */
2413   else if (vr0.type == VR_UNDEFINED)
2414     set_value_range_to_varying (&vr0);
2415   else if (vr1.type == VR_UNDEFINED)
2416     set_value_range_to_varying (&vr1);
2417
2418   /* Now canonicalize anti-ranges to ranges when they are not symbolic
2419      and express ~[] op X as ([]' op X) U ([]'' op X).  */
2420   if (vr0.type == VR_ANTI_RANGE
2421       && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
2422     {
2423       extract_range_from_binary_expr_1 (vr, code, expr_type, &vrtem0, vr1_);
2424       if (vrtem1.type != VR_UNDEFINED)
2425         {
2426           value_range_t vrres = VR_INITIALIZER;
2427           extract_range_from_binary_expr_1 (&vrres, code, expr_type,
2428                                             &vrtem1, vr1_);
2429           vrp_meet (vr, &vrres);
2430         }
2431       return;
2432     }
2433   /* Likewise for X op ~[].  */
2434   if (vr1.type == VR_ANTI_RANGE
2435       && ranges_from_anti_range (&vr1, &vrtem0, &vrtem1))
2436     {
2437       extract_range_from_binary_expr_1 (vr, code, expr_type, vr0_, &vrtem0);
2438       if (vrtem1.type != VR_UNDEFINED)
2439         {
2440           value_range_t vrres = VR_INITIALIZER;
2441           extract_range_from_binary_expr_1 (&vrres, code, expr_type,
2442                                             vr0_, &vrtem1);
2443           vrp_meet (vr, &vrres);
2444         }
2445       return;
2446     }
2447
2448   /* The type of the resulting value range defaults to VR0.TYPE.  */
2449   type = vr0.type;
2450
2451   /* Refuse to operate on VARYING ranges, ranges of different kinds
2452      and symbolic ranges.  As an exception, we allow BIT_{AND,IOR}
2453      because we may be able to derive a useful range even if one of
2454      the operands is VR_VARYING or symbolic range.  Similarly for
2455      divisions, MIN/MAX and PLUS/MINUS.
2456
2457      TODO, we may be able to derive anti-ranges in some cases.  */
2458   if (code != BIT_AND_EXPR
2459       && code != BIT_IOR_EXPR
2460       && code != TRUNC_DIV_EXPR
2461       && code != FLOOR_DIV_EXPR
2462       && code != CEIL_DIV_EXPR
2463       && code != EXACT_DIV_EXPR
2464       && code != ROUND_DIV_EXPR
2465       && code != TRUNC_MOD_EXPR
2466       && code != MIN_EXPR
2467       && code != MAX_EXPR
2468       && code != PLUS_EXPR
2469       && code != MINUS_EXPR
2470       && code != RSHIFT_EXPR
2471       && (vr0.type == VR_VARYING
2472           || vr1.type == VR_VARYING
2473           || vr0.type != vr1.type
2474           || symbolic_range_p (&vr0)
2475           || symbolic_range_p (&vr1)))
2476     {
2477       set_value_range_to_varying (vr);
2478       return;
2479     }
2480
2481   /* Now evaluate the expression to determine the new range.  */
2482   if (POINTER_TYPE_P (expr_type))
2483     {
2484       if (code == MIN_EXPR || code == MAX_EXPR)
2485         {
2486           /* For MIN/MAX expressions with pointers, we only care about
2487              nullness, if both are non null, then the result is nonnull.
2488              If both are null, then the result is null. Otherwise they
2489              are varying.  */
2490           if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
2491             set_value_range_to_nonnull (vr, expr_type);
2492           else if (range_is_null (&vr0) && range_is_null (&vr1))
2493             set_value_range_to_null (vr, expr_type);
2494           else
2495             set_value_range_to_varying (vr);
2496         }
2497       else if (code == POINTER_PLUS_EXPR)
2498         {
2499           /* For pointer types, we are really only interested in asserting
2500              whether the expression evaluates to non-NULL.  */
2501           if (range_is_nonnull (&vr0) || range_is_nonnull (&vr1))
2502             set_value_range_to_nonnull (vr, expr_type);
2503           else if (range_is_null (&vr0) && range_is_null (&vr1))
2504             set_value_range_to_null (vr, expr_type);
2505           else
2506             set_value_range_to_varying (vr);
2507         }
2508       else if (code == BIT_AND_EXPR)
2509         {
2510           /* For pointer types, we are really only interested in asserting
2511              whether the expression evaluates to non-NULL.  */
2512           if (range_is_nonnull (&vr0) && range_is_nonnull (&vr1))
2513             set_value_range_to_nonnull (vr, expr_type);
2514           else if (range_is_null (&vr0) || range_is_null (&vr1))
2515             set_value_range_to_null (vr, expr_type);
2516           else
2517             set_value_range_to_varying (vr);
2518         }
2519       else
2520         set_value_range_to_varying (vr);
2521
2522       return;
2523     }
2524
2525   /* For integer ranges, apply the operation to each end of the
2526      range and see what we end up with.  */
2527   if (code == PLUS_EXPR || code == MINUS_EXPR)
2528     {
2529       const bool minus_p = (code == MINUS_EXPR);
2530       tree min_op0 = vr0.min;
2531       tree min_op1 = minus_p ? vr1.max : vr1.min;
2532       tree max_op0 = vr0.max;
2533       tree max_op1 = minus_p ? vr1.min : vr1.max;
2534       tree sym_min_op0 = NULL_TREE;
2535       tree sym_min_op1 = NULL_TREE;
2536       tree sym_max_op0 = NULL_TREE;
2537       tree sym_max_op1 = NULL_TREE;
2538       bool neg_min_op0, neg_min_op1, neg_max_op0, neg_max_op1;
2539
2540       /* If we have a PLUS or MINUS with two VR_RANGEs, either constant or
2541          single-symbolic ranges, try to compute the precise resulting range,
2542          but only if we know that this resulting range will also be constant
2543          or single-symbolic.  */
2544       if (vr0.type == VR_RANGE && vr1.type == VR_RANGE
2545           && (TREE_CODE (min_op0) == INTEGER_CST
2546               || (sym_min_op0
2547                   = get_single_symbol (min_op0, &neg_min_op0, &min_op0)))
2548           && (TREE_CODE (min_op1) == INTEGER_CST
2549               || (sym_min_op1
2550                   = get_single_symbol (min_op1, &neg_min_op1, &min_op1)))
2551           && (!(sym_min_op0 && sym_min_op1)
2552               || (sym_min_op0 == sym_min_op1
2553                   && neg_min_op0 == (minus_p ? neg_min_op1 : !neg_min_op1)))
2554           && (TREE_CODE (max_op0) == INTEGER_CST
2555               || (sym_max_op0
2556                   = get_single_symbol (max_op0, &neg_max_op0, &max_op0)))
2557           && (TREE_CODE (max_op1) == INTEGER_CST
2558               || (sym_max_op1
2559                   = get_single_symbol (max_op1, &neg_max_op1, &max_op1)))
2560           && (!(sym_max_op0 && sym_max_op1)
2561               || (sym_max_op0 == sym_max_op1
2562                   && neg_max_op0 == (minus_p ? neg_max_op1 : !neg_max_op1))))
2563         {
2564           const signop sgn = TYPE_SIGN (expr_type);
2565           const unsigned int prec = TYPE_PRECISION (expr_type);
2566           wide_int type_min, type_max, wmin, wmax;
2567           int min_ovf = 0;
2568           int max_ovf = 0;
2569
2570           /* Get the lower and upper bounds of the type.  */
2571           if (TYPE_OVERFLOW_WRAPS (expr_type))
2572             {
2573               type_min = wi::min_value (prec, sgn);
2574               type_max = wi::max_value (prec, sgn);
2575             }
2576           else
2577             {
2578               type_min = vrp_val_min (expr_type);
2579               type_max = vrp_val_max (expr_type);
2580             }
2581
2582           /* Combine the lower bounds, if any.  */
2583           if (min_op0 && min_op1)
2584             {
2585               if (minus_p)
2586                 {
2587                   wmin = wi::sub (min_op0, min_op1);
2588
2589                   /* Check for overflow.  */
2590                   if (wi::cmp (0, min_op1, sgn)
2591                       != wi::cmp (wmin, min_op0, sgn))
2592                     min_ovf = wi::cmp (min_op0, min_op1, sgn);
2593                 }
2594               else
2595                 {
2596                   wmin = wi::add (min_op0, min_op1);
2597
2598                   /* Check for overflow.  */
2599                   if (wi::cmp (min_op1, 0, sgn)
2600                       != wi::cmp (wmin, min_op0, sgn))
2601                     min_ovf = wi::cmp (min_op0, wmin, sgn);
2602                 }
2603             }
2604           else if (min_op0)
2605             wmin = min_op0;
2606           else if (min_op1)
2607             wmin = minus_p ? wi::neg (min_op1) : min_op1;
2608           else
2609             wmin = wi::shwi (0, prec);
2610
2611           /* Combine the upper bounds, if any.  */
2612           if (max_op0 && max_op1)
2613             {
2614               if (minus_p)
2615                 {
2616                   wmax = wi::sub (max_op0, max_op1);
2617
2618                   /* Check for overflow.  */
2619                   if (wi::cmp (0, max_op1, sgn)
2620                       != wi::cmp (wmax, max_op0, sgn))
2621                     max_ovf = wi::cmp (max_op0, max_op1, sgn);
2622                 }
2623               else
2624                 {
2625                   wmax = wi::add (max_op0, max_op1);
2626
2627                   if (wi::cmp (max_op1, 0, sgn)
2628                       != wi::cmp (wmax, max_op0, sgn))
2629                     max_ovf = wi::cmp (max_op0, wmax, sgn);
2630                 }
2631             }
2632           else if (max_op0)
2633             wmax = max_op0;
2634           else if (max_op1)
2635             wmax = minus_p ? wi::neg (max_op1) : max_op1;
2636           else
2637             wmax = wi::shwi (0, prec);
2638
2639           /* Check for type overflow.  */
2640           if (min_ovf == 0)
2641             {
2642               if (wi::cmp (wmin, type_min, sgn) == -1)
2643                 min_ovf = -1;
2644               else if (wi::cmp (wmin, type_max, sgn) == 1)
2645                 min_ovf = 1;
2646             }
2647           if (max_ovf == 0)
2648             {
2649               if (wi::cmp (wmax, type_min, sgn) == -1)
2650                 max_ovf = -1;
2651               else if (wi::cmp (wmax, type_max, sgn) == 1)
2652                 max_ovf = 1;
2653             }
2654
2655           /* If we have overflow for the constant part and the resulting
2656              range will be symbolic, drop to VR_VARYING.  */
2657           if ((min_ovf && sym_min_op0 != sym_min_op1)
2658               || (max_ovf && sym_max_op0 != sym_max_op1))
2659             {
2660               set_value_range_to_varying (vr);
2661               return;
2662             }
2663
2664           if (TYPE_OVERFLOW_WRAPS (expr_type))
2665             {
2666               /* If overflow wraps, truncate the values and adjust the
2667                  range kind and bounds appropriately.  */
2668               wide_int tmin = wide_int::from (wmin, prec, sgn);
2669               wide_int tmax = wide_int::from (wmax, prec, sgn);
2670               if (min_ovf == max_ovf)
2671                 {
2672                   /* No overflow or both overflow or underflow.  The
2673                      range kind stays VR_RANGE.  */
2674                   min = wide_int_to_tree (expr_type, tmin);
2675                   max = wide_int_to_tree (expr_type, tmax);
2676                 }
2677               else if (min_ovf == -1 && max_ovf == 1)
2678                 {
2679                   /* Underflow and overflow, drop to VR_VARYING.  */
2680                   set_value_range_to_varying (vr);
2681                   return;
2682                 }
2683               else
2684                 {
2685                   /* Min underflow or max overflow.  The range kind
2686                      changes to VR_ANTI_RANGE.  */
2687                   bool covers = false;
2688                   wide_int tem = tmin;
2689                   gcc_assert ((min_ovf == -1 && max_ovf == 0)
2690                               || (max_ovf == 1 && min_ovf == 0));
2691                   type = VR_ANTI_RANGE;
2692                   tmin = tmax + 1;
2693                   if (wi::cmp (tmin, tmax, sgn) < 0)
2694                     covers = true;
2695                   tmax = tem - 1;
2696                   if (wi::cmp (tmax, tem, sgn) > 0)
2697                     covers = true;
2698                   /* If the anti-range would cover nothing, drop to varying.
2699                      Likewise if the anti-range bounds are outside of the
2700                      types values.  */
2701                   if (covers || wi::cmp (tmin, tmax, sgn) > 0)
2702                     {
2703                       set_value_range_to_varying (vr);
2704                       return;
2705                     }
2706                   min = wide_int_to_tree (expr_type, tmin);
2707                   max = wide_int_to_tree (expr_type, tmax);
2708                 }
2709             }
2710           else
2711             {
2712               /* If overflow does not wrap, saturate to the types min/max
2713                  value.  */
2714               if (min_ovf == -1)
2715                 {
2716                   if (needs_overflow_infinity (expr_type)
2717                       && supports_overflow_infinity (expr_type))
2718                     min = negative_overflow_infinity (expr_type);
2719                   else
2720                     min = wide_int_to_tree (expr_type, type_min);
2721                 }
2722               else if (min_ovf == 1)
2723                 {
2724                   if (needs_overflow_infinity (expr_type)
2725                       && supports_overflow_infinity (expr_type))
2726                     min = positive_overflow_infinity (expr_type);
2727                   else
2728                     min = wide_int_to_tree (expr_type, type_max);
2729                 }
2730               else
2731                 min = wide_int_to_tree (expr_type, wmin);
2732
2733               if (max_ovf == -1)
2734                 {
2735                   if (needs_overflow_infinity (expr_type)
2736                       && supports_overflow_infinity (expr_type))
2737                     max = negative_overflow_infinity (expr_type);
2738                   else
2739                     max = wide_int_to_tree (expr_type, type_min);
2740                 }
2741               else if (max_ovf == 1)
2742                 {
2743                   if (needs_overflow_infinity (expr_type)
2744                       && supports_overflow_infinity (expr_type))
2745                     max = positive_overflow_infinity (expr_type);
2746                   else
2747                     max = wide_int_to_tree (expr_type, type_max);
2748                 }
2749               else
2750                 max = wide_int_to_tree (expr_type, wmax);
2751             }
2752
2753           if (needs_overflow_infinity (expr_type)
2754               && supports_overflow_infinity (expr_type))
2755             {
2756               if ((min_op0 && is_negative_overflow_infinity (min_op0))
2757                   || (min_op1
2758                       && (minus_p
2759                           ? is_positive_overflow_infinity (min_op1)
2760                           : is_negative_overflow_infinity (min_op1))))
2761                 min = negative_overflow_infinity (expr_type);
2762               if ((max_op0 && is_positive_overflow_infinity (max_op0))
2763                   || (max_op1
2764                       && (minus_p
2765                           ? is_negative_overflow_infinity (max_op1)
2766                           : is_positive_overflow_infinity (max_op1))))
2767                 max = positive_overflow_infinity (expr_type);
2768             }
2769
2770           /* If the result lower bound is constant, we're done;
2771              otherwise, build the symbolic lower bound.  */
2772           if (sym_min_op0 == sym_min_op1)
2773             ;
2774           else if (sym_min_op0)
2775             min = build_symbolic_expr (expr_type, sym_min_op0,
2776                                        neg_min_op0, min);
2777           else if (sym_min_op1)
2778             min = build_symbolic_expr (expr_type, sym_min_op1,
2779                                        neg_min_op1 ^ minus_p, min);
2780
2781           /* Likewise for the upper bound.  */
2782           if (sym_max_op0 == sym_max_op1)
2783             ;
2784           else if (sym_max_op0)
2785             max = build_symbolic_expr (expr_type, sym_max_op0,
2786                                        neg_max_op0, max);
2787           else if (sym_max_op1)
2788             max = build_symbolic_expr (expr_type, sym_max_op1,
2789                                        neg_max_op1 ^ minus_p, max);
2790         }
2791       else
2792         {
2793           /* For other cases, for example if we have a PLUS_EXPR with two
2794              VR_ANTI_RANGEs, drop to VR_VARYING.  It would take more effort
2795              to compute a precise range for such a case.
2796              ???  General even mixed range kind operations can be expressed
2797              by for example transforming ~[3, 5] + [1, 2] to range-only
2798              operations and a union primitive:
2799                [-INF, 2] + [1, 2]  U  [5, +INF] + [1, 2]
2800                    [-INF+1, 4]     U    [6, +INF(OVF)]
2801              though usually the union is not exactly representable with
2802              a single range or anti-range as the above is
2803                  [-INF+1, +INF(OVF)] intersected with ~[5, 5]
2804              but one could use a scheme similar to equivalences for this. */
2805           set_value_range_to_varying (vr);
2806           return;
2807         }
2808     }
2809   else if (code == MIN_EXPR
2810            || code == MAX_EXPR)
2811     {
2812       if (vr0.type == VR_RANGE
2813           && !symbolic_range_p (&vr0))
2814         {
2815           type = VR_RANGE;
2816           if (vr1.type == VR_RANGE
2817               && !symbolic_range_p (&vr1))
2818             {
2819               /* For operations that make the resulting range directly
2820                  proportional to the original ranges, apply the operation to
2821                  the same end of each range.  */
2822               min = vrp_int_const_binop (code, vr0.min, vr1.min);
2823               max = vrp_int_const_binop (code, vr0.max, vr1.max);
2824             }
2825           else if (code == MIN_EXPR)
2826             {
2827               min = vrp_val_min (expr_type);
2828               max = vr0.max;
2829             }
2830           else if (code == MAX_EXPR)
2831             {
2832               min = vr0.min;
2833               max = vrp_val_max (expr_type);
2834             }
2835         }
2836       else if (vr1.type == VR_RANGE
2837                && !symbolic_range_p (&vr1))
2838         {
2839           type = VR_RANGE;
2840           if (code == MIN_EXPR)
2841             {
2842               min = vrp_val_min (expr_type);
2843               max = vr1.max;
2844             }
2845           else if (code == MAX_EXPR)
2846             {
2847               min = vr1.min;
2848               max = vrp_val_max (expr_type);
2849             }
2850         }
2851       else
2852         {
2853           set_value_range_to_varying (vr);
2854           return;
2855         }
2856     }
2857   else if (code == MULT_EXPR)
2858     {
2859       /* Fancy code so that with unsigned, [-3,-1]*[-3,-1] does not
2860          drop to varying.  This test requires 2*prec bits if both
2861          operands are signed and 2*prec + 2 bits if either is not.  */
2862
2863       signop sign = TYPE_SIGN (expr_type);
2864       unsigned int prec = TYPE_PRECISION (expr_type);
2865
2866       if (range_int_cst_p (&vr0)
2867           && range_int_cst_p (&vr1)
2868           && TYPE_OVERFLOW_WRAPS (expr_type))
2869         {
2870           typedef FIXED_WIDE_INT (WIDE_INT_MAX_PRECISION * 2) vrp_int;
2871           typedef generic_wide_int
2872              <wi::extended_tree <WIDE_INT_MAX_PRECISION * 2> > vrp_int_cst;
2873           vrp_int sizem1 = wi::mask <vrp_int> (prec, false);
2874           vrp_int size = sizem1 + 1;
2875
2876           /* Extend the values using the sign of the result to PREC2.
2877              From here on out, everthing is just signed math no matter
2878              what the input types were.  */
2879           vrp_int min0 = vrp_int_cst (vr0.min);
2880           vrp_int max0 = vrp_int_cst (vr0.max);
2881           vrp_int min1 = vrp_int_cst (vr1.min);
2882           vrp_int max1 = vrp_int_cst (vr1.max);
2883           /* Canonicalize the intervals.  */
2884           if (sign == UNSIGNED)
2885             {
2886               if (wi::ltu_p (size, min0 + max0))
2887                 {
2888                   min0 -= size;
2889                   max0 -= size;
2890                 }
2891
2892               if (wi::ltu_p (size, min1 + max1))
2893                 {
2894                   min1 -= size;
2895                   max1 -= size;
2896                 }
2897             }
2898
2899           vrp_int prod0 = min0 * min1;
2900           vrp_int prod1 = min0 * max1;
2901           vrp_int prod2 = max0 * min1;
2902           vrp_int prod3 = max0 * max1;
2903
2904           /* Sort the 4 products so that min is in prod0 and max is in
2905              prod3.  */
2906           /* min0min1 > max0max1 */
2907           if (wi::gts_p (prod0, prod3))
2908             {
2909               vrp_int tmp = prod3;
2910               prod3 = prod0;
2911               prod0 = tmp;
2912             }
2913
2914           /* min0max1 > max0min1 */
2915           if (wi::gts_p (prod1, prod2))
2916             {
2917               vrp_int tmp = prod2;
2918               prod2 = prod1;
2919               prod1 = tmp;
2920             }
2921
2922           if (wi::gts_p (prod0, prod1))
2923             {
2924               vrp_int tmp = prod1;
2925               prod1 = prod0;
2926               prod0 = tmp;
2927             }
2928
2929           if (wi::gts_p (prod2, prod3))
2930             {
2931               vrp_int tmp = prod3;
2932               prod3 = prod2;
2933               prod2 = tmp;
2934             }
2935
2936           /* diff = max - min.  */
2937           prod2 = prod3 - prod0;
2938           if (wi::geu_p (prod2, sizem1))
2939             {
2940               /* the range covers all values.  */
2941               set_value_range_to_varying (vr);
2942               return;
2943             }
2944
2945           /* The following should handle the wrapping and selecting
2946              VR_ANTI_RANGE for us.  */
2947           min = wide_int_to_tree (expr_type, prod0);
2948           max = wide_int_to_tree (expr_type, prod3);
2949           set_and_canonicalize_value_range (vr, VR_RANGE, min, max, NULL);
2950           return;
2951         }
2952
2953       /* If we have an unsigned MULT_EXPR with two VR_ANTI_RANGEs,
2954          drop to VR_VARYING.  It would take more effort to compute a
2955          precise range for such a case.  For example, if we have
2956          op0 == 65536 and op1 == 65536 with their ranges both being
2957          ~[0,0] on a 32-bit machine, we would have op0 * op1 == 0, so
2958          we cannot claim that the product is in ~[0,0].  Note that we
2959          are guaranteed to have vr0.type == vr1.type at this
2960          point.  */
2961       if (vr0.type == VR_ANTI_RANGE
2962           && !TYPE_OVERFLOW_UNDEFINED (expr_type))
2963         {
2964           set_value_range_to_varying (vr);
2965           return;
2966         }
2967
2968       extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2969       return;
2970     }
2971   else if (code == RSHIFT_EXPR
2972            || code == LSHIFT_EXPR)
2973     {
2974       /* If we have a RSHIFT_EXPR with any shift values outside [0..prec-1],
2975          then drop to VR_VARYING.  Outside of this range we get undefined
2976          behavior from the shift operation.  We cannot even trust
2977          SHIFT_COUNT_TRUNCATED at this stage, because that applies to rtl
2978          shifts, and the operation at the tree level may be widened.  */
2979       if (range_int_cst_p (&vr1)
2980           && compare_tree_int (vr1.min, 0) >= 0
2981           && compare_tree_int (vr1.max, TYPE_PRECISION (expr_type)) == -1)
2982         {
2983           if (code == RSHIFT_EXPR)
2984             {
2985               /* Even if vr0 is VARYING or otherwise not usable, we can derive
2986                  useful ranges just from the shift count.  E.g.
2987                  x >> 63 for signed 64-bit x is always [-1, 0].  */
2988               if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
2989                 {
2990                   vr0.type = type = VR_RANGE;
2991                   vr0.min = vrp_val_min (expr_type);
2992                   vr0.max = vrp_val_max (expr_type);
2993                 }
2994               extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
2995               return;
2996             }
2997           /* We can map lshifts by constants to MULT_EXPR handling.  */
2998           else if (code == LSHIFT_EXPR
2999                    && range_int_cst_singleton_p (&vr1))
3000             {
3001               bool saved_flag_wrapv;
3002               value_range_t vr1p = VR_INITIALIZER;
3003               vr1p.type = VR_RANGE;
3004               vr1p.min = (wide_int_to_tree
3005                           (expr_type,
3006                            wi::set_bit_in_zero (tree_to_shwi (vr1.min),
3007                                                 TYPE_PRECISION (expr_type))));
3008               vr1p.max = vr1p.min;
3009               /* We have to use a wrapping multiply though as signed overflow
3010                  on lshifts is implementation defined in C89.  */
3011               saved_flag_wrapv = flag_wrapv;
3012               flag_wrapv = 1;
3013               extract_range_from_binary_expr_1 (vr, MULT_EXPR, expr_type,
3014                                                 &vr0, &vr1p);
3015               flag_wrapv = saved_flag_wrapv;
3016               return;
3017             }
3018           else if (code == LSHIFT_EXPR
3019                    && range_int_cst_p (&vr0))
3020             {
3021               int prec = TYPE_PRECISION (expr_type);
3022               int overflow_pos = prec;
3023               int bound_shift;
3024               wide_int low_bound, high_bound;
3025               bool uns = TYPE_UNSIGNED (expr_type);
3026               bool in_bounds = false;
3027
3028               if (!uns)
3029                 overflow_pos -= 1;
3030
3031               bound_shift = overflow_pos - tree_to_shwi (vr1.max);
3032               /* If bound_shift == HOST_BITS_PER_WIDE_INT, the llshift can
3033                  overflow.  However, for that to happen, vr1.max needs to be
3034                  zero, which means vr1 is a singleton range of zero, which
3035                  means it should be handled by the previous LSHIFT_EXPR
3036                  if-clause.  */
3037               wide_int bound = wi::set_bit_in_zero (bound_shift, prec);
3038               wide_int complement = ~(bound - 1);
3039
3040               if (uns)
3041                 {
3042                   low_bound = bound;
3043                   high_bound = complement;
3044                   if (wi::ltu_p (vr0.max, low_bound))
3045                     {
3046                       /* [5, 6] << [1, 2] == [10, 24].  */
3047                       /* We're shifting out only zeroes, the value increases
3048                          monotonically.  */
3049                       in_bounds = true;
3050                     }
3051                   else if (wi::ltu_p (high_bound, vr0.min))
3052                     {
3053                       /* [0xffffff00, 0xffffffff] << [1, 2]
3054                          == [0xfffffc00, 0xfffffffe].  */
3055                       /* We're shifting out only ones, the value decreases
3056                          monotonically.  */
3057                       in_bounds = true;
3058                     }
3059                 }
3060               else
3061                 {
3062                   /* [-1, 1] << [1, 2] == [-4, 4].  */
3063                   low_bound = complement;
3064                   high_bound = bound;
3065                   if (wi::lts_p (vr0.max, high_bound)
3066                       && wi::lts_p (low_bound, vr0.min))
3067                     {
3068                       /* For non-negative numbers, we're shifting out only
3069                          zeroes, the value increases monotonically.
3070                          For negative numbers, we're shifting out only ones, the
3071                          value decreases monotomically.  */
3072                       in_bounds = true;
3073                     }
3074                 }
3075
3076               if (in_bounds)
3077                 {
3078                   extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
3079                   return;
3080                 }
3081             }
3082         }
3083       set_value_range_to_varying (vr);
3084       return;
3085     }
3086   else if (code == TRUNC_DIV_EXPR
3087            || code == FLOOR_DIV_EXPR
3088            || code == CEIL_DIV_EXPR
3089            || code == EXACT_DIV_EXPR
3090            || code == ROUND_DIV_EXPR)
3091     {
3092       if (vr0.type != VR_RANGE || symbolic_range_p (&vr0))
3093         {
3094           /* For division, if op1 has VR_RANGE but op0 does not, something
3095              can be deduced just from that range.  Say [min, max] / [4, max]
3096              gives [min / 4, max / 4] range.  */
3097           if (vr1.type == VR_RANGE
3098               && !symbolic_range_p (&vr1)
3099               && range_includes_zero_p (vr1.min, vr1.max) == 0)
3100             {
3101               vr0.type = type = VR_RANGE;
3102               vr0.min = vrp_val_min (expr_type);
3103               vr0.max = vrp_val_max (expr_type);
3104             }
3105           else
3106             {
3107               set_value_range_to_varying (vr);
3108               return;
3109             }
3110         }
3111
3112       /* For divisions, if flag_non_call_exceptions is true, we must
3113          not eliminate a division by zero.  */
3114       if (cfun->can_throw_non_call_exceptions
3115           && (vr1.type != VR_RANGE
3116               || range_includes_zero_p (vr1.min, vr1.max) != 0))
3117         {
3118           set_value_range_to_varying (vr);
3119           return;
3120         }
3121
3122       /* For divisions, if op0 is VR_RANGE, we can deduce a range
3123          even if op1 is VR_VARYING, VR_ANTI_RANGE, symbolic or can
3124          include 0.  */
3125       if (vr0.type == VR_RANGE
3126           && (vr1.type != VR_RANGE
3127               || range_includes_zero_p (vr1.min, vr1.max) != 0))
3128         {
3129           tree zero = build_int_cst (TREE_TYPE (vr0.min), 0);
3130           int cmp;
3131
3132           min = NULL_TREE;
3133           max = NULL_TREE;
3134           if (TYPE_UNSIGNED (expr_type)
3135               || value_range_nonnegative_p (&vr1))
3136             {
3137               /* For unsigned division or when divisor is known
3138                  to be non-negative, the range has to cover
3139                  all numbers from 0 to max for positive max
3140                  and all numbers from min to 0 for negative min.  */
3141               cmp = compare_values (vr0.max, zero);
3142               if (cmp == -1)
3143                 max = zero;
3144               else if (cmp == 0 || cmp == 1)
3145                 max = vr0.max;
3146               else
3147                 type = VR_VARYING;
3148               cmp = compare_values (vr0.min, zero);
3149               if (cmp == 1)
3150                 min = zero;
3151               else if (cmp == 0 || cmp == -1)
3152                 min = vr0.min;
3153               else
3154                 type = VR_VARYING;
3155             }
3156           else
3157             {
3158               /* Otherwise the range is -max .. max or min .. -min
3159                  depending on which bound is bigger in absolute value,
3160                  as the division can change the sign.  */
3161               abs_extent_range (vr, vr0.min, vr0.max);
3162               return;
3163             }
3164           if (type == VR_VARYING)
3165             {
3166               set_value_range_to_varying (vr);
3167               return;
3168             }
3169         }
3170       else
3171         {
3172           extract_range_from_multiplicative_op_1 (vr, code, &vr0, &vr1);
3173           return;
3174         }
3175     }
3176   else if (code == TRUNC_MOD_EXPR)
3177     {
3178       if (vr1.type != VR_RANGE
3179           || range_includes_zero_p (vr1.min, vr1.max) != 0
3180           || vrp_val_is_min (vr1.min))
3181         {
3182           set_value_range_to_varying (vr);
3183           return;
3184         }
3185       type = VR_RANGE;
3186       /* Compute MAX <|vr1.min|, |vr1.max|> - 1.  */
3187       max = fold_unary_to_constant (ABS_EXPR, expr_type, vr1.min);
3188       if (tree_int_cst_lt (max, vr1.max))
3189         max = vr1.max;
3190       max = int_const_binop (MINUS_EXPR, max, build_int_cst (TREE_TYPE (max), 1));
3191       /* If the dividend is non-negative the modulus will be
3192          non-negative as well.  */
3193       if (TYPE_UNSIGNED (expr_type)
3194           || value_range_nonnegative_p (&vr0))
3195         min = build_int_cst (TREE_TYPE (max), 0);
3196       else
3197         min = fold_unary_to_constant (NEGATE_EXPR, expr_type, max);
3198     }
3199   else if (code == BIT_AND_EXPR || code == BIT_IOR_EXPR || code == BIT_XOR_EXPR)
3200     {
3201       bool int_cst_range0, int_cst_range1;
3202       wide_int may_be_nonzero0, may_be_nonzero1;
3203       wide_int must_be_nonzero0, must_be_nonzero1;
3204
3205       int_cst_range0 = zero_nonzero_bits_from_vr (expr_type, &vr0,
3206                                                   &may_be_nonzero0,
3207                                                   &must_be_nonzero0);
3208       int_cst_range1 = zero_nonzero_bits_from_vr (expr_type, &vr1,
3209                                                   &may_be_nonzero1,
3210                                                   &must_be_nonzero1);
3211
3212       type = VR_RANGE;
3213       if (code == BIT_AND_EXPR)
3214         {
3215           min = wide_int_to_tree (expr_type,
3216                                   must_be_nonzero0 & must_be_nonzero1);
3217           wide_int wmax = may_be_nonzero0 & may_be_nonzero1;
3218           /* If both input ranges contain only negative values we can
3219              truncate the result range maximum to the minimum of the
3220              input range maxima.  */
3221           if (int_cst_range0 && int_cst_range1
3222               && tree_int_cst_sgn (vr0.max) < 0
3223               && tree_int_cst_sgn (vr1.max) < 0)
3224             {
3225               wmax = wi::min (wmax, vr0.max, TYPE_SIGN (expr_type));
3226               wmax = wi::min (wmax, vr1.max, TYPE_SIGN (expr_type));
3227             }
3228           /* If either input range contains only non-negative values
3229              we can truncate the result range maximum to the respective
3230              maximum of the input range.  */
3231           if (int_cst_range0 && tree_int_cst_sgn (vr0.min) >= 0)
3232             wmax = wi::min (wmax, vr0.max, TYPE_SIGN (expr_type));
3233           if (int_cst_range1 && tree_int_cst_sgn (vr1.min) >= 0)
3234             wmax = wi::min (wmax, vr1.max, TYPE_SIGN (expr_type));
3235           max = wide_int_to_tree (expr_type, wmax);
3236         }
3237       else if (code == BIT_IOR_EXPR)
3238         {
3239           max = wide_int_to_tree (expr_type,
3240                                   may_be_nonzero0 | may_be_nonzero1);
3241           wide_int wmin = must_be_nonzero0 | must_be_nonzero1;
3242           /* If the input ranges contain only positive values we can
3243              truncate the minimum of the result range to the maximum
3244              of the input range minima.  */
3245           if (int_cst_range0 && int_cst_range1
3246               && tree_int_cst_sgn (vr0.min) >= 0
3247               && tree_int_cst_sgn (vr1.min) >= 0)
3248             {
3249               wmin = wi::max (wmin, vr0.min, TYPE_SIGN (expr_type));
3250               wmin = wi::max (wmin, vr1.min, TYPE_SIGN (expr_type));
3251             }
3252           /* If either input range contains only negative values
3253              we can truncate the minimum of the result range to the
3254              respective minimum range.  */
3255           if (int_cst_range0 && tree_int_cst_sgn (vr0.max) < 0)
3256             wmin = wi::max (wmin, vr0.min, TYPE_SIGN (expr_type));
3257           if (int_cst_range1 && tree_int_cst_sgn (vr1.max) < 0)
3258             wmin = wi::max (wmin, vr1.min, TYPE_SIGN (expr_type));
3259           min = wide_int_to_tree (expr_type, wmin);
3260         }
3261       else if (code == BIT_XOR_EXPR)
3262         {
3263           wide_int result_zero_bits = ((must_be_nonzero0 & must_be_nonzero1)
3264                                        | ~(may_be_nonzero0 | may_be_nonzero1));
3265           wide_int result_one_bits
3266             = (must_be_nonzero0.and_not (may_be_nonzero1)
3267                | must_be_nonzero1.and_not (may_be_nonzero0));
3268           max = wide_int_to_tree (expr_type, ~result_zero_bits);
3269           min = wide_int_to_tree (expr_type, result_one_bits);
3270           /* If the range has all positive or all negative values the
3271              result is better than VARYING.  */
3272           if (tree_int_cst_sgn (min) < 0
3273               || tree_int_cst_sgn (max) >= 0)
3274             ;
3275           else
3276             max = min = NULL_TREE;
3277         }
3278     }
3279   else
3280     gcc_unreachable ();
3281
3282   /* If either MIN or MAX overflowed, then set the resulting range to
3283      VARYING.  But we do accept an overflow infinity representation.  */
3284   if (min == NULL_TREE
3285       || (TREE_OVERFLOW_P (min) && !is_overflow_infinity (min))
3286       || max == NULL_TREE
3287       || (TREE_OVERFLOW_P (max) && !is_overflow_infinity (max)))
3288     {
3289       set_value_range_to_varying (vr);
3290       return;
3291     }
3292
3293   /* We punt if:
3294      1) [-INF, +INF]
3295      2) [-INF, +-INF(OVF)]
3296      3) [+-INF(OVF), +INF]
3297      4) [+-INF(OVF), +-INF(OVF)]
3298      We learn nothing when we have INF and INF(OVF) on both sides.
3299      Note that we do accept [-INF, -INF] and [+INF, +INF] without
3300      overflow.  */
3301   if ((vrp_val_is_min (min) || is_overflow_infinity (min))
3302       && (vrp_val_is_max (max) || is_overflow_infinity (max)))
3303     {
3304       set_value_range_to_varying (vr);
3305       return;
3306     }
3307
3308   cmp = compare_values (min, max);
3309   if (cmp == -2 || cmp == 1)
3310     {
3311       /* If the new range has its limits swapped around (MIN > MAX),
3312          then the operation caused one of them to wrap around, mark
3313          the new range VARYING.  */
3314       set_value_range_to_varying (vr);
3315     }
3316   else
3317     set_value_range (vr, type, min, max, NULL);
3318 }
3319
3320 /* Extract range information from a binary expression OP0 CODE OP1 based on
3321    the ranges of each of its operands with resulting type EXPR_TYPE.
3322    The resulting range is stored in *VR.  */
3323
3324 static void
3325 extract_range_from_binary_expr (value_range_t *vr,
3326                                 enum tree_code code,
3327                                 tree expr_type, tree op0, tree op1)
3328 {
3329   value_range_t vr0 = VR_INITIALIZER;
3330   value_range_t vr1 = VR_INITIALIZER;
3331
3332   /* Get value ranges for each operand.  For constant operands, create
3333      a new value range with the operand to simplify processing.  */
3334   if (TREE_CODE (op0) == SSA_NAME)
3335     vr0 = *(get_value_range (op0));
3336   else if (is_gimple_min_invariant (op0))
3337     set_value_range_to_value (&vr0, op0, NULL);
3338   else
3339     set_value_range_to_varying (&vr0);
3340
3341   if (TREE_CODE (op1) == SSA_NAME)
3342     vr1 = *(get_value_range (op1));
3343   else if (is_gimple_min_invariant (op1))
3344     set_value_range_to_value (&vr1, op1, NULL);
3345   else
3346     set_value_range_to_varying (&vr1);
3347
3348   extract_range_from_binary_expr_1 (vr, code, expr_type, &vr0, &vr1);
3349
3350   /* Try harder for PLUS and MINUS if the range of one operand is symbolic
3351      and based on the other operand, for example if it was deduced from a
3352      symbolic comparison.  When a bound of the range of the first operand
3353      is invariant, we set the corresponding bound of the new range to INF
3354      in order to avoid recursing on the range of the second operand.  */
3355   if (vr->type == VR_VARYING
3356       && (code == PLUS_EXPR || code == MINUS_EXPR)
3357       && TREE_CODE (op1) == SSA_NAME
3358       && vr0.type == VR_RANGE
3359       && symbolic_range_based_on_p (&vr0, op1))
3360     {
3361       const bool minus_p = (code == MINUS_EXPR);
3362       value_range_t n_vr1 = VR_INITIALIZER;
3363
3364       /* Try with VR0 and [-INF, OP1].  */
3365       if (is_gimple_min_invariant (minus_p ? vr0.max : vr0.min))
3366         set_value_range (&n_vr1, VR_RANGE, vrp_val_min (expr_type), op1, NULL);
3367
3368       /* Try with VR0 and [OP1, +INF].  */
3369       else if (is_gimple_min_invariant (minus_p ? vr0.min : vr0.max))
3370         set_value_range (&n_vr1, VR_RANGE, op1, vrp_val_max (expr_type), NULL);
3371
3372       /* Try with VR0 and [OP1, OP1].  */
3373       else
3374         set_value_range (&n_vr1, VR_RANGE, op1, op1, NULL);
3375
3376       extract_range_from_binary_expr_1 (vr, code, expr_type, &vr0, &n_vr1);
3377     }
3378
3379   if (vr->type == VR_VARYING
3380       && (code == PLUS_EXPR || code == MINUS_EXPR)
3381       && TREE_CODE (op0) == SSA_NAME
3382       && vr1.type == VR_RANGE
3383       && symbolic_range_based_on_p (&vr1, op0))
3384     {
3385       const bool minus_p = (code == MINUS_EXPR);
3386       value_range_t n_vr0 = VR_INITIALIZER;
3387
3388       /* Try with [-INF, OP0] and VR1.  */
3389       if (is_gimple_min_invariant (minus_p ? vr1.max : vr1.min))
3390         set_value_range (&n_vr0, VR_RANGE, vrp_val_min (expr_type), op0, NULL);
3391
3392       /* Try with [OP0, +INF] and VR1.  */
3393       else if (is_gimple_min_invariant (minus_p ? vr1.min : vr1.max))
3394         set_value_range (&n_vr0, VR_RANGE, op0, vrp_val_max (expr_type), NULL);
3395
3396       /* Try with [OP0, OP0] and VR1.  */
3397       else
3398         set_value_range (&n_vr0, VR_RANGE, op0, op0, NULL);
3399
3400       extract_range_from_binary_expr_1 (vr, code, expr_type, &n_vr0, &vr1);
3401     }
3402 }
3403
3404 /* Extract range information from a unary operation CODE based on
3405    the range of its operand *VR0 with type OP0_TYPE with resulting type TYPE.
3406    The The resulting range is stored in *VR.  */
3407
3408 static void
3409 extract_range_from_unary_expr_1 (value_range_t *vr,
3410                                  enum tree_code code, tree type,
3411                                  value_range_t *vr0_, tree op0_type)
3412 {
3413   value_range_t vr0 = *vr0_, vrtem0 = VR_INITIALIZER, vrtem1 = VR_INITIALIZER;
3414
3415   /* VRP only operates on integral and pointer types.  */
3416   if (!(INTEGRAL_TYPE_P (op0_type)
3417         || POINTER_TYPE_P (op0_type))
3418       || !(INTEGRAL_TYPE_P (type)
3419            || POINTER_TYPE_P (type)))
3420     {
3421       set_value_range_to_varying (vr);
3422       return;
3423     }
3424
3425   /* If VR0 is UNDEFINED, so is the result.  */
3426   if (vr0.type == VR_UNDEFINED)
3427     {
3428       set_value_range_to_undefined (vr);
3429       return;
3430     }
3431
3432   /* Handle operations that we express in terms of others.  */
3433   if (code == PAREN_EXPR || code == OBJ_TYPE_REF)
3434     {
3435       /* PAREN_EXPR and OBJ_TYPE_REF are simple copies.  */
3436       copy_value_range (vr, &vr0);
3437       return;
3438     }
3439   else if (code == NEGATE_EXPR)
3440     {
3441       /* -X is simply 0 - X, so re-use existing code that also handles
3442          anti-ranges fine.  */
3443       value_range_t zero = VR_INITIALIZER;
3444       set_value_range_to_value (&zero, build_int_cst (type, 0), NULL);
3445       extract_range_from_binary_expr_1 (vr, MINUS_EXPR, type, &zero, &vr0);
3446       return;
3447     }
3448   else if (code == BIT_NOT_EXPR)
3449     {
3450       /* ~X is simply -1 - X, so re-use existing code that also handles
3451          anti-ranges fine.  */
3452       value_range_t minusone = VR_INITIALIZER;
3453       set_value_range_to_value (&minusone, build_int_cst (type, -1), NULL);
3454       extract_range_from_binary_expr_1 (vr, MINUS_EXPR,
3455                                         type, &minusone, &vr0);
3456       return;
3457     }
3458
3459   /* Now canonicalize anti-ranges to ranges when they are not symbolic
3460      and express op ~[]  as (op []') U (op []'').  */
3461   if (vr0.type == VR_ANTI_RANGE
3462       && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
3463     {
3464       extract_range_from_unary_expr_1 (vr, code, type, &vrtem0, op0_type);
3465       if (vrtem1.type != VR_UNDEFINED)
3466         {
3467           value_range_t vrres = VR_INITIALIZER;
3468           extract_range_from_unary_expr_1 (&vrres, code, type,
3469                                            &vrtem1, op0_type);
3470           vrp_meet (vr, &vrres);
3471         }
3472       return;
3473     }
3474
3475   if (CONVERT_EXPR_CODE_P (code))
3476     {
3477       tree inner_type = op0_type;
3478       tree outer_type = type;
3479
3480       /* If the expression evaluates to a pointer, we are only interested in
3481          determining if it evaluates to NULL [0, 0] or non-NULL (~[0, 0]).  */
3482       if (POINTER_TYPE_P (type))
3483         {
3484           if (range_is_nonnull (&vr0))
3485             set_value_range_to_nonnull (vr, type);
3486           else if (range_is_null (&vr0))
3487             set_value_range_to_null (vr, type);
3488           else
3489             set_value_range_to_varying (vr);
3490           return;
3491         }
3492
3493       /* If VR0 is varying and we increase the type precision, assume
3494          a full range for the following transformation.  */
3495       if (vr0.type == VR_VARYING
3496           && INTEGRAL_TYPE_P (inner_type)
3497           && TYPE_PRECISION (inner_type) < TYPE_PRECISION (outer_type))
3498         {
3499           vr0.type = VR_RANGE;
3500           vr0.min = TYPE_MIN_VALUE (inner_type);
3501           vr0.max = TYPE_MAX_VALUE (inner_type);
3502         }
3503
3504       /* If VR0 is a constant range or anti-range and the conversion is
3505          not truncating we can convert the min and max values and
3506          canonicalize the resulting range.  Otherwise we can do the
3507          conversion if the size of the range is less than what the
3508          precision of the target type can represent and the range is
3509          not an anti-range.  */
3510       if ((vr0.type == VR_RANGE
3511            || vr0.type == VR_ANTI_RANGE)
3512           && TREE_CODE (vr0.min) == INTEGER_CST
3513           && TREE_CODE (vr0.max) == INTEGER_CST
3514           && (!is_overflow_infinity (vr0.min)
3515               || (vr0.type == VR_RANGE
3516                   && TYPE_PRECISION (outer_type) > TYPE_PRECISION (inner_type)
3517                   && needs_overflow_infinity (outer_type)
3518                   && supports_overflow_infinity (outer_type)))
3519           && (!is_overflow_infinity (vr0.max)
3520               || (vr0.type == VR_RANGE
3521                   && TYPE_PRECISION (outer_type) > TYPE_PRECISION (inner_type)
3522                   && needs_overflow_infinity (outer_type)
3523                   && supports_overflow_infinity (outer_type)))
3524           && (TYPE_PRECISION (outer_type) >= TYPE_PRECISION (inner_type)
3525               || (vr0.type == VR_RANGE
3526                   && integer_zerop (int_const_binop (RSHIFT_EXPR,
3527                        int_const_binop (MINUS_EXPR, vr0.max, vr0.min),
3528                          size_int (TYPE_PRECISION (outer_type)))))))
3529         {
3530           tree new_min, new_max;
3531           if (is_overflow_infinity (vr0.min))
3532             new_min = negative_overflow_infinity (outer_type);
3533           else
3534             new_min = force_fit_type (outer_type, wi::to_widest (vr0.min),
3535                                       0, false);
3536           if (is_overflow_infinity (vr0.max))
3537             new_max = positive_overflow_infinity (outer_type);
3538           else
3539             new_max = force_fit_type (outer_type, wi::to_widest (vr0.max),
3540                                       0, false);
3541           set_and_canonicalize_value_range (vr, vr0.type,
3542                                             new_min, new_max, NULL);
3543           return;
3544         }
3545
3546       set_value_range_to_varying (vr);
3547       return;
3548     }
3549   else if (code == ABS_EXPR)
3550     {
3551       tree min, max;
3552       int cmp;
3553
3554       /* Pass through vr0 in the easy cases.  */
3555       if (TYPE_UNSIGNED (type)
3556           || value_range_nonnegative_p (&vr0))
3557         {
3558           copy_value_range (vr, &vr0);
3559           return;
3560         }
3561
3562       /* For the remaining varying or symbolic ranges we can't do anything
3563          useful.  */
3564       if (vr0.type == VR_VARYING
3565           || symbolic_range_p (&vr0))
3566         {
3567           set_value_range_to_varying (vr);
3568           return;
3569         }
3570
3571       /* -TYPE_MIN_VALUE = TYPE_MIN_VALUE with flag_wrapv so we can't get a
3572          useful range.  */
3573       if (!TYPE_OVERFLOW_UNDEFINED (type)
3574           && ((vr0.type == VR_RANGE
3575                && vrp_val_is_min (vr0.min))
3576               || (vr0.type == VR_ANTI_RANGE
3577                   && !vrp_val_is_min (vr0.min))))
3578         {
3579           set_value_range_to_varying (vr);
3580           return;
3581         }
3582
3583       /* ABS_EXPR may flip the range around, if the original range
3584          included negative values.  */
3585       if (is_overflow_infinity (vr0.min))
3586         min = positive_overflow_infinity (type);
3587       else if (!vrp_val_is_min (vr0.min))
3588         min = fold_unary_to_constant (code, type, vr0.min);
3589       else if (!needs_overflow_infinity (type))
3590         min = TYPE_MAX_VALUE (type);
3591       else if (supports_overflow_infinity (type))
3592         min = positive_overflow_infinity (type);
3593       else
3594         {
3595           set_value_range_to_varying (vr);
3596           return;
3597         }
3598
3599       if (is_overflow_infinity (vr0.max))
3600         max = positive_overflow_infinity (type);
3601       else if (!vrp_val_is_min (vr0.max))
3602         max = fold_unary_to_constant (code, type, vr0.max);
3603       else if (!needs_overflow_infinity (type))
3604         max = TYPE_MAX_VALUE (type);
3605       else if (supports_overflow_infinity (type)
3606                /* We shouldn't generate [+INF, +INF] as set_value_range
3607                   doesn't like this and ICEs.  */
3608                && !is_positive_overflow_infinity (min))
3609         max = positive_overflow_infinity (type);
3610       else
3611         {
3612           set_value_range_to_varying (vr);
3613           return;
3614         }
3615
3616       cmp = compare_values (min, max);
3617
3618       /* If a VR_ANTI_RANGEs contains zero, then we have
3619          ~[-INF, min(MIN, MAX)].  */
3620       if (vr0.type == VR_ANTI_RANGE)
3621         {
3622           if (range_includes_zero_p (vr0.min, vr0.max) == 1)
3623             {
3624               /* Take the lower of the two values.  */
3625               if (cmp != 1)
3626                 max = min;
3627
3628               /* Create ~[-INF, min (abs(MIN), abs(MAX))]
3629                  or ~[-INF + 1, min (abs(MIN), abs(MAX))] when
3630                  flag_wrapv is set and the original anti-range doesn't include
3631                  TYPE_MIN_VALUE, remember -TYPE_MIN_VALUE = TYPE_MIN_VALUE.  */
3632               if (TYPE_OVERFLOW_WRAPS (type))
3633                 {
3634                   tree type_min_value = TYPE_MIN_VALUE (type);
3635
3636                   min = (vr0.min != type_min_value
3637                          ? int_const_binop (PLUS_EXPR, type_min_value,
3638                                             build_int_cst (TREE_TYPE (type_min_value), 1))
3639                          : type_min_value);
3640                 }
3641               else
3642                 {
3643                   if (overflow_infinity_range_p (&vr0))
3644                     min = negative_overflow_infinity (type);
3645                   else
3646                     min = TYPE_MIN_VALUE (type);
3647                 }
3648             }
3649           else
3650             {
3651               /* All else has failed, so create the range [0, INF], even for
3652                  flag_wrapv since TYPE_MIN_VALUE is in the original
3653                  anti-range.  */
3654               vr0.type = VR_RANGE;
3655               min = build_int_cst (type, 0);
3656               if (needs_overflow_infinity (type))
3657                 {
3658                   if (supports_overflow_infinity (type))
3659                     max = positive_overflow_infinity (type);
3660                   else
3661                     {
3662                       set_value_range_to_varying (vr);
3663                       return;
3664                     }
3665                 }
3666               else
3667                 max = TYPE_MAX_VALUE (type);
3668             }
3669         }
3670
3671       /* If the range contains zero then we know that the minimum value in the
3672          range will be zero.  */
3673       else if (range_includes_zero_p (vr0.min, vr0.max) == 1)
3674         {
3675           if (cmp == 1)
3676             max = min;
3677           min = build_int_cst (type, 0);
3678         }
3679       else
3680         {
3681           /* If the range was reversed, swap MIN and MAX.  */
3682           if (cmp == 1)
3683             {
3684               tree t = min;
3685               min = max;
3686               max = t;
3687             }
3688         }
3689
3690       cmp = compare_values (min, max);
3691       if (cmp == -2 || cmp == 1)
3692         {
3693           /* If the new range has its limits swapped around (MIN > MAX),
3694              then the operation caused one of them to wrap around, mark
3695              the new range VARYING.  */
3696           set_value_range_to_varying (vr);
3697         }
3698       else
3699         set_value_range (vr, vr0.type, min, max, NULL);
3700       return;
3701     }
3702
3703   /* For unhandled operations fall back to varying.  */
3704   set_value_range_to_varying (vr);
3705   return;
3706 }
3707
3708
3709 /* Extract range information from a unary expression CODE OP0 based on
3710    the range of its operand with resulting type TYPE.
3711    The resulting range is stored in *VR.  */
3712
3713 static void
3714 extract_range_from_unary_expr (value_range_t *vr, enum tree_code code,
3715                                tree type, tree op0)
3716 {
3717   value_range_t vr0 = VR_INITIALIZER;
3718
3719   /* Get value ranges for the operand.  For constant operands, create
3720      a new value range with the operand to simplify processing.  */
3721   if (TREE_CODE (op0) == SSA_NAME)
3722     vr0 = *(get_value_range (op0));
3723   else if (is_gimple_min_invariant (op0))
3724     set_value_range_to_value (&vr0, op0, NULL);
3725   else
3726     set_value_range_to_varying (&vr0);
3727
3728   extract_range_from_unary_expr_1 (vr, code, type, &vr0, TREE_TYPE (op0));
3729 }
3730
3731
3732 /* Extract range information from a conditional expression STMT based on
3733    the ranges of each of its operands and the expression code.  */
3734
3735 static void
3736 extract_range_from_cond_expr (value_range_t *vr, gassign *stmt)
3737 {
3738   tree op0, op1;
3739   value_range_t vr0 = VR_INITIALIZER;
3740   value_range_t vr1 = VR_INITIALIZER;
3741
3742   /* Get value ranges for each operand.  For constant operands, create
3743      a new value range with the operand to simplify processing.  */
3744   op0 = gimple_assign_rhs2 (stmt);
3745   if (TREE_CODE (op0) == SSA_NAME)
3746     vr0 = *(get_value_range (op0));
3747   else if (is_gimple_min_invariant (op0))
3748     set_value_range_to_value (&vr0, op0, NULL);
3749   else
3750     set_value_range_to_varying (&vr0);
3751
3752   op1 = gimple_assign_rhs3 (stmt);
3753   if (TREE_CODE (op1) == SSA_NAME)
3754     vr1 = *(get_value_range (op1));
3755   else if (is_gimple_min_invariant (op1))
3756     set_value_range_to_value (&vr1, op1, NULL);
3757   else
3758     set_value_range_to_varying (&vr1);
3759
3760   /* The resulting value range is the union of the operand ranges */
3761   copy_value_range (vr, &vr0);
3762   vrp_meet (vr, &vr1);
3763 }
3764
3765
3766 /* Extract range information from a comparison expression EXPR based
3767    on the range of its operand and the expression code.  */
3768
3769 static void
3770 extract_range_from_comparison (value_range_t *vr, enum tree_code code,
3771                                tree type, tree op0, tree op1)
3772 {
3773   bool sop = false;
3774   tree val;
3775
3776   val = vrp_evaluate_conditional_warnv_with_ops (code, op0, op1, false, &sop,
3777                                                  NULL);
3778
3779   /* A disadvantage of using a special infinity as an overflow
3780      representation is that we lose the ability to record overflow
3781      when we don't have an infinity.  So we have to ignore a result
3782      which relies on overflow.  */
3783
3784   if (val && !is_overflow_infinity (val) && !sop)
3785     {
3786       /* Since this expression was found on the RHS of an assignment,
3787          its type may be different from _Bool.  Convert VAL to EXPR's
3788          type.  */
3789       val = fold_convert (type, val);
3790       if (is_gimple_min_invariant (val))
3791         set_value_range_to_value (vr, val, vr->equiv);
3792       else
3793         set_value_range (vr, VR_RANGE, val, val, vr->equiv);
3794     }
3795   else
3796     /* The result of a comparison is always true or false.  */
3797     set_value_range_to_truthvalue (vr, type);
3798 }
3799
3800 /* Helper function for simplify_internal_call_using_ranges and
3801    extract_range_basic.  Return true if OP0 SUBCODE OP1 for
3802    SUBCODE {PLUS,MINUS,MULT}_EXPR is known to never overflow or
3803    always overflow.  Set *OVF to true if it is known to always
3804    overflow.  */
3805
3806 static bool
3807 check_for_binary_op_overflow (enum tree_code subcode, tree type,
3808                               tree op0, tree op1, bool *ovf)
3809 {
3810   value_range_t vr0 = VR_INITIALIZER;
3811   value_range_t vr1 = VR_INITIALIZER;
3812   if (TREE_CODE (op0) == SSA_NAME)
3813     vr0 = *get_value_range (op0);
3814   else if (TREE_CODE (op0) == INTEGER_CST)
3815     set_value_range_to_value (&vr0, op0, NULL);
3816   else
3817     set_value_range_to_varying (&vr0);
3818
3819   if (TREE_CODE (op1) == SSA_NAME)
3820     vr1 = *get_value_range (op1);
3821   else if (TREE_CODE (op1) == INTEGER_CST)
3822     set_value_range_to_value (&vr1, op1, NULL);
3823   else
3824     set_value_range_to_varying (&vr1);
3825
3826   if (!range_int_cst_p (&vr0)
3827       || TREE_OVERFLOW (vr0.min)
3828       || TREE_OVERFLOW (vr0.max))
3829     {
3830       vr0.min = vrp_val_min (TREE_TYPE (op0));
3831       vr0.max = vrp_val_max (TREE_TYPE (op0));
3832     }
3833   if (!range_int_cst_p (&vr1)
3834       || TREE_OVERFLOW (vr1.min)
3835       || TREE_OVERFLOW (vr1.max))
3836     {
3837       vr1.min = vrp_val_min (TREE_TYPE (op1));
3838       vr1.max = vrp_val_max (TREE_TYPE (op1));
3839     }
3840   *ovf = arith_overflowed_p (subcode, type, vr0.min,
3841                              subcode == MINUS_EXPR ? vr1.max : vr1.min);
3842   if (arith_overflowed_p (subcode, type, vr0.max,
3843                           subcode == MINUS_EXPR ? vr1.min : vr1.max) != *ovf)
3844     return false;
3845   if (subcode == MULT_EXPR)
3846     {
3847       if (arith_overflowed_p (subcode, type, vr0.min, vr1.max) != *ovf
3848           || arith_overflowed_p (subcode, type, vr0.max, vr1.min) != *ovf)
3849         return false;
3850     }
3851   if (*ovf)
3852     {
3853       /* So far we found that there is an overflow on the boundaries.
3854          That doesn't prove that there is an overflow even for all values
3855          in between the boundaries.  For that compute widest_int range
3856          of the result and see if it doesn't overlap the range of
3857          type.  */
3858       widest_int wmin, wmax;
3859       widest_int w[4];
3860       int i;
3861       w[0] = wi::to_widest (vr0.min);
3862       w[1] = wi::to_widest (vr0.max);
3863       w[2] = wi::to_widest (vr1.min);
3864       w[3] = wi::to_widest (vr1.max);
3865       for (i = 0; i < 4; i++)
3866         {
3867           widest_int wt;
3868           switch (subcode)
3869             {
3870             case PLUS_EXPR:
3871               wt = wi::add (w[i & 1], w[2 + (i & 2) / 2]);
3872               break;
3873             case MINUS_EXPR:
3874               wt = wi::sub (w[i & 1], w[2 + (i & 2) / 2]);
3875               break;
3876             case MULT_EXPR:
3877               wt = wi::mul (w[i & 1], w[2 + (i & 2) / 2]);
3878               break;
3879             default:
3880               gcc_unreachable ();
3881             }
3882           if (i == 0)
3883             {
3884               wmin = wt;
3885               wmax = wt;
3886             }
3887           else
3888             {
3889               wmin = wi::smin (wmin, wt);
3890               wmax = wi::smax (wmax, wt);
3891             }
3892         }
3893       /* The result of op0 CODE op1 is known to be in range
3894          [wmin, wmax].  */
3895       widest_int wtmin = wi::to_widest (vrp_val_min (type));
3896       widest_int wtmax = wi::to_widest (vrp_val_max (type));
3897       /* If all values in [wmin, wmax] are smaller than
3898          [wtmin, wtmax] or all are larger than [wtmin, wtmax],
3899          the arithmetic operation will always overflow.  */
3900       if (wi::lts_p (wmax, wtmin) || wi::gts_p (wmin, wtmax))
3901         return true;
3902       return false;
3903     }
3904   return true;
3905 }
3906
3907 /* Try to derive a nonnegative or nonzero range out of STMT relying
3908    primarily on generic routines in fold in conjunction with range data.
3909    Store the result in *VR */
3910
3911 static void
3912 extract_range_basic (value_range_t *vr, gimple stmt)
3913 {
3914   bool sop = false;
3915   tree type = gimple_expr_type (stmt);
3916
3917   if (gimple_call_builtin_p (stmt, BUILT_IN_NORMAL))
3918     {
3919       tree fndecl = gimple_call_fndecl (stmt), arg;
3920       int mini, maxi, zerov = 0, prec;
3921
3922       switch (DECL_FUNCTION_CODE (fndecl))
3923         {
3924         case BUILT_IN_CONSTANT_P:
3925           /* If the call is __builtin_constant_p and the argument is a
3926              function parameter resolve it to false.  This avoids bogus
3927              array bound warnings.
3928              ???  We could do this as early as inlining is finished.  */
3929           arg = gimple_call_arg (stmt, 0);
3930           if (TREE_CODE (arg) == SSA_NAME
3931               && SSA_NAME_IS_DEFAULT_DEF (arg)
3932               && TREE_CODE (SSA_NAME_VAR (arg)) == PARM_DECL)
3933             {
3934               set_value_range_to_null (vr, type);
3935               return;
3936             }
3937           break;
3938           /* Both __builtin_ffs* and __builtin_popcount return
3939              [0, prec].  */
3940         CASE_INT_FN (BUILT_IN_FFS):
3941         CASE_INT_FN (BUILT_IN_POPCOUNT):
3942           arg = gimple_call_arg (stmt, 0);
3943           prec = TYPE_PRECISION (TREE_TYPE (arg));
3944           mini = 0;
3945           maxi = prec;
3946           if (TREE_CODE (arg) == SSA_NAME)
3947             {
3948               value_range_t *vr0 = get_value_range (arg);
3949               /* If arg is non-zero, then ffs or popcount
3950                  are non-zero.  */
3951               if (((vr0->type == VR_RANGE
3952                     && range_includes_zero_p (vr0->min, vr0->max) == 0)
3953                    || (vr0->type == VR_ANTI_RANGE
3954                        && range_includes_zero_p (vr0->min, vr0->max) == 1))
3955                   && !is_overflow_infinity (vr0->min)
3956                   && !is_overflow_infinity (vr0->max))
3957                 mini = 1;
3958               /* If some high bits are known to be zero,
3959                  we can decrease the maximum.  */
3960               if (vr0->type == VR_RANGE
3961                   && TREE_CODE (vr0->max) == INTEGER_CST
3962                   && !operand_less_p (vr0->min,
3963                                       build_zero_cst (TREE_TYPE (vr0->min)))
3964                   && !is_overflow_infinity (vr0->max))
3965                 maxi = tree_floor_log2 (vr0->max) + 1;
3966             }
3967           goto bitop_builtin;
3968           /* __builtin_parity* returns [0, 1].  */
3969         CASE_INT_FN (BUILT_IN_PARITY):
3970           mini = 0;
3971           maxi = 1;
3972           goto bitop_builtin;
3973           /* __builtin_c[lt]z* return [0, prec-1], except for
3974              when the argument is 0, but that is undefined behavior.
3975              On many targets where the CLZ RTL or optab value is defined
3976              for 0 the value is prec, so include that in the range
3977              by default.  */
3978         CASE_INT_FN (BUILT_IN_CLZ):
3979           arg = gimple_call_arg (stmt, 0);
3980           prec = TYPE_PRECISION (TREE_TYPE (arg));
3981           mini = 0;
3982           maxi = prec;
3983           if (optab_handler (clz_optab, TYPE_MODE (TREE_TYPE (arg)))
3984               != CODE_FOR_nothing
3985               && CLZ_DEFINED_VALUE_AT_ZERO (TYPE_MODE (TREE_TYPE (arg)),
3986                                             zerov)
3987               /* Handle only the single common value.  */
3988               && zerov != prec)
3989             /* Magic value to give up, unless vr0 proves
3990                arg is non-zero.  */
3991             mini = -2;
3992           if (TREE_CODE (arg) == SSA_NAME)
3993             {
3994               value_range_t *vr0 = get_value_range (arg);
3995               /* From clz of VR_RANGE minimum we can compute
3996                  result maximum.  */
3997               if (vr0->type == VR_RANGE
3998                   && TREE_CODE (vr0->min) == INTEGER_CST
3999                   && !is_overflow_infinity (vr0->min))
4000                 {
4001                   maxi = prec - 1 - tree_floor_log2 (vr0->min);
4002                   if (maxi != prec)
4003                     mini = 0;
4004                 }
4005               else if (vr0->type == VR_ANTI_RANGE
4006                        && integer_zerop (vr0->min)
4007                        && !is_overflow_infinity (vr0->min))
4008                 {
4009                   maxi = prec - 1;
4010                   mini = 0;
4011                 }
4012               if (mini == -2)
4013                 break;
4014               /* From clz of VR_RANGE maximum we can compute
4015                  result minimum.  */
4016               if (vr0->type == VR_RANGE
4017                   && TREE_CODE (vr0->max) == INTEGER_CST
4018                   && !is_overflow_infinity (vr0->max))
4019                 {
4020                   mini = prec - 1 - tree_floor_log2 (vr0->max);
4021                   if (mini == prec)
4022                     break;
4023                 }
4024             }
4025           if (mini == -2)
4026             break;
4027           goto bitop_builtin;
4028           /* __builtin_ctz* return [0, prec-1], except for
4029              when the argument is 0, but that is undefined behavior.
4030              If there is a ctz optab for this mode and
4031              CTZ_DEFINED_VALUE_AT_ZERO, include that in the range,
4032              otherwise just assume 0 won't be seen.  */
4033         CASE_INT_FN (BUILT_IN_CTZ):
4034           arg = gimple_call_arg (stmt, 0);
4035           prec = TYPE_PRECISION (TREE_TYPE (arg));
4036           mini = 0;
4037           maxi = prec - 1;
4038           if (optab_handler (ctz_optab, TYPE_MODE (TREE_TYPE (arg)))
4039               != CODE_FOR_nothing
4040               && CTZ_DEFINED_VALUE_AT_ZERO (TYPE_MODE (TREE_TYPE (arg)),
4041                                             zerov))
4042             {
4043               /* Handle only the two common values.  */
4044               if (zerov == -1)
4045                 mini = -1;
4046               else if (zerov == prec)
4047                 maxi = prec;
4048               else
4049                 /* Magic value to give up, unless vr0 proves
4050                    arg is non-zero.  */
4051                 mini = -2;
4052             }
4053           if (TREE_CODE (arg) == SSA_NAME)
4054             {
4055               value_range_t *vr0 = get_value_range (arg);
4056               /* If arg is non-zero, then use [0, prec - 1].  */
4057               if (((vr0->type == VR_RANGE
4058                     && integer_nonzerop (vr0->min))
4059                    || (vr0->type == VR_ANTI_RANGE
4060                        && integer_zerop (vr0->min)))
4061                   && !is_overflow_infinity (vr0->min))
4062                 {
4063                   mini = 0;
4064                   maxi = prec - 1;
4065                 }
4066               /* If some high bits are known to be zero,
4067                  we can decrease the result maximum.  */
4068               if (vr0->type == VR_RANGE
4069                   && TREE_CODE (vr0->max) == INTEGER_CST
4070                   && !is_overflow_infinity (vr0->max))
4071                 {
4072                   maxi = tree_floor_log2 (vr0->max);
4073                   /* For vr0 [0, 0] give up.  */
4074                   if (maxi == -1)
4075                     break;
4076                 }
4077             }
4078           if (mini == -2)
4079             break;
4080           goto bitop_builtin;
4081           /* __builtin_clrsb* returns [0, prec-1].  */
4082         CASE_INT_FN (BUILT_IN_CLRSB):
4083           arg = gimple_call_arg (stmt, 0);
4084           prec = TYPE_PRECISION (TREE_TYPE (arg));
4085           mini = 0;
4086           maxi = prec - 1;
4087           goto bitop_builtin;
4088         bitop_builtin:
4089           set_value_range (vr, VR_RANGE, build_int_cst (type, mini),
4090                            build_int_cst (type, maxi), NULL);
4091           return;
4092         default:
4093           break;
4094         }
4095     }
4096   else if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
4097     {
4098       enum tree_code subcode = ERROR_MARK;
4099       switch (gimple_call_internal_fn (stmt))
4100         {
4101         case IFN_UBSAN_CHECK_ADD:
4102           subcode = PLUS_EXPR;
4103           break;
4104         case IFN_UBSAN_CHECK_SUB:
4105           subcode = MINUS_EXPR;
4106           break;
4107         case IFN_UBSAN_CHECK_MUL:
4108           subcode = MULT_EXPR;
4109           break;
4110         default:
4111           break;
4112         }
4113       if (subcode != ERROR_MARK)
4114         {
4115           bool saved_flag_wrapv = flag_wrapv;
4116           /* Pretend the arithmetics is wrapping.  If there is
4117              any overflow, we'll complain, but will actually do
4118              wrapping operation.  */
4119           flag_wrapv = 1;
4120           extract_range_from_binary_expr (vr, subcode, type,
4121                                           gimple_call_arg (stmt, 0),
4122                                           gimple_call_arg (stmt, 1));
4123           flag_wrapv = saved_flag_wrapv;
4124
4125           /* If for both arguments vrp_valueize returned non-NULL,
4126              this should have been already folded and if not, it
4127              wasn't folded because of overflow.  Avoid removing the
4128              UBSAN_CHECK_* calls in that case.  */
4129           if (vr->type == VR_RANGE
4130               && (vr->min == vr->max
4131                   || operand_equal_p (vr->min, vr->max, 0)))
4132             set_value_range_to_varying (vr);
4133           return;
4134         }
4135     }
4136   /* Handle extraction of the two results (result of arithmetics and
4137      a flag whether arithmetics overflowed) from {ADD,SUB,MUL}_OVERFLOW
4138      internal function.  */
4139   else if (is_gimple_assign (stmt)
4140            && (gimple_assign_rhs_code (stmt) == REALPART_EXPR
4141                || gimple_assign_rhs_code (stmt) == IMAGPART_EXPR)
4142            && INTEGRAL_TYPE_P (type))
4143     {
4144       enum tree_code code = gimple_assign_rhs_code (stmt);
4145       tree op = gimple_assign_rhs1 (stmt);
4146       if (TREE_CODE (op) == code && TREE_CODE (TREE_OPERAND (op, 0)) == SSA_NAME)
4147         {
4148           gimple g = SSA_NAME_DEF_STMT (TREE_OPERAND (op, 0));
4149           if (is_gimple_call (g) && gimple_call_internal_p (g))
4150             {
4151               enum tree_code subcode = ERROR_MARK;
4152               switch (gimple_call_internal_fn (g))
4153                 {
4154                 case IFN_ADD_OVERFLOW:
4155                   subcode = PLUS_EXPR;
4156                   break;
4157                 case IFN_SUB_OVERFLOW:
4158                   subcode = MINUS_EXPR;
4159                   break;
4160                 case IFN_MUL_OVERFLOW:
4161                   subcode = MULT_EXPR;
4162                   break;
4163                 default:
4164                   break;
4165                 }
4166               if (subcode != ERROR_MARK)
4167                 {
4168                   tree op0 = gimple_call_arg (g, 0);
4169                   tree op1 = gimple_call_arg (g, 1);
4170                   if (code == IMAGPART_EXPR)
4171                     {
4172                       bool ovf = false;
4173                       if (check_for_binary_op_overflow (subcode, type,
4174                                                         op0, op1, &ovf))
4175                         set_value_range_to_value (vr,
4176                                                   build_int_cst (type, ovf),
4177                                                   NULL);
4178                       else
4179                         set_value_range (vr, VR_RANGE, build_int_cst (type, 0),
4180                                          build_int_cst (type, 1), NULL);
4181                     }
4182                   else if (types_compatible_p (type, TREE_TYPE (op0))
4183                            && types_compatible_p (type, TREE_TYPE (op1)))
4184                     {
4185                       bool saved_flag_wrapv = flag_wrapv;
4186                       /* Pretend the arithmetics is wrapping.  If there is
4187                          any overflow, IMAGPART_EXPR will be set.  */
4188                       flag_wrapv = 1;
4189                       extract_range_from_binary_expr (vr, subcode, type,
4190                                                       op0, op1);
4191                       flag_wrapv = saved_flag_wrapv;
4192                     }
4193                   else
4194                     {
4195                       value_range_t vr0 = VR_INITIALIZER;
4196                       value_range_t vr1 = VR_INITIALIZER;
4197                       bool saved_flag_wrapv = flag_wrapv;
4198                       /* Pretend the arithmetics is wrapping.  If there is
4199                          any overflow, IMAGPART_EXPR will be set.  */
4200                       flag_wrapv = 1;
4201                       extract_range_from_unary_expr (&vr0, NOP_EXPR,
4202                                                      type, op0);
4203                       extract_range_from_unary_expr (&vr1, NOP_EXPR,
4204                                                      type, op1);
4205                       extract_range_from_binary_expr_1 (vr, subcode, type,
4206                                                         &vr0, &vr1);
4207                       flag_wrapv = saved_flag_wrapv;
4208                     }
4209                   return;
4210                 }
4211             }
4212         }
4213     }
4214   if (INTEGRAL_TYPE_P (type)
4215       && gimple_stmt_nonnegative_warnv_p (stmt, &sop))
4216     set_value_range_to_nonnegative (vr, type,
4217                                     sop || stmt_overflow_infinity (stmt));
4218   else if (vrp_stmt_computes_nonzero (stmt, &sop)
4219            && !sop)
4220     set_value_range_to_nonnull (vr, type);
4221   else
4222     set_value_range_to_varying (vr);
4223 }
4224
4225
4226 /* Try to compute a useful range out of assignment STMT and store it
4227    in *VR.  */
4228
4229 static void
4230 extract_range_from_assignment (value_range_t *vr, gassign *stmt)
4231 {
4232   enum tree_code code = gimple_assign_rhs_code (stmt);
4233
4234   if (code == ASSERT_EXPR)
4235     extract_range_from_assert (vr, gimple_assign_rhs1 (stmt));
4236   else if (code == SSA_NAME)
4237     extract_range_from_ssa_name (vr, gimple_assign_rhs1 (stmt));
4238   else if (TREE_CODE_CLASS (code) == tcc_binary)
4239     extract_range_from_binary_expr (vr, gimple_assign_rhs_code (stmt),
4240                                     gimple_expr_type (stmt),
4241                                     gimple_assign_rhs1 (stmt),
4242                                     gimple_assign_rhs2 (stmt));
4243   else if (TREE_CODE_CLASS (code) == tcc_unary)
4244     extract_range_from_unary_expr (vr, gimple_assign_rhs_code (stmt),
4245                                    gimple_expr_type (stmt),
4246                                    gimple_assign_rhs1 (stmt));
4247   else if (code == COND_EXPR)
4248     extract_range_from_cond_expr (vr, stmt);
4249   else if (TREE_CODE_CLASS (code) == tcc_comparison)
4250     extract_range_from_comparison (vr, gimple_assign_rhs_code (stmt),
4251                                    gimple_expr_type (stmt),
4252                                    gimple_assign_rhs1 (stmt),
4253                                    gimple_assign_rhs2 (stmt));
4254   else if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS
4255            && is_gimple_min_invariant (gimple_assign_rhs1 (stmt)))
4256     set_value_range_to_value (vr, gimple_assign_rhs1 (stmt), NULL);
4257   else
4258     set_value_range_to_varying (vr);
4259
4260   if (vr->type == VR_VARYING)
4261     extract_range_basic (vr, stmt);
4262 }
4263
4264 /* Given a range VR, a LOOP and a variable VAR, determine whether it
4265    would be profitable to adjust VR using scalar evolution information
4266    for VAR.  If so, update VR with the new limits.  */
4267
4268 static void
4269 adjust_range_with_scev (value_range_t *vr, struct loop *loop,
4270                         gimple stmt, tree var)
4271 {
4272   tree init, step, chrec, tmin, tmax, min, max, type, tem;
4273   enum ev_direction dir;
4274
4275   /* TODO.  Don't adjust anti-ranges.  An anti-range may provide
4276      better opportunities than a regular range, but I'm not sure.  */
4277   if (vr->type == VR_ANTI_RANGE)
4278     return;
4279
4280   chrec = instantiate_parameters (loop, analyze_scalar_evolution (loop, var));
4281
4282   /* Like in PR19590, scev can return a constant function.  */
4283   if (is_gimple_min_invariant (chrec))
4284     {
4285       set_value_range_to_value (vr, chrec, vr->equiv);
4286       return;
4287     }
4288
4289   if (TREE_CODE (chrec) != POLYNOMIAL_CHREC)
4290     return;
4291
4292   init = initial_condition_in_loop_num (chrec, loop->num);
4293   tem = op_with_constant_singleton_value_range (init);
4294   if (tem)
4295     init = tem;
4296   step = evolution_part_in_loop_num (chrec, loop->num);
4297   tem = op_with_constant_singleton_value_range (step);
4298   if (tem)
4299     step = tem;
4300
4301   /* If STEP is symbolic, we can't know whether INIT will be the
4302      minimum or maximum value in the range.  Also, unless INIT is
4303      a simple expression, compare_values and possibly other functions
4304      in tree-vrp won't be able to handle it.  */
4305   if (step == NULL_TREE
4306       || !is_gimple_min_invariant (step)
4307       || !valid_value_p (init))
4308     return;
4309
4310   dir = scev_direction (chrec);
4311   if (/* Do not adjust ranges if we do not know whether the iv increases
4312          or decreases,  ... */
4313       dir == EV_DIR_UNKNOWN
4314       /* ... or if it may wrap.  */
4315       || scev_probably_wraps_p (init, step, stmt, get_chrec_loop (chrec),
4316                                 true))
4317     return;
4318
4319   /* We use TYPE_MIN_VALUE and TYPE_MAX_VALUE here instead of
4320      negative_overflow_infinity and positive_overflow_infinity,
4321      because we have concluded that the loop probably does not
4322      wrap.  */
4323
4324   type = TREE_TYPE (var);
4325   if (POINTER_TYPE_P (type) || !TYPE_MIN_VALUE (type))
4326     tmin = lower_bound_in_type (type, type);
4327   else
4328     tmin = TYPE_MIN_VALUE (type);
4329   if (POINTER_TYPE_P (type) || !TYPE_MAX_VALUE (type))
4330     tmax = upper_bound_in_type (type, type);
4331   else
4332     tmax = TYPE_MAX_VALUE (type);
4333
4334   /* Try to use estimated number of iterations for the loop to constrain the
4335      final value in the evolution.  */
4336   if (TREE_CODE (step) == INTEGER_CST
4337       && is_gimple_val (init)
4338       && (TREE_CODE (init) != SSA_NAME
4339           || get_value_range (init)->type == VR_RANGE))
4340     {
4341       widest_int nit;
4342
4343       /* We are only entering here for loop header PHI nodes, so using
4344          the number of latch executions is the correct thing to use.  */
4345       if (max_loop_iterations (loop, &nit))
4346         {
4347           value_range_t maxvr = VR_INITIALIZER;
4348           signop sgn = TYPE_SIGN (TREE_TYPE (step));
4349           bool overflow;
4350
4351           widest_int wtmp = wi::mul (wi::to_widest (step), nit, sgn,
4352                                      &overflow);
4353           /* If the multiplication overflowed we can't do a meaningful
4354              adjustment.  Likewise if the result doesn't fit in the type
4355              of the induction variable.  For a signed type we have to
4356              check whether the result has the expected signedness which
4357              is that of the step as number of iterations is unsigned.  */
4358           if (!overflow
4359               && wi::fits_to_tree_p (wtmp, TREE_TYPE (init))
4360               && (sgn == UNSIGNED
4361                   || wi::gts_p (wtmp, 0) == wi::gts_p (step, 0)))
4362             {
4363               tem = wide_int_to_tree (TREE_TYPE (init), wtmp);
4364               extract_range_from_binary_expr (&maxvr, PLUS_EXPR,
4365                                               TREE_TYPE (init), init, tem);
4366               /* Likewise if the addition did.  */
4367               if (maxvr.type == VR_RANGE)
4368                 {
4369                   tmin = maxvr.min;
4370                   tmax = maxvr.max;
4371                 }
4372             }
4373         }
4374     }
4375
4376   if (vr->type == VR_VARYING || vr->type == VR_UNDEFINED)
4377     {
4378       min = tmin;
4379       max = tmax;
4380
4381       /* For VARYING or UNDEFINED ranges, just about anything we get
4382          from scalar evolutions should be better.  */
4383
4384       if (dir == EV_DIR_DECREASES)
4385         max = init;
4386       else
4387         min = init;
4388     }
4389   else if (vr->type == VR_RANGE)
4390     {
4391       min = vr->min;
4392       max = vr->max;
4393
4394       if (dir == EV_DIR_DECREASES)
4395         {
4396           /* INIT is the maximum value.  If INIT is lower than VR->MAX
4397              but no smaller than VR->MIN, set VR->MAX to INIT.  */
4398           if (compare_values (init, max) == -1)
4399             max = init;
4400
4401           /* According to the loop information, the variable does not
4402              overflow.  If we think it does, probably because of an
4403              overflow due to arithmetic on a different INF value,
4404              reset now.  */
4405           if (is_negative_overflow_infinity (min)
4406               || compare_values (min, tmin) == -1)
4407             min = tmin;
4408
4409         }
4410       else
4411         {
4412           /* If INIT is bigger than VR->MIN, set VR->MIN to INIT.  */
4413           if (compare_values (init, min) == 1)
4414             min = init;
4415
4416           if (is_positive_overflow_infinity (max)
4417               || compare_values (tmax, max) == -1)
4418             max = tmax;
4419         }
4420     }
4421   else
4422     return;
4423
4424   /* If we just created an invalid range with the minimum
4425      greater than the maximum, we fail conservatively.
4426      This should happen only in unreachable
4427      parts of code, or for invalid programs.  */
4428   if (compare_values (min, max) == 1
4429       || (is_negative_overflow_infinity (min)
4430           && is_positive_overflow_infinity (max)))
4431     return;
4432
4433   set_value_range (vr, VR_RANGE, min, max, vr->equiv);
4434 }
4435
4436
4437 /* Given two numeric value ranges VR0, VR1 and a comparison code COMP:
4438
4439    - Return BOOLEAN_TRUE_NODE if VR0 COMP VR1 always returns true for
4440      all the values in the ranges.
4441
4442    - Return BOOLEAN_FALSE_NODE if the comparison always returns false.
4443
4444    - Return NULL_TREE if it is not always possible to determine the
4445      value of the comparison.
4446
4447    Also set *STRICT_OVERFLOW_P to indicate whether a range with an
4448    overflow infinity was used in the test.  */
4449
4450
4451 static tree
4452 compare_ranges (enum tree_code comp, value_range_t *vr0, value_range_t *vr1,
4453                 bool *strict_overflow_p)
4454 {
4455   /* VARYING or UNDEFINED ranges cannot be compared.  */
4456   if (vr0->type == VR_VARYING
4457       || vr0->type == VR_UNDEFINED
4458       || vr1->type == VR_VARYING
4459       || vr1->type == VR_UNDEFINED)
4460     return NULL_TREE;
4461
4462   /* Anti-ranges need to be handled separately.  */
4463   if (vr0->type == VR_ANTI_RANGE || vr1->type == VR_ANTI_RANGE)
4464     {
4465       /* If both are anti-ranges, then we cannot compute any
4466          comparison.  */
4467       if (vr0->type == VR_ANTI_RANGE && vr1->type == VR_ANTI_RANGE)
4468         return NULL_TREE;
4469
4470       /* These comparisons are never statically computable.  */
4471       if (comp == GT_EXPR
4472           || comp == GE_EXPR
4473           || comp == LT_EXPR
4474           || comp == LE_EXPR)
4475         return NULL_TREE;
4476
4477       /* Equality can be computed only between a range and an
4478          anti-range.  ~[VAL1, VAL2] == [VAL1, VAL2] is always false.  */
4479       if (vr0->type == VR_RANGE)
4480         {
4481           /* To simplify processing, make VR0 the anti-range.  */
4482           value_range_t *tmp = vr0;
4483           vr0 = vr1;
4484           vr1 = tmp;
4485         }
4486
4487       gcc_assert (comp == NE_EXPR || comp == EQ_EXPR);
4488
4489       if (compare_values_warnv (vr0->min, vr1->min, strict_overflow_p) == 0
4490           && compare_values_warnv (vr0->max, vr1->max, strict_overflow_p) == 0)
4491         return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
4492
4493       return NULL_TREE;
4494     }
4495
4496   if (!usable_range_p (vr0, strict_overflow_p)
4497       || !usable_range_p (vr1, strict_overflow_p))
4498     return NULL_TREE;
4499
4500   /* Simplify processing.  If COMP is GT_EXPR or GE_EXPR, switch the
4501      operands around and change the comparison code.  */
4502   if (comp == GT_EXPR || comp == GE_EXPR)
4503     {
4504       value_range_t *tmp;
4505       comp = (comp == GT_EXPR) ? LT_EXPR : LE_EXPR;
4506       tmp = vr0;
4507       vr0 = vr1;
4508       vr1 = tmp;
4509     }
4510
4511   if (comp == EQ_EXPR)
4512     {
4513       /* Equality may only be computed if both ranges represent
4514          exactly one value.  */
4515       if (compare_values_warnv (vr0->min, vr0->max, strict_overflow_p) == 0
4516           && compare_values_warnv (vr1->min, vr1->max, strict_overflow_p) == 0)
4517         {
4518           int cmp_min = compare_values_warnv (vr0->min, vr1->min,
4519                                               strict_overflow_p);
4520           int cmp_max = compare_values_warnv (vr0->max, vr1->max,
4521                                               strict_overflow_p);
4522           if (cmp_min == 0 && cmp_max == 0)
4523             return boolean_true_node;
4524           else if (cmp_min != -2 && cmp_max != -2)
4525             return boolean_false_node;
4526         }
4527       /* If [V0_MIN, V1_MAX] < [V1_MIN, V1_MAX] then V0 != V1.  */
4528       else if (compare_values_warnv (vr0->min, vr1->max,
4529                                      strict_overflow_p) == 1
4530                || compare_values_warnv (vr1->min, vr0->max,
4531                                         strict_overflow_p) == 1)
4532         return boolean_false_node;
4533
4534       return NULL_TREE;
4535     }
4536   else if (comp == NE_EXPR)
4537     {
4538       int cmp1, cmp2;
4539
4540       /* If VR0 is completely to the left or completely to the right
4541          of VR1, they are always different.  Notice that we need to
4542          make sure that both comparisons yield similar results to
4543          avoid comparing values that cannot be compared at
4544          compile-time.  */
4545       cmp1 = compare_values_warnv (vr0->max, vr1->min, strict_overflow_p);
4546       cmp2 = compare_values_warnv (vr0->min, vr1->max, strict_overflow_p);
4547       if ((cmp1 == -1 && cmp2 == -1) || (cmp1 == 1 && cmp2 == 1))
4548         return boolean_true_node;
4549
4550       /* If VR0 and VR1 represent a single value and are identical,
4551          return false.  */
4552       else if (compare_values_warnv (vr0->min, vr0->max,
4553                                      strict_overflow_p) == 0
4554                && compare_values_warnv (vr1->min, vr1->max,
4555                                         strict_overflow_p) == 0
4556                && compare_values_warnv (vr0->min, vr1->min,
4557                                         strict_overflow_p) == 0
4558                && compare_values_warnv (vr0->max, vr1->max,
4559                                         strict_overflow_p) == 0)
4560         return boolean_false_node;
4561
4562       /* Otherwise, they may or may not be different.  */
4563       else
4564         return NULL_TREE;
4565     }
4566   else if (comp == LT_EXPR || comp == LE_EXPR)
4567     {
4568       int tst;
4569
4570       /* If VR0 is to the left of VR1, return true.  */
4571       tst = compare_values_warnv (vr0->max, vr1->min, strict_overflow_p);
4572       if ((comp == LT_EXPR && tst == -1)
4573           || (comp == LE_EXPR && (tst == -1 || tst == 0)))
4574         {
4575           if (overflow_infinity_range_p (vr0)
4576               || overflow_infinity_range_p (vr1))
4577             *strict_overflow_p = true;
4578           return boolean_true_node;
4579         }
4580
4581       /* If VR0 is to the right of VR1, return false.  */
4582       tst = compare_values_warnv (vr0->min, vr1->max, strict_overflow_p);
4583       if ((comp == LT_EXPR && (tst == 0 || tst == 1))
4584           || (comp == LE_EXPR && tst == 1))
4585         {
4586           if (overflow_infinity_range_p (vr0)
4587               || overflow_infinity_range_p (vr1))
4588             *strict_overflow_p = true;
4589           return boolean_false_node;
4590         }
4591
4592       /* Otherwise, we don't know.  */
4593       return NULL_TREE;
4594     }
4595
4596   gcc_unreachable ();
4597 }
4598
4599
4600 /* Given a value range VR, a value VAL and a comparison code COMP, return
4601    BOOLEAN_TRUE_NODE if VR COMP VAL always returns true for all the
4602    values in VR.  Return BOOLEAN_FALSE_NODE if the comparison
4603    always returns false.  Return NULL_TREE if it is not always
4604    possible to determine the value of the comparison.  Also set
4605    *STRICT_OVERFLOW_P to indicate whether a range with an overflow
4606    infinity was used in the test.  */
4607
4608 static tree
4609 compare_range_with_value (enum tree_code comp, value_range_t *vr, tree val,
4610                           bool *strict_overflow_p)
4611 {
4612   if (vr->type == VR_VARYING || vr->type == VR_UNDEFINED)
4613     return NULL_TREE;
4614
4615   /* Anti-ranges need to be handled separately.  */
4616   if (vr->type == VR_ANTI_RANGE)
4617     {
4618       /* For anti-ranges, the only predicates that we can compute at
4619          compile time are equality and inequality.  */
4620       if (comp == GT_EXPR
4621           || comp == GE_EXPR
4622           || comp == LT_EXPR
4623           || comp == LE_EXPR)
4624         return NULL_TREE;
4625
4626       /* ~[VAL_1, VAL_2] OP VAL is known if VAL_1 <= VAL <= VAL_2.  */
4627       if (value_inside_range (val, vr->min, vr->max) == 1)
4628         return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
4629
4630       return NULL_TREE;
4631     }
4632
4633   if (!usable_range_p (vr, strict_overflow_p))
4634     return NULL_TREE;
4635
4636   if (comp == EQ_EXPR)
4637     {
4638       /* EQ_EXPR may only be computed if VR represents exactly
4639          one value.  */
4640       if (compare_values_warnv (vr->min, vr->max, strict_overflow_p) == 0)
4641         {
4642           int cmp = compare_values_warnv (vr->min, val, strict_overflow_p);
4643           if (cmp == 0)
4644             return boolean_true_node;
4645           else if (cmp == -1 || cmp == 1 || cmp == 2)
4646             return boolean_false_node;
4647         }
4648       else if (compare_values_warnv (val, vr->min, strict_overflow_p) == -1
4649                || compare_values_warnv (vr->max, val, strict_overflow_p) == -1)
4650         return boolean_false_node;
4651
4652       return NULL_TREE;
4653     }
4654   else if (comp == NE_EXPR)
4655     {
4656       /* If VAL is not inside VR, then they are always different.  */
4657       if (compare_values_warnv (vr->max, val, strict_overflow_p) == -1
4658           || compare_values_warnv (vr->min, val, strict_overflow_p) == 1)
4659         return boolean_true_node;
4660
4661       /* If VR represents exactly one value equal to VAL, then return
4662          false.  */
4663       if (compare_values_warnv (vr->min, vr->max, strict_overflow_p) == 0
4664           && compare_values_warnv (vr->min, val, strict_overflow_p) == 0)
4665         return boolean_false_node;
4666
4667       /* Otherwise, they may or may not be different.  */
4668       return NULL_TREE;
4669     }
4670   else if (comp == LT_EXPR || comp == LE_EXPR)
4671     {
4672       int tst;
4673
4674       /* If VR is to the left of VAL, return true.  */
4675       tst = compare_values_warnv (vr->max, val, strict_overflow_p);
4676       if ((comp == LT_EXPR && tst == -1)
4677           || (comp == LE_EXPR && (tst == -1 || tst == 0)))
4678         {
4679           if (overflow_infinity_range_p (vr))
4680             *strict_overflow_p = true;
4681           return boolean_true_node;
4682         }
4683
4684       /* If VR is to the right of VAL, return false.  */
4685       tst = compare_values_warnv (vr->min, val, strict_overflow_p);
4686       if ((comp == LT_EXPR && (tst == 0 || tst == 1))
4687           || (comp == LE_EXPR && tst == 1))
4688         {
4689           if (overflow_infinity_range_p (vr))
4690             *strict_overflow_p = true;
4691           return boolean_false_node;
4692         }
4693
4694       /* Otherwise, we don't know.  */
4695       return NULL_TREE;
4696     }
4697   else if (comp == GT_EXPR || comp == GE_EXPR)
4698     {
4699       int tst;
4700
4701       /* If VR is to the right of VAL, return true.  */
4702       tst = compare_values_warnv (vr->min, val, strict_overflow_p);
4703       if ((comp == GT_EXPR && tst == 1)
4704           || (comp == GE_EXPR && (tst == 0 || tst == 1)))
4705         {
4706           if (overflow_infinity_range_p (vr))
4707             *strict_overflow_p = true;
4708           return boolean_true_node;
4709         }
4710
4711       /* If VR is to the left of VAL, return false.  */
4712       tst = compare_values_warnv (vr->max, val, strict_overflow_p);
4713       if ((comp == GT_EXPR && (tst == -1 || tst == 0))
4714           || (comp == GE_EXPR && tst == -1))
4715         {
4716           if (overflow_infinity_range_p (vr))
4717             *strict_overflow_p = true;
4718           return boolean_false_node;
4719         }
4720
4721       /* Otherwise, we don't know.  */
4722       return NULL_TREE;
4723     }
4724
4725   gcc_unreachable ();
4726 }
4727
4728
4729 /* Debugging dumps.  */
4730
4731 void dump_value_range (FILE *, value_range_t *);
4732 void debug_value_range (value_range_t *);
4733 void dump_all_value_ranges (FILE *);
4734 void debug_all_value_ranges (void);
4735 void dump_vr_equiv (FILE *, bitmap);
4736 void debug_vr_equiv (bitmap);
4737
4738
4739 /* Dump value range VR to FILE.  */
4740
4741 void
4742 dump_value_range (FILE *file, value_range_t *vr)
4743 {
4744   if (vr == NULL)
4745     fprintf (file, "[]");
4746   else if (vr->type == VR_UNDEFINED)
4747     fprintf (file, "UNDEFINED");
4748   else if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
4749     {
4750       tree type = TREE_TYPE (vr->min);
4751
4752       fprintf (file, "%s[", (vr->type == VR_ANTI_RANGE) ? "~" : "");
4753
4754       if (is_negative_overflow_infinity (vr->min))
4755         fprintf (file, "-INF(OVF)");
4756       else if (INTEGRAL_TYPE_P (type)
4757                && !TYPE_UNSIGNED (type)
4758                && vrp_val_is_min (vr->min))
4759         fprintf (file, "-INF");
4760       else
4761         print_generic_expr (file, vr->min, 0);
4762
4763       fprintf (file, ", ");
4764
4765       if (is_positive_overflow_infinity (vr->max))
4766         fprintf (file, "+INF(OVF)");
4767       else if (INTEGRAL_TYPE_P (type)
4768                && vrp_val_is_max (vr->max))
4769         fprintf (file, "+INF");
4770       else
4771         print_generic_expr (file, vr->max, 0);
4772
4773       fprintf (file, "]");
4774
4775       if (vr->equiv)
4776         {
4777           bitmap_iterator bi;
4778           unsigned i, c = 0;
4779
4780           fprintf (file, "  EQUIVALENCES: { ");
4781
4782           EXECUTE_IF_SET_IN_BITMAP (vr->equiv, 0, i, bi)
4783             {
4784               print_generic_expr (file, ssa_name (i), 0);
4785               fprintf (file, " ");
4786               c++;
4787             }
4788
4789           fprintf (file, "} (%u elements)", c);
4790         }
4791     }
4792   else if (vr->type == VR_VARYING)
4793     fprintf (file, "VARYING");
4794   else
4795     fprintf (file, "INVALID RANGE");
4796 }
4797
4798
4799 /* Dump value range VR to stderr.  */
4800
4801 DEBUG_FUNCTION void
4802 debug_value_range (value_range_t *vr)
4803 {
4804   dump_value_range (stderr, vr);
4805   fprintf (stderr, "\n");
4806 }
4807
4808
4809 /* Dump value ranges of all SSA_NAMEs to FILE.  */
4810
4811 void
4812 dump_all_value_ranges (FILE *file)
4813 {
4814   size_t i;
4815
4816   for (i = 0; i < num_vr_values; i++)
4817     {
4818       if (vr_value[i])
4819         {
4820           print_generic_expr (file, ssa_name (i), 0);
4821           fprintf (file, ": ");
4822           dump_value_range (file, vr_value[i]);
4823           fprintf (file, "\n");
4824         }
4825     }
4826
4827   fprintf (file, "\n");
4828 }
4829
4830
4831 /* Dump all value ranges to stderr.  */
4832
4833 DEBUG_FUNCTION void
4834 debug_all_value_ranges (void)
4835 {
4836   dump_all_value_ranges (stderr);
4837 }
4838
4839
4840 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
4841    create a new SSA name N and return the assertion assignment
4842    'N = ASSERT_EXPR <V, V OP W>'.  */
4843
4844 static gimple
4845 build_assert_expr_for (tree cond, tree v)
4846 {
4847   tree a;
4848   gassign *assertion;
4849
4850   gcc_assert (TREE_CODE (v) == SSA_NAME
4851               && COMPARISON_CLASS_P (cond));
4852
4853   a = build2 (ASSERT_EXPR, TREE_TYPE (v), v, cond);
4854   assertion = gimple_build_assign (NULL_TREE, a);
4855
4856   /* The new ASSERT_EXPR, creates a new SSA name that replaces the
4857      operand of the ASSERT_EXPR.  Create it so the new name and the old one
4858      are registered in the replacement table so that we can fix the SSA web
4859      after adding all the ASSERT_EXPRs.  */
4860   create_new_def_for (v, assertion, NULL);
4861
4862   return assertion;
4863 }
4864
4865
4866 /* Return false if EXPR is a predicate expression involving floating
4867    point values.  */
4868
4869 static inline bool
4870 fp_predicate (gimple stmt)
4871 {
4872   GIMPLE_CHECK (stmt, GIMPLE_COND);
4873
4874   return FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)));
4875 }
4876
4877 /* If the range of values taken by OP can be inferred after STMT executes,
4878    return the comparison code (COMP_CODE_P) and value (VAL_P) that
4879    describes the inferred range.  Return true if a range could be
4880    inferred.  */
4881
4882 static bool
4883 infer_value_range (gimple stmt, tree op, enum tree_code *comp_code_p, tree *val_p)
4884 {
4885   *val_p = NULL_TREE;
4886   *comp_code_p = ERROR_MARK;
4887
4888   /* Do not attempt to infer anything in names that flow through
4889      abnormal edges.  */
4890   if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
4891     return false;
4892
4893   /* Similarly, don't infer anything from statements that may throw
4894      exceptions. ??? Relax this requirement?  */
4895   if (stmt_could_throw_p (stmt))
4896     return false;
4897
4898   /* If STMT is the last statement of a basic block with no normal
4899      successors, there is no point inferring anything about any of its
4900      operands.  We would not be able to find a proper insertion point
4901      for the assertion, anyway.  */
4902   if (stmt_ends_bb_p (stmt))
4903     {
4904       edge_iterator ei;
4905       edge e;
4906
4907       FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
4908         if (!(e->flags & EDGE_ABNORMAL))
4909           break;
4910       if (e == NULL)
4911         return false;
4912     }
4913
4914   if (infer_nonnull_range (stmt, op, true, true))
4915     {
4916       *val_p = build_int_cst (TREE_TYPE (op), 0);
4917       *comp_code_p = NE_EXPR;
4918       return true;
4919     }
4920
4921   return false;
4922 }
4923
4924
4925 void dump_asserts_for (FILE *, tree);
4926 void debug_asserts_for (tree);
4927 void dump_all_asserts (FILE *);
4928 void debug_all_asserts (void);
4929
4930 /* Dump all the registered assertions for NAME to FILE.  */
4931
4932 void
4933 dump_asserts_for (FILE *file, tree name)
4934 {
4935   assert_locus_t loc;
4936
4937   fprintf (file, "Assertions to be inserted for ");
4938   print_generic_expr (file, name, 0);
4939   fprintf (file, "\n");
4940
4941   loc = asserts_for[SSA_NAME_VERSION (name)];
4942   while (loc)
4943     {
4944       fprintf (file, "\t");
4945       print_gimple_stmt (file, gsi_stmt (loc->si), 0, 0);
4946       fprintf (file, "\n\tBB #%d", loc->bb->index);
4947       if (loc->e)
4948         {
4949           fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
4950                    loc->e->dest->index);
4951           dump_edge_info (file, loc->e, dump_flags, 0);
4952         }
4953       fprintf (file, "\n\tPREDICATE: ");
4954       print_generic_expr (file, name, 0);
4955       fprintf (file, " %s ", get_tree_code_name (loc->comp_code));
4956       print_generic_expr (file, loc->val, 0);
4957       fprintf (file, "\n\n");
4958       loc = loc->next;
4959     }
4960
4961   fprintf (file, "\n");
4962 }
4963
4964
4965 /* Dump all the registered assertions for NAME to stderr.  */
4966
4967 DEBUG_FUNCTION void
4968 debug_asserts_for (tree name)
4969 {
4970   dump_asserts_for (stderr, name);
4971 }
4972
4973
4974 /* Dump all the registered assertions for all the names to FILE.  */
4975
4976 void
4977 dump_all_asserts (FILE *file)
4978 {
4979   unsigned i;
4980   bitmap_iterator bi;
4981
4982   fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
4983   EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
4984     dump_asserts_for (file, ssa_name (i));
4985   fprintf (file, "\n");
4986 }
4987
4988
4989 /* Dump all the registered assertions for all the names to stderr.  */
4990
4991 DEBUG_FUNCTION void
4992 debug_all_asserts (void)
4993 {
4994   dump_all_asserts (stderr);
4995 }
4996
4997
4998 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
4999    'EXPR COMP_CODE VAL' at a location that dominates block BB or
5000    E->DEST, then register this location as a possible insertion point
5001    for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
5002
5003    BB, E and SI provide the exact insertion point for the new
5004    ASSERT_EXPR.  If BB is NULL, then the ASSERT_EXPR is to be inserted
5005    on edge E.  Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
5006    BB.  If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
5007    must not be NULL.  */
5008
5009 static void
5010 register_new_assert_for (tree name, tree expr,
5011                          enum tree_code comp_code,
5012                          tree val,
5013                          basic_block bb,
5014                          edge e,
5015                          gimple_stmt_iterator si)
5016 {
5017   assert_locus_t n, loc, last_loc;
5018   basic_block dest_bb;
5019
5020   gcc_checking_assert (bb == NULL || e == NULL);
5021
5022   if (e == NULL)
5023     gcc_checking_assert (gimple_code (gsi_stmt (si)) != GIMPLE_COND
5024                          && gimple_code (gsi_stmt (si)) != GIMPLE_SWITCH);
5025
5026   /* Never build an assert comparing against an integer constant with
5027      TREE_OVERFLOW set.  This confuses our undefined overflow warning
5028      machinery.  */
5029   if (TREE_OVERFLOW_P (val))
5030     val = drop_tree_overflow (val);
5031
5032   /* The new assertion A will be inserted at BB or E.  We need to
5033      determine if the new location is dominated by a previously
5034      registered location for A.  If we are doing an edge insertion,
5035      assume that A will be inserted at E->DEST.  Note that this is not
5036      necessarily true.
5037
5038      If E is a critical edge, it will be split.  But even if E is
5039      split, the new block will dominate the same set of blocks that
5040      E->DEST dominates.
5041
5042      The reverse, however, is not true, blocks dominated by E->DEST
5043      will not be dominated by the new block created to split E.  So,
5044      if the insertion location is on a critical edge, we will not use
5045      the new location to move another assertion previously registered
5046      at a block dominated by E->DEST.  */
5047   dest_bb = (bb) ? bb : e->dest;
5048
5049   /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
5050      VAL at a block dominating DEST_BB, then we don't need to insert a new
5051      one.  Similarly, if the same assertion already exists at a block
5052      dominated by DEST_BB and the new location is not on a critical
5053      edge, then update the existing location for the assertion (i.e.,
5054      move the assertion up in the dominance tree).
5055
5056      Note, this is implemented as a simple linked list because there
5057      should not be more than a handful of assertions registered per
5058      name.  If this becomes a performance problem, a table hashed by
5059      COMP_CODE and VAL could be implemented.  */
5060   loc = asserts_for[SSA_NAME_VERSION (name)];
5061   last_loc = loc;
5062   while (loc)
5063     {
5064       if (loc->comp_code == comp_code
5065           && (loc->val == val
5066               || operand_equal_p (loc->val, val, 0))
5067           && (loc->expr == expr
5068               || operand_equal_p (loc->expr, expr, 0)))
5069         {
5070           /* If E is not a critical edge and DEST_BB
5071              dominates the existing location for the assertion, move
5072              the assertion up in the dominance tree by updating its
5073              location information.  */
5074           if ((e == NULL || !EDGE_CRITICAL_P (e))
5075               && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
5076             {
5077               loc->bb = dest_bb;
5078               loc->e = e;
5079               loc->si = si;
5080               return;
5081             }
5082         }
5083
5084       /* Update the last node of the list and move to the next one.  */
5085       last_loc = loc;
5086       loc = loc->next;
5087     }
5088
5089   /* If we didn't find an assertion already registered for
5090      NAME COMP_CODE VAL, add a new one at the end of the list of
5091      assertions associated with NAME.  */
5092   n = XNEW (struct assert_locus_d);
5093   n->bb = dest_bb;
5094   n->e = e;
5095   n->si = si;
5096   n->comp_code = comp_code;
5097   n->val = val;
5098   n->expr = expr;
5099   n->next = NULL;
5100
5101   if (last_loc)
5102     last_loc->next = n;
5103   else
5104     asserts_for[SSA_NAME_VERSION (name)] = n;
5105
5106   bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
5107 }
5108
5109 /* (COND_OP0 COND_CODE COND_OP1) is a predicate which uses NAME.
5110    Extract a suitable test code and value and store them into *CODE_P and
5111    *VAL_P so the predicate is normalized to NAME *CODE_P *VAL_P.
5112
5113    If no extraction was possible, return FALSE, otherwise return TRUE.
5114
5115    If INVERT is true, then we invert the result stored into *CODE_P.  */
5116
5117 static bool
5118 extract_code_and_val_from_cond_with_ops (tree name, enum tree_code cond_code,
5119                                          tree cond_op0, tree cond_op1,
5120                                          bool invert, enum tree_code *code_p,
5121                                          tree *val_p)
5122 {
5123   enum tree_code comp_code;
5124   tree val;
5125
5126   /* Otherwise, we have a comparison of the form NAME COMP VAL
5127      or VAL COMP NAME.  */
5128   if (name == cond_op1)
5129     {
5130       /* If the predicate is of the form VAL COMP NAME, flip
5131          COMP around because we need to register NAME as the
5132          first operand in the predicate.  */
5133       comp_code = swap_tree_comparison (cond_code);
5134       val = cond_op0;
5135     }
5136   else
5137     {
5138       /* The comparison is of the form NAME COMP VAL, so the
5139          comparison code remains unchanged.  */
5140       comp_code = cond_code;
5141       val = cond_op1;
5142     }
5143
5144   /* Invert the comparison code as necessary.  */
5145   if (invert)
5146     comp_code = invert_tree_comparison (comp_code, 0);
5147
5148   /* VRP does not handle float types.  */
5149   if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (val)))
5150     return false;
5151
5152   /* Do not register always-false predicates.
5153      FIXME:  this works around a limitation in fold() when dealing with
5154      enumerations.  Given 'enum { N1, N2 } x;', fold will not
5155      fold 'if (x > N2)' to 'if (0)'.  */
5156   if ((comp_code == GT_EXPR || comp_code == LT_EXPR)
5157       && INTEGRAL_TYPE_P (TREE_TYPE (val)))
5158     {
5159       tree min = TYPE_MIN_VALUE (TREE_TYPE (val));
5160       tree max = TYPE_MAX_VALUE (TREE_TYPE (val));
5161
5162       if (comp_code == GT_EXPR
5163           && (!max
5164               || compare_values (val, max) == 0))
5165         return false;
5166
5167       if (comp_code == LT_EXPR
5168           && (!min
5169               || compare_values (val, min) == 0))
5170         return false;
5171     }
5172   *code_p = comp_code;
5173   *val_p = val;
5174   return true;
5175 }
5176
5177 /* Find out smallest RES where RES > VAL && (RES & MASK) == RES, if any
5178    (otherwise return VAL).  VAL and MASK must be zero-extended for
5179    precision PREC.  If SGNBIT is non-zero, first xor VAL with SGNBIT
5180    (to transform signed values into unsigned) and at the end xor
5181    SGNBIT back.  */
5182
5183 static wide_int
5184 masked_increment (const wide_int &val_in, const wide_int &mask,
5185                   const wide_int &sgnbit, unsigned int prec)
5186 {
5187   wide_int bit = wi::one (prec), res;
5188   unsigned int i;
5189
5190   wide_int val = val_in ^ sgnbit;
5191   for (i = 0; i < prec; i++, bit += bit)
5192     {
5193       res = mask;
5194       if ((res & bit) == 0)
5195         continue;
5196       res = bit - 1;
5197       res = (val + bit).and_not (res);
5198       res &= mask;
5199       if (wi::gtu_p (res, val))
5200         return res ^ sgnbit;
5201     }
5202   return val ^ sgnbit;
5203 }
5204
5205 /* Try to register an edge assertion for SSA name NAME on edge E for
5206    the condition COND contributing to the conditional jump pointed to by BSI.
5207    Invert the condition COND if INVERT is true.  */
5208
5209 static void
5210 register_edge_assert_for_2 (tree name, edge e, gimple_stmt_iterator bsi,
5211                             enum tree_code cond_code,
5212                             tree cond_op0, tree cond_op1, bool invert)
5213 {
5214   tree val;
5215   enum tree_code comp_code;
5216
5217   if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
5218                                                 cond_op0,
5219                                                 cond_op1,
5220                                                 invert, &comp_code, &val))
5221     return;
5222
5223   /* Only register an ASSERT_EXPR if NAME was found in the sub-graph
5224      reachable from E.  */
5225   if (live_on_edge (e, name)
5226       && !has_single_use (name))
5227     register_new_assert_for (name, name, comp_code, val, NULL, e, bsi);
5228
5229   /* In the case of NAME <= CST and NAME being defined as
5230      NAME = (unsigned) NAME2 + CST2 we can assert NAME2 >= -CST2
5231      and NAME2 <= CST - CST2.  We can do the same for NAME > CST.
5232      This catches range and anti-range tests.  */
5233   if ((comp_code == LE_EXPR
5234        || comp_code == GT_EXPR)
5235       && TREE_CODE (val) == INTEGER_CST
5236       && TYPE_UNSIGNED (TREE_TYPE (val)))
5237     {
5238       gimple def_stmt = SSA_NAME_DEF_STMT (name);
5239       tree cst2 = NULL_TREE, name2 = NULL_TREE, name3 = NULL_TREE;
5240
5241       /* Extract CST2 from the (optional) addition.  */
5242       if (is_gimple_assign (def_stmt)
5243           && gimple_assign_rhs_code (def_stmt) == PLUS_EXPR)
5244         {
5245           name2 = gimple_assign_rhs1 (def_stmt);
5246           cst2 = gimple_assign_rhs2 (def_stmt);
5247           if (TREE_CODE (name2) == SSA_NAME
5248               && TREE_CODE (cst2) == INTEGER_CST)
5249             def_stmt = SSA_NAME_DEF_STMT (name2);
5250         }
5251
5252       /* Extract NAME2 from the (optional) sign-changing cast.  */
5253       if (gimple_assign_cast_p (def_stmt))
5254         {
5255           if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt))
5256               && ! TYPE_UNSIGNED (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
5257               && (TYPE_PRECISION (gimple_expr_type (def_stmt))
5258                   == TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))))
5259             name3 = gimple_assign_rhs1 (def_stmt);
5260         }
5261
5262       /* If name3 is used later, create an ASSERT_EXPR for it.  */
5263       if (name3 != NULL_TREE
5264           && TREE_CODE (name3) == SSA_NAME
5265           && (cst2 == NULL_TREE
5266               || TREE_CODE (cst2) == INTEGER_CST)
5267           && INTEGRAL_TYPE_P (TREE_TYPE (name3))
5268           && live_on_edge (e, name3)
5269           && !has_single_use (name3))
5270         {
5271           tree tmp;
5272
5273           /* Build an expression for the range test.  */
5274           tmp = build1 (NOP_EXPR, TREE_TYPE (name), name3);
5275           if (cst2 != NULL_TREE)
5276             tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
5277
5278           if (dump_file)
5279             {
5280               fprintf (dump_file, "Adding assert for ");
5281               print_generic_expr (dump_file, name3, 0);
5282               fprintf (dump_file, " from ");
5283               print_generic_expr (dump_file, tmp, 0);
5284               fprintf (dump_file, "\n");
5285             }
5286
5287           register_new_assert_for (name3, tmp, comp_code, val, NULL, e, bsi);
5288         }
5289
5290       /* If name2 is used later, create an ASSERT_EXPR for it.  */
5291       if (name2 != NULL_TREE
5292           && TREE_CODE (name2) == SSA_NAME
5293           && TREE_CODE (cst2) == INTEGER_CST
5294           && INTEGRAL_TYPE_P (TREE_TYPE (name2))
5295           && live_on_edge (e, name2)
5296           && !has_single_use (name2))
5297         {
5298           tree tmp;
5299
5300           /* Build an expression for the range test.  */
5301           tmp = name2;
5302           if (TREE_TYPE (name) != TREE_TYPE (name2))
5303             tmp = build1 (NOP_EXPR, TREE_TYPE (name), tmp);
5304           if (cst2 != NULL_TREE)
5305             tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
5306
5307           if (dump_file)
5308             {
5309               fprintf (dump_file, "Adding assert for ");
5310               print_generic_expr (dump_file, name2, 0);
5311               fprintf (dump_file, " from ");
5312               print_generic_expr (dump_file, tmp, 0);
5313               fprintf (dump_file, "\n");
5314             }
5315
5316           register_new_assert_for (name2, tmp, comp_code, val, NULL, e, bsi);
5317         }
5318     }
5319
5320   /* In the case of post-in/decrement tests like if (i++) ... and uses
5321      of the in/decremented value on the edge the extra name we want to
5322      assert for is not on the def chain of the name compared.  Instead
5323      it is in the set of use stmts.  */
5324   if ((comp_code == NE_EXPR
5325        || comp_code == EQ_EXPR)
5326       && TREE_CODE (val) == INTEGER_CST)
5327     {
5328       imm_use_iterator ui;
5329       gimple use_stmt;
5330       FOR_EACH_IMM_USE_STMT (use_stmt, ui, name)
5331         {
5332           /* Cut off to use-stmts that are in the predecessor.  */
5333           if (gimple_bb (use_stmt) != e->src)
5334             continue;
5335
5336           if (!is_gimple_assign (use_stmt))
5337             continue;
5338
5339           enum tree_code code = gimple_assign_rhs_code (use_stmt);
5340           if (code != PLUS_EXPR
5341               && code != MINUS_EXPR)
5342             continue;
5343
5344           tree cst = gimple_assign_rhs2 (use_stmt);
5345           if (TREE_CODE (cst) != INTEGER_CST)
5346             continue;
5347
5348           tree name2 = gimple_assign_lhs (use_stmt);
5349           if (live_on_edge (e, name2))
5350             {
5351               cst = int_const_binop (code, val, cst);
5352               register_new_assert_for (name2, name2, comp_code, cst,
5353                                        NULL, e, bsi);
5354             }
5355         }
5356     }
5357  
5358   if (TREE_CODE_CLASS (comp_code) == tcc_comparison
5359       && TREE_CODE (val) == INTEGER_CST)
5360     {
5361       gimple def_stmt = SSA_NAME_DEF_STMT (name);
5362       tree name2 = NULL_TREE, names[2], cst2 = NULL_TREE;
5363       tree val2 = NULL_TREE;
5364       unsigned int prec = TYPE_PRECISION (TREE_TYPE (val));
5365       wide_int mask = wi::zero (prec);
5366       unsigned int nprec = prec;
5367       enum tree_code rhs_code = ERROR_MARK;
5368
5369       if (is_gimple_assign (def_stmt))
5370         rhs_code = gimple_assign_rhs_code (def_stmt);
5371
5372       /* Add asserts for NAME cmp CST and NAME being defined
5373          as NAME = (int) NAME2.  */
5374       if (!TYPE_UNSIGNED (TREE_TYPE (val))
5375           && (comp_code == LE_EXPR || comp_code == LT_EXPR
5376               || comp_code == GT_EXPR || comp_code == GE_EXPR)
5377           && gimple_assign_cast_p (def_stmt))
5378         {
5379           name2 = gimple_assign_rhs1 (def_stmt);
5380           if (CONVERT_EXPR_CODE_P (rhs_code)
5381               && INTEGRAL_TYPE_P (TREE_TYPE (name2))
5382               && TYPE_UNSIGNED (TREE_TYPE (name2))
5383               && prec == TYPE_PRECISION (TREE_TYPE (name2))
5384               && (comp_code == LE_EXPR || comp_code == GT_EXPR
5385                   || !tree_int_cst_equal (val,
5386                                           TYPE_MIN_VALUE (TREE_TYPE (val))))
5387               && live_on_edge (e, name2)
5388               && !has_single_use (name2))
5389             {
5390               tree tmp, cst;
5391               enum tree_code new_comp_code = comp_code;
5392
5393               cst = fold_convert (TREE_TYPE (name2),
5394                                   TYPE_MIN_VALUE (TREE_TYPE (val)));
5395               /* Build an expression for the range test.  */
5396               tmp = build2 (PLUS_EXPR, TREE_TYPE (name2), name2, cst);
5397               cst = fold_build2 (PLUS_EXPR, TREE_TYPE (name2), cst,
5398                                  fold_convert (TREE_TYPE (name2), val));
5399               if (comp_code == LT_EXPR || comp_code == GE_EXPR)
5400                 {
5401                   new_comp_code = comp_code == LT_EXPR ? LE_EXPR : GT_EXPR;
5402                   cst = fold_build2 (MINUS_EXPR, TREE_TYPE (name2), cst,
5403                                      build_int_cst (TREE_TYPE (name2), 1));
5404                 }
5405
5406               if (dump_file)
5407                 {
5408                   fprintf (dump_file, "Adding assert for ");
5409                   print_generic_expr (dump_file, name2, 0);
5410                   fprintf (dump_file, " from ");
5411                   print_generic_expr (dump_file, tmp, 0);
5412                   fprintf (dump_file, "\n");
5413                 }
5414
5415               register_new_assert_for (name2, tmp, new_comp_code, cst, NULL,
5416                                        e, bsi);
5417             }
5418         }
5419
5420       /* Add asserts for NAME cmp CST and NAME being defined as
5421          NAME = NAME2 >> CST2.
5422
5423          Extract CST2 from the right shift.  */
5424       if (rhs_code == RSHIFT_EXPR)
5425         {
5426           name2 = gimple_assign_rhs1 (def_stmt);
5427           cst2 = gimple_assign_rhs2 (def_stmt);
5428           if (TREE_CODE (name2) == SSA_NAME
5429               && tree_fits_uhwi_p (cst2)
5430               && INTEGRAL_TYPE_P (TREE_TYPE (name2))
5431               && IN_RANGE (tree_to_uhwi (cst2), 1, prec - 1)
5432               && prec == GET_MODE_PRECISION (TYPE_MODE (TREE_TYPE (val)))
5433               && live_on_edge (e, name2)
5434               && !has_single_use (name2))
5435             {
5436               mask = wi::mask (tree_to_uhwi (cst2), false, prec);
5437               val2 = fold_binary (LSHIFT_EXPR, TREE_TYPE (val), val, cst2);
5438             }
5439         }
5440       if (val2 != NULL_TREE
5441           && TREE_CODE (val2) == INTEGER_CST
5442           && simple_cst_equal (fold_build2 (RSHIFT_EXPR,
5443                                             TREE_TYPE (val),
5444                                             val2, cst2), val))
5445         {
5446           enum tree_code new_comp_code = comp_code;
5447           tree tmp, new_val;
5448
5449           tmp = name2;
5450           if (comp_code == EQ_EXPR || comp_code == NE_EXPR)
5451             {
5452               if (!TYPE_UNSIGNED (TREE_TYPE (val)))
5453                 {
5454                   tree type = build_nonstandard_integer_type (prec, 1);
5455                   tmp = build1 (NOP_EXPR, type, name2);
5456                   val2 = fold_convert (type, val2);
5457                 }
5458               tmp = fold_build2 (MINUS_EXPR, TREE_TYPE (tmp), tmp, val2);
5459               new_val = wide_int_to_tree (TREE_TYPE (tmp), mask);
5460               new_comp_code = comp_code == EQ_EXPR ? LE_EXPR : GT_EXPR;
5461             }
5462           else if (comp_code == LT_EXPR || comp_code == GE_EXPR)
5463             {
5464               wide_int minval
5465                 = wi::min_value (prec, TYPE_SIGN (TREE_TYPE (val)));
5466               new_val = val2;
5467               if (minval == new_val)
5468                 new_val = NULL_TREE;
5469             }
5470           else
5471             {
5472               wide_int maxval
5473                 = wi::max_value (prec, TYPE_SIGN (TREE_TYPE (val)));
5474               mask |= val2;
5475               if (mask == maxval)
5476                 new_val = NULL_TREE;
5477               else
5478                 new_val = wide_int_to_tree (TREE_TYPE (val2), mask);
5479             }
5480
5481           if (new_val)
5482             {
5483               if (dump_file)
5484                 {
5485                   fprintf (dump_file, "Adding assert for ");
5486                   print_generic_expr (dump_file, name2, 0);
5487                   fprintf (dump_file, " from ");
5488                   print_generic_expr (dump_file, tmp, 0);
5489                   fprintf (dump_file, "\n");
5490                 }
5491
5492               register_new_assert_for (name2, tmp, new_comp_code, new_val,
5493                                        NULL, e, bsi);
5494             }
5495         }
5496
5497       /* Add asserts for NAME cmp CST and NAME being defined as
5498          NAME = NAME2 & CST2.
5499
5500          Extract CST2 from the and.
5501
5502          Also handle
5503          NAME = (unsigned) NAME2;
5504          casts where NAME's type is unsigned and has smaller precision
5505          than NAME2's type as if it was NAME = NAME2 & MASK.  */
5506       names[0] = NULL_TREE;
5507       names[1] = NULL_TREE;
5508       cst2 = NULL_TREE;
5509       if (rhs_code == BIT_AND_EXPR
5510           || (CONVERT_EXPR_CODE_P (rhs_code)
5511               && TREE_CODE (TREE_TYPE (val)) == INTEGER_TYPE
5512               && TYPE_UNSIGNED (TREE_TYPE (val))
5513               && TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
5514                  > prec))
5515         {
5516           name2 = gimple_assign_rhs1 (def_stmt);
5517           if (rhs_code == BIT_AND_EXPR)
5518             cst2 = gimple_assign_rhs2 (def_stmt);
5519           else
5520             {
5521               cst2 = TYPE_MAX_VALUE (TREE_TYPE (val));
5522               nprec = TYPE_PRECISION (TREE_TYPE (name2));
5523             }
5524           if (TREE_CODE (name2) == SSA_NAME
5525               && INTEGRAL_TYPE_P (TREE_TYPE (name2))
5526               && TREE_CODE (cst2) == INTEGER_CST
5527               && !integer_zerop (cst2)
5528               && (nprec > 1
5529                   || TYPE_UNSIGNED (TREE_TYPE (val))))
5530             {
5531               gimple def_stmt2 = SSA_NAME_DEF_STMT (name2);
5532               if (gimple_assign_cast_p (def_stmt2))
5533                 {
5534                   names[1] = gimple_assign_rhs1 (def_stmt2);
5535                   if (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt2))
5536                       || !INTEGRAL_TYPE_P (TREE_TYPE (names[1]))
5537                       || (TYPE_PRECISION (TREE_TYPE (name2))
5538                           != TYPE_PRECISION (TREE_TYPE (names[1])))
5539                       || !live_on_edge (e, names[1])
5540                       || has_single_use (names[1]))
5541                     names[1] = NULL_TREE;
5542                 }
5543               if (live_on_edge (e, name2)
5544                   && !has_single_use (name2))
5545                 names[0] = name2;
5546             }
5547         }
5548       if (names[0] || names[1])
5549         {
5550           wide_int minv, maxv, valv, cst2v;
5551           wide_int tem, sgnbit;
5552           bool valid_p = false, valn, cst2n;
5553           enum tree_code ccode = comp_code;
5554
5555           valv = wide_int::from (val, nprec, UNSIGNED);
5556           cst2v = wide_int::from (cst2, nprec, UNSIGNED);
5557           valn = wi::neg_p (valv, TYPE_SIGN (TREE_TYPE (val)));
5558           cst2n = wi::neg_p (cst2v, TYPE_SIGN (TREE_TYPE (val)));
5559           /* If CST2 doesn't have most significant bit set,
5560              but VAL is negative, we have comparison like
5561              if ((x & 0x123) > -4) (always true).  Just give up.  */
5562           if (!cst2n && valn)
5563             ccode = ERROR_MARK;
5564           if (cst2n)
5565             sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
5566           else
5567             sgnbit = wi::zero (nprec);
5568           minv = valv & cst2v;
5569           switch (ccode)
5570             {
5571             case EQ_EXPR:
5572               /* Minimum unsigned value for equality is VAL & CST2
5573                  (should be equal to VAL, otherwise we probably should
5574                  have folded the comparison into false) and
5575                  maximum unsigned value is VAL | ~CST2.  */
5576               maxv = valv | ~cst2v;
5577               valid_p = true;
5578               break;
5579
5580             case NE_EXPR:
5581               tem = valv | ~cst2v;
5582               /* If VAL is 0, handle (X & CST2) != 0 as (X & CST2) > 0U.  */
5583               if (valv == 0)
5584                 {
5585                   cst2n = false;
5586                   sgnbit = wi::zero (nprec);
5587                   goto gt_expr;
5588                 }
5589               /* If (VAL | ~CST2) is all ones, handle it as
5590                  (X & CST2) < VAL.  */
5591               if (tem == -1)
5592                 {
5593                   cst2n = false;
5594                   valn = false;
5595                   sgnbit = wi::zero (nprec);
5596                   goto lt_expr;
5597                 }
5598               if (!cst2n && wi::neg_p (cst2v))
5599                 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
5600               if (sgnbit != 0)
5601                 {
5602                   if (valv == sgnbit)
5603                     {
5604                       cst2n = true;
5605                       valn = true;
5606                       goto gt_expr;
5607                     }
5608                   if (tem == wi::mask (nprec - 1, false, nprec))
5609                     {
5610                       cst2n = true;
5611                       goto lt_expr;
5612                     }
5613                   if (!cst2n)
5614                     sgnbit = wi::zero (nprec);
5615                 }
5616               break;
5617
5618             case GE_EXPR:
5619               /* Minimum unsigned value for >= if (VAL & CST2) == VAL
5620                  is VAL and maximum unsigned value is ~0.  For signed
5621                  comparison, if CST2 doesn't have most significant bit
5622                  set, handle it similarly.  If CST2 has MSB set,
5623                  the minimum is the same, and maximum is ~0U/2.  */
5624               if (minv != valv)
5625                 {
5626                   /* If (VAL & CST2) != VAL, X & CST2 can't be equal to
5627                      VAL.  */
5628                   minv = masked_increment (valv, cst2v, sgnbit, nprec);
5629                   if (minv == valv)
5630                     break;
5631                 }
5632               maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
5633               valid_p = true;
5634               break;
5635
5636             case GT_EXPR:
5637             gt_expr:
5638               /* Find out smallest MINV where MINV > VAL
5639                  && (MINV & CST2) == MINV, if any.  If VAL is signed and
5640                  CST2 has MSB set, compute it biased by 1 << (nprec - 1).  */
5641               minv = masked_increment (valv, cst2v, sgnbit, nprec);
5642               if (minv == valv)
5643                 break;
5644               maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
5645               valid_p = true;
5646               break;
5647
5648             case LE_EXPR:
5649               /* Minimum unsigned value for <= is 0 and maximum
5650                  unsigned value is VAL | ~CST2 if (VAL & CST2) == VAL.
5651                  Otherwise, find smallest VAL2 where VAL2 > VAL
5652                  && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
5653                  as maximum.
5654                  For signed comparison, if CST2 doesn't have most
5655                  significant bit set, handle it similarly.  If CST2 has
5656                  MSB set, the maximum is the same and minimum is INT_MIN.  */
5657               if (minv == valv)
5658                 maxv = valv;
5659               else
5660                 {
5661                   maxv = masked_increment (valv, cst2v, sgnbit, nprec);
5662                   if (maxv == valv)
5663                     break;
5664                   maxv -= 1;
5665                 }
5666               maxv |= ~cst2v;
5667               minv = sgnbit;
5668               valid_p = true;
5669               break;
5670
5671             case LT_EXPR:
5672             lt_expr:
5673               /* Minimum unsigned value for < is 0 and maximum
5674                  unsigned value is (VAL-1) | ~CST2 if (VAL & CST2) == VAL.
5675                  Otherwise, find smallest VAL2 where VAL2 > VAL
5676                  && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
5677                  as maximum.
5678                  For signed comparison, if CST2 doesn't have most
5679                  significant bit set, handle it similarly.  If CST2 has
5680                  MSB set, the maximum is the same and minimum is INT_MIN.  */
5681               if (minv == valv)
5682                 {
5683                   if (valv == sgnbit)
5684                     break;
5685                   maxv = valv;
5686                 }
5687               else
5688                 {
5689                   maxv = masked_increment (valv, cst2v, sgnbit, nprec);
5690                   if (maxv == valv)
5691                     break;
5692                 }
5693               maxv -= 1;
5694               maxv |= ~cst2v;
5695               minv = sgnbit;
5696               valid_p = true;
5697               break;
5698
5699             default:
5700               break;
5701             }
5702           if (valid_p
5703               && (maxv - minv) != -1)
5704             {
5705               tree tmp, new_val, type;
5706               int i;
5707
5708               for (i = 0; i < 2; i++)
5709                 if (names[i])
5710                   {
5711                     wide_int maxv2 = maxv;
5712                     tmp = names[i];
5713                     type = TREE_TYPE (names[i]);
5714                     if (!TYPE_UNSIGNED (type))
5715                       {
5716                         type = build_nonstandard_integer_type (nprec, 1);
5717                         tmp = build1 (NOP_EXPR, type, names[i]);
5718                       }
5719                     if (minv != 0)
5720                       {
5721                         tmp = build2 (PLUS_EXPR, type, tmp,
5722                                       wide_int_to_tree (type, -minv));
5723                         maxv2 = maxv - minv;
5724                       }
5725                     new_val = wide_int_to_tree (type, maxv2);
5726
5727                     if (dump_file)
5728                       {
5729                         fprintf (dump_file, "Adding assert for ");
5730                         print_generic_expr (dump_file, names[i], 0);
5731                         fprintf (dump_file, " from ");
5732                         print_generic_expr (dump_file, tmp, 0);
5733                         fprintf (dump_file, "\n");
5734                       }
5735
5736                     register_new_assert_for (names[i], tmp, LE_EXPR,
5737                                              new_val, NULL, e, bsi);
5738                   }
5739             }
5740         }
5741     }
5742 }
5743
5744 /* OP is an operand of a truth value expression which is known to have
5745    a particular value.  Register any asserts for OP and for any
5746    operands in OP's defining statement.
5747
5748    If CODE is EQ_EXPR, then we want to register OP is zero (false),
5749    if CODE is NE_EXPR, then we want to register OP is nonzero (true).   */
5750
5751 static void
5752 register_edge_assert_for_1 (tree op, enum tree_code code,
5753                             edge e, gimple_stmt_iterator bsi)
5754 {
5755   gimple op_def;
5756   tree val;
5757   enum tree_code rhs_code;
5758
5759   /* We only care about SSA_NAMEs.  */
5760   if (TREE_CODE (op) != SSA_NAME)
5761     return;
5762
5763   /* We know that OP will have a zero or nonzero value.  If OP is used
5764      more than once go ahead and register an assert for OP.  */
5765   if (live_on_edge (e, op)
5766       && !has_single_use (op))
5767     {
5768       val = build_int_cst (TREE_TYPE (op), 0);
5769       register_new_assert_for (op, op, code, val, NULL, e, bsi);
5770     }
5771
5772   /* Now look at how OP is set.  If it's set from a comparison,
5773      a truth operation or some bit operations, then we may be able
5774      to register information about the operands of that assignment.  */
5775   op_def = SSA_NAME_DEF_STMT (op);
5776   if (gimple_code (op_def) != GIMPLE_ASSIGN)
5777     return;
5778
5779   rhs_code = gimple_assign_rhs_code (op_def);
5780
5781   if (TREE_CODE_CLASS (rhs_code) == tcc_comparison)
5782     {
5783       bool invert = (code == EQ_EXPR ? true : false);
5784       tree op0 = gimple_assign_rhs1 (op_def);
5785       tree op1 = gimple_assign_rhs2 (op_def);
5786
5787       if (TREE_CODE (op0) == SSA_NAME)
5788         register_edge_assert_for_2 (op0, e, bsi, rhs_code, op0, op1, invert);
5789       if (TREE_CODE (op1) == SSA_NAME)
5790         register_edge_assert_for_2 (op1, e, bsi, rhs_code, op0, op1, invert);
5791     }
5792   else if ((code == NE_EXPR
5793             && gimple_assign_rhs_code (op_def) == BIT_AND_EXPR)
5794            || (code == EQ_EXPR
5795                && gimple_assign_rhs_code (op_def) == BIT_IOR_EXPR))
5796     {
5797       /* Recurse on each operand.  */
5798       tree op0 = gimple_assign_rhs1 (op_def);
5799       tree op1 = gimple_assign_rhs2 (op_def);
5800       if (TREE_CODE (op0) == SSA_NAME
5801           && has_single_use (op0))
5802         register_edge_assert_for_1 (op0, code, e, bsi);
5803       if (TREE_CODE (op1) == SSA_NAME
5804           && has_single_use (op1))
5805         register_edge_assert_for_1 (op1, code, e, bsi);
5806     }
5807   else if (gimple_assign_rhs_code (op_def) == BIT_NOT_EXPR
5808            && TYPE_PRECISION (TREE_TYPE (gimple_assign_lhs (op_def))) == 1)
5809     {
5810       /* Recurse, flipping CODE.  */
5811       code = invert_tree_comparison (code, false);
5812       register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, bsi);
5813     }
5814   else if (gimple_assign_rhs_code (op_def) == SSA_NAME)
5815     {
5816       /* Recurse through the copy.  */
5817       register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, bsi);
5818     }
5819   else if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (op_def)))
5820     {
5821       /* Recurse through the type conversion, unless it is a narrowing
5822          conversion or conversion from non-integral type.  */
5823       tree rhs = gimple_assign_rhs1 (op_def);
5824       if (INTEGRAL_TYPE_P (TREE_TYPE (rhs))
5825           && (TYPE_PRECISION (TREE_TYPE (rhs))
5826               <= TYPE_PRECISION (TREE_TYPE (op))))
5827         register_edge_assert_for_1 (rhs, code, e, bsi);
5828     }
5829 }
5830
5831 /* Try to register an edge assertion for SSA name NAME on edge E for
5832    the condition COND contributing to the conditional jump pointed to by
5833    SI.  */
5834
5835 static void
5836 register_edge_assert_for (tree name, edge e, gimple_stmt_iterator si,
5837                           enum tree_code cond_code, tree cond_op0,
5838                           tree cond_op1)
5839 {
5840   tree val;
5841   enum tree_code comp_code;
5842   bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
5843
5844   /* Do not attempt to infer anything in names that flow through
5845      abnormal edges.  */
5846   if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
5847     return;
5848
5849   if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
5850                                                 cond_op0, cond_op1,
5851                                                 is_else_edge,
5852                                                 &comp_code, &val))
5853     return;
5854
5855   /* Register ASSERT_EXPRs for name.  */
5856   register_edge_assert_for_2 (name, e, si, cond_code, cond_op0,
5857                               cond_op1, is_else_edge);
5858
5859
5860   /* If COND is effectively an equality test of an SSA_NAME against
5861      the value zero or one, then we may be able to assert values
5862      for SSA_NAMEs which flow into COND.  */
5863
5864   /* In the case of NAME == 1 or NAME != 0, for BIT_AND_EXPR defining
5865      statement of NAME we can assert both operands of the BIT_AND_EXPR
5866      have nonzero value.  */
5867   if (((comp_code == EQ_EXPR && integer_onep (val))
5868        || (comp_code == NE_EXPR && integer_zerop (val))))
5869     {
5870       gimple def_stmt = SSA_NAME_DEF_STMT (name);
5871
5872       if (is_gimple_assign (def_stmt)
5873           && gimple_assign_rhs_code (def_stmt) == BIT_AND_EXPR)
5874         {
5875           tree op0 = gimple_assign_rhs1 (def_stmt);
5876           tree op1 = gimple_assign_rhs2 (def_stmt);
5877           register_edge_assert_for_1 (op0, NE_EXPR, e, si);
5878           register_edge_assert_for_1 (op1, NE_EXPR, e, si);
5879         }
5880     }
5881
5882   /* In the case of NAME == 0 or NAME != 1, for BIT_IOR_EXPR defining
5883      statement of NAME we can assert both operands of the BIT_IOR_EXPR
5884      have zero value.  */
5885   if (((comp_code == EQ_EXPR && integer_zerop (val))
5886        || (comp_code == NE_EXPR && integer_onep (val))))
5887     {
5888       gimple def_stmt = SSA_NAME_DEF_STMT (name);
5889
5890       /* For BIT_IOR_EXPR only if NAME == 0 both operands have
5891          necessarily zero value, or if type-precision is one.  */
5892       if (is_gimple_assign (def_stmt)
5893           && (gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR
5894               && (TYPE_PRECISION (TREE_TYPE (name)) == 1
5895                   || comp_code == EQ_EXPR)))
5896         {
5897           tree op0 = gimple_assign_rhs1 (def_stmt);
5898           tree op1 = gimple_assign_rhs2 (def_stmt);
5899           register_edge_assert_for_1 (op0, EQ_EXPR, e, si);
5900           register_edge_assert_for_1 (op1, EQ_EXPR, e, si);
5901         }
5902     }
5903 }
5904
5905
5906 /* Determine whether the outgoing edges of BB should receive an
5907    ASSERT_EXPR for each of the operands of BB's LAST statement.
5908    The last statement of BB must be a COND_EXPR.
5909
5910    If any of the sub-graphs rooted at BB have an interesting use of
5911    the predicate operands, an assert location node is added to the
5912    list of assertions for the corresponding operands.  */
5913
5914 static void
5915 find_conditional_asserts (basic_block bb, gcond *last)
5916 {
5917   gimple_stmt_iterator bsi;
5918   tree op;
5919   edge_iterator ei;
5920   edge e;
5921   ssa_op_iter iter;
5922
5923   bsi = gsi_for_stmt (last);
5924
5925   /* Look for uses of the operands in each of the sub-graphs
5926      rooted at BB.  We need to check each of the outgoing edges
5927      separately, so that we know what kind of ASSERT_EXPR to
5928      insert.  */
5929   FOR_EACH_EDGE (e, ei, bb->succs)
5930     {
5931       if (e->dest == bb)
5932         continue;
5933
5934       /* Register the necessary assertions for each operand in the
5935          conditional predicate.  */
5936       FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
5937         register_edge_assert_for (op, e, bsi,
5938                                   gimple_cond_code (last),
5939                                   gimple_cond_lhs (last),
5940                                   gimple_cond_rhs (last));
5941     }
5942 }
5943
5944 struct case_info
5945 {
5946   tree expr;
5947   basic_block bb;
5948 };
5949
5950 /* Compare two case labels sorting first by the destination bb index
5951    and then by the case value.  */
5952
5953 static int
5954 compare_case_labels (const void *p1, const void *p2)
5955 {
5956   const struct case_info *ci1 = (const struct case_info *) p1;
5957   const struct case_info *ci2 = (const struct case_info *) p2;
5958   int idx1 = ci1->bb->index;
5959   int idx2 = ci2->bb->index;
5960
5961   if (idx1 < idx2)
5962     return -1;
5963   else if (idx1 == idx2)
5964     {
5965       /* Make sure the default label is first in a group.  */
5966       if (!CASE_LOW (ci1->expr))
5967         return -1;
5968       else if (!CASE_LOW (ci2->expr))
5969         return 1;
5970       else
5971         return tree_int_cst_compare (CASE_LOW (ci1->expr),
5972                                      CASE_LOW (ci2->expr));
5973     }
5974   else
5975     return 1;
5976 }
5977
5978 /* Determine whether the outgoing edges of BB should receive an
5979    ASSERT_EXPR for each of the operands of BB's LAST statement.
5980    The last statement of BB must be a SWITCH_EXPR.
5981
5982    If any of the sub-graphs rooted at BB have an interesting use of
5983    the predicate operands, an assert location node is added to the
5984    list of assertions for the corresponding operands.  */
5985
5986 static void
5987 find_switch_asserts (basic_block bb, gswitch *last)
5988 {
5989   gimple_stmt_iterator bsi;
5990   tree op;
5991   edge e;
5992   struct case_info *ci;
5993   size_t n = gimple_switch_num_labels (last);
5994 #if GCC_VERSION >= 4000
5995   unsigned int idx;
5996 #else
5997   /* Work around GCC 3.4 bug (PR 37086).  */
5998   volatile unsigned int idx;
5999 #endif
6000
6001   bsi = gsi_for_stmt (last);
6002   op = gimple_switch_index (last);
6003   if (TREE_CODE (op) != SSA_NAME)
6004     return;
6005
6006   /* Build a vector of case labels sorted by destination label.  */
6007   ci = XNEWVEC (struct case_info, n);
6008   for (idx = 0; idx < n; ++idx)
6009     {
6010       ci[idx].expr = gimple_switch_label (last, idx);
6011       ci[idx].bb = label_to_block (CASE_LABEL (ci[idx].expr));
6012     }
6013   qsort (ci, n, sizeof (struct case_info), compare_case_labels);
6014
6015   for (idx = 0; idx < n; ++idx)
6016     {
6017       tree min, max;
6018       tree cl = ci[idx].expr;
6019       basic_block cbb = ci[idx].bb;
6020
6021       min = CASE_LOW (cl);
6022       max = CASE_HIGH (cl);
6023
6024       /* If there are multiple case labels with the same destination
6025          we need to combine them to a single value range for the edge.  */
6026       if (idx + 1 < n && cbb == ci[idx + 1].bb)
6027         {
6028           /* Skip labels until the last of the group.  */
6029           do {
6030             ++idx;
6031           } while (idx < n && cbb == ci[idx].bb);
6032           --idx;
6033
6034           /* Pick up the maximum of the case label range.  */
6035           if (CASE_HIGH (ci[idx].expr))
6036             max = CASE_HIGH (ci[idx].expr);
6037           else
6038             max = CASE_LOW (ci[idx].expr);
6039         }
6040
6041       /* Nothing to do if the range includes the default label until we
6042          can register anti-ranges.  */
6043       if (min == NULL_TREE)
6044         continue;
6045
6046       /* Find the edge to register the assert expr on.  */
6047       e = find_edge (bb, cbb);
6048
6049       /* Register the necessary assertions for the operand in the
6050          SWITCH_EXPR.  */
6051       register_edge_assert_for (op, e, bsi,
6052                                 max ? GE_EXPR : EQ_EXPR,
6053                                 op, fold_convert (TREE_TYPE (op), min));
6054       if (max)
6055         register_edge_assert_for (op, e, bsi, LE_EXPR, op,
6056                                   fold_convert (TREE_TYPE (op), max));
6057     }
6058
6059   XDELETEVEC (ci);
6060 }
6061
6062
6063 /* Traverse all the statements in block BB looking for statements that
6064    may generate useful assertions for the SSA names in their operand.
6065    If a statement produces a useful assertion A for name N_i, then the
6066    list of assertions already generated for N_i is scanned to
6067    determine if A is actually needed.
6068
6069    If N_i already had the assertion A at a location dominating the
6070    current location, then nothing needs to be done.  Otherwise, the
6071    new location for A is recorded instead.
6072
6073    1- For every statement S in BB, all the variables used by S are
6074       added to bitmap FOUND_IN_SUBGRAPH.
6075
6076    2- If statement S uses an operand N in a way that exposes a known
6077       value range for N, then if N was not already generated by an
6078       ASSERT_EXPR, create a new assert location for N.  For instance,
6079       if N is a pointer and the statement dereferences it, we can
6080       assume that N is not NULL.
6081
6082    3- COND_EXPRs are a special case of #2.  We can derive range
6083       information from the predicate but need to insert different
6084       ASSERT_EXPRs for each of the sub-graphs rooted at the
6085       conditional block.  If the last statement of BB is a conditional
6086       expression of the form 'X op Y', then
6087
6088       a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
6089
6090       b) If the conditional is the only entry point to the sub-graph
6091          corresponding to the THEN_CLAUSE, recurse into it.  On
6092          return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
6093          an ASSERT_EXPR is added for the corresponding variable.
6094
6095       c) Repeat step (b) on the ELSE_CLAUSE.
6096
6097       d) Mark X and Y in FOUND_IN_SUBGRAPH.
6098
6099       For instance,
6100
6101             if (a == 9)
6102               b = a;
6103             else
6104               b = c + 1;
6105
6106       In this case, an assertion on the THEN clause is useful to
6107       determine that 'a' is always 9 on that edge.  However, an assertion
6108       on the ELSE clause would be unnecessary.
6109
6110    4- If BB does not end in a conditional expression, then we recurse
6111       into BB's dominator children.
6112
6113    At the end of the recursive traversal, every SSA name will have a
6114    list of locations where ASSERT_EXPRs should be added.  When a new
6115    location for name N is found, it is registered by calling
6116    register_new_assert_for.  That function keeps track of all the
6117    registered assertions to prevent adding unnecessary assertions.
6118    For instance, if a pointer P_4 is dereferenced more than once in a
6119    dominator tree, only the location dominating all the dereference of
6120    P_4 will receive an ASSERT_EXPR.  */
6121
6122 static void
6123 find_assert_locations_1 (basic_block bb, sbitmap live)
6124 {
6125   gimple last;
6126
6127   last = last_stmt (bb);
6128
6129   /* If BB's last statement is a conditional statement involving integer
6130      operands, determine if we need to add ASSERT_EXPRs.  */
6131   if (last
6132       && gimple_code (last) == GIMPLE_COND
6133       && !fp_predicate (last)
6134       && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
6135     find_conditional_asserts (bb, as_a <gcond *> (last));
6136
6137   /* If BB's last statement is a switch statement involving integer
6138      operands, determine if we need to add ASSERT_EXPRs.  */
6139   if (last
6140       && gimple_code (last) == GIMPLE_SWITCH
6141       && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
6142     find_switch_asserts (bb, as_a <gswitch *> (last));
6143
6144   /* Traverse all the statements in BB marking used names and looking
6145      for statements that may infer assertions for their used operands.  */
6146   for (gimple_stmt_iterator si = gsi_last_bb (bb); !gsi_end_p (si);
6147        gsi_prev (&si))
6148     {
6149       gimple stmt;
6150       tree op;
6151       ssa_op_iter i;
6152
6153       stmt = gsi_stmt (si);
6154
6155       if (is_gimple_debug (stmt))
6156         continue;
6157
6158       /* See if we can derive an assertion for any of STMT's operands.  */
6159       FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
6160         {
6161           tree value;
6162           enum tree_code comp_code;
6163
6164           /* If op is not live beyond this stmt, do not bother to insert
6165              asserts for it.  */
6166           if (!bitmap_bit_p (live, SSA_NAME_VERSION (op)))
6167             continue;
6168
6169           /* If OP is used in such a way that we can infer a value
6170              range for it, and we don't find a previous assertion for
6171              it, create a new assertion location node for OP.  */
6172           if (infer_value_range (stmt, op, &comp_code, &value))
6173             {
6174               /* If we are able to infer a nonzero value range for OP,
6175                  then walk backwards through the use-def chain to see if OP
6176                  was set via a typecast.
6177
6178                  If so, then we can also infer a nonzero value range
6179                  for the operand of the NOP_EXPR.  */
6180               if (comp_code == NE_EXPR && integer_zerop (value))
6181                 {
6182                   tree t = op;
6183                   gimple def_stmt = SSA_NAME_DEF_STMT (t);
6184
6185                   while (is_gimple_assign (def_stmt)
6186                          && CONVERT_EXPR_CODE_P
6187                              (gimple_assign_rhs_code (def_stmt))
6188                          && TREE_CODE
6189                              (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
6190                          && POINTER_TYPE_P
6191                              (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
6192                     {
6193                       t = gimple_assign_rhs1 (def_stmt);
6194                       def_stmt = SSA_NAME_DEF_STMT (t);
6195
6196                       /* Note we want to register the assert for the
6197                          operand of the NOP_EXPR after SI, not after the
6198                          conversion.  */
6199                       if (! has_single_use (t))
6200                         register_new_assert_for (t, t, comp_code, value,
6201                                                  bb, NULL, si);
6202                     }
6203                 }
6204
6205               register_new_assert_for (op, op, comp_code, value, bb, NULL, si);
6206             }
6207         }
6208
6209       /* Update live.  */
6210       FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
6211         bitmap_set_bit (live, SSA_NAME_VERSION (op));
6212       FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_DEF)
6213         bitmap_clear_bit (live, SSA_NAME_VERSION (op));
6214     }
6215
6216   /* Traverse all PHI nodes in BB, updating live.  */
6217   for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
6218        gsi_next (&si))
6219     {
6220       use_operand_p arg_p;
6221       ssa_op_iter i;
6222       gphi *phi = si.phi ();
6223       tree res = gimple_phi_result (phi);
6224
6225       if (virtual_operand_p (res))
6226         continue;
6227
6228       FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
6229         {
6230           tree arg = USE_FROM_PTR (arg_p);
6231           if (TREE_CODE (arg) == SSA_NAME)
6232             bitmap_set_bit (live, SSA_NAME_VERSION (arg));
6233         }
6234
6235       bitmap_clear_bit (live, SSA_NAME_VERSION (res));
6236     }
6237 }
6238
6239 /* Do an RPO walk over the function computing SSA name liveness
6240    on-the-fly and deciding on assert expressions to insert.  */
6241
6242 static void
6243 find_assert_locations (void)
6244 {
6245   int *rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
6246   int *bb_rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
6247   int *last_rpo = XCNEWVEC (int, last_basic_block_for_fn (cfun));
6248   int rpo_cnt, i;
6249
6250   live = XCNEWVEC (sbitmap, last_basic_block_for_fn (cfun));
6251   rpo_cnt = pre_and_rev_post_order_compute (NULL, rpo, false);
6252   for (i = 0; i < rpo_cnt; ++i)
6253     bb_rpo[rpo[i]] = i;
6254
6255   /* Pre-seed loop latch liveness from loop header PHI nodes.  Due to
6256      the order we compute liveness and insert asserts we otherwise
6257      fail to insert asserts into the loop latch.  */
6258   loop_p loop;
6259   FOR_EACH_LOOP (loop, 0)
6260     {
6261       i = loop->latch->index;
6262       unsigned int j = single_succ_edge (loop->latch)->dest_idx;
6263       for (gphi_iterator gsi = gsi_start_phis (loop->header);
6264            !gsi_end_p (gsi); gsi_next (&gsi))
6265         {
6266           gphi *phi = gsi.phi ();
6267           if (virtual_operand_p (gimple_phi_result (phi)))
6268             continue;
6269           tree arg = gimple_phi_arg_def (phi, j);
6270           if (TREE_CODE (arg) == SSA_NAME)
6271             {
6272               if (live[i] == NULL)
6273                 {
6274                   live[i] = sbitmap_alloc (num_ssa_names);
6275                   bitmap_clear (live[i]);
6276                 }
6277               bitmap_set_bit (live[i], SSA_NAME_VERSION (arg));
6278             }
6279         }
6280     }
6281
6282   for (i = rpo_cnt - 1; i >= 0; --i)
6283     {
6284       basic_block bb = BASIC_BLOCK_FOR_FN (cfun, rpo[i]);
6285       edge e;
6286       edge_iterator ei;
6287
6288       if (!live[rpo[i]])
6289         {
6290           live[rpo[i]] = sbitmap_alloc (num_ssa_names);
6291           bitmap_clear (live[rpo[i]]);
6292         }
6293
6294       /* Process BB and update the live information with uses in
6295          this block.  */
6296       find_assert_locations_1 (bb, live[rpo[i]]);
6297
6298       /* Merge liveness into the predecessor blocks and free it.  */
6299       if (!bitmap_empty_p (live[rpo[i]]))
6300         {
6301           int pred_rpo = i;
6302           FOR_EACH_EDGE (e, ei, bb->preds)
6303             {
6304               int pred = e->src->index;
6305               if ((e->flags & EDGE_DFS_BACK) || pred == ENTRY_BLOCK)
6306                 continue;
6307
6308               if (!live[pred])
6309                 {
6310                   live[pred] = sbitmap_alloc (num_ssa_names);
6311                   bitmap_clear (live[pred]);
6312                 }
6313               bitmap_ior (live[pred], live[pred], live[rpo[i]]);
6314
6315               if (bb_rpo[pred] < pred_rpo)
6316                 pred_rpo = bb_rpo[pred];
6317             }
6318
6319           /* Record the RPO number of the last visited block that needs
6320              live information from this block.  */
6321           last_rpo[rpo[i]] = pred_rpo;
6322         }
6323       else
6324         {
6325           sbitmap_free (live[rpo[i]]);
6326           live[rpo[i]] = NULL;
6327         }
6328
6329       /* We can free all successors live bitmaps if all their
6330          predecessors have been visited already.  */
6331       FOR_EACH_EDGE (e, ei, bb->succs)
6332         if (last_rpo[e->dest->index] == i
6333             && live[e->dest->index])
6334           {
6335             sbitmap_free (live[e->dest->index]);
6336             live[e->dest->index] = NULL;
6337           }
6338     }
6339
6340   XDELETEVEC (rpo);
6341   XDELETEVEC (bb_rpo);
6342   XDELETEVEC (last_rpo);
6343   for (i = 0; i < last_basic_block_for_fn (cfun); ++i)
6344     if (live[i])
6345       sbitmap_free (live[i]);
6346   XDELETEVEC (live);
6347 }
6348
6349 /* Create an ASSERT_EXPR for NAME and insert it in the location
6350    indicated by LOC.  Return true if we made any edge insertions.  */
6351
6352 static bool
6353 process_assert_insertions_for (tree name, assert_locus_t loc)
6354 {
6355   /* Build the comparison expression NAME_i COMP_CODE VAL.  */
6356   gimple stmt;
6357   tree cond;
6358   gimple assert_stmt;
6359   edge_iterator ei;
6360   edge e;
6361
6362   /* If we have X <=> X do not insert an assert expr for that.  */
6363   if (loc->expr == loc->val)
6364     return false;
6365
6366   cond = build2 (loc->comp_code, boolean_type_node, loc->expr, loc->val);
6367   assert_stmt = build_assert_expr_for (cond, name);
6368   if (loc->e)
6369     {
6370       /* We have been asked to insert the assertion on an edge.  This
6371          is used only by COND_EXPR and SWITCH_EXPR assertions.  */
6372       gcc_checking_assert (gimple_code (gsi_stmt (loc->si)) == GIMPLE_COND
6373                            || (gimple_code (gsi_stmt (loc->si))
6374                                == GIMPLE_SWITCH));
6375
6376       gsi_insert_on_edge (loc->e, assert_stmt);
6377       return true;
6378     }
6379
6380   /* Otherwise, we can insert right after LOC->SI iff the
6381      statement must not be the last statement in the block.  */
6382   stmt = gsi_stmt (loc->si);
6383   if (!stmt_ends_bb_p (stmt))
6384     {
6385       gsi_insert_after (&loc->si, assert_stmt, GSI_SAME_STMT);
6386       return false;
6387     }
6388
6389   /* If STMT must be the last statement in BB, we can only insert new
6390      assertions on the non-abnormal edge out of BB.  Note that since
6391      STMT is not control flow, there may only be one non-abnormal edge
6392      out of BB.  */
6393   FOR_EACH_EDGE (e, ei, loc->bb->succs)
6394     if (!(e->flags & EDGE_ABNORMAL))
6395       {
6396         gsi_insert_on_edge (e, assert_stmt);
6397         return true;
6398       }
6399
6400   gcc_unreachable ();
6401 }
6402
6403
6404 /* Process all the insertions registered for every name N_i registered
6405    in NEED_ASSERT_FOR.  The list of assertions to be inserted are
6406    found in ASSERTS_FOR[i].  */
6407
6408 static void
6409 process_assert_insertions (void)
6410 {
6411   unsigned i;
6412   bitmap_iterator bi;
6413   bool update_edges_p = false;
6414   int num_asserts = 0;
6415
6416   if (dump_file && (dump_flags & TDF_DETAILS))
6417     dump_all_asserts (dump_file);
6418
6419   EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
6420     {
6421       assert_locus_t loc = asserts_for[i];
6422       gcc_assert (loc);
6423
6424       while (loc)
6425         {
6426           assert_locus_t next = loc->next;
6427           update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
6428           free (loc);
6429           loc = next;
6430           num_asserts++;
6431         }
6432     }
6433
6434   if (update_edges_p)
6435     gsi_commit_edge_inserts ();
6436
6437   statistics_counter_event (cfun, "Number of ASSERT_EXPR expressions inserted",
6438                             num_asserts);
6439 }
6440
6441
6442 /* Traverse the flowgraph looking for conditional jumps to insert range
6443    expressions.  These range expressions are meant to provide information
6444    to optimizations that need to reason in terms of value ranges.  They
6445    will not be expanded into RTL.  For instance, given:
6446
6447    x = ...
6448    y = ...
6449    if (x < y)
6450      y = x - 2;
6451    else
6452      x = y + 3;
6453
6454    this pass will transform the code into:
6455
6456    x = ...
6457    y = ...
6458    if (x < y)
6459     {
6460       x = ASSERT_EXPR <x, x < y>
6461       y = x - 2
6462     }
6463    else
6464     {
6465       y = ASSERT_EXPR <y, x >= y>
6466       x = y + 3
6467     }
6468
6469    The idea is that once copy and constant propagation have run, other
6470    optimizations will be able to determine what ranges of values can 'x'
6471    take in different paths of the code, simply by checking the reaching
6472    definition of 'x'.  */
6473
6474 static void
6475 insert_range_assertions (void)
6476 {
6477   need_assert_for = BITMAP_ALLOC (NULL);
6478   asserts_for = XCNEWVEC (assert_locus_t, num_ssa_names);
6479
6480   calculate_dominance_info (CDI_DOMINATORS);
6481
6482   find_assert_locations ();
6483   if (!bitmap_empty_p (need_assert_for))
6484     {
6485       process_assert_insertions ();
6486       update_ssa (TODO_update_ssa_no_phi);
6487     }
6488
6489   if (dump_file && (dump_flags & TDF_DETAILS))
6490     {
6491       fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
6492       dump_function_to_file (current_function_decl, dump_file, dump_flags);
6493     }
6494
6495   free (asserts_for);
6496   BITMAP_FREE (need_assert_for);
6497 }
6498
6499 /* Checks one ARRAY_REF in REF, located at LOCUS. Ignores flexible arrays
6500    and "struct" hacks. If VRP can determine that the
6501    array subscript is a constant, check if it is outside valid
6502    range. If the array subscript is a RANGE, warn if it is
6503    non-overlapping with valid range.
6504    IGNORE_OFF_BY_ONE is true if the ARRAY_REF is inside a ADDR_EXPR.  */
6505
6506 static void
6507 check_array_ref (location_t location, tree ref, bool ignore_off_by_one)
6508 {
6509   value_range_t* vr = NULL;
6510   tree low_sub, up_sub;
6511   tree low_bound, up_bound, up_bound_p1;
6512   tree base;
6513
6514   if (TREE_NO_WARNING (ref))
6515     return;
6516
6517   low_sub = up_sub = TREE_OPERAND (ref, 1);
6518   up_bound = array_ref_up_bound (ref);
6519
6520   /* Can not check flexible arrays.  */
6521   if (!up_bound
6522       || TREE_CODE (up_bound) != INTEGER_CST)
6523     return;
6524
6525   /* Accesses to trailing arrays via pointers may access storage
6526      beyond the types array bounds.  */
6527   base = get_base_address (ref);
6528   if ((warn_array_bounds < 2)
6529       && base && TREE_CODE (base) == MEM_REF)
6530     {
6531       tree cref, next = NULL_TREE;
6532
6533       if (TREE_CODE (TREE_OPERAND (ref, 0)) != COMPONENT_REF)
6534         return;
6535
6536       cref = TREE_OPERAND (ref, 0);
6537       if (TREE_CODE (TREE_TYPE (TREE_OPERAND (cref, 0))) == RECORD_TYPE)
6538         for (next = DECL_CHAIN (TREE_OPERAND (cref, 1));
6539              next && TREE_CODE (next) != FIELD_DECL;
6540              next = DECL_CHAIN (next))
6541           ;
6542
6543       /* If this is the last field in a struct type or a field in a
6544          union type do not warn.  */
6545       if (!next)
6546         return;
6547     }
6548
6549   low_bound = array_ref_low_bound (ref);
6550   up_bound_p1 = int_const_binop (PLUS_EXPR, up_bound,
6551                                  build_int_cst (TREE_TYPE (up_bound), 1));
6552
6553   if (TREE_CODE (low_sub) == SSA_NAME)
6554     {
6555       vr = get_value_range (low_sub);
6556       if (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE)
6557         {
6558           low_sub = vr->type == VR_RANGE ? vr->max : vr->min;
6559           up_sub = vr->type == VR_RANGE ? vr->min : vr->max;
6560         }
6561     }
6562
6563   if (vr && vr->type == VR_ANTI_RANGE)
6564     {
6565       if (TREE_CODE (up_sub) == INTEGER_CST
6566           && tree_int_cst_lt (up_bound, up_sub)
6567           && TREE_CODE (low_sub) == INTEGER_CST
6568           && tree_int_cst_lt (low_sub, low_bound))
6569         {
6570           warning_at (location, OPT_Warray_bounds,
6571                       "array subscript is outside array bounds");
6572           TREE_NO_WARNING (ref) = 1;
6573         }
6574     }
6575   else if (TREE_CODE (up_sub) == INTEGER_CST
6576            && (ignore_off_by_one
6577                ? (tree_int_cst_lt (up_bound, up_sub)
6578                   && !tree_int_cst_equal (up_bound_p1, up_sub))
6579                : (tree_int_cst_lt (up_bound, up_sub)
6580                   || tree_int_cst_equal (up_bound_p1, up_sub))))
6581     {
6582       if (dump_file && (dump_flags & TDF_DETAILS))
6583         {
6584           fprintf (dump_file, "Array bound warning for ");
6585           dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
6586           fprintf (dump_file, "\n");
6587         }
6588       warning_at (location, OPT_Warray_bounds,
6589                   "array subscript is above array bounds");
6590       TREE_NO_WARNING (ref) = 1;
6591     }
6592   else if (TREE_CODE (low_sub) == INTEGER_CST
6593            && tree_int_cst_lt (low_sub, low_bound))
6594     {
6595       if (dump_file && (dump_flags & TDF_DETAILS))
6596         {
6597           fprintf (dump_file, "Array bound warning for ");
6598           dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
6599           fprintf (dump_file, "\n");
6600         }
6601       warning_at (location, OPT_Warray_bounds,
6602                   "array subscript is below array bounds");
6603       TREE_NO_WARNING (ref) = 1;
6604     }
6605 }
6606
6607 /* Searches if the expr T, located at LOCATION computes
6608    address of an ARRAY_REF, and call check_array_ref on it.  */
6609
6610 static void
6611 search_for_addr_array (tree t, location_t location)
6612 {
6613   while (TREE_CODE (t) == SSA_NAME)
6614     {
6615       gimple g = SSA_NAME_DEF_STMT (t);
6616
6617       if (gimple_code (g) != GIMPLE_ASSIGN)
6618         return;
6619
6620       if (get_gimple_rhs_class (gimple_assign_rhs_code (g))
6621           != GIMPLE_SINGLE_RHS)
6622         return;
6623
6624       t = gimple_assign_rhs1 (g);
6625     }
6626
6627
6628   /* We are only interested in addresses of ARRAY_REF's.  */
6629   if (TREE_CODE (t) != ADDR_EXPR)
6630     return;
6631
6632   /* Check each ARRAY_REFs in the reference chain. */
6633   do
6634     {
6635       if (TREE_CODE (t) == ARRAY_REF)
6636         check_array_ref (location, t, true /*ignore_off_by_one*/);
6637
6638       t = TREE_OPERAND (t, 0);
6639     }
6640   while (handled_component_p (t));
6641
6642   if (TREE_CODE (t) == MEM_REF
6643       && TREE_CODE (TREE_OPERAND (t, 0)) == ADDR_EXPR
6644       && !TREE_NO_WARNING (t))
6645     {
6646       tree tem = TREE_OPERAND (TREE_OPERAND (t, 0), 0);
6647       tree low_bound, up_bound, el_sz;
6648       offset_int idx;
6649       if (TREE_CODE (TREE_TYPE (tem)) != ARRAY_TYPE
6650           || TREE_CODE (TREE_TYPE (TREE_TYPE (tem))) == ARRAY_TYPE
6651           || !TYPE_DOMAIN (TREE_TYPE (tem)))
6652         return;
6653
6654       low_bound = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
6655       up_bound = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
6656       el_sz = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (tem)));
6657       if (!low_bound
6658           || TREE_CODE (low_bound) != INTEGER_CST
6659           || !up_bound
6660           || TREE_CODE (up_bound) != INTEGER_CST
6661           || !el_sz
6662           || TREE_CODE (el_sz) != INTEGER_CST)
6663         return;
6664
6665       idx = mem_ref_offset (t);
6666       idx = wi::sdiv_trunc (idx, wi::to_offset (el_sz));
6667       if (wi::lts_p (idx, 0))
6668         {
6669           if (dump_file && (dump_flags & TDF_DETAILS))
6670             {
6671               fprintf (dump_file, "Array bound warning for ");
6672               dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
6673               fprintf (dump_file, "\n");
6674             }
6675           warning_at (location, OPT_Warray_bounds,
6676                       "array subscript is below array bounds");
6677           TREE_NO_WARNING (t) = 1;
6678         }
6679       else if (wi::gts_p (idx, (wi::to_offset (up_bound)
6680                                 - wi::to_offset (low_bound) + 1)))
6681         {
6682           if (dump_file && (dump_flags & TDF_DETAILS))
6683             {
6684               fprintf (dump_file, "Array bound warning for ");
6685               dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
6686               fprintf (dump_file, "\n");
6687             }
6688           warning_at (location, OPT_Warray_bounds,
6689                       "array subscript is above array bounds");
6690           TREE_NO_WARNING (t) = 1;
6691         }
6692     }
6693 }
6694
6695 /* walk_tree() callback that checks if *TP is
6696    an ARRAY_REF inside an ADDR_EXPR (in which an array
6697    subscript one outside the valid range is allowed). Call
6698    check_array_ref for each ARRAY_REF found. The location is
6699    passed in DATA.  */
6700
6701 static tree
6702 check_array_bounds (tree *tp, int *walk_subtree, void *data)
6703 {
6704   tree t = *tp;
6705   struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
6706   location_t location;
6707
6708   if (EXPR_HAS_LOCATION (t))
6709     location = EXPR_LOCATION (t);
6710   else
6711     {
6712       location_t *locp = (location_t *) wi->info;
6713       location = *locp;
6714     }
6715
6716   *walk_subtree = TRUE;
6717
6718   if (TREE_CODE (t) == ARRAY_REF)
6719     check_array_ref (location, t, false /*ignore_off_by_one*/);
6720
6721   if (TREE_CODE (t) == MEM_REF
6722       || (TREE_CODE (t) == RETURN_EXPR && TREE_OPERAND (t, 0)))
6723     search_for_addr_array (TREE_OPERAND (t, 0), location);
6724
6725   if (TREE_CODE (t) == ADDR_EXPR)
6726     *walk_subtree = FALSE;
6727
6728   return NULL_TREE;
6729 }
6730
6731 /* Walk over all statements of all reachable BBs and call check_array_bounds
6732    on them.  */
6733
6734 static void
6735 check_all_array_refs (void)
6736 {
6737   basic_block bb;
6738   gimple_stmt_iterator si;
6739
6740   FOR_EACH_BB_FN (bb, cfun)
6741     {
6742       edge_iterator ei;
6743       edge e;
6744       bool executable = false;
6745
6746       /* Skip blocks that were found to be unreachable.  */
6747       FOR_EACH_EDGE (e, ei, bb->preds)
6748         executable |= !!(e->flags & EDGE_EXECUTABLE);
6749       if (!executable)
6750         continue;
6751
6752       for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
6753         {
6754           gimple stmt = gsi_stmt (si);
6755           struct walk_stmt_info wi;
6756           if (!gimple_has_location (stmt))
6757             continue;
6758
6759           if (is_gimple_call (stmt))
6760             {
6761               size_t i;
6762               size_t n = gimple_call_num_args (stmt);
6763               for (i = 0; i < n; i++)
6764                 {
6765                   tree arg = gimple_call_arg (stmt, i);
6766                   search_for_addr_array (arg, gimple_location (stmt));
6767                 }
6768             }
6769           else
6770             {
6771               memset (&wi, 0, sizeof (wi));
6772               wi.info = CONST_CAST (void *, (const void *)
6773                                     gimple_location_ptr (stmt));
6774
6775               walk_gimple_op (gsi_stmt (si),
6776                               check_array_bounds,
6777                               &wi);
6778             }
6779         }
6780     }
6781 }
6782
6783 /* Return true if all imm uses of VAR are either in STMT, or
6784    feed (optionally through a chain of single imm uses) GIMPLE_COND
6785    in basic block COND_BB.  */
6786
6787 static bool
6788 all_imm_uses_in_stmt_or_feed_cond (tree var, gimple stmt, basic_block cond_bb)
6789 {
6790   use_operand_p use_p, use2_p;
6791   imm_use_iterator iter;
6792
6793   FOR_EACH_IMM_USE_FAST (use_p, iter, var)
6794     if (USE_STMT (use_p) != stmt)
6795       {
6796         gimple use_stmt = USE_STMT (use_p), use_stmt2;
6797         if (is_gimple_debug (use_stmt))
6798           continue;
6799         while (is_gimple_assign (use_stmt)
6800                && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
6801                && single_imm_use (gimple_assign_lhs (use_stmt),
6802                                   &use2_p, &use_stmt2))
6803           use_stmt = use_stmt2;
6804         if (gimple_code (use_stmt) != GIMPLE_COND
6805             || gimple_bb (use_stmt) != cond_bb)
6806           return false;
6807       }
6808   return true;
6809 }
6810
6811 /* Handle
6812    _4 = x_3 & 31;
6813    if (_4 != 0)
6814      goto <bb 6>;
6815    else
6816      goto <bb 7>;
6817    <bb 6>:
6818    __builtin_unreachable ();
6819    <bb 7>:
6820    x_5 = ASSERT_EXPR <x_3, ...>;
6821    If x_3 has no other immediate uses (checked by caller),
6822    var is the x_3 var from ASSERT_EXPR, we can clear low 5 bits
6823    from the non-zero bitmask.  */
6824
6825 static void
6826 maybe_set_nonzero_bits (basic_block bb, tree var)
6827 {
6828   edge e = single_pred_edge (bb);
6829   basic_block cond_bb = e->src;
6830   gimple stmt = last_stmt (cond_bb);
6831   tree cst;
6832
6833   if (stmt == NULL
6834       || gimple_code (stmt) != GIMPLE_COND
6835       || gimple_cond_code (stmt) != ((e->flags & EDGE_TRUE_VALUE)
6836                                      ? EQ_EXPR : NE_EXPR)
6837       || TREE_CODE (gimple_cond_lhs (stmt)) != SSA_NAME
6838       || !integer_zerop (gimple_cond_rhs (stmt)))
6839     return;
6840
6841   stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt));
6842   if (!is_gimple_assign (stmt)
6843       || gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
6844       || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
6845     return;
6846   if (gimple_assign_rhs1 (stmt) != var)
6847     {
6848       gimple stmt2;
6849
6850       if (TREE_CODE (gimple_assign_rhs1 (stmt)) != SSA_NAME)
6851         return;
6852       stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
6853       if (!gimple_assign_cast_p (stmt2)
6854           || gimple_assign_rhs1 (stmt2) != var
6855           || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt2))
6856           || (TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (stmt)))
6857                               != TYPE_PRECISION (TREE_TYPE (var))))
6858         return;
6859     }
6860   cst = gimple_assign_rhs2 (stmt);
6861   set_nonzero_bits (var, wi::bit_and_not (get_nonzero_bits (var), cst));
6862 }
6863
6864 /* Convert range assertion expressions into the implied copies and
6865    copy propagate away the copies.  Doing the trivial copy propagation
6866    here avoids the need to run the full copy propagation pass after
6867    VRP.
6868
6869    FIXME, this will eventually lead to copy propagation removing the
6870    names that had useful range information attached to them.  For
6871    instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
6872    then N_i will have the range [3, +INF].
6873
6874    However, by converting the assertion into the implied copy
6875    operation N_i = N_j, we will then copy-propagate N_j into the uses
6876    of N_i and lose the range information.  We may want to hold on to
6877    ASSERT_EXPRs a little while longer as the ranges could be used in
6878    things like jump threading.
6879
6880    The problem with keeping ASSERT_EXPRs around is that passes after
6881    VRP need to handle them appropriately.
6882
6883    Another approach would be to make the range information a first
6884    class property of the SSA_NAME so that it can be queried from
6885    any pass.  This is made somewhat more complex by the need for
6886    multiple ranges to be associated with one SSA_NAME.  */
6887
6888 static void
6889 remove_range_assertions (void)
6890 {
6891   basic_block bb;
6892   gimple_stmt_iterator si;
6893   /* 1 if looking at ASSERT_EXPRs immediately at the beginning of
6894      a basic block preceeded by GIMPLE_COND branching to it and
6895      __builtin_trap, -1 if not yet checked, 0 otherwise.  */
6896   int is_unreachable;
6897
6898   /* Note that the BSI iterator bump happens at the bottom of the
6899      loop and no bump is necessary if we're removing the statement
6900      referenced by the current BSI.  */
6901   FOR_EACH_BB_FN (bb, cfun)
6902     for (si = gsi_after_labels (bb), is_unreachable = -1; !gsi_end_p (si);)
6903       {
6904         gimple stmt = gsi_stmt (si);
6905         gimple use_stmt;
6906
6907         if (is_gimple_assign (stmt)
6908             && gimple_assign_rhs_code (stmt) == ASSERT_EXPR)
6909           {
6910             tree lhs = gimple_assign_lhs (stmt);
6911             tree rhs = gimple_assign_rhs1 (stmt);
6912             tree var;
6913             tree cond = fold (ASSERT_EXPR_COND (rhs));
6914             use_operand_p use_p;
6915             imm_use_iterator iter;
6916
6917             gcc_assert (cond != boolean_false_node);
6918
6919             var = ASSERT_EXPR_VAR (rhs);
6920             gcc_assert (TREE_CODE (var) == SSA_NAME);
6921
6922             if (!POINTER_TYPE_P (TREE_TYPE (lhs))
6923                 && SSA_NAME_RANGE_INFO (lhs))
6924               {
6925                 if (is_unreachable == -1)
6926                   {
6927                     is_unreachable = 0;
6928                     if (single_pred_p (bb)
6929                         && assert_unreachable_fallthru_edge_p
6930                                                     (single_pred_edge (bb)))
6931                       is_unreachable = 1;
6932                   }
6933                 /* Handle
6934                    if (x_7 >= 10 && x_7 < 20)
6935                      __builtin_unreachable ();
6936                    x_8 = ASSERT_EXPR <x_7, ...>;
6937                    if the only uses of x_7 are in the ASSERT_EXPR and
6938                    in the condition.  In that case, we can copy the
6939                    range info from x_8 computed in this pass also
6940                    for x_7.  */
6941                 if (is_unreachable
6942                     && all_imm_uses_in_stmt_or_feed_cond (var, stmt,
6943                                                           single_pred (bb)))
6944                   {
6945                     set_range_info (var, SSA_NAME_RANGE_TYPE (lhs),
6946                                     SSA_NAME_RANGE_INFO (lhs)->get_min (),
6947                                     SSA_NAME_RANGE_INFO (lhs)->get_max ());
6948                     maybe_set_nonzero_bits (bb, var);
6949                   }
6950               }
6951
6952             /* Propagate the RHS into every use of the LHS.  */
6953             FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
6954               FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
6955                 SET_USE (use_p, var);
6956
6957             /* And finally, remove the copy, it is not needed.  */
6958             gsi_remove (&si, true);
6959             release_defs (stmt);
6960           }
6961         else
6962           {
6963             if (!is_gimple_debug (gsi_stmt (si)))
6964               is_unreachable = 0;
6965             gsi_next (&si);
6966           }
6967       }
6968 }
6969
6970
6971 /* Return true if STMT is interesting for VRP.  */
6972
6973 static bool
6974 stmt_interesting_for_vrp (gimple stmt)
6975 {
6976   if (gimple_code (stmt) == GIMPLE_PHI)
6977     {
6978       tree res = gimple_phi_result (stmt);
6979       return (!virtual_operand_p (res)
6980               && (INTEGRAL_TYPE_P (TREE_TYPE (res))
6981                   || POINTER_TYPE_P (TREE_TYPE (res))));
6982     }
6983   else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
6984     {
6985       tree lhs = gimple_get_lhs (stmt);
6986
6987       /* In general, assignments with virtual operands are not useful
6988          for deriving ranges, with the obvious exception of calls to
6989          builtin functions.  */
6990       if (lhs && TREE_CODE (lhs) == SSA_NAME
6991           && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
6992               || POINTER_TYPE_P (TREE_TYPE (lhs)))
6993           && (is_gimple_call (stmt)
6994               || !gimple_vuse (stmt)))
6995         return true;
6996       else if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
6997         switch (gimple_call_internal_fn (stmt))
6998           {
6999           case IFN_ADD_OVERFLOW:
7000           case IFN_SUB_OVERFLOW:
7001           case IFN_MUL_OVERFLOW:
7002             /* These internal calls return _Complex integer type,
7003                but are interesting to VRP nevertheless.  */
7004             if (lhs && TREE_CODE (lhs) == SSA_NAME)
7005               return true;
7006             break;
7007           default:
7008             break;
7009           }
7010     }
7011   else if (gimple_code (stmt) == GIMPLE_COND
7012            || gimple_code (stmt) == GIMPLE_SWITCH)
7013     return true;
7014
7015   return false;
7016 }
7017
7018
7019 /* Initialize local data structures for VRP.  */
7020
7021 static void
7022 vrp_initialize (void)
7023 {
7024   basic_block bb;
7025
7026   values_propagated = false;
7027   num_vr_values = num_ssa_names;
7028   vr_value = XCNEWVEC (value_range_t *, num_vr_values);
7029   vr_phi_edge_counts = XCNEWVEC (int, num_ssa_names);
7030
7031   FOR_EACH_BB_FN (bb, cfun)
7032     {
7033       for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
7034            gsi_next (&si))
7035         {
7036           gphi *phi = si.phi ();
7037           if (!stmt_interesting_for_vrp (phi))
7038             {
7039               tree lhs = PHI_RESULT (phi);
7040               set_value_range_to_varying (get_value_range (lhs));
7041               prop_set_simulate_again (phi, false);
7042             }
7043           else
7044             prop_set_simulate_again (phi, true);
7045         }
7046
7047       for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
7048            gsi_next (&si))
7049         {
7050           gimple stmt = gsi_stmt (si);
7051
7052           /* If the statement is a control insn, then we do not
7053              want to avoid simulating the statement once.  Failure
7054              to do so means that those edges will never get added.  */
7055           if (stmt_ends_bb_p (stmt))
7056             prop_set_simulate_again (stmt, true);
7057           else if (!stmt_interesting_for_vrp (stmt))
7058             {
7059               ssa_op_iter i;
7060               tree def;
7061               FOR_EACH_SSA_TREE_OPERAND (def, stmt, i, SSA_OP_DEF)
7062                 set_value_range_to_varying (get_value_range (def));
7063               prop_set_simulate_again (stmt, false);
7064             }
7065           else
7066             prop_set_simulate_again (stmt, true);
7067         }
7068     }
7069 }
7070
7071 /* Return the singleton value-range for NAME or NAME.  */
7072
7073 static inline tree
7074 vrp_valueize (tree name)
7075 {
7076   if (TREE_CODE (name) == SSA_NAME)
7077     {
7078       value_range_t *vr = get_value_range (name);
7079       if (vr->type == VR_RANGE
7080           && (vr->min == vr->max
7081               || operand_equal_p (vr->min, vr->max, 0)))
7082         return vr->min;
7083     }
7084   return name;
7085 }
7086
7087 /* Return the singleton value-range for NAME if that is a constant
7088    but signal to not follow SSA edges.  */
7089
7090 static inline tree
7091 vrp_valueize_1 (tree name)
7092 {
7093   if (TREE_CODE (name) == SSA_NAME)
7094     {
7095       /* If the definition may be simulated again we cannot follow
7096          this SSA edge as the SSA propagator does not necessarily
7097          re-visit the use.  */
7098       gimple def_stmt = SSA_NAME_DEF_STMT (name);
7099       if (prop_simulate_again_p (def_stmt))
7100         return NULL_TREE;
7101       value_range_t *vr = get_value_range (name);
7102       if (range_int_cst_singleton_p (vr))
7103         return vr->min;
7104     }
7105   return name;
7106 }
7107
7108 /* Visit assignment STMT.  If it produces an interesting range, record
7109    the SSA name in *OUTPUT_P.  */
7110
7111 static enum ssa_prop_result
7112 vrp_visit_assignment_or_call (gimple stmt, tree *output_p)
7113 {
7114   tree def, lhs;
7115   ssa_op_iter iter;
7116   enum gimple_code code = gimple_code (stmt);
7117   lhs = gimple_get_lhs (stmt);
7118
7119   /* We only keep track of ranges in integral and pointer types.  */
7120   if (TREE_CODE (lhs) == SSA_NAME
7121       && ((INTEGRAL_TYPE_P (TREE_TYPE (lhs))
7122            /* It is valid to have NULL MIN/MAX values on a type.  See
7123               build_range_type.  */
7124            && TYPE_MIN_VALUE (TREE_TYPE (lhs))
7125            && TYPE_MAX_VALUE (TREE_TYPE (lhs)))
7126           || POINTER_TYPE_P (TREE_TYPE (lhs))))
7127     {
7128       value_range_t new_vr = VR_INITIALIZER;
7129
7130       /* Try folding the statement to a constant first.  */
7131       tree tem = gimple_fold_stmt_to_constant_1 (stmt, vrp_valueize,
7132                                                  vrp_valueize_1);
7133       if (tem && is_gimple_min_invariant (tem))
7134         set_value_range_to_value (&new_vr, tem, NULL);
7135       /* Then dispatch to value-range extracting functions.  */
7136       else if (code == GIMPLE_CALL)
7137         extract_range_basic (&new_vr, stmt);
7138       else
7139         extract_range_from_assignment (&new_vr, as_a <gassign *> (stmt));
7140
7141       if (update_value_range (lhs, &new_vr))
7142         {
7143           *output_p = lhs;
7144
7145           if (dump_file && (dump_flags & TDF_DETAILS))
7146             {
7147               fprintf (dump_file, "Found new range for ");
7148               print_generic_expr (dump_file, lhs, 0);
7149               fprintf (dump_file, ": ");
7150               dump_value_range (dump_file, &new_vr);
7151               fprintf (dump_file, "\n");
7152             }
7153
7154           if (new_vr.type == VR_VARYING)
7155             return SSA_PROP_VARYING;
7156
7157           return SSA_PROP_INTERESTING;
7158         }
7159
7160       return SSA_PROP_NOT_INTERESTING;
7161     }
7162   else if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
7163     switch (gimple_call_internal_fn (stmt))
7164       {
7165       case IFN_ADD_OVERFLOW:
7166       case IFN_SUB_OVERFLOW:
7167       case IFN_MUL_OVERFLOW:
7168         /* These internal calls return _Complex integer type,
7169            which VRP does not track, but the immediate uses
7170            thereof might be interesting.  */
7171         if (lhs && TREE_CODE (lhs) == SSA_NAME)
7172           {
7173             imm_use_iterator iter;
7174             use_operand_p use_p;
7175             enum ssa_prop_result res = SSA_PROP_VARYING;
7176
7177             set_value_range_to_varying (get_value_range (lhs));
7178
7179             FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
7180               {
7181                 gimple use_stmt = USE_STMT (use_p);
7182                 if (!is_gimple_assign (use_stmt))
7183                   continue;
7184                 enum tree_code rhs_code = gimple_assign_rhs_code (use_stmt);
7185                 if (rhs_code != REALPART_EXPR && rhs_code != IMAGPART_EXPR)
7186                   continue;
7187                 tree rhs1 = gimple_assign_rhs1 (use_stmt);
7188                 tree use_lhs = gimple_assign_lhs (use_stmt);
7189                 if (TREE_CODE (rhs1) != rhs_code
7190                     || TREE_OPERAND (rhs1, 0) != lhs
7191                     || TREE_CODE (use_lhs) != SSA_NAME
7192                     || !stmt_interesting_for_vrp (use_stmt)
7193                     || (!INTEGRAL_TYPE_P (TREE_TYPE (use_lhs))
7194                         || !TYPE_MIN_VALUE (TREE_TYPE (use_lhs))
7195                         || !TYPE_MAX_VALUE (TREE_TYPE (use_lhs))))
7196                   continue;
7197
7198                 /* If there is a change in the value range for any of the
7199                    REALPART_EXPR/IMAGPART_EXPR immediate uses, return
7200                    SSA_PROP_INTERESTING.  If there are any REALPART_EXPR
7201                    or IMAGPART_EXPR immediate uses, but none of them have
7202                    a change in their value ranges, return
7203                    SSA_PROP_NOT_INTERESTING.  If there are no
7204                    {REAL,IMAG}PART_EXPR uses at all,
7205                    return SSA_PROP_VARYING.  */
7206                 value_range_t new_vr = VR_INITIALIZER;
7207                 extract_range_basic (&new_vr, use_stmt);
7208                 value_range_t *old_vr = get_value_range (use_lhs);
7209                 if (old_vr->type != new_vr.type
7210                     || !vrp_operand_equal_p (old_vr->min, new_vr.min)
7211                     || !vrp_operand_equal_p (old_vr->max, new_vr.max)
7212                     || !vrp_bitmap_equal_p (old_vr->equiv, new_vr.equiv))
7213                   res = SSA_PROP_INTERESTING;
7214                 else
7215                   res = SSA_PROP_NOT_INTERESTING;
7216                 BITMAP_FREE (new_vr.equiv);
7217                 if (res == SSA_PROP_INTERESTING)
7218                   {
7219                     *output_p = lhs;
7220                     return res;
7221                   }
7222               }
7223
7224             return res;
7225           }
7226         break;
7227       default:
7228         break;
7229       }
7230
7231   /* Every other statement produces no useful ranges.  */
7232   FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF)
7233     set_value_range_to_varying (get_value_range (def));
7234
7235   return SSA_PROP_VARYING;
7236 }
7237
7238 /* Helper that gets the value range of the SSA_NAME with version I
7239    or a symbolic range containing the SSA_NAME only if the value range
7240    is varying or undefined.  */
7241
7242 static inline value_range_t
7243 get_vr_for_comparison (int i)
7244 {
7245   value_range_t vr = *get_value_range (ssa_name (i));
7246
7247   /* If name N_i does not have a valid range, use N_i as its own
7248      range.  This allows us to compare against names that may
7249      have N_i in their ranges.  */
7250   if (vr.type == VR_VARYING || vr.type == VR_UNDEFINED)
7251     {
7252       vr.type = VR_RANGE;
7253       vr.min = ssa_name (i);
7254       vr.max = ssa_name (i);
7255     }
7256
7257   return vr;
7258 }
7259
7260 /* Compare all the value ranges for names equivalent to VAR with VAL
7261    using comparison code COMP.  Return the same value returned by
7262    compare_range_with_value, including the setting of
7263    *STRICT_OVERFLOW_P.  */
7264
7265 static tree
7266 compare_name_with_value (enum tree_code comp, tree var, tree val,
7267                          bool *strict_overflow_p)
7268 {
7269   bitmap_iterator bi;
7270   unsigned i;
7271   bitmap e;
7272   tree retval, t;
7273   int used_strict_overflow;
7274   bool sop;
7275   value_range_t equiv_vr;
7276
7277   /* Get the set of equivalences for VAR.  */
7278   e = get_value_range (var)->equiv;
7279
7280   /* Start at -1.  Set it to 0 if we do a comparison without relying
7281      on overflow, or 1 if all comparisons rely on overflow.  */
7282   used_strict_overflow = -1;
7283
7284   /* Compare vars' value range with val.  */
7285   equiv_vr = get_vr_for_comparison (SSA_NAME_VERSION (var));
7286   sop = false;
7287   retval = compare_range_with_value (comp, &equiv_vr, val, &sop);
7288   if (retval)
7289     used_strict_overflow = sop ? 1 : 0;
7290
7291   /* If the equiv set is empty we have done all work we need to do.  */
7292   if (e == NULL)
7293     {
7294       if (retval
7295           && used_strict_overflow > 0)
7296         *strict_overflow_p = true;
7297       return retval;
7298     }
7299
7300   EXECUTE_IF_SET_IN_BITMAP (e, 0, i, bi)
7301     {
7302       equiv_vr = get_vr_for_comparison (i);
7303       sop = false;
7304       t = compare_range_with_value (comp, &equiv_vr, val, &sop);
7305       if (t)
7306         {
7307           /* If we get different answers from different members
7308              of the equivalence set this check must be in a dead
7309              code region.  Folding it to a trap representation
7310              would be correct here.  For now just return don't-know.  */
7311           if (retval != NULL
7312               && t != retval)
7313             {
7314               retval = NULL_TREE;
7315               break;
7316             }
7317           retval = t;
7318
7319           if (!sop)
7320             used_strict_overflow = 0;
7321           else if (used_strict_overflow < 0)
7322             used_strict_overflow = 1;
7323         }
7324     }
7325
7326   if (retval
7327       && used_strict_overflow > 0)
7328     *strict_overflow_p = true;
7329
7330   return retval;
7331 }
7332
7333
7334 /* Given a comparison code COMP and names N1 and N2, compare all the
7335    ranges equivalent to N1 against all the ranges equivalent to N2
7336    to determine the value of N1 COMP N2.  Return the same value
7337    returned by compare_ranges.  Set *STRICT_OVERFLOW_P to indicate
7338    whether we relied on an overflow infinity in the comparison.  */
7339
7340
7341 static tree
7342 compare_names (enum tree_code comp, tree n1, tree n2,
7343                bool *strict_overflow_p)
7344 {
7345   tree t, retval;
7346   bitmap e1, e2;
7347   bitmap_iterator bi1, bi2;
7348   unsigned i1, i2;
7349   int used_strict_overflow;
7350   static bitmap_obstack *s_obstack = NULL;
7351   static bitmap s_e1 = NULL, s_e2 = NULL;
7352
7353   /* Compare the ranges of every name equivalent to N1 against the
7354      ranges of every name equivalent to N2.  */
7355   e1 = get_value_range (n1)->equiv;
7356   e2 = get_value_range (n2)->equiv;
7357
7358   /* Use the fake bitmaps if e1 or e2 are not available.  */
7359   if (s_obstack == NULL)
7360     {
7361       s_obstack = XNEW (bitmap_obstack);
7362       bitmap_obstack_initialize (s_obstack);
7363       s_e1 = BITMAP_ALLOC (s_obstack);
7364       s_e2 = BITMAP_ALLOC (s_obstack);
7365     }
7366   if (e1 == NULL)
7367     e1 = s_e1;
7368   if (e2 == NULL)
7369     e2 = s_e2;
7370
7371   /* Add N1 and N2 to their own set of equivalences to avoid
7372      duplicating the body of the loop just to check N1 and N2
7373      ranges.  */
7374   bitmap_set_bit (e1, SSA_NAME_VERSION (n1));
7375   bitmap_set_bit (e2, SSA_NAME_VERSION (n2));
7376
7377   /* If the equivalence sets have a common intersection, then the two
7378      names can be compared without checking their ranges.  */
7379   if (bitmap_intersect_p (e1, e2))
7380     {
7381       bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7382       bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7383
7384       return (comp == EQ_EXPR || comp == GE_EXPR || comp == LE_EXPR)
7385              ? boolean_true_node
7386              : boolean_false_node;
7387     }
7388
7389   /* Start at -1.  Set it to 0 if we do a comparison without relying
7390      on overflow, or 1 if all comparisons rely on overflow.  */
7391   used_strict_overflow = -1;
7392
7393   /* Otherwise, compare all the equivalent ranges.  First, add N1 and
7394      N2 to their own set of equivalences to avoid duplicating the body
7395      of the loop just to check N1 and N2 ranges.  */
7396   EXECUTE_IF_SET_IN_BITMAP (e1, 0, i1, bi1)
7397     {
7398       value_range_t vr1 = get_vr_for_comparison (i1);
7399
7400       t = retval = NULL_TREE;
7401       EXECUTE_IF_SET_IN_BITMAP (e2, 0, i2, bi2)
7402         {
7403           bool sop = false;
7404
7405           value_range_t vr2 = get_vr_for_comparison (i2);
7406
7407           t = compare_ranges (comp, &vr1, &vr2, &sop);
7408           if (t)
7409             {
7410               /* If we get different answers from different members
7411                  of the equivalence set this check must be in a dead
7412                  code region.  Folding it to a trap representation
7413                  would be correct here.  For now just return don't-know.  */
7414               if (retval != NULL
7415                   && t != retval)
7416                 {
7417                   bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7418                   bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7419                   return NULL_TREE;
7420                 }
7421               retval = t;
7422
7423               if (!sop)
7424                 used_strict_overflow = 0;
7425               else if (used_strict_overflow < 0)
7426                 used_strict_overflow = 1;
7427             }
7428         }
7429
7430       if (retval)
7431         {
7432           bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7433           bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7434           if (used_strict_overflow > 0)
7435             *strict_overflow_p = true;
7436           return retval;
7437         }
7438     }
7439
7440   /* None of the equivalent ranges are useful in computing this
7441      comparison.  */
7442   bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
7443   bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
7444   return NULL_TREE;
7445 }
7446
7447 /* Helper function for vrp_evaluate_conditional_warnv.  */
7448
7449 static tree
7450 vrp_evaluate_conditional_warnv_with_ops_using_ranges (enum tree_code code,
7451                                                       tree op0, tree op1,
7452                                                       bool * strict_overflow_p)
7453 {
7454   value_range_t *vr0, *vr1;
7455
7456   vr0 = (TREE_CODE (op0) == SSA_NAME) ? get_value_range (op0) : NULL;
7457   vr1 = (TREE_CODE (op1) == SSA_NAME) ? get_value_range (op1) : NULL;
7458
7459   tree res = NULL_TREE;
7460   if (vr0 && vr1)
7461     res = compare_ranges (code, vr0, vr1, strict_overflow_p);
7462   if (!res && vr0)
7463     res = compare_range_with_value (code, vr0, op1, strict_overflow_p);
7464   if (!res && vr1)
7465     res = (compare_range_with_value
7466             (swap_tree_comparison (code), vr1, op0, strict_overflow_p));
7467   return res;
7468 }
7469
7470 /* Helper function for vrp_evaluate_conditional_warnv. */
7471
7472 static tree
7473 vrp_evaluate_conditional_warnv_with_ops (enum tree_code code, tree op0,
7474                                          tree op1, bool use_equiv_p,
7475                                          bool *strict_overflow_p, bool *only_ranges)
7476 {
7477   tree ret;
7478   if (only_ranges)
7479     *only_ranges = true;
7480
7481   /* We only deal with integral and pointer types.  */
7482   if (!INTEGRAL_TYPE_P (TREE_TYPE (op0))
7483       && !POINTER_TYPE_P (TREE_TYPE (op0)))
7484     return NULL_TREE;
7485
7486   if (use_equiv_p)
7487     {
7488       if (only_ranges
7489           && (ret = vrp_evaluate_conditional_warnv_with_ops_using_ranges
7490                       (code, op0, op1, strict_overflow_p)))
7491         return ret;
7492       *only_ranges = false;
7493       if (TREE_CODE (op0) == SSA_NAME && TREE_CODE (op1) == SSA_NAME)
7494         return compare_names (code, op0, op1, strict_overflow_p);
7495       else if (TREE_CODE (op0) == SSA_NAME)
7496         return compare_name_with_value (code, op0, op1, strict_overflow_p);
7497       else if (TREE_CODE (op1) == SSA_NAME)
7498         return (compare_name_with_value
7499                 (swap_tree_comparison (code), op1, op0, strict_overflow_p));
7500     }
7501   else
7502     return vrp_evaluate_conditional_warnv_with_ops_using_ranges (code, op0, op1,
7503                                                                  strict_overflow_p);
7504   return NULL_TREE;
7505 }
7506
7507 /* Given (CODE OP0 OP1) within STMT, try to simplify it based on value range
7508    information.  Return NULL if the conditional can not be evaluated.
7509    The ranges of all the names equivalent with the operands in COND
7510    will be used when trying to compute the value.  If the result is
7511    based on undefined signed overflow, issue a warning if
7512    appropriate.  */
7513
7514 static tree
7515 vrp_evaluate_conditional (enum tree_code code, tree op0, tree op1, gimple stmt)
7516 {
7517   bool sop;
7518   tree ret;
7519   bool only_ranges;
7520
7521   /* Some passes and foldings leak constants with overflow flag set
7522      into the IL.  Avoid doing wrong things with these and bail out.  */
7523   if ((TREE_CODE (op0) == INTEGER_CST
7524        && TREE_OVERFLOW (op0))
7525       || (TREE_CODE (op1) == INTEGER_CST
7526           && TREE_OVERFLOW (op1)))
7527     return NULL_TREE;
7528
7529   sop = false;
7530   ret = vrp_evaluate_conditional_warnv_with_ops (code, op0, op1, true, &sop,
7531                                                  &only_ranges);
7532
7533   if (ret && sop)
7534     {
7535       enum warn_strict_overflow_code wc;
7536       const char* warnmsg;
7537
7538       if (is_gimple_min_invariant (ret))
7539         {
7540           wc = WARN_STRICT_OVERFLOW_CONDITIONAL;
7541           warnmsg = G_("assuming signed overflow does not occur when "
7542                        "simplifying conditional to constant");
7543         }
7544       else
7545         {
7546           wc = WARN_STRICT_OVERFLOW_COMPARISON;
7547           warnmsg = G_("assuming signed overflow does not occur when "
7548                        "simplifying conditional");
7549         }
7550
7551       if (issue_strict_overflow_warning (wc))
7552         {
7553           location_t location;
7554
7555           if (!gimple_has_location (stmt))
7556             location = input_location;
7557           else
7558             location = gimple_location (stmt);
7559           warning_at (location, OPT_Wstrict_overflow, "%s", warnmsg);
7560         }
7561     }
7562
7563   if (warn_type_limits
7564       && ret && only_ranges
7565       && TREE_CODE_CLASS (code) == tcc_comparison
7566       && TREE_CODE (op0) == SSA_NAME)
7567     {
7568       /* If the comparison is being folded and the operand on the LHS
7569          is being compared against a constant value that is outside of
7570          the natural range of OP0's type, then the predicate will
7571          always fold regardless of the value of OP0.  If -Wtype-limits
7572          was specified, emit a warning.  */
7573       tree type = TREE_TYPE (op0);
7574       value_range_t *vr0 = get_value_range (op0);
7575
7576       if (vr0->type == VR_RANGE
7577           && INTEGRAL_TYPE_P (type)
7578           && vrp_val_is_min (vr0->min)
7579           && vrp_val_is_max (vr0->max)
7580           && is_gimple_min_invariant (op1))
7581         {
7582           location_t location;
7583
7584           if (!gimple_has_location (stmt))
7585             location = input_location;
7586           else
7587             location = gimple_location (stmt);
7588
7589           warning_at (location, OPT_Wtype_limits,
7590                       integer_zerop (ret)
7591                       ? G_("comparison always false "
7592                            "due to limited range of data type")
7593                       : G_("comparison always true "
7594                            "due to limited range of data type"));
7595         }
7596     }
7597
7598   return ret;
7599 }
7600
7601
7602 /* Visit conditional statement STMT.  If we can determine which edge
7603    will be taken out of STMT's basic block, record it in
7604    *TAKEN_EDGE_P and return SSA_PROP_INTERESTING.  Otherwise, return
7605    SSA_PROP_VARYING.  */
7606
7607 static enum ssa_prop_result
7608 vrp_visit_cond_stmt (gcond *stmt, edge *taken_edge_p)
7609 {
7610   tree val;
7611   bool sop;
7612
7613   *taken_edge_p = NULL;
7614
7615   if (dump_file && (dump_flags & TDF_DETAILS))
7616     {
7617       tree use;
7618       ssa_op_iter i;
7619
7620       fprintf (dump_file, "\nVisiting conditional with predicate: ");
7621       print_gimple_stmt (dump_file, stmt, 0, 0);
7622       fprintf (dump_file, "\nWith known ranges\n");
7623
7624       FOR_EACH_SSA_TREE_OPERAND (use, stmt, i, SSA_OP_USE)
7625         {
7626           fprintf (dump_file, "\t");
7627           print_generic_expr (dump_file, use, 0);
7628           fprintf (dump_file, ": ");
7629           dump_value_range (dump_file, vr_value[SSA_NAME_VERSION (use)]);
7630         }
7631
7632       fprintf (dump_file, "\n");
7633     }
7634
7635   /* Compute the value of the predicate COND by checking the known
7636      ranges of each of its operands.
7637
7638      Note that we cannot evaluate all the equivalent ranges here
7639      because those ranges may not yet be final and with the current
7640      propagation strategy, we cannot determine when the value ranges
7641      of the names in the equivalence set have changed.
7642
7643      For instance, given the following code fragment
7644
7645         i_5 = PHI <8, i_13>
7646         ...
7647         i_14 = ASSERT_EXPR <i_5, i_5 != 0>
7648         if (i_14 == 1)
7649           ...
7650
7651      Assume that on the first visit to i_14, i_5 has the temporary
7652      range [8, 8] because the second argument to the PHI function is
7653      not yet executable.  We derive the range ~[0, 0] for i_14 and the
7654      equivalence set { i_5 }.  So, when we visit 'if (i_14 == 1)' for
7655      the first time, since i_14 is equivalent to the range [8, 8], we
7656      determine that the predicate is always false.
7657
7658      On the next round of propagation, i_13 is determined to be
7659      VARYING, which causes i_5 to drop down to VARYING.  So, another
7660      visit to i_14 is scheduled.  In this second visit, we compute the
7661      exact same range and equivalence set for i_14, namely ~[0, 0] and
7662      { i_5 }.  But we did not have the previous range for i_5
7663      registered, so vrp_visit_assignment thinks that the range for
7664      i_14 has not changed.  Therefore, the predicate 'if (i_14 == 1)'
7665      is not visited again, which stops propagation from visiting
7666      statements in the THEN clause of that if().
7667
7668      To properly fix this we would need to keep the previous range
7669      value for the names in the equivalence set.  This way we would've
7670      discovered that from one visit to the other i_5 changed from
7671      range [8, 8] to VR_VARYING.
7672
7673      However, fixing this apparent limitation may not be worth the
7674      additional checking.  Testing on several code bases (GCC, DLV,
7675      MICO, TRAMP3D and SPEC2000) showed that doing this results in
7676      4 more predicates folded in SPEC.  */
7677   sop = false;
7678
7679   val = vrp_evaluate_conditional_warnv_with_ops (gimple_cond_code (stmt),
7680                                                  gimple_cond_lhs (stmt),
7681                                                  gimple_cond_rhs (stmt),
7682                                                  false, &sop, NULL);
7683   if (val)
7684     {
7685       if (!sop)
7686         *taken_edge_p = find_taken_edge (gimple_bb (stmt), val);
7687       else
7688         {
7689           if (dump_file && (dump_flags & TDF_DETAILS))
7690             fprintf (dump_file,
7691                      "\nIgnoring predicate evaluation because "
7692                      "it assumes that signed overflow is undefined");
7693           val = NULL_TREE;
7694         }
7695     }
7696
7697   if (dump_file && (dump_flags & TDF_DETAILS))
7698     {
7699       fprintf (dump_file, "\nPredicate evaluates to: ");
7700       if (val == NULL_TREE)
7701         fprintf (dump_file, "DON'T KNOW\n");
7702       else
7703         print_generic_stmt (dump_file, val, 0);
7704     }
7705
7706   return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
7707 }
7708
7709 /* Searches the case label vector VEC for the index *IDX of the CASE_LABEL
7710    that includes the value VAL.  The search is restricted to the range
7711    [START_IDX, n - 1] where n is the size of VEC.
7712
7713    If there is a CASE_LABEL for VAL, its index is placed in IDX and true is
7714    returned.
7715
7716    If there is no CASE_LABEL for VAL and there is one that is larger than VAL,
7717    it is placed in IDX and false is returned.
7718
7719    If VAL is larger than any CASE_LABEL, n is placed on IDX and false is
7720    returned. */
7721
7722 static bool
7723 find_case_label_index (gswitch *stmt, size_t start_idx, tree val, size_t *idx)
7724 {
7725   size_t n = gimple_switch_num_labels (stmt);
7726   size_t low, high;
7727
7728   /* Find case label for minimum of the value range or the next one.
7729      At each iteration we are searching in [low, high - 1]. */
7730
7731   for (low = start_idx, high = n; high != low; )
7732     {
7733       tree t;
7734       int cmp;
7735       /* Note that i != high, so we never ask for n. */
7736       size_t i = (high + low) / 2;
7737       t = gimple_switch_label (stmt, i);
7738
7739       /* Cache the result of comparing CASE_LOW and val.  */
7740       cmp = tree_int_cst_compare (CASE_LOW (t), val);
7741
7742       if (cmp == 0)
7743         {
7744           /* Ranges cannot be empty. */
7745           *idx = i;
7746           return true;
7747         }
7748       else if (cmp > 0)
7749         high = i;
7750       else
7751         {
7752           low = i + 1;
7753           if (CASE_HIGH (t) != NULL
7754               && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
7755             {
7756               *idx = i;
7757               return true;
7758             }
7759         }
7760     }
7761
7762   *idx = high;
7763   return false;
7764 }
7765
7766 /* Searches the case label vector VEC for the range of CASE_LABELs that is used
7767    for values between MIN and MAX. The first index is placed in MIN_IDX. The
7768    last index is placed in MAX_IDX. If the range of CASE_LABELs is empty
7769    then MAX_IDX < MIN_IDX.
7770    Returns true if the default label is not needed. */
7771
7772 static bool
7773 find_case_label_range (gswitch *stmt, tree min, tree max, size_t *min_idx,
7774                        size_t *max_idx)
7775 {
7776   size_t i, j;
7777   bool min_take_default = !find_case_label_index (stmt, 1, min, &i);
7778   bool max_take_default = !find_case_label_index (stmt, i, max, &j);
7779
7780   if (i == j
7781       && min_take_default
7782       && max_take_default)
7783     {
7784       /* Only the default case label reached.
7785          Return an empty range. */
7786       *min_idx = 1;
7787       *max_idx = 0;
7788       return false;
7789     }
7790   else
7791     {
7792       bool take_default = min_take_default || max_take_default;
7793       tree low, high;
7794       size_t k;
7795
7796       if (max_take_default)
7797         j--;
7798
7799       /* If the case label range is continuous, we do not need
7800          the default case label.  Verify that.  */
7801       high = CASE_LOW (gimple_switch_label (stmt, i));
7802       if (CASE_HIGH (gimple_switch_label (stmt, i)))
7803         high = CASE_HIGH (gimple_switch_label (stmt, i));
7804       for (k = i + 1; k <= j; ++k)
7805         {
7806           low = CASE_LOW (gimple_switch_label (stmt, k));
7807           if (!integer_onep (int_const_binop (MINUS_EXPR, low, high)))
7808             {
7809               take_default = true;
7810               break;
7811             }
7812           high = low;
7813           if (CASE_HIGH (gimple_switch_label (stmt, k)))
7814             high = CASE_HIGH (gimple_switch_label (stmt, k));
7815         }
7816
7817       *min_idx = i;
7818       *max_idx = j;
7819       return !take_default;
7820     }
7821 }
7822
7823 /* Searches the case label vector VEC for the ranges of CASE_LABELs that are
7824    used in range VR.  The indices are placed in MIN_IDX1, MAX_IDX, MIN_IDX2 and
7825    MAX_IDX2.  If the ranges of CASE_LABELs are empty then MAX_IDX1 < MIN_IDX1.
7826    Returns true if the default label is not needed.  */
7827
7828 static bool
7829 find_case_label_ranges (gswitch *stmt, value_range_t *vr, size_t *min_idx1,
7830                         size_t *max_idx1, size_t *min_idx2,
7831                         size_t *max_idx2)
7832 {
7833   size_t i, j, k, l;
7834   unsigned int n = gimple_switch_num_labels (stmt);
7835   bool take_default;
7836   tree case_low, case_high;
7837   tree min = vr->min, max = vr->max;
7838
7839   gcc_checking_assert (vr->type == VR_RANGE || vr->type == VR_ANTI_RANGE);
7840
7841   take_default = !find_case_label_range (stmt, min, max, &i, &j);
7842
7843   /* Set second range to emtpy.  */
7844   *min_idx2 = 1;
7845   *max_idx2 = 0;
7846
7847   if (vr->type == VR_RANGE)
7848     {
7849       *min_idx1 = i;
7850       *max_idx1 = j;
7851       return !take_default;
7852     }
7853
7854   /* Set first range to all case labels.  */
7855   *min_idx1 = 1;
7856   *max_idx1 = n - 1;
7857
7858   if (i > j)
7859     return false;
7860
7861   /* Make sure all the values of case labels [i , j] are contained in
7862      range [MIN, MAX].  */
7863   case_low = CASE_LOW (gimple_switch_label (stmt, i));
7864   case_high = CASE_HIGH (gimple_switch_label (stmt, j));
7865   if (tree_int_cst_compare (case_low, min) < 0)
7866     i += 1;
7867   if (case_high != NULL_TREE
7868       && tree_int_cst_compare (max, case_high) < 0)
7869     j -= 1;
7870
7871   if (i > j)
7872     return false;
7873
7874   /* If the range spans case labels [i, j], the corresponding anti-range spans
7875      the labels [1, i - 1] and [j + 1, n -  1].  */
7876   k = j + 1;
7877   l = n - 1;
7878   if (k > l)
7879     {
7880       k = 1;
7881       l = 0;
7882     }
7883
7884   j = i - 1;
7885   i = 1;
7886   if (i > j)
7887     {
7888       i = k;
7889       j = l;
7890       k = 1;
7891       l = 0;
7892     }
7893
7894   *min_idx1 = i;
7895   *max_idx1 = j;
7896   *min_idx2 = k;
7897   *max_idx2 = l;
7898   return false;
7899 }
7900
7901 /* Visit switch statement STMT.  If we can determine which edge
7902    will be taken out of STMT's basic block, record it in
7903    *TAKEN_EDGE_P and return SSA_PROP_INTERESTING.  Otherwise, return
7904    SSA_PROP_VARYING.  */
7905
7906 static enum ssa_prop_result
7907 vrp_visit_switch_stmt (gswitch *stmt, edge *taken_edge_p)
7908 {
7909   tree op, val;
7910   value_range_t *vr;
7911   size_t i = 0, j = 0, k, l;
7912   bool take_default;
7913
7914   *taken_edge_p = NULL;
7915   op = gimple_switch_index (stmt);
7916   if (TREE_CODE (op) != SSA_NAME)
7917     return SSA_PROP_VARYING;
7918
7919   vr = get_value_range (op);
7920   if (dump_file && (dump_flags & TDF_DETAILS))
7921     {
7922       fprintf (dump_file, "\nVisiting switch expression with operand ");
7923       print_generic_expr (dump_file, op, 0);
7924       fprintf (dump_file, " with known range ");
7925       dump_value_range (dump_file, vr);
7926       fprintf (dump_file, "\n");
7927     }
7928
7929   if ((vr->type != VR_RANGE
7930        && vr->type != VR_ANTI_RANGE)
7931       || symbolic_range_p (vr))
7932     return SSA_PROP_VARYING;
7933
7934   /* Find the single edge that is taken from the switch expression.  */
7935   take_default = !find_case_label_ranges (stmt, vr, &i, &j, &k, &l);
7936
7937   /* Check if the range spans no CASE_LABEL. If so, we only reach the default
7938      label */
7939   if (j < i)
7940     {
7941       gcc_assert (take_default);
7942       val = gimple_switch_default_label (stmt);
7943     }
7944   else
7945     {
7946       /* Check if labels with index i to j and maybe the default label
7947          are all reaching the same label.  */
7948
7949       val = gimple_switch_label (stmt, i);
7950       if (take_default
7951           && CASE_LABEL (gimple_switch_default_label (stmt))
7952           != CASE_LABEL (val))
7953         {
7954           if (dump_file && (dump_flags & TDF_DETAILS))
7955             fprintf (dump_file, "  not a single destination for this "
7956                      "range\n");
7957           return SSA_PROP_VARYING;
7958         }
7959       for (++i; i <= j; ++i)
7960         {
7961           if (CASE_LABEL (gimple_switch_label (stmt, i)) != CASE_LABEL (val))
7962             {
7963               if (dump_file && (dump_flags & TDF_DETAILS))
7964                 fprintf (dump_file, "  not a single destination for this "
7965                          "range\n");
7966               return SSA_PROP_VARYING;
7967             }
7968         }
7969       for (; k <= l; ++k)
7970         {
7971           if (CASE_LABEL (gimple_switch_label (stmt, k)) != CASE_LABEL (val))
7972             {
7973               if (dump_file && (dump_flags & TDF_DETAILS))
7974                 fprintf (dump_file, "  not a single destination for this "
7975                          "range\n");
7976               return SSA_PROP_VARYING;
7977             }
7978         }
7979     }
7980
7981   *taken_edge_p = find_edge (gimple_bb (stmt),
7982                              label_to_block (CASE_LABEL (val)));
7983
7984   if (dump_file && (dump_flags & TDF_DETAILS))
7985     {
7986       fprintf (dump_file, "  will take edge to ");
7987       print_generic_stmt (dump_file, CASE_LABEL (val), 0);
7988     }
7989
7990   return SSA_PROP_INTERESTING;
7991 }
7992
7993
7994 /* Evaluate statement STMT.  If the statement produces a useful range,
7995    return SSA_PROP_INTERESTING and record the SSA name with the
7996    interesting range into *OUTPUT_P.
7997
7998    If STMT is a conditional branch and we can determine its truth
7999    value, the taken edge is recorded in *TAKEN_EDGE_P.
8000
8001    If STMT produces a varying value, return SSA_PROP_VARYING.  */
8002
8003 static enum ssa_prop_result
8004 vrp_visit_stmt (gimple stmt, edge *taken_edge_p, tree *output_p)
8005 {
8006   tree def;
8007   ssa_op_iter iter;
8008
8009   if (dump_file && (dump_flags & TDF_DETAILS))
8010     {
8011       fprintf (dump_file, "\nVisiting statement:\n");
8012       print_gimple_stmt (dump_file, stmt, 0, dump_flags);
8013     }
8014
8015   if (!stmt_interesting_for_vrp (stmt))
8016     gcc_assert (stmt_ends_bb_p (stmt));
8017   else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
8018     return vrp_visit_assignment_or_call (stmt, output_p);
8019   else if (gimple_code (stmt) == GIMPLE_COND)
8020     return vrp_visit_cond_stmt (as_a <gcond *> (stmt), taken_edge_p);
8021   else if (gimple_code (stmt) == GIMPLE_SWITCH)
8022     return vrp_visit_switch_stmt (as_a <gswitch *> (stmt), taken_edge_p);
8023
8024   /* All other statements produce nothing of interest for VRP, so mark
8025      their outputs varying and prevent further simulation.  */
8026   FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF)
8027     set_value_range_to_varying (get_value_range (def));
8028
8029   return SSA_PROP_VARYING;
8030 }
8031
8032 /* Union the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
8033    { VR1TYPE, VR0MIN, VR0MAX } and store the result
8034    in { *VR0TYPE, *VR0MIN, *VR0MAX }.  This may not be the smallest
8035    possible such range.  The resulting range is not canonicalized.  */
8036
8037 static void
8038 union_ranges (enum value_range_type *vr0type,
8039               tree *vr0min, tree *vr0max,
8040               enum value_range_type vr1type,
8041               tree vr1min, tree vr1max)
8042 {
8043   bool mineq = operand_equal_p (*vr0min, vr1min, 0);
8044   bool maxeq = operand_equal_p (*vr0max, vr1max, 0);
8045
8046   /* [] is vr0, () is vr1 in the following classification comments.  */
8047   if (mineq && maxeq)
8048     {
8049       /* [(  )] */
8050       if (*vr0type == vr1type)
8051         /* Nothing to do for equal ranges.  */
8052         ;
8053       else if ((*vr0type == VR_RANGE
8054                 && vr1type == VR_ANTI_RANGE)
8055                || (*vr0type == VR_ANTI_RANGE
8056                    && vr1type == VR_RANGE))
8057         {
8058           /* For anti-range with range union the result is varying.  */
8059           goto give_up;
8060         }
8061       else
8062         gcc_unreachable ();
8063     }
8064   else if (operand_less_p (*vr0max, vr1min) == 1
8065            || operand_less_p (vr1max, *vr0min) == 1)
8066     {
8067       /* [ ] ( ) or ( ) [ ]
8068          If the ranges have an empty intersection, result of the union
8069          operation is the anti-range or if both are anti-ranges
8070          it covers all.  */
8071       if (*vr0type == VR_ANTI_RANGE
8072           && vr1type == VR_ANTI_RANGE)
8073         goto give_up;
8074       else if (*vr0type == VR_ANTI_RANGE
8075                && vr1type == VR_RANGE)
8076         ;
8077       else if (*vr0type == VR_RANGE
8078                && vr1type == VR_ANTI_RANGE)
8079         {
8080           *vr0type = vr1type;
8081           *vr0min = vr1min;
8082           *vr0max = vr1max;
8083         }
8084       else if (*vr0type == VR_RANGE
8085                && vr1type == VR_RANGE)
8086         {
8087           /* The result is the convex hull of both ranges.  */
8088           if (operand_less_p (*vr0max, vr1min) == 1)
8089             {
8090               /* If the result can be an anti-range, create one.  */
8091               if (TREE_CODE (*vr0max) == INTEGER_CST
8092                   && TREE_CODE (vr1min) == INTEGER_CST
8093                   && vrp_val_is_min (*vr0min)
8094                   && vrp_val_is_max (vr1max))
8095                 {
8096                   tree min = int_const_binop (PLUS_EXPR,
8097                                               *vr0max,
8098                                               build_int_cst (TREE_TYPE (*vr0max), 1));
8099                   tree max = int_const_binop (MINUS_EXPR,
8100                                               vr1min,
8101                                               build_int_cst (TREE_TYPE (vr1min), 1));
8102                   if (!operand_less_p (max, min))
8103                     {
8104                       *vr0type = VR_ANTI_RANGE;
8105                       *vr0min = min;
8106                       *vr0max = max;
8107                     }
8108                   else
8109                     *vr0max = vr1max;
8110                 }
8111               else
8112                 *vr0max = vr1max;
8113             }
8114           else
8115             {
8116               /* If the result can be an anti-range, create one.  */
8117               if (TREE_CODE (vr1max) == INTEGER_CST
8118                   && TREE_CODE (*vr0min) == INTEGER_CST
8119                   && vrp_val_is_min (vr1min)
8120                   && vrp_val_is_max (*vr0max))
8121                 {
8122                   tree min = int_const_binop (PLUS_EXPR,
8123                                               vr1max,
8124                                               build_int_cst (TREE_TYPE (vr1max), 1));
8125                   tree max = int_const_binop (MINUS_EXPR,
8126                                               *vr0min,
8127                                               build_int_cst (TREE_TYPE (*vr0min), 1));
8128                   if (!operand_less_p (max, min))
8129                     {
8130                       *vr0type = VR_ANTI_RANGE;
8131                       *vr0min = min;
8132                       *vr0max = max;
8133                     }
8134                   else
8135                     *vr0min = vr1min;
8136                 }
8137               else
8138                 *vr0min = vr1min;
8139             }
8140         }
8141       else
8142         gcc_unreachable ();
8143     }
8144   else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
8145            && (mineq || operand_less_p (*vr0min, vr1min) == 1))
8146     {
8147       /* [ (  ) ] or [(  ) ] or [ (  )] */
8148       if (*vr0type == VR_RANGE
8149           && vr1type == VR_RANGE)
8150         ;
8151       else if (*vr0type == VR_ANTI_RANGE
8152                && vr1type == VR_ANTI_RANGE)
8153         {
8154           *vr0type = vr1type;
8155           *vr0min = vr1min;
8156           *vr0max = vr1max;
8157         }
8158       else if (*vr0type == VR_ANTI_RANGE
8159                && vr1type == VR_RANGE)
8160         {
8161           /* Arbitrarily choose the right or left gap.  */
8162           if (!mineq && TREE_CODE (vr1min) == INTEGER_CST)
8163             *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8164                                        build_int_cst (TREE_TYPE (vr1min), 1));
8165           else if (!maxeq && TREE_CODE (vr1max) == INTEGER_CST)
8166             *vr0min = int_const_binop (PLUS_EXPR, vr1max,
8167                                        build_int_cst (TREE_TYPE (vr1max), 1));
8168           else
8169             goto give_up;
8170         }
8171       else if (*vr0type == VR_RANGE
8172                && vr1type == VR_ANTI_RANGE)
8173         /* The result covers everything.  */
8174         goto give_up;
8175       else
8176         gcc_unreachable ();
8177     }
8178   else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
8179            && (mineq || operand_less_p (vr1min, *vr0min) == 1))
8180     {
8181       /* ( [  ] ) or ([  ] ) or ( [  ]) */
8182       if (*vr0type == VR_RANGE
8183           && vr1type == VR_RANGE)
8184         {
8185           *vr0type = vr1type;
8186           *vr0min = vr1min;
8187           *vr0max = vr1max;
8188         }
8189       else if (*vr0type == VR_ANTI_RANGE
8190                && vr1type == VR_ANTI_RANGE)
8191         ;
8192       else if (*vr0type == VR_RANGE
8193                && vr1type == VR_ANTI_RANGE)
8194         {
8195           *vr0type = VR_ANTI_RANGE;
8196           if (!mineq && TREE_CODE (*vr0min) == INTEGER_CST)
8197             {
8198               *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
8199                                          build_int_cst (TREE_TYPE (*vr0min), 1));
8200               *vr0min = vr1min;
8201             }
8202           else if (!maxeq && TREE_CODE (*vr0max) == INTEGER_CST)
8203             {
8204               *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8205                                          build_int_cst (TREE_TYPE (*vr0max), 1));
8206               *vr0max = vr1max;
8207             }
8208           else
8209             goto give_up;
8210         }
8211       else if (*vr0type == VR_ANTI_RANGE
8212                && vr1type == VR_RANGE)
8213         /* The result covers everything.  */
8214         goto give_up;
8215       else
8216         gcc_unreachable ();
8217     }
8218   else if ((operand_less_p (vr1min, *vr0max) == 1
8219             || operand_equal_p (vr1min, *vr0max, 0))
8220            && operand_less_p (*vr0min, vr1min) == 1
8221            && operand_less_p (*vr0max, vr1max) == 1)
8222     {
8223       /* [  (  ]  ) or [   ](   ) */
8224       if (*vr0type == VR_RANGE
8225           && vr1type == VR_RANGE)
8226         *vr0max = vr1max;
8227       else if (*vr0type == VR_ANTI_RANGE
8228                && vr1type == VR_ANTI_RANGE)
8229         *vr0min = vr1min;
8230       else if (*vr0type == VR_ANTI_RANGE
8231                && vr1type == VR_RANGE)
8232         {
8233           if (TREE_CODE (vr1min) == INTEGER_CST)
8234             *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8235                                        build_int_cst (TREE_TYPE (vr1min), 1));
8236           else
8237             goto give_up;
8238         }
8239       else if (*vr0type == VR_RANGE
8240                && vr1type == VR_ANTI_RANGE)
8241         {
8242           if (TREE_CODE (*vr0max) == INTEGER_CST)
8243             {
8244               *vr0type = vr1type;
8245               *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8246                                          build_int_cst (TREE_TYPE (*vr0max), 1));
8247               *vr0max = vr1max;
8248             }
8249           else
8250             goto give_up;
8251         }
8252       else
8253         gcc_unreachable ();
8254     }
8255   else if ((operand_less_p (*vr0min, vr1max) == 1
8256             || operand_equal_p (*vr0min, vr1max, 0))
8257            && operand_less_p (vr1min, *vr0min) == 1
8258            && operand_less_p (vr1max, *vr0max) == 1)
8259     {
8260       /* (  [  )  ] or (   )[   ] */
8261       if (*vr0type == VR_RANGE
8262           && vr1type == VR_RANGE)
8263         *vr0min = vr1min;
8264       else if (*vr0type == VR_ANTI_RANGE
8265                && vr1type == VR_ANTI_RANGE)
8266         *vr0max = vr1max;
8267       else if (*vr0type == VR_ANTI_RANGE
8268                && vr1type == VR_RANGE)
8269         {
8270           if (TREE_CODE (vr1max) == INTEGER_CST)
8271             *vr0min = int_const_binop (PLUS_EXPR, vr1max,
8272                                        build_int_cst (TREE_TYPE (vr1max), 1));
8273           else
8274             goto give_up;
8275         }
8276       else if (*vr0type == VR_RANGE
8277                && vr1type == VR_ANTI_RANGE)
8278         {
8279           if (TREE_CODE (*vr0min) == INTEGER_CST)
8280             {
8281               *vr0type = vr1type;
8282               *vr0min = vr1min;
8283               *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
8284                                          build_int_cst (TREE_TYPE (*vr0min), 1));
8285             }
8286           else
8287             goto give_up;
8288         }
8289       else
8290         gcc_unreachable ();
8291     }
8292   else
8293     goto give_up;
8294
8295   return;
8296
8297 give_up:
8298   *vr0type = VR_VARYING;
8299   *vr0min = NULL_TREE;
8300   *vr0max = NULL_TREE;
8301 }
8302
8303 /* Intersect the two value-ranges { *VR0TYPE, *VR0MIN, *VR0MAX } and
8304    { VR1TYPE, VR0MIN, VR0MAX } and store the result
8305    in { *VR0TYPE, *VR0MIN, *VR0MAX }.  This may not be the smallest
8306    possible such range.  The resulting range is not canonicalized.  */
8307
8308 static void
8309 intersect_ranges (enum value_range_type *vr0type,
8310                   tree *vr0min, tree *vr0max,
8311                   enum value_range_type vr1type,
8312                   tree vr1min, tree vr1max)
8313 {
8314   bool mineq = operand_equal_p (*vr0min, vr1min, 0);
8315   bool maxeq = operand_equal_p (*vr0max, vr1max, 0);
8316
8317   /* [] is vr0, () is vr1 in the following classification comments.  */
8318   if (mineq && maxeq)
8319     {
8320       /* [(  )] */
8321       if (*vr0type == vr1type)
8322         /* Nothing to do for equal ranges.  */
8323         ;
8324       else if ((*vr0type == VR_RANGE
8325                 && vr1type == VR_ANTI_RANGE)
8326                || (*vr0type == VR_ANTI_RANGE
8327                    && vr1type == VR_RANGE))
8328         {
8329           /* For anti-range with range intersection the result is empty.  */
8330           *vr0type = VR_UNDEFINED;
8331           *vr0min = NULL_TREE;
8332           *vr0max = NULL_TREE;
8333         }
8334       else
8335         gcc_unreachable ();
8336     }
8337   else if (operand_less_p (*vr0max, vr1min) == 1
8338            || operand_less_p (vr1max, *vr0min) == 1)
8339     {
8340       /* [ ] ( ) or ( ) [ ]
8341          If the ranges have an empty intersection, the result of the
8342          intersect operation is the range for intersecting an
8343          anti-range with a range or empty when intersecting two ranges.  */
8344       if (*vr0type == VR_RANGE
8345           && vr1type == VR_ANTI_RANGE)
8346         ;
8347       else if (*vr0type == VR_ANTI_RANGE
8348                && vr1type == VR_RANGE)
8349         {
8350           *vr0type = vr1type;
8351           *vr0min = vr1min;
8352           *vr0max = vr1max;
8353         }
8354       else if (*vr0type == VR_RANGE
8355                && vr1type == VR_RANGE)
8356         {
8357           *vr0type = VR_UNDEFINED;
8358           *vr0min = NULL_TREE;
8359           *vr0max = NULL_TREE;
8360         }
8361       else if (*vr0type == VR_ANTI_RANGE
8362                && vr1type == VR_ANTI_RANGE)
8363         {
8364           /* If the anti-ranges are adjacent to each other merge them.  */
8365           if (TREE_CODE (*vr0max) == INTEGER_CST
8366               && TREE_CODE (vr1min) == INTEGER_CST
8367               && operand_less_p (*vr0max, vr1min) == 1
8368               && integer_onep (int_const_binop (MINUS_EXPR,
8369                                                 vr1min, *vr0max)))
8370             *vr0max = vr1max;
8371           else if (TREE_CODE (vr1max) == INTEGER_CST
8372                    && TREE_CODE (*vr0min) == INTEGER_CST
8373                    && operand_less_p (vr1max, *vr0min) == 1
8374                    && integer_onep (int_const_binop (MINUS_EXPR,
8375                                                      *vr0min, vr1max)))
8376             *vr0min = vr1min;
8377           /* Else arbitrarily take VR0.  */
8378         }
8379     }
8380   else if ((maxeq || operand_less_p (vr1max, *vr0max) == 1)
8381            && (mineq || operand_less_p (*vr0min, vr1min) == 1))
8382     {
8383       /* [ (  ) ] or [(  ) ] or [ (  )] */
8384       if (*vr0type == VR_RANGE
8385           && vr1type == VR_RANGE)
8386         {
8387           /* If both are ranges the result is the inner one.  */
8388           *vr0type = vr1type;
8389           *vr0min = vr1min;
8390           *vr0max = vr1max;
8391         }
8392       else if (*vr0type == VR_RANGE
8393                && vr1type == VR_ANTI_RANGE)
8394         {
8395           /* Choose the right gap if the left one is empty.  */
8396           if (mineq)
8397             {
8398               if (TREE_CODE (vr1max) == INTEGER_CST)
8399                 *vr0min = int_const_binop (PLUS_EXPR, vr1max,
8400                                            build_int_cst (TREE_TYPE (vr1max), 1));
8401               else
8402                 *vr0min = vr1max;
8403             }
8404           /* Choose the left gap if the right one is empty.  */
8405           else if (maxeq)
8406             {
8407               if (TREE_CODE (vr1min) == INTEGER_CST)
8408                 *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8409                                            build_int_cst (TREE_TYPE (vr1min), 1));
8410               else
8411                 *vr0max = vr1min;
8412             }
8413           /* Choose the anti-range if the range is effectively varying.  */
8414           else if (vrp_val_is_min (*vr0min)
8415                    && vrp_val_is_max (*vr0max))
8416             {
8417               *vr0type = vr1type;
8418               *vr0min = vr1min;
8419               *vr0max = vr1max;
8420             }
8421           /* Else choose the range.  */
8422         }
8423       else if (*vr0type == VR_ANTI_RANGE
8424                && vr1type == VR_ANTI_RANGE)
8425         /* If both are anti-ranges the result is the outer one.  */
8426         ;
8427       else if (*vr0type == VR_ANTI_RANGE
8428                && vr1type == VR_RANGE)
8429         {
8430           /* The intersection is empty.  */
8431           *vr0type = VR_UNDEFINED;
8432           *vr0min = NULL_TREE;
8433           *vr0max = NULL_TREE;
8434         }
8435       else
8436         gcc_unreachable ();
8437     }
8438   else if ((maxeq || operand_less_p (*vr0max, vr1max) == 1)
8439            && (mineq || operand_less_p (vr1min, *vr0min) == 1))
8440     {
8441       /* ( [  ] ) or ([  ] ) or ( [  ]) */
8442       if (*vr0type == VR_RANGE
8443           && vr1type == VR_RANGE)
8444         /* Choose the inner range.  */
8445         ;
8446       else if (*vr0type == VR_ANTI_RANGE
8447                && vr1type == VR_RANGE)
8448         {
8449           /* Choose the right gap if the left is empty.  */
8450           if (mineq)
8451             {
8452               *vr0type = VR_RANGE;
8453               if (TREE_CODE (*vr0max) == INTEGER_CST)
8454                 *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8455                                            build_int_cst (TREE_TYPE (*vr0max), 1));
8456               else
8457                 *vr0min = *vr0max;
8458               *vr0max = vr1max;
8459             }
8460           /* Choose the left gap if the right is empty.  */
8461           else if (maxeq)
8462             {
8463               *vr0type = VR_RANGE;
8464               if (TREE_CODE (*vr0min) == INTEGER_CST)
8465                 *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
8466                                            build_int_cst (TREE_TYPE (*vr0min), 1));
8467               else
8468                 *vr0max = *vr0min;
8469               *vr0min = vr1min;
8470             }
8471           /* Choose the anti-range if the range is effectively varying.  */
8472           else if (vrp_val_is_min (vr1min)
8473                    && vrp_val_is_max (vr1max))
8474             ;
8475           /* Else choose the range.  */
8476           else
8477             {
8478               *vr0type = vr1type;
8479               *vr0min = vr1min;
8480               *vr0max = vr1max;
8481             }
8482         }
8483       else if (*vr0type == VR_ANTI_RANGE
8484                && vr1type == VR_ANTI_RANGE)
8485         {
8486           /* If both are anti-ranges the result is the outer one.  */
8487           *vr0type = vr1type;
8488           *vr0min = vr1min;
8489           *vr0max = vr1max;
8490         }
8491       else if (vr1type == VR_ANTI_RANGE
8492                && *vr0type == VR_RANGE)
8493         {
8494           /* The intersection is empty.  */
8495           *vr0type = VR_UNDEFINED;
8496           *vr0min = NULL_TREE;
8497           *vr0max = NULL_TREE;
8498         }
8499       else
8500         gcc_unreachable ();
8501     }
8502   else if ((operand_less_p (vr1min, *vr0max) == 1
8503             || operand_equal_p (vr1min, *vr0max, 0))
8504            && operand_less_p (*vr0min, vr1min) == 1)
8505     {
8506       /* [  (  ]  ) or [  ](  ) */
8507       if (*vr0type == VR_ANTI_RANGE
8508           && vr1type == VR_ANTI_RANGE)
8509         *vr0max = vr1max;
8510       else if (*vr0type == VR_RANGE
8511                && vr1type == VR_RANGE)
8512         *vr0min = vr1min;
8513       else if (*vr0type == VR_RANGE
8514                && vr1type == VR_ANTI_RANGE)
8515         {
8516           if (TREE_CODE (vr1min) == INTEGER_CST)
8517             *vr0max = int_const_binop (MINUS_EXPR, vr1min,
8518                                        build_int_cst (TREE_TYPE (vr1min), 1));
8519           else
8520             *vr0max = vr1min;
8521         }
8522       else if (*vr0type == VR_ANTI_RANGE
8523                && vr1type == VR_RANGE)
8524         {
8525           *vr0type = VR_RANGE;
8526           if (TREE_CODE (*vr0max) == INTEGER_CST)
8527             *vr0min = int_const_binop (PLUS_EXPR, *vr0max,
8528                                        build_int_cst (TREE_TYPE (*vr0max), 1));
8529           else
8530             *vr0min = *vr0max;
8531           *vr0max = vr1max;
8532         }
8533       else
8534         gcc_unreachable ();
8535     }
8536   else if ((operand_less_p (*vr0min, vr1max) == 1
8537             || operand_equal_p (*vr0min, vr1max, 0))
8538            && operand_less_p (vr1min, *vr0min) == 1)
8539     {
8540       /* (  [  )  ] or (  )[  ] */
8541       if (*vr0type == VR_ANTI_RANGE
8542           && vr1type == VR_ANTI_RANGE)
8543         *vr0min = vr1min;
8544       else if (*vr0type == VR_RANGE
8545                && vr1type == VR_RANGE)
8546         *vr0max = vr1max;
8547       else if (*vr0type == VR_RANGE
8548                && vr1type == VR_ANTI_RANGE)
8549         {
8550           if (TREE_CODE (vr1max) == INTEGER_CST)
8551             *vr0min = int_const_binop (PLUS_EXPR, vr1max,
8552                                        build_int_cst (TREE_TYPE (vr1max), 1));
8553           else
8554             *vr0min = vr1max;
8555         }
8556       else if (*vr0type == VR_ANTI_RANGE
8557                && vr1type == VR_RANGE)
8558         {
8559           *vr0type = VR_RANGE;
8560           if (TREE_CODE (*vr0min) == INTEGER_CST)
8561             *vr0max = int_const_binop (MINUS_EXPR, *vr0min,
8562                                        build_int_cst (TREE_TYPE (*vr0min), 1));
8563           else
8564             *vr0max = *vr0min;
8565           *vr0min = vr1min;
8566         }
8567       else
8568         gcc_unreachable ();
8569     }
8570
8571   /* As a fallback simply use { *VRTYPE, *VR0MIN, *VR0MAX } as
8572      result for the intersection.  That's always a conservative
8573      correct estimate.  */
8574
8575   return;
8576 }
8577
8578
8579 /* Intersect the two value-ranges *VR0 and *VR1 and store the result
8580    in *VR0.  This may not be the smallest possible such range.  */
8581
8582 static void
8583 vrp_intersect_ranges_1 (value_range_t *vr0, value_range_t *vr1)
8584 {
8585   value_range_t saved;
8586
8587   /* If either range is VR_VARYING the other one wins.  */
8588   if (vr1->type == VR_VARYING)
8589     return;
8590   if (vr0->type == VR_VARYING)
8591     {
8592       copy_value_range (vr0, vr1);
8593       return;
8594     }
8595
8596   /* When either range is VR_UNDEFINED the resulting range is
8597      VR_UNDEFINED, too.  */
8598   if (vr0->type == VR_UNDEFINED)
8599     return;
8600   if (vr1->type == VR_UNDEFINED)
8601     {
8602       set_value_range_to_undefined (vr0);
8603       return;
8604     }
8605
8606   /* Save the original vr0 so we can return it as conservative intersection
8607      result when our worker turns things to varying.  */
8608   saved = *vr0;
8609   intersect_ranges (&vr0->type, &vr0->min, &vr0->max,
8610                     vr1->type, vr1->min, vr1->max);
8611   /* Make sure to canonicalize the result though as the inversion of a
8612      VR_RANGE can still be a VR_RANGE.  */
8613   set_and_canonicalize_value_range (vr0, vr0->type,
8614                                     vr0->min, vr0->max, vr0->equiv);
8615   /* If that failed, use the saved original VR0.  */
8616   if (vr0->type == VR_VARYING)
8617     {
8618       *vr0 = saved;
8619       return;
8620     }
8621   /* If the result is VR_UNDEFINED there is no need to mess with
8622      the equivalencies.  */
8623   if (vr0->type == VR_UNDEFINED)
8624     return;
8625
8626   /* The resulting set of equivalences for range intersection is the union of
8627      the two sets.  */
8628   if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
8629     bitmap_ior_into (vr0->equiv, vr1->equiv);
8630   else if (vr1->equiv && !vr0->equiv)
8631     bitmap_copy (vr0->equiv, vr1->equiv);
8632 }
8633
8634 static void
8635 vrp_intersect_ranges (value_range_t *vr0, value_range_t *vr1)
8636 {
8637   if (dump_file && (dump_flags & TDF_DETAILS))
8638     {
8639       fprintf (dump_file, "Intersecting\n  ");
8640       dump_value_range (dump_file, vr0);
8641       fprintf (dump_file, "\nand\n  ");
8642       dump_value_range (dump_file, vr1);
8643       fprintf (dump_file, "\n");
8644     }
8645   vrp_intersect_ranges_1 (vr0, vr1);
8646   if (dump_file && (dump_flags & TDF_DETAILS))
8647     {
8648       fprintf (dump_file, "to\n  ");
8649       dump_value_range (dump_file, vr0);
8650       fprintf (dump_file, "\n");
8651     }
8652 }
8653
8654 /* Meet operation for value ranges.  Given two value ranges VR0 and
8655    VR1, store in VR0 a range that contains both VR0 and VR1.  This
8656    may not be the smallest possible such range.  */
8657
8658 static void
8659 vrp_meet_1 (value_range_t *vr0, value_range_t *vr1)
8660 {
8661   value_range_t saved;
8662
8663   if (vr0->type == VR_UNDEFINED)
8664     {
8665       set_value_range (vr0, vr1->type, vr1->min, vr1->max, vr1->equiv);
8666       return;
8667     }
8668
8669   if (vr1->type == VR_UNDEFINED)
8670     {
8671       /* VR0 already has the resulting range.  */
8672       return;
8673     }
8674
8675   if (vr0->type == VR_VARYING)
8676     {
8677       /* Nothing to do.  VR0 already has the resulting range.  */
8678       return;
8679     }
8680
8681   if (vr1->type == VR_VARYING)
8682     {
8683       set_value_range_to_varying (vr0);
8684       return;
8685     }
8686
8687   saved = *vr0;
8688   union_ranges (&vr0->type, &vr0->min, &vr0->max,
8689                 vr1->type, vr1->min, vr1->max);
8690   if (vr0->type == VR_VARYING)
8691     {
8692       /* Failed to find an efficient meet.  Before giving up and setting
8693          the result to VARYING, see if we can at least derive a useful
8694          anti-range.  FIXME, all this nonsense about distinguishing
8695          anti-ranges from ranges is necessary because of the odd
8696          semantics of range_includes_zero_p and friends.  */
8697       if (((saved.type == VR_RANGE
8698             && range_includes_zero_p (saved.min, saved.max) == 0)
8699            || (saved.type == VR_ANTI_RANGE
8700                && range_includes_zero_p (saved.min, saved.max) == 1))
8701           && ((vr1->type == VR_RANGE
8702                && range_includes_zero_p (vr1->min, vr1->max) == 0)
8703               || (vr1->type == VR_ANTI_RANGE
8704                   && range_includes_zero_p (vr1->min, vr1->max) == 1)))
8705         {
8706           set_value_range_to_nonnull (vr0, TREE_TYPE (saved.min));
8707
8708           /* Since this meet operation did not result from the meeting of
8709              two equivalent names, VR0 cannot have any equivalences.  */
8710           if (vr0->equiv)
8711             bitmap_clear (vr0->equiv);
8712           return;
8713         }
8714
8715       set_value_range_to_varying (vr0);
8716       return;
8717     }
8718   set_and_canonicalize_value_range (vr0, vr0->type, vr0->min, vr0->max,
8719                                     vr0->equiv);
8720   if (vr0->type == VR_VARYING)
8721     return;
8722
8723   /* The resulting set of equivalences is always the intersection of
8724      the two sets.  */
8725   if (vr0->equiv && vr1->equiv && vr0->equiv != vr1->equiv)
8726     bitmap_and_into (vr0->equiv, vr1->equiv);
8727   else if (vr0->equiv && !vr1->equiv)
8728     bitmap_clear (vr0->equiv);
8729 }
8730
8731 static void
8732 vrp_meet (value_range_t *vr0, value_range_t *vr1)
8733 {
8734   if (dump_file && (dump_flags & TDF_DETAILS))
8735     {
8736       fprintf (dump_file, "Meeting\n  ");
8737       dump_value_range (dump_file, vr0);
8738       fprintf (dump_file, "\nand\n  ");
8739       dump_value_range (dump_file, vr1);
8740       fprintf (dump_file, "\n");
8741     }
8742   vrp_meet_1 (vr0, vr1);
8743   if (dump_file && (dump_flags & TDF_DETAILS))
8744     {
8745       fprintf (dump_file, "to\n  ");
8746       dump_value_range (dump_file, vr0);
8747       fprintf (dump_file, "\n");
8748     }
8749 }
8750
8751
8752 /* Visit all arguments for PHI node PHI that flow through executable
8753    edges.  If a valid value range can be derived from all the incoming
8754    value ranges, set a new range for the LHS of PHI.  */
8755
8756 static enum ssa_prop_result
8757 vrp_visit_phi_node (gphi *phi)
8758 {
8759   size_t i;
8760   tree lhs = PHI_RESULT (phi);
8761   value_range_t *lhs_vr = get_value_range (lhs);
8762   value_range_t vr_result = VR_INITIALIZER;
8763   bool first = true;
8764   int edges, old_edges;
8765   struct loop *l;
8766
8767   if (dump_file && (dump_flags & TDF_DETAILS))
8768     {
8769       fprintf (dump_file, "\nVisiting PHI node: ");
8770       print_gimple_stmt (dump_file, phi, 0, dump_flags);
8771     }
8772
8773   edges = 0;
8774   for (i = 0; i < gimple_phi_num_args (phi); i++)
8775     {
8776       edge e = gimple_phi_arg_edge (phi, i);
8777
8778       if (dump_file && (dump_flags & TDF_DETAILS))
8779         {
8780           fprintf (dump_file,
8781               "    Argument #%d (%d -> %d %sexecutable)\n",
8782               (int) i, e->src->index, e->dest->index,
8783               (e->flags & EDGE_EXECUTABLE) ? "" : "not ");
8784         }
8785
8786       if (e->flags & EDGE_EXECUTABLE)
8787         {
8788           tree arg = PHI_ARG_DEF (phi, i);
8789           value_range_t vr_arg;
8790
8791           ++edges;
8792
8793           if (TREE_CODE (arg) == SSA_NAME)
8794             {
8795               vr_arg = *(get_value_range (arg));
8796               /* Do not allow equivalences or symbolic ranges to leak in from
8797                  backedges.  That creates invalid equivalencies.
8798                  See PR53465 and PR54767.  */
8799               if (e->flags & EDGE_DFS_BACK)
8800                 {
8801                   if (vr_arg.type == VR_RANGE
8802                       || vr_arg.type == VR_ANTI_RANGE)
8803                     {
8804                       vr_arg.equiv = NULL;
8805                       if (symbolic_range_p (&vr_arg))
8806                         {
8807                           vr_arg.type = VR_VARYING;
8808                           vr_arg.min = NULL_TREE;
8809                           vr_arg.max = NULL_TREE;
8810                         }
8811                     }
8812                 }
8813               else
8814                 {
8815                   /* If the non-backedge arguments range is VR_VARYING then
8816                      we can still try recording a simple equivalence.  */
8817                   if (vr_arg.type == VR_VARYING)
8818                     {
8819                       vr_arg.type = VR_RANGE;
8820                       vr_arg.min = arg;
8821                       vr_arg.max = arg;
8822                       vr_arg.equiv = NULL;
8823                     }
8824                 }
8825             }
8826           else
8827             {
8828               if (TREE_OVERFLOW_P (arg))
8829                 arg = drop_tree_overflow (arg);
8830
8831               vr_arg.type = VR_RANGE;
8832               vr_arg.min = arg;
8833               vr_arg.max = arg;
8834               vr_arg.equiv = NULL;
8835             }
8836
8837           if (dump_file && (dump_flags & TDF_DETAILS))
8838             {
8839               fprintf (dump_file, "\t");
8840               print_generic_expr (dump_file, arg, dump_flags);
8841               fprintf (dump_file, ": ");
8842               dump_value_range (dump_file, &vr_arg);
8843               fprintf (dump_file, "\n");
8844             }
8845
8846           if (first)
8847             copy_value_range (&vr_result, &vr_arg);
8848           else
8849             vrp_meet (&vr_result, &vr_arg);
8850           first = false;
8851
8852           if (vr_result.type == VR_VARYING)
8853             break;
8854         }
8855     }
8856
8857   if (vr_result.type == VR_VARYING)
8858     goto varying;
8859   else if (vr_result.type == VR_UNDEFINED)
8860     goto update_range;
8861
8862   old_edges = vr_phi_edge_counts[SSA_NAME_VERSION (lhs)];
8863   vr_phi_edge_counts[SSA_NAME_VERSION (lhs)] = edges;
8864
8865   /* To prevent infinite iterations in the algorithm, derive ranges
8866      when the new value is slightly bigger or smaller than the
8867      previous one.  We don't do this if we have seen a new executable
8868      edge; this helps us avoid an overflow infinity for conditionals
8869      which are not in a loop.  If the old value-range was VR_UNDEFINED
8870      use the updated range and iterate one more time.  */
8871   if (edges > 0
8872       && gimple_phi_num_args (phi) > 1
8873       && edges == old_edges
8874       && lhs_vr->type != VR_UNDEFINED)
8875     {
8876       /* Compare old and new ranges, fall back to varying if the
8877          values are not comparable.  */
8878       int cmp_min = compare_values (lhs_vr->min, vr_result.min);
8879       if (cmp_min == -2)
8880         goto varying;
8881       int cmp_max = compare_values (lhs_vr->max, vr_result.max);
8882       if (cmp_max == -2)
8883         goto varying;
8884
8885       /* For non VR_RANGE or for pointers fall back to varying if
8886          the range changed.  */
8887       if ((lhs_vr->type != VR_RANGE || vr_result.type != VR_RANGE
8888            || POINTER_TYPE_P (TREE_TYPE (lhs)))
8889           && (cmp_min != 0 || cmp_max != 0))
8890         goto varying;
8891
8892       /* If the new minimum is larger than than the previous one
8893          retain the old value.  If the new minimum value is smaller
8894          than the previous one and not -INF go all the way to -INF + 1.
8895          In the first case, to avoid infinite bouncing between different
8896          minimums, and in the other case to avoid iterating millions of
8897          times to reach -INF.  Going to -INF + 1 also lets the following
8898          iteration compute whether there will be any overflow, at the
8899          expense of one additional iteration.  */
8900       if (cmp_min < 0)
8901         vr_result.min = lhs_vr->min;
8902       else if (cmp_min > 0
8903                && !vrp_val_is_min (vr_result.min))
8904         vr_result.min
8905           = int_const_binop (PLUS_EXPR,
8906                              vrp_val_min (TREE_TYPE (vr_result.min)),
8907                              build_int_cst (TREE_TYPE (vr_result.min), 1));
8908
8909       /* Similarly for the maximum value.  */
8910       if (cmp_max > 0)
8911         vr_result.max = lhs_vr->max;
8912       else if (cmp_max < 0
8913                && !vrp_val_is_max (vr_result.max))
8914         vr_result.max
8915           = int_const_binop (MINUS_EXPR,
8916                              vrp_val_max (TREE_TYPE (vr_result.min)),
8917                              build_int_cst (TREE_TYPE (vr_result.min), 1));
8918
8919       /* If we dropped either bound to +-INF then if this is a loop
8920          PHI node SCEV may known more about its value-range.  */
8921       if ((cmp_min > 0 || cmp_min < 0
8922            || cmp_max < 0 || cmp_max > 0)
8923           && (l = loop_containing_stmt (phi))
8924           && l->header == gimple_bb (phi))
8925         adjust_range_with_scev (&vr_result, l, phi, lhs);
8926
8927       /* If we will end up with a (-INF, +INF) range, set it to
8928          VARYING.  Same if the previous max value was invalid for
8929          the type and we end up with vr_result.min > vr_result.max.  */
8930       if ((vrp_val_is_max (vr_result.max)
8931            && vrp_val_is_min (vr_result.min))
8932           || compare_values (vr_result.min,
8933                              vr_result.max) > 0)
8934         goto varying;
8935     }
8936
8937   /* If the new range is different than the previous value, keep
8938      iterating.  */
8939 update_range:
8940   if (update_value_range (lhs, &vr_result))
8941     {
8942       if (dump_file && (dump_flags & TDF_DETAILS))
8943         {
8944           fprintf (dump_file, "Found new range for ");
8945           print_generic_expr (dump_file, lhs, 0);
8946           fprintf (dump_file, ": ");
8947           dump_value_range (dump_file, &vr_result);
8948           fprintf (dump_file, "\n");
8949         }
8950
8951       return SSA_PROP_INTERESTING;
8952     }
8953
8954   /* Nothing changed, don't add outgoing edges.  */
8955   return SSA_PROP_NOT_INTERESTING;
8956
8957   /* No match found.  Set the LHS to VARYING.  */
8958 varying:
8959   set_value_range_to_varying (lhs_vr);
8960   return SSA_PROP_VARYING;
8961 }
8962
8963 /* Simplify boolean operations if the source is known
8964    to be already a boolean.  */
8965 static bool
8966 simplify_truth_ops_using_ranges (gimple_stmt_iterator *gsi, gimple stmt)
8967 {
8968   enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
8969   tree lhs, op0, op1;
8970   bool need_conversion;
8971
8972   /* We handle only !=/== case here.  */
8973   gcc_assert (rhs_code == EQ_EXPR || rhs_code == NE_EXPR);
8974
8975   op0 = gimple_assign_rhs1 (stmt);
8976   if (!op_with_boolean_value_range_p (op0))
8977     return false;
8978
8979   op1 = gimple_assign_rhs2 (stmt);
8980   if (!op_with_boolean_value_range_p (op1))
8981     return false;
8982
8983   /* Reduce number of cases to handle to NE_EXPR.  As there is no
8984      BIT_XNOR_EXPR we cannot replace A == B with a single statement.  */
8985   if (rhs_code == EQ_EXPR)
8986     {
8987       if (TREE_CODE (op1) == INTEGER_CST)
8988         op1 = int_const_binop (BIT_XOR_EXPR, op1,
8989                                build_int_cst (TREE_TYPE (op1), 1));
8990       else
8991         return false;
8992     }
8993
8994   lhs = gimple_assign_lhs (stmt);
8995   need_conversion
8996     = !useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (op0));
8997
8998   /* Make sure to not sign-extend a 1-bit 1 when converting the result.  */
8999   if (need_conversion
9000       && !TYPE_UNSIGNED (TREE_TYPE (op0))
9001       && TYPE_PRECISION (TREE_TYPE (op0)) == 1
9002       && TYPE_PRECISION (TREE_TYPE (lhs)) > 1)
9003     return false;
9004
9005   /* For A != 0 we can substitute A itself.  */
9006   if (integer_zerop (op1))
9007     gimple_assign_set_rhs_with_ops (gsi,
9008                                     need_conversion
9009                                     ? NOP_EXPR : TREE_CODE (op0), op0);
9010   /* For A != B we substitute A ^ B.  Either with conversion.  */
9011   else if (need_conversion)
9012     {
9013       tree tem = make_ssa_name (TREE_TYPE (op0));
9014       gassign *newop
9015         = gimple_build_assign (tem, BIT_XOR_EXPR, op0, op1);
9016       gsi_insert_before (gsi, newop, GSI_SAME_STMT);
9017       gimple_assign_set_rhs_with_ops (gsi, NOP_EXPR, tem);
9018     }
9019   /* Or without.  */
9020   else
9021     gimple_assign_set_rhs_with_ops (gsi, BIT_XOR_EXPR, op0, op1);
9022   update_stmt (gsi_stmt (*gsi));
9023
9024   return true;
9025 }
9026
9027 /* Simplify a division or modulo operator to a right shift or
9028    bitwise and if the first operand is unsigned or is greater
9029    than zero and the second operand is an exact power of two.
9030    For TRUNC_MOD_EXPR op0 % op1 with constant op1, optimize it
9031    into just op0 if op0's range is known to be a subset of
9032    [-op1 + 1, op1 - 1] for signed and [0, op1 - 1] for unsigned
9033    modulo.  */
9034
9035 static bool
9036 simplify_div_or_mod_using_ranges (gimple stmt)
9037 {
9038   enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
9039   tree val = NULL;
9040   tree op0 = gimple_assign_rhs1 (stmt);
9041   tree op1 = gimple_assign_rhs2 (stmt);
9042   value_range_t *vr = get_value_range (op0);
9043
9044   if (rhs_code == TRUNC_MOD_EXPR
9045       && TREE_CODE (op1) == INTEGER_CST
9046       && tree_int_cst_sgn (op1) == 1
9047       && range_int_cst_p (vr)
9048       && tree_int_cst_lt (vr->max, op1))
9049     {
9050       if (TYPE_UNSIGNED (TREE_TYPE (op0))
9051           || tree_int_cst_sgn (vr->min) >= 0
9052           || tree_int_cst_lt (fold_unary (NEGATE_EXPR, TREE_TYPE (op1), op1),
9053                               vr->min))
9054         {
9055           /* If op0 already has the range op0 % op1 has,
9056              then TRUNC_MOD_EXPR won't change anything.  */
9057           gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
9058           gimple_assign_set_rhs_from_tree (&gsi, op0);
9059           update_stmt (stmt);
9060           return true;
9061         }
9062     }
9063
9064   if (!integer_pow2p (op1))
9065     return false;
9066
9067   if (TYPE_UNSIGNED (TREE_TYPE (op0)))
9068     {
9069       val = integer_one_node;
9070     }
9071   else
9072     {
9073       bool sop = false;
9074
9075       val = compare_range_with_value (GE_EXPR, vr, integer_zero_node, &sop);
9076
9077       if (val
9078           && sop
9079           && integer_onep (val)
9080           && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
9081         {
9082           location_t location;
9083
9084           if (!gimple_has_location (stmt))
9085             location = input_location;
9086           else
9087             location = gimple_location (stmt);
9088           warning_at (location, OPT_Wstrict_overflow,
9089                       "assuming signed overflow does not occur when "
9090                       "simplifying %</%> or %<%%%> to %<>>%> or %<&%>");
9091         }
9092     }
9093
9094   if (val && integer_onep (val))
9095     {
9096       tree t;
9097
9098       if (rhs_code == TRUNC_DIV_EXPR)
9099         {
9100           t = build_int_cst (integer_type_node, tree_log2 (op1));
9101           gimple_assign_set_rhs_code (stmt, RSHIFT_EXPR);
9102           gimple_assign_set_rhs1 (stmt, op0);
9103           gimple_assign_set_rhs2 (stmt, t);
9104         }
9105       else
9106         {
9107           t = build_int_cst (TREE_TYPE (op1), 1);
9108           t = int_const_binop (MINUS_EXPR, op1, t);
9109           t = fold_convert (TREE_TYPE (op0), t);
9110
9111           gimple_assign_set_rhs_code (stmt, BIT_AND_EXPR);
9112           gimple_assign_set_rhs1 (stmt, op0);
9113           gimple_assign_set_rhs2 (stmt, t);
9114         }
9115
9116       update_stmt (stmt);
9117       return true;
9118     }
9119
9120   return false;
9121 }
9122
9123 /* If the operand to an ABS_EXPR is >= 0, then eliminate the
9124    ABS_EXPR.  If the operand is <= 0, then simplify the
9125    ABS_EXPR into a NEGATE_EXPR.  */
9126
9127 static bool
9128 simplify_abs_using_ranges (gimple stmt)
9129 {
9130   tree val = NULL;
9131   tree op = gimple_assign_rhs1 (stmt);
9132   tree type = TREE_TYPE (op);
9133   value_range_t *vr = get_value_range (op);
9134
9135   if (TYPE_UNSIGNED (type))
9136     {
9137       val = integer_zero_node;
9138     }
9139   else if (vr)
9140     {
9141       bool sop = false;
9142
9143       val = compare_range_with_value (LE_EXPR, vr, integer_zero_node, &sop);
9144       if (!val)
9145         {
9146           sop = false;
9147           val = compare_range_with_value (GE_EXPR, vr, integer_zero_node,
9148                                           &sop);
9149
9150           if (val)
9151             {
9152               if (integer_zerop (val))
9153                 val = integer_one_node;
9154               else if (integer_onep (val))
9155                 val = integer_zero_node;
9156             }
9157         }
9158
9159       if (val
9160           && (integer_onep (val) || integer_zerop (val)))
9161         {
9162           if (sop && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
9163             {
9164               location_t location;
9165
9166               if (!gimple_has_location (stmt))
9167                 location = input_location;
9168               else
9169                 location = gimple_location (stmt);
9170               warning_at (location, OPT_Wstrict_overflow,
9171                           "assuming signed overflow does not occur when "
9172                           "simplifying %<abs (X)%> to %<X%> or %<-X%>");
9173             }
9174
9175           gimple_assign_set_rhs1 (stmt, op);
9176           if (integer_onep (val))
9177             gimple_assign_set_rhs_code (stmt, NEGATE_EXPR);
9178           else
9179             gimple_assign_set_rhs_code (stmt, SSA_NAME);
9180           update_stmt (stmt);
9181           return true;
9182         }
9183     }
9184
9185   return false;
9186 }
9187
9188 /* Optimize away redundant BIT_AND_EXPR and BIT_IOR_EXPR.
9189    If all the bits that are being cleared by & are already
9190    known to be zero from VR, or all the bits that are being
9191    set by | are already known to be one from VR, the bit
9192    operation is redundant.  */
9193
9194 static bool
9195 simplify_bit_ops_using_ranges (gimple_stmt_iterator *gsi, gimple stmt)
9196 {
9197   tree op0 = gimple_assign_rhs1 (stmt);
9198   tree op1 = gimple_assign_rhs2 (stmt);
9199   tree op = NULL_TREE;
9200   value_range_t vr0 = VR_INITIALIZER;
9201   value_range_t vr1 = VR_INITIALIZER;
9202   wide_int may_be_nonzero0, may_be_nonzero1;
9203   wide_int must_be_nonzero0, must_be_nonzero1;
9204   wide_int mask;
9205
9206   if (TREE_CODE (op0) == SSA_NAME)
9207     vr0 = *(get_value_range (op0));
9208   else if (is_gimple_min_invariant (op0))
9209     set_value_range_to_value (&vr0, op0, NULL);
9210   else
9211     return false;
9212
9213   if (TREE_CODE (op1) == SSA_NAME)
9214     vr1 = *(get_value_range (op1));
9215   else if (is_gimple_min_invariant (op1))
9216     set_value_range_to_value (&vr1, op1, NULL);
9217   else
9218     return false;
9219
9220   if (!zero_nonzero_bits_from_vr (TREE_TYPE (op0), &vr0, &may_be_nonzero0,
9221                                   &must_be_nonzero0))
9222     return false;
9223   if (!zero_nonzero_bits_from_vr (TREE_TYPE (op1), &vr1, &may_be_nonzero1,
9224                                   &must_be_nonzero1))
9225     return false;
9226
9227   switch (gimple_assign_rhs_code (stmt))
9228     {
9229     case BIT_AND_EXPR:
9230       mask = may_be_nonzero0.and_not (must_be_nonzero1);
9231       if (mask == 0)
9232         {
9233           op = op0;
9234           break;
9235         }
9236       mask = may_be_nonzero1.and_not (must_be_nonzero0);
9237       if (mask == 0)
9238         {
9239           op = op1;
9240           break;
9241         }
9242       break;
9243     case BIT_IOR_EXPR:
9244       mask = may_be_nonzero0.and_not (must_be_nonzero1);
9245       if (mask == 0)
9246         {
9247           op = op1;
9248           break;
9249         }
9250       mask = may_be_nonzero1.and_not (must_be_nonzero0);
9251       if (mask == 0)
9252         {
9253           op = op0;
9254           break;
9255         }
9256       break;
9257     default:
9258       gcc_unreachable ();
9259     }
9260
9261   if (op == NULL_TREE)
9262     return false;
9263
9264   gimple_assign_set_rhs_with_ops (gsi, TREE_CODE (op), op);
9265   update_stmt (gsi_stmt (*gsi));
9266   return true;
9267 }
9268
9269 /* We are comparing trees OP0 and OP1 using COND_CODE.  OP0 has
9270    a known value range VR.
9271
9272    If there is one and only one value which will satisfy the
9273    conditional, then return that value.  Else return NULL.
9274
9275    If signed overflow must be undefined for the value to satisfy
9276    the conditional, then set *STRICT_OVERFLOW_P to true.  */
9277
9278 static tree
9279 test_for_singularity (enum tree_code cond_code, tree op0,
9280                       tree op1, value_range_t *vr,
9281                       bool *strict_overflow_p)
9282 {
9283   tree min = NULL;
9284   tree max = NULL;
9285
9286   /* Extract minimum/maximum values which satisfy the
9287      the conditional as it was written.  */
9288   if (cond_code == LE_EXPR || cond_code == LT_EXPR)
9289     {
9290       /* This should not be negative infinity; there is no overflow
9291          here.  */
9292       min = TYPE_MIN_VALUE (TREE_TYPE (op0));
9293
9294       max = op1;
9295       if (cond_code == LT_EXPR && !is_overflow_infinity (max))
9296         {
9297           tree one = build_int_cst (TREE_TYPE (op0), 1);
9298           max = fold_build2 (MINUS_EXPR, TREE_TYPE (op0), max, one);
9299           if (EXPR_P (max))
9300             TREE_NO_WARNING (max) = 1;
9301         }
9302     }
9303   else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
9304     {
9305       /* This should not be positive infinity; there is no overflow
9306          here.  */
9307       max = TYPE_MAX_VALUE (TREE_TYPE (op0));
9308
9309       min = op1;
9310       if (cond_code == GT_EXPR && !is_overflow_infinity (min))
9311         {
9312           tree one = build_int_cst (TREE_TYPE (op0), 1);
9313           min = fold_build2 (PLUS_EXPR, TREE_TYPE (op0), min, one);
9314           if (EXPR_P (min))
9315             TREE_NO_WARNING (min) = 1;
9316         }
9317     }
9318
9319   /* Now refine the minimum and maximum values using any
9320      value range information we have for op0.  */
9321   if (min && max)
9322     {
9323       if (compare_values (vr->min, min) == 1)
9324         min = vr->min;
9325       if (compare_values (vr->max, max) == -1)
9326         max = vr->max;
9327
9328       /* If the new min/max values have converged to a single value,
9329          then there is only one value which can satisfy the condition,
9330          return that value.  */
9331       if (operand_equal_p (min, max, 0) && is_gimple_min_invariant (min))
9332         {
9333           if ((cond_code == LE_EXPR || cond_code == LT_EXPR)
9334               && is_overflow_infinity (vr->max))
9335             *strict_overflow_p = true;
9336           if ((cond_code == GE_EXPR || cond_code == GT_EXPR)
9337               && is_overflow_infinity (vr->min))
9338             *strict_overflow_p = true;
9339
9340           return min;
9341         }
9342     }
9343   return NULL;
9344 }
9345
9346 /* Return whether the value range *VR fits in an integer type specified
9347    by PRECISION and UNSIGNED_P.  */
9348
9349 static bool
9350 range_fits_type_p (value_range_t *vr, unsigned dest_precision, signop dest_sgn)
9351 {
9352   tree src_type;
9353   unsigned src_precision;
9354   widest_int tem;
9355   signop src_sgn;
9356
9357   /* We can only handle integral and pointer types.  */
9358   src_type = TREE_TYPE (vr->min);
9359   if (!INTEGRAL_TYPE_P (src_type)
9360       && !POINTER_TYPE_P (src_type))
9361     return false;
9362
9363   /* An extension is fine unless VR is SIGNED and dest_sgn is UNSIGNED,
9364      and so is an identity transform.  */
9365   src_precision = TYPE_PRECISION (TREE_TYPE (vr->min));
9366   src_sgn = TYPE_SIGN (src_type);
9367   if ((src_precision < dest_precision
9368        && !(dest_sgn == UNSIGNED && src_sgn == SIGNED))
9369       || (src_precision == dest_precision && src_sgn == dest_sgn))
9370     return true;
9371
9372   /* Now we can only handle ranges with constant bounds.  */
9373   if (vr->type != VR_RANGE
9374       || TREE_CODE (vr->min) != INTEGER_CST
9375       || TREE_CODE (vr->max) != INTEGER_CST)
9376     return false;
9377
9378   /* For sign changes, the MSB of the wide_int has to be clear.
9379      An unsigned value with its MSB set cannot be represented by
9380      a signed wide_int, while a negative value cannot be represented
9381      by an unsigned wide_int.  */
9382   if (src_sgn != dest_sgn
9383       && (wi::lts_p (vr->min, 0) || wi::lts_p (vr->max, 0)))
9384     return false;
9385
9386   /* Then we can perform the conversion on both ends and compare
9387      the result for equality.  */
9388   tem = wi::ext (wi::to_widest (vr->min), dest_precision, dest_sgn);
9389   if (tem != wi::to_widest (vr->min))
9390     return false;
9391   tem = wi::ext (wi::to_widest (vr->max), dest_precision, dest_sgn);
9392   if (tem != wi::to_widest (vr->max))
9393     return false;
9394
9395   return true;
9396 }
9397
9398 /* Simplify a conditional using a relational operator to an equality
9399    test if the range information indicates only one value can satisfy
9400    the original conditional.  */
9401
9402 static bool
9403 simplify_cond_using_ranges (gcond *stmt)
9404 {
9405   tree op0 = gimple_cond_lhs (stmt);
9406   tree op1 = gimple_cond_rhs (stmt);
9407   enum tree_code cond_code = gimple_cond_code (stmt);
9408
9409   if (cond_code != NE_EXPR
9410       && cond_code != EQ_EXPR
9411       && TREE_CODE (op0) == SSA_NAME
9412       && INTEGRAL_TYPE_P (TREE_TYPE (op0))
9413       && is_gimple_min_invariant (op1))
9414     {
9415       value_range_t *vr = get_value_range (op0);
9416
9417       /* If we have range information for OP0, then we might be
9418          able to simplify this conditional. */
9419       if (vr->type == VR_RANGE)
9420         {
9421           enum warn_strict_overflow_code wc = WARN_STRICT_OVERFLOW_COMPARISON;
9422           bool sop = false;
9423           tree new_tree = test_for_singularity (cond_code, op0, op1, vr, &sop);
9424
9425           if (new_tree
9426               && (!sop || TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (op0))))
9427             {
9428               if (dump_file)
9429                 {
9430                   fprintf (dump_file, "Simplified relational ");
9431                   print_gimple_stmt (dump_file, stmt, 0, 0);
9432                   fprintf (dump_file, " into ");
9433                 }
9434
9435               gimple_cond_set_code (stmt, EQ_EXPR);
9436               gimple_cond_set_lhs (stmt, op0);
9437               gimple_cond_set_rhs (stmt, new_tree);
9438
9439               update_stmt (stmt);
9440
9441               if (dump_file)
9442                 {
9443                   print_gimple_stmt (dump_file, stmt, 0, 0);
9444                   fprintf (dump_file, "\n");
9445                 }
9446
9447               if (sop && issue_strict_overflow_warning (wc))
9448                 {
9449                   location_t location = input_location;
9450                   if (gimple_has_location (stmt))
9451                     location = gimple_location (stmt);
9452
9453                   warning_at (location, OPT_Wstrict_overflow,
9454                               "assuming signed overflow does not occur when "
9455                               "simplifying conditional");
9456                 }
9457
9458               return true;
9459             }
9460
9461           /* Try again after inverting the condition.  We only deal
9462              with integral types here, so no need to worry about
9463              issues with inverting FP comparisons.  */
9464           sop = false;
9465           new_tree = test_for_singularity
9466                        (invert_tree_comparison (cond_code, false),
9467                         op0, op1, vr, &sop);
9468
9469           if (new_tree
9470               && (!sop || TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (op0))))
9471             {
9472               if (dump_file)
9473                 {
9474                   fprintf (dump_file, "Simplified relational ");
9475                   print_gimple_stmt (dump_file, stmt, 0, 0);
9476                   fprintf (dump_file, " into ");
9477                 }
9478
9479               gimple_cond_set_code (stmt, NE_EXPR);
9480               gimple_cond_set_lhs (stmt, op0);
9481               gimple_cond_set_rhs (stmt, new_tree);
9482
9483               update_stmt (stmt);
9484
9485               if (dump_file)
9486                 {
9487                   print_gimple_stmt (dump_file, stmt, 0, 0);
9488                   fprintf (dump_file, "\n");
9489                 }
9490
9491               if (sop && issue_strict_overflow_warning (wc))
9492                 {
9493                   location_t location = input_location;
9494                   if (gimple_has_location (stmt))
9495                     location = gimple_location (stmt);
9496
9497                   warning_at (location, OPT_Wstrict_overflow,
9498                               "assuming signed overflow does not occur when "
9499                               "simplifying conditional");
9500                 }
9501
9502               return true;
9503             }
9504         }
9505     }
9506
9507   /* If we have a comparison of an SSA_NAME (OP0) against a constant,
9508      see if OP0 was set by a type conversion where the source of
9509      the conversion is another SSA_NAME with a range that fits
9510      into the range of OP0's type.
9511
9512      If so, the conversion is redundant as the earlier SSA_NAME can be
9513      used for the comparison directly if we just massage the constant in the
9514      comparison.  */
9515   if (TREE_CODE (op0) == SSA_NAME
9516       && TREE_CODE (op1) == INTEGER_CST)
9517     {
9518       gimple def_stmt = SSA_NAME_DEF_STMT (op0);
9519       tree innerop;
9520
9521       if (!is_gimple_assign (def_stmt)
9522           || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)))
9523         return false;
9524
9525       innerop = gimple_assign_rhs1 (def_stmt);
9526
9527       if (TREE_CODE (innerop) == SSA_NAME
9528           && !POINTER_TYPE_P (TREE_TYPE (innerop)))
9529         {
9530           value_range_t *vr = get_value_range (innerop);
9531
9532           if (range_int_cst_p (vr)
9533               && range_fits_type_p (vr,
9534                                     TYPE_PRECISION (TREE_TYPE (op0)),
9535                                     TYPE_SIGN (TREE_TYPE (op0)))
9536               && int_fits_type_p (op1, TREE_TYPE (innerop))
9537               /* The range must not have overflowed, or if it did overflow
9538                  we must not be wrapping/trapping overflow and optimizing
9539                  with strict overflow semantics.  */
9540               && ((!is_negative_overflow_infinity (vr->min)
9541                    && !is_positive_overflow_infinity (vr->max))
9542                   || TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (innerop))))
9543             {
9544               /* If the range overflowed and the user has asked for warnings
9545                  when strict overflow semantics were used to optimize code,
9546                  issue an appropriate warning.  */
9547               if (cond_code != EQ_EXPR && cond_code != NE_EXPR
9548                   && (is_negative_overflow_infinity (vr->min)
9549                       || is_positive_overflow_infinity (vr->max))
9550                   && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_CONDITIONAL))
9551                 {
9552                   location_t location;
9553
9554                   if (!gimple_has_location (stmt))
9555                     location = input_location;
9556                   else
9557                     location = gimple_location (stmt);
9558                   warning_at (location, OPT_Wstrict_overflow,
9559                       "assuming signed overflow does not occur when "
9560                       "simplifying conditional");
9561                 }
9562
9563               tree newconst = fold_convert (TREE_TYPE (innerop), op1);
9564               gimple_cond_set_lhs (stmt, innerop);
9565               gimple_cond_set_rhs (stmt, newconst);
9566               return true;
9567             }
9568         }
9569     }
9570
9571   return false;
9572 }
9573
9574 /* Simplify a switch statement using the value range of the switch
9575    argument.  */
9576
9577 static bool
9578 simplify_switch_using_ranges (gswitch *stmt)
9579 {
9580   tree op = gimple_switch_index (stmt);
9581   value_range_t *vr;
9582   bool take_default;
9583   edge e;
9584   edge_iterator ei;
9585   size_t i = 0, j = 0, n, n2;
9586   tree vec2;
9587   switch_update su;
9588   size_t k = 1, l = 0;
9589
9590   if (TREE_CODE (op) == SSA_NAME)
9591     {
9592       vr = get_value_range (op);
9593
9594       /* We can only handle integer ranges.  */
9595       if ((vr->type != VR_RANGE
9596            && vr->type != VR_ANTI_RANGE)
9597           || symbolic_range_p (vr))
9598         return false;
9599
9600       /* Find case label for min/max of the value range.  */
9601       take_default = !find_case_label_ranges (stmt, vr, &i, &j, &k, &l);
9602     }
9603   else if (TREE_CODE (op) == INTEGER_CST)
9604     {
9605       take_default = !find_case_label_index (stmt, 1, op, &i);
9606       if (take_default)
9607         {
9608           i = 1;
9609           j = 0;
9610         }
9611       else
9612         {
9613           j = i;
9614         }
9615     }
9616   else
9617     return false;
9618
9619   n = gimple_switch_num_labels (stmt);
9620
9621   /* Bail out if this is just all edges taken.  */
9622   if (i == 1
9623       && j == n - 1
9624       && take_default)
9625     return false;
9626
9627   /* Build a new vector of taken case labels.  */
9628   vec2 = make_tree_vec (j - i + 1 + l - k + 1 + (int)take_default);
9629   n2 = 0;
9630
9631   /* Add the default edge, if necessary.  */
9632   if (take_default)
9633     TREE_VEC_ELT (vec2, n2++) = gimple_switch_default_label (stmt);
9634
9635   for (; i <= j; ++i, ++n2)
9636     TREE_VEC_ELT (vec2, n2) = gimple_switch_label (stmt, i);
9637
9638   for (; k <= l; ++k, ++n2)
9639     TREE_VEC_ELT (vec2, n2) = gimple_switch_label (stmt, k);
9640
9641   /* Mark needed edges.  */
9642   for (i = 0; i < n2; ++i)
9643     {
9644       e = find_edge (gimple_bb (stmt),
9645                      label_to_block (CASE_LABEL (TREE_VEC_ELT (vec2, i))));
9646       e->aux = (void *)-1;
9647     }
9648
9649   /* Queue not needed edges for later removal.  */
9650   FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
9651     {
9652       if (e->aux == (void *)-1)
9653         {
9654           e->aux = NULL;
9655           continue;
9656         }
9657
9658       if (dump_file && (dump_flags & TDF_DETAILS))
9659         {
9660           fprintf (dump_file, "removing unreachable case label\n");
9661         }
9662       to_remove_edges.safe_push (e);
9663       e->flags &= ~EDGE_EXECUTABLE;
9664     }
9665
9666   /* And queue an update for the stmt.  */
9667   su.stmt = stmt;
9668   su.vec = vec2;
9669   to_update_switch_stmts.safe_push (su);
9670   return false;
9671 }
9672
9673 /* Simplify an integral conversion from an SSA name in STMT.  */
9674
9675 static bool
9676 simplify_conversion_using_ranges (gimple stmt)
9677 {
9678   tree innerop, middleop, finaltype;
9679   gimple def_stmt;
9680   value_range_t *innervr;
9681   signop inner_sgn, middle_sgn, final_sgn;
9682   unsigned inner_prec, middle_prec, final_prec;
9683   widest_int innermin, innermed, innermax, middlemin, middlemed, middlemax;
9684
9685   finaltype = TREE_TYPE (gimple_assign_lhs (stmt));
9686   if (!INTEGRAL_TYPE_P (finaltype))
9687     return false;
9688   middleop = gimple_assign_rhs1 (stmt);
9689   def_stmt = SSA_NAME_DEF_STMT (middleop);
9690   if (!is_gimple_assign (def_stmt)
9691       || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)))
9692     return false;
9693   innerop = gimple_assign_rhs1 (def_stmt);
9694   if (TREE_CODE (innerop) != SSA_NAME
9695       || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (innerop))
9696     return false;
9697
9698   /* Get the value-range of the inner operand.  */
9699   innervr = get_value_range (innerop);
9700   if (innervr->type != VR_RANGE
9701       || TREE_CODE (innervr->min) != INTEGER_CST
9702       || TREE_CODE (innervr->max) != INTEGER_CST)
9703     return false;
9704
9705   /* Simulate the conversion chain to check if the result is equal if
9706      the middle conversion is removed.  */
9707   innermin = wi::to_widest (innervr->min);
9708   innermax = wi::to_widest (innervr->max);
9709
9710   inner_prec = TYPE_PRECISION (TREE_TYPE (innerop));
9711   middle_prec = TYPE_PRECISION (TREE_TYPE (middleop));
9712   final_prec = TYPE_PRECISION (finaltype);
9713
9714   /* If the first conversion is not injective, the second must not
9715      be widening.  */
9716   if (wi::gtu_p (innermax - innermin,
9717                  wi::mask <widest_int> (middle_prec, false))
9718       && middle_prec < final_prec)
9719     return false;
9720   /* We also want a medium value so that we can track the effect that
9721      narrowing conversions with sign change have.  */
9722   inner_sgn = TYPE_SIGN (TREE_TYPE (innerop));
9723   if (inner_sgn == UNSIGNED)
9724     innermed = wi::shifted_mask <widest_int> (1, inner_prec - 1, false);
9725   else
9726     innermed = 0;
9727   if (wi::cmp (innermin, innermed, inner_sgn) >= 0
9728       || wi::cmp (innermed, innermax, inner_sgn) >= 0)
9729     innermed = innermin;
9730
9731   middle_sgn = TYPE_SIGN (TREE_TYPE (middleop));
9732   middlemin = wi::ext (innermin, middle_prec, middle_sgn);
9733   middlemed = wi::ext (innermed, middle_prec, middle_sgn);
9734   middlemax = wi::ext (innermax, middle_prec, middle_sgn);
9735
9736   /* Require that the final conversion applied to both the original
9737      and the intermediate range produces the same result.  */
9738   final_sgn = TYPE_SIGN (finaltype);
9739   if (wi::ext (middlemin, final_prec, final_sgn)
9740          != wi::ext (innermin, final_prec, final_sgn)
9741       || wi::ext (middlemed, final_prec, final_sgn)
9742          != wi::ext (innermed, final_prec, final_sgn)
9743       || wi::ext (middlemax, final_prec, final_sgn)
9744          != wi::ext (innermax, final_prec, final_sgn))
9745     return false;
9746
9747   gimple_assign_set_rhs1 (stmt, innerop);
9748   update_stmt (stmt);
9749   return true;
9750 }
9751
9752 /* Simplify a conversion from integral SSA name to float in STMT.  */
9753
9754 static bool
9755 simplify_float_conversion_using_ranges (gimple_stmt_iterator *gsi, gimple stmt)
9756 {
9757   tree rhs1 = gimple_assign_rhs1 (stmt);
9758   value_range_t *vr = get_value_range (rhs1);
9759   machine_mode fltmode = TYPE_MODE (TREE_TYPE (gimple_assign_lhs (stmt)));
9760   machine_mode mode;
9761   tree tem;
9762   gassign *conv;
9763
9764   /* We can only handle constant ranges.  */
9765   if (vr->type != VR_RANGE
9766       || TREE_CODE (vr->min) != INTEGER_CST
9767       || TREE_CODE (vr->max) != INTEGER_CST)
9768     return false;
9769
9770   /* First check if we can use a signed type in place of an unsigned.  */
9771   if (TYPE_UNSIGNED (TREE_TYPE (rhs1))
9772       && (can_float_p (fltmode, TYPE_MODE (TREE_TYPE (rhs1)), 0)
9773           != CODE_FOR_nothing)
9774       && range_fits_type_p (vr, TYPE_PRECISION (TREE_TYPE (rhs1)), SIGNED))
9775     mode = TYPE_MODE (TREE_TYPE (rhs1));
9776   /* If we can do the conversion in the current input mode do nothing.  */
9777   else if (can_float_p (fltmode, TYPE_MODE (TREE_TYPE (rhs1)),
9778                         TYPE_UNSIGNED (TREE_TYPE (rhs1))) != CODE_FOR_nothing)
9779     return false;
9780   /* Otherwise search for a mode we can use, starting from the narrowest
9781      integer mode available.  */
9782   else
9783     {
9784       mode = GET_CLASS_NARROWEST_MODE (MODE_INT);
9785       do
9786         {
9787           /* If we cannot do a signed conversion to float from mode
9788              or if the value-range does not fit in the signed type
9789              try with a wider mode.  */
9790           if (can_float_p (fltmode, mode, 0) != CODE_FOR_nothing
9791               && range_fits_type_p (vr, GET_MODE_PRECISION (mode), SIGNED))
9792             break;
9793
9794           mode = GET_MODE_WIDER_MODE (mode);
9795           /* But do not widen the input.  Instead leave that to the
9796              optabs expansion code.  */
9797           if (GET_MODE_PRECISION (mode) > TYPE_PRECISION (TREE_TYPE (rhs1)))
9798             return false;
9799         }
9800       while (mode != VOIDmode);
9801       if (mode == VOIDmode)
9802         return false;
9803     }
9804
9805   /* It works, insert a truncation or sign-change before the
9806      float conversion.  */
9807   tem = make_ssa_name (build_nonstandard_integer_type
9808                           (GET_MODE_PRECISION (mode), 0));
9809   conv = gimple_build_assign (tem, NOP_EXPR, rhs1);
9810   gsi_insert_before (gsi, conv, GSI_SAME_STMT);
9811   gimple_assign_set_rhs1 (stmt, tem);
9812   update_stmt (stmt);
9813
9814   return true;
9815 }
9816
9817 /* Simplify an internal fn call using ranges if possible.  */
9818
9819 static bool
9820 simplify_internal_call_using_ranges (gimple_stmt_iterator *gsi, gimple stmt)
9821 {
9822   enum tree_code subcode;
9823   bool is_ubsan = false;
9824   bool ovf = false;
9825   switch (gimple_call_internal_fn (stmt))
9826     {
9827     case IFN_UBSAN_CHECK_ADD:
9828       subcode = PLUS_EXPR;
9829       is_ubsan = true;
9830       break;
9831     case IFN_UBSAN_CHECK_SUB:
9832       subcode = MINUS_EXPR;
9833       is_ubsan = true;
9834       break;
9835     case IFN_UBSAN_CHECK_MUL:
9836       subcode = MULT_EXPR;
9837       is_ubsan = true;
9838       break;
9839     case IFN_ADD_OVERFLOW:
9840       subcode = PLUS_EXPR;
9841       break;
9842     case IFN_SUB_OVERFLOW:
9843       subcode = MINUS_EXPR;
9844       break;
9845     case IFN_MUL_OVERFLOW:
9846       subcode = MULT_EXPR;
9847       break;
9848     default:
9849       return false;
9850     }
9851
9852   tree op0 = gimple_call_arg (stmt, 0);
9853   tree op1 = gimple_call_arg (stmt, 1);
9854   tree type;
9855   if (is_ubsan)
9856     type = TREE_TYPE (op0);
9857   else if (gimple_call_lhs (stmt) == NULL_TREE)
9858     return false;
9859   else
9860     type = TREE_TYPE (TREE_TYPE (gimple_call_lhs (stmt)));
9861   if (!check_for_binary_op_overflow (subcode, type, op0, op1, &ovf)
9862       || (is_ubsan && ovf))
9863     return false;
9864
9865   gimple g;
9866   location_t loc = gimple_location (stmt);
9867   if (is_ubsan)
9868     g = gimple_build_assign (gimple_call_lhs (stmt), subcode, op0, op1);
9869   else
9870     {
9871       int prec = TYPE_PRECISION (type);
9872       tree utype = type;
9873       if (ovf
9874           || !useless_type_conversion_p (type, TREE_TYPE (op0))
9875           || !useless_type_conversion_p (type, TREE_TYPE (op1)))
9876         utype = build_nonstandard_integer_type (prec, 1);
9877       if (TREE_CODE (op0) == INTEGER_CST)
9878         op0 = fold_convert (utype, op0);
9879       else if (!useless_type_conversion_p (utype, TREE_TYPE (op0)))
9880         {
9881           g = gimple_build_assign (make_ssa_name (utype), NOP_EXPR, op0);
9882           gimple_set_location (g, loc);
9883           gsi_insert_before (gsi, g, GSI_SAME_STMT);
9884           op0 = gimple_assign_lhs (g);
9885         }
9886       if (TREE_CODE (op1) == INTEGER_CST)
9887         op1 = fold_convert (utype, op1);
9888       else if (!useless_type_conversion_p (utype, TREE_TYPE (op1)))
9889         {
9890           g = gimple_build_assign (make_ssa_name (utype), NOP_EXPR, op1);
9891           gimple_set_location (g, loc);
9892           gsi_insert_before (gsi, g, GSI_SAME_STMT);
9893           op1 = gimple_assign_lhs (g);
9894         }
9895       g = gimple_build_assign (make_ssa_name (utype), subcode, op0, op1);
9896       gimple_set_location (g, loc);
9897       gsi_insert_before (gsi, g, GSI_SAME_STMT);
9898       if (utype != type)
9899         {
9900           g = gimple_build_assign (make_ssa_name (type), NOP_EXPR,
9901                                    gimple_assign_lhs (g));
9902           gimple_set_location (g, loc);
9903           gsi_insert_before (gsi, g, GSI_SAME_STMT);
9904         }
9905       g = gimple_build_assign (gimple_call_lhs (stmt), COMPLEX_EXPR,
9906                                gimple_assign_lhs (g),
9907                                build_int_cst (type, ovf));
9908     }
9909   gimple_set_location (g, loc);
9910   gsi_replace (gsi, g, false);
9911   return true;
9912 }
9913
9914 /* Simplify STMT using ranges if possible.  */
9915
9916 static bool
9917 simplify_stmt_using_ranges (gimple_stmt_iterator *gsi)
9918 {
9919   gimple stmt = gsi_stmt (*gsi);
9920   if (is_gimple_assign (stmt))
9921     {
9922       enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
9923       tree rhs1 = gimple_assign_rhs1 (stmt);
9924
9925       switch (rhs_code)
9926         {
9927         case EQ_EXPR:
9928         case NE_EXPR:
9929           /* Transform EQ_EXPR, NE_EXPR into BIT_XOR_EXPR or identity
9930              if the RHS is zero or one, and the LHS are known to be boolean
9931              values.  */
9932           if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
9933             return simplify_truth_ops_using_ranges (gsi, stmt);
9934           break;
9935
9936       /* Transform TRUNC_DIV_EXPR and TRUNC_MOD_EXPR into RSHIFT_EXPR
9937          and BIT_AND_EXPR respectively if the first operand is greater
9938          than zero and the second operand is an exact power of two.
9939          Also optimize TRUNC_MOD_EXPR away if the second operand is
9940          constant and the first operand already has the right value
9941          range.  */
9942         case TRUNC_DIV_EXPR:
9943         case TRUNC_MOD_EXPR:
9944           if (TREE_CODE (rhs1) == SSA_NAME
9945               && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
9946             return simplify_div_or_mod_using_ranges (stmt);
9947           break;
9948
9949       /* Transform ABS (X) into X or -X as appropriate.  */
9950         case ABS_EXPR:
9951           if (TREE_CODE (rhs1) == SSA_NAME
9952               && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
9953             return simplify_abs_using_ranges (stmt);
9954           break;
9955
9956         case BIT_AND_EXPR:
9957         case BIT_IOR_EXPR:
9958           /* Optimize away BIT_AND_EXPR and BIT_IOR_EXPR
9959              if all the bits being cleared are already cleared or
9960              all the bits being set are already set.  */
9961           if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
9962             return simplify_bit_ops_using_ranges (gsi, stmt);
9963           break;
9964
9965         CASE_CONVERT:
9966           if (TREE_CODE (rhs1) == SSA_NAME
9967               && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
9968             return simplify_conversion_using_ranges (stmt);
9969           break;
9970
9971         case FLOAT_EXPR:
9972           if (TREE_CODE (rhs1) == SSA_NAME
9973               && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
9974             return simplify_float_conversion_using_ranges (gsi, stmt);
9975           break;
9976
9977         default:
9978           break;
9979         }
9980     }
9981   else if (gimple_code (stmt) == GIMPLE_COND)
9982     return simplify_cond_using_ranges (as_a <gcond *> (stmt));
9983   else if (gimple_code (stmt) == GIMPLE_SWITCH)
9984     return simplify_switch_using_ranges (as_a <gswitch *> (stmt));
9985   else if (is_gimple_call (stmt)
9986            && gimple_call_internal_p (stmt))
9987     return simplify_internal_call_using_ranges (gsi, stmt);
9988
9989   return false;
9990 }
9991
9992 /* If the statement pointed by SI has a predicate whose value can be
9993    computed using the value range information computed by VRP, compute
9994    its value and return true.  Otherwise, return false.  */
9995
9996 static bool
9997 fold_predicate_in (gimple_stmt_iterator *si)
9998 {
9999   bool assignment_p = false;
10000   tree val;
10001   gimple stmt = gsi_stmt (*si);
10002
10003   if (is_gimple_assign (stmt)
10004       && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
10005     {
10006       assignment_p = true;
10007       val = vrp_evaluate_conditional (gimple_assign_rhs_code (stmt),
10008                                       gimple_assign_rhs1 (stmt),
10009                                       gimple_assign_rhs2 (stmt),
10010                                       stmt);
10011     }
10012   else if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
10013     val = vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
10014                                     gimple_cond_lhs (cond_stmt),
10015                                     gimple_cond_rhs (cond_stmt),
10016                                     stmt);
10017   else
10018     return false;
10019
10020   if (val)
10021     {
10022       if (assignment_p)
10023         val = fold_convert (gimple_expr_type (stmt), val);
10024
10025       if (dump_file)
10026         {
10027           fprintf (dump_file, "Folding predicate ");
10028           print_gimple_expr (dump_file, stmt, 0, 0);
10029           fprintf (dump_file, " to ");
10030           print_generic_expr (dump_file, val, 0);
10031           fprintf (dump_file, "\n");
10032         }
10033
10034       if (is_gimple_assign (stmt))
10035         gimple_assign_set_rhs_from_tree (si, val);
10036       else
10037         {
10038           gcc_assert (gimple_code (stmt) == GIMPLE_COND);
10039           gcond *cond_stmt = as_a <gcond *> (stmt);
10040           if (integer_zerop (val))
10041             gimple_cond_make_false (cond_stmt);
10042           else if (integer_onep (val))
10043             gimple_cond_make_true (cond_stmt);
10044           else
10045             gcc_unreachable ();
10046         }
10047
10048       return true;
10049     }
10050
10051   return false;
10052 }
10053
10054 /* Callback for substitute_and_fold folding the stmt at *SI.  */
10055
10056 static bool
10057 vrp_fold_stmt (gimple_stmt_iterator *si)
10058 {
10059   if (fold_predicate_in (si))
10060     return true;
10061
10062   return simplify_stmt_using_ranges (si);
10063 }
10064
10065 /* Stack of dest,src equivalency pairs that need to be restored after
10066    each attempt to thread a block's incoming edge to an outgoing edge.
10067
10068    A NULL entry is used to mark the end of pairs which need to be
10069    restored.  */
10070 static vec<tree> equiv_stack;
10071
10072 /* A trivial wrapper so that we can present the generic jump threading
10073    code with a simple API for simplifying statements.  STMT is the
10074    statement we want to simplify, WITHIN_STMT provides the location
10075    for any overflow warnings.  */
10076
10077 static tree
10078 simplify_stmt_for_jump_threading (gimple stmt, gimple within_stmt)
10079 {
10080   if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
10081     return vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
10082                                      gimple_cond_lhs (cond_stmt),
10083                                      gimple_cond_rhs (cond_stmt),
10084                                      within_stmt);
10085
10086   if (gassign *assign_stmt = dyn_cast <gassign *> (stmt))
10087     {
10088       value_range_t new_vr = VR_INITIALIZER;
10089       tree lhs = gimple_assign_lhs (assign_stmt);
10090
10091       if (TREE_CODE (lhs) == SSA_NAME
10092           && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
10093               || POINTER_TYPE_P (TREE_TYPE (lhs))))
10094         {
10095           extract_range_from_assignment (&new_vr, assign_stmt);
10096           if (range_int_cst_singleton_p (&new_vr))
10097             return new_vr.min;
10098         }
10099     }
10100
10101   return NULL_TREE;
10102 }
10103
10104 /* Blocks which have more than one predecessor and more than
10105    one successor present jump threading opportunities, i.e.,
10106    when the block is reached from a specific predecessor, we
10107    may be able to determine which of the outgoing edges will
10108    be traversed.  When this optimization applies, we are able
10109    to avoid conditionals at runtime and we may expose secondary
10110    optimization opportunities.
10111
10112    This routine is effectively a driver for the generic jump
10113    threading code.  It basically just presents the generic code
10114    with edges that may be suitable for jump threading.
10115
10116    Unlike DOM, we do not iterate VRP if jump threading was successful.
10117    While iterating may expose new opportunities for VRP, it is expected
10118    those opportunities would be very limited and the compile time cost
10119    to expose those opportunities would be significant.
10120
10121    As jump threading opportunities are discovered, they are registered
10122    for later realization.  */
10123
10124 static void
10125 identify_jump_threads (void)
10126 {
10127   basic_block bb;
10128   gcond *dummy;
10129   int i;
10130   edge e;
10131
10132   /* Ugh.  When substituting values earlier in this pass we can
10133      wipe the dominance information.  So rebuild the dominator
10134      information as we need it within the jump threading code.  */
10135   calculate_dominance_info (CDI_DOMINATORS);
10136
10137   /* We do not allow VRP information to be used for jump threading
10138      across a back edge in the CFG.  Otherwise it becomes too
10139      difficult to avoid eliminating loop exit tests.  Of course
10140      EDGE_DFS_BACK is not accurate at this time so we have to
10141      recompute it.  */
10142   mark_dfs_back_edges ();
10143
10144   /* Do not thread across edges we are about to remove.  Just marking
10145      them as EDGE_DFS_BACK will do.  */
10146   FOR_EACH_VEC_ELT (to_remove_edges, i, e)
10147     e->flags |= EDGE_DFS_BACK;
10148
10149   /* Allocate our unwinder stack to unwind any temporary equivalences
10150      that might be recorded.  */
10151   equiv_stack.create (20);
10152
10153   /* To avoid lots of silly node creation, we create a single
10154      conditional and just modify it in-place when attempting to
10155      thread jumps.  */
10156   dummy = gimple_build_cond (EQ_EXPR,
10157                              integer_zero_node, integer_zero_node,
10158                              NULL, NULL);
10159
10160   /* Walk through all the blocks finding those which present a
10161      potential jump threading opportunity.  We could set this up
10162      as a dominator walker and record data during the walk, but
10163      I doubt it's worth the effort for the classes of jump
10164      threading opportunities we are trying to identify at this
10165      point in compilation.  */
10166   FOR_EACH_BB_FN (bb, cfun)
10167     {
10168       gimple last;
10169
10170       /* If the generic jump threading code does not find this block
10171          interesting, then there is nothing to do.  */
10172       if (! potentially_threadable_block (bb))
10173         continue;
10174
10175       /* We only care about blocks ending in a COND_EXPR.  While there
10176          may be some value in handling SWITCH_EXPR here, I doubt it's
10177          terribly important.  */
10178       last = gsi_stmt (gsi_last_bb (bb));
10179
10180       /* We're basically looking for a switch or any kind of conditional with
10181          integral or pointer type arguments.  Note the type of the second
10182          argument will be the same as the first argument, so no need to
10183          check it explicitly.  */
10184       if (gimple_code (last) == GIMPLE_SWITCH
10185           || (gimple_code (last) == GIMPLE_COND
10186               && TREE_CODE (gimple_cond_lhs (last)) == SSA_NAME
10187               && (INTEGRAL_TYPE_P (TREE_TYPE (gimple_cond_lhs (last)))
10188                   || POINTER_TYPE_P (TREE_TYPE (gimple_cond_lhs (last))))
10189               && (TREE_CODE (gimple_cond_rhs (last)) == SSA_NAME
10190                   || is_gimple_min_invariant (gimple_cond_rhs (last)))))
10191         {
10192           edge_iterator ei;
10193
10194           /* We've got a block with multiple predecessors and multiple
10195              successors which also ends in a suitable conditional or
10196              switch statement.  For each predecessor, see if we can thread
10197              it to a specific successor.  */
10198           FOR_EACH_EDGE (e, ei, bb->preds)
10199             {
10200               /* Do not thread across back edges or abnormal edges
10201                  in the CFG.  */
10202               if (e->flags & (EDGE_DFS_BACK | EDGE_COMPLEX))
10203                 continue;
10204
10205               thread_across_edge (dummy, e, true, &equiv_stack,
10206                                   simplify_stmt_for_jump_threading);
10207             }
10208         }
10209     }
10210
10211   /* We do not actually update the CFG or SSA graphs at this point as
10212      ASSERT_EXPRs are still in the IL and cfg cleanup code does not yet
10213      handle ASSERT_EXPRs gracefully.  */
10214 }
10215
10216 /* We identified all the jump threading opportunities earlier, but could
10217    not transform the CFG at that time.  This routine transforms the
10218    CFG and arranges for the dominator tree to be rebuilt if necessary.
10219
10220    Note the SSA graph update will occur during the normal TODO
10221    processing by the pass manager.  */
10222 static void
10223 finalize_jump_threads (void)
10224 {
10225   thread_through_all_blocks (false);
10226   equiv_stack.release ();
10227 }
10228
10229
10230 /* Traverse all the blocks folding conditionals with known ranges.  */
10231
10232 static void
10233 vrp_finalize (void)
10234 {
10235   size_t i;
10236
10237   values_propagated = true;
10238
10239   if (dump_file)
10240     {
10241       fprintf (dump_file, "\nValue ranges after VRP:\n\n");
10242       dump_all_value_ranges (dump_file);
10243       fprintf (dump_file, "\n");
10244     }
10245
10246   substitute_and_fold (op_with_constant_singleton_value_range,
10247                        vrp_fold_stmt, false);
10248
10249   if (warn_array_bounds && first_pass_instance)
10250     check_all_array_refs ();
10251
10252   /* We must identify jump threading opportunities before we release
10253      the datastructures built by VRP.  */
10254   identify_jump_threads ();
10255
10256   /* Set value range to non pointer SSA_NAMEs.  */
10257   for (i  = 0; i < num_vr_values; i++)
10258     if (vr_value[i])
10259       {
10260         tree name = ssa_name (i);
10261
10262       if (!name
10263           || POINTER_TYPE_P (TREE_TYPE (name))
10264           || (vr_value[i]->type == VR_VARYING)
10265           || (vr_value[i]->type == VR_UNDEFINED))
10266         continue;
10267
10268         if ((TREE_CODE (vr_value[i]->min) == INTEGER_CST)
10269             && (TREE_CODE (vr_value[i]->max) == INTEGER_CST)
10270             && (vr_value[i]->type == VR_RANGE
10271                 || vr_value[i]->type == VR_ANTI_RANGE))
10272           set_range_info (name, vr_value[i]->type, vr_value[i]->min,
10273                           vr_value[i]->max);
10274       }
10275
10276   /* Free allocated memory.  */
10277   for (i = 0; i < num_vr_values; i++)
10278     if (vr_value[i])
10279       {
10280         BITMAP_FREE (vr_value[i]->equiv);
10281         free (vr_value[i]);
10282       }
10283
10284   free (vr_value);
10285   free (vr_phi_edge_counts);
10286
10287   /* So that we can distinguish between VRP data being available
10288      and not available.  */
10289   vr_value = NULL;
10290   vr_phi_edge_counts = NULL;
10291 }
10292
10293
10294 /* Main entry point to VRP (Value Range Propagation).  This pass is
10295    loosely based on J. R. C. Patterson, ``Accurate Static Branch
10296    Prediction by Value Range Propagation,'' in SIGPLAN Conference on
10297    Programming Language Design and Implementation, pp. 67-78, 1995.
10298    Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
10299
10300    This is essentially an SSA-CCP pass modified to deal with ranges
10301    instead of constants.
10302
10303    While propagating ranges, we may find that two or more SSA name
10304    have equivalent, though distinct ranges.  For instance,
10305
10306      1  x_9 = p_3->a;
10307      2  p_4 = ASSERT_EXPR <p_3, p_3 != 0>
10308      3  if (p_4 == q_2)
10309      4    p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
10310      5  endif
10311      6  if (q_2)
10312
10313    In the code above, pointer p_5 has range [q_2, q_2], but from the
10314    code we can also determine that p_5 cannot be NULL and, if q_2 had
10315    a non-varying range, p_5's range should also be compatible with it.
10316
10317    These equivalences are created by two expressions: ASSERT_EXPR and
10318    copy operations.  Since p_5 is an assertion on p_4, and p_4 was the
10319    result of another assertion, then we can use the fact that p_5 and
10320    p_4 are equivalent when evaluating p_5's range.
10321
10322    Together with value ranges, we also propagate these equivalences
10323    between names so that we can take advantage of information from
10324    multiple ranges when doing final replacement.  Note that this
10325    equivalency relation is transitive but not symmetric.
10326
10327    In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
10328    cannot assert that q_2 is equivalent to p_5 because q_2 may be used
10329    in contexts where that assertion does not hold (e.g., in line 6).
10330
10331    TODO, the main difference between this pass and Patterson's is that
10332    we do not propagate edge probabilities.  We only compute whether
10333    edges can be taken or not.  That is, instead of having a spectrum
10334    of jump probabilities between 0 and 1, we only deal with 0, 1 and
10335    DON'T KNOW.  In the future, it may be worthwhile to propagate
10336    probabilities to aid branch prediction.  */
10337
10338 static unsigned int
10339 execute_vrp (void)
10340 {
10341   int i;
10342   edge e;
10343   switch_update *su;
10344
10345   loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
10346   rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
10347   scev_initialize ();
10348
10349   /* ???  This ends up using stale EDGE_DFS_BACK for liveness computation.
10350      Inserting assertions may split edges which will invalidate
10351      EDGE_DFS_BACK.  */
10352   insert_range_assertions ();
10353
10354   to_remove_edges.create (10);
10355   to_update_switch_stmts.create (5);
10356   threadedge_initialize_values ();
10357
10358   /* For visiting PHI nodes we need EDGE_DFS_BACK computed.  */
10359   mark_dfs_back_edges ();
10360
10361   vrp_initialize ();
10362   ssa_propagate (vrp_visit_stmt, vrp_visit_phi_node);
10363   vrp_finalize ();
10364
10365   free_numbers_of_iterations_estimates ();
10366
10367   /* ASSERT_EXPRs must be removed before finalizing jump threads
10368      as finalizing jump threads calls the CFG cleanup code which
10369      does not properly handle ASSERT_EXPRs.  */
10370   remove_range_assertions ();
10371
10372   /* If we exposed any new variables, go ahead and put them into
10373      SSA form now, before we handle jump threading.  This simplifies
10374      interactions between rewriting of _DECL nodes into SSA form
10375      and rewriting SSA_NAME nodes into SSA form after block
10376      duplication and CFG manipulation.  */
10377   update_ssa (TODO_update_ssa);
10378
10379   finalize_jump_threads ();
10380
10381   /* Remove dead edges from SWITCH_EXPR optimization.  This leaves the
10382      CFG in a broken state and requires a cfg_cleanup run.  */
10383   FOR_EACH_VEC_ELT (to_remove_edges, i, e)
10384     remove_edge (e);
10385   /* Update SWITCH_EXPR case label vector.  */
10386   FOR_EACH_VEC_ELT (to_update_switch_stmts, i, su)
10387     {
10388       size_t j;
10389       size_t n = TREE_VEC_LENGTH (su->vec);
10390       tree label;
10391       gimple_switch_set_num_labels (su->stmt, n);
10392       for (j = 0; j < n; j++)
10393         gimple_switch_set_label (su->stmt, j, TREE_VEC_ELT (su->vec, j));
10394       /* As we may have replaced the default label with a regular one
10395          make sure to make it a real default label again.  This ensures
10396          optimal expansion.  */
10397       label = gimple_switch_label (su->stmt, 0);
10398       CASE_LOW (label) = NULL_TREE;
10399       CASE_HIGH (label) = NULL_TREE;
10400     }
10401
10402   if (to_remove_edges.length () > 0)
10403     {
10404       free_dominance_info (CDI_DOMINATORS);
10405       loops_state_set (LOOPS_NEED_FIXUP);
10406     }
10407
10408   to_remove_edges.release ();
10409   to_update_switch_stmts.release ();
10410   threadedge_finalize_values ();
10411
10412   scev_finalize ();
10413   loop_optimizer_finalize ();
10414   return 0;
10415 }
10416
10417 namespace {
10418
10419 const pass_data pass_data_vrp =
10420 {
10421   GIMPLE_PASS, /* type */
10422   "vrp", /* name */
10423   OPTGROUP_NONE, /* optinfo_flags */
10424   TV_TREE_VRP, /* tv_id */
10425   PROP_ssa, /* properties_required */
10426   0, /* properties_provided */
10427   0, /* properties_destroyed */
10428   0, /* todo_flags_start */
10429   ( TODO_cleanup_cfg | TODO_update_ssa ), /* todo_flags_finish */
10430 };
10431
10432 class pass_vrp : public gimple_opt_pass
10433 {
10434 public:
10435   pass_vrp (gcc::context *ctxt)
10436     : gimple_opt_pass (pass_data_vrp, ctxt)
10437   {}
10438
10439   /* opt_pass methods: */
10440   opt_pass * clone () { return new pass_vrp (m_ctxt); }
10441   virtual bool gate (function *) { return flag_tree_vrp != 0; }
10442   virtual unsigned int execute (function *) { return execute_vrp (); }
10443
10444 }; // class pass_vrp
10445
10446 } // anon namespace
10447
10448 gimple_opt_pass *
10449 make_pass_vrp (gcc::context *ctxt)
10450 {
10451   return new pass_vrp (ctxt);
10452 }