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