Daily bump.
[official-gcc.git] / gcc / tree-vrp.c
blobdd7723629ba037a96b08c9379d039dba18bc20ee
1 /* Support routines for Value Range Propagation (VRP).
2 Copyright (C) 2005-2021 Free Software Foundation, Inc.
3 Contributed by Diego Novillo <dnovillo@redhat.com>.
5 This file is part of GCC.
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.
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.
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/>. */
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "basic-block.h"
25 #include "bitmap.h"
26 #include "sbitmap.h"
27 #include "options.h"
28 #include "dominance.h"
29 #include "function.h"
30 #include "cfg.h"
31 #include "tree.h"
32 #include "gimple.h"
33 #include "tree-pass.h"
34 #include "ssa.h"
35 #include "gimple-pretty-print.h"
36 #include "fold-const.h"
37 #include "cfganal.h"
38 #include "gimple-iterator.h"
39 #include "tree-cfg.h"
40 #include "tree-ssa-loop-manip.h"
41 #include "tree-ssa-loop-niter.h"
42 #include "tree-into-ssa.h"
43 #include "cfgloop.h"
44 #include "tree-scalar-evolution.h"
45 #include "tree-ssa-propagate.h"
46 #include "domwalk.h"
47 #include "vr-values.h"
48 #include "gimple-array-bounds.h"
49 #include "gimple-range.h"
50 #include "gimple-range-path.h"
51 #include "value-pointer-equiv.h"
52 #include "gimple-fold.h"
54 /* Set of SSA names found live during the RPO traversal of the function
55 for still active basic-blocks. */
56 class live_names
58 public:
59 live_names ();
60 ~live_names ();
61 void set (tree, basic_block);
62 void clear (tree, basic_block);
63 void merge (basic_block dest, basic_block src);
64 bool live_on_block_p (tree, basic_block);
65 bool live_on_edge_p (tree, edge);
66 bool block_has_live_names_p (basic_block);
67 void clear_block (basic_block);
69 private:
70 sbitmap *live;
71 unsigned num_blocks;
72 void init_bitmap_if_needed (basic_block);
75 void
76 live_names::init_bitmap_if_needed (basic_block bb)
78 unsigned i = bb->index;
79 if (!live[i])
81 live[i] = sbitmap_alloc (num_ssa_names);
82 bitmap_clear (live[i]);
86 bool
87 live_names::block_has_live_names_p (basic_block bb)
89 unsigned i = bb->index;
90 return live[i] && bitmap_empty_p (live[i]);
93 void
94 live_names::clear_block (basic_block bb)
96 unsigned i = bb->index;
97 if (live[i])
99 sbitmap_free (live[i]);
100 live[i] = NULL;
104 void
105 live_names::merge (basic_block dest, basic_block src)
107 init_bitmap_if_needed (dest);
108 init_bitmap_if_needed (src);
109 bitmap_ior (live[dest->index], live[dest->index], live[src->index]);
112 void
113 live_names::set (tree name, basic_block bb)
115 init_bitmap_if_needed (bb);
116 bitmap_set_bit (live[bb->index], SSA_NAME_VERSION (name));
119 void
120 live_names::clear (tree name, basic_block bb)
122 unsigned i = bb->index;
123 if (live[i])
124 bitmap_clear_bit (live[i], SSA_NAME_VERSION (name));
127 live_names::live_names ()
129 num_blocks = last_basic_block_for_fn (cfun);
130 live = XCNEWVEC (sbitmap, num_blocks);
133 live_names::~live_names ()
135 for (unsigned i = 0; i < num_blocks; ++i)
136 if (live[i])
137 sbitmap_free (live[i]);
138 XDELETEVEC (live);
141 bool
142 live_names::live_on_block_p (tree name, basic_block bb)
144 return (live[bb->index]
145 && bitmap_bit_p (live[bb->index], SSA_NAME_VERSION (name)));
148 /* Return true if the SSA name NAME is live on the edge E. */
150 bool
151 live_names::live_on_edge_p (tree name, edge e)
153 return live_on_block_p (name, e->dest);
157 /* VR_TYPE describes a range with mininum value *MIN and maximum
158 value *MAX. Restrict the range to the set of values that have
159 no bits set outside NONZERO_BITS. Update *MIN and *MAX and
160 return the new range type.
162 SGN gives the sign of the values described by the range. */
164 enum value_range_kind
165 intersect_range_with_nonzero_bits (enum value_range_kind vr_type,
166 wide_int *min, wide_int *max,
167 const wide_int &nonzero_bits,
168 signop sgn)
170 if (vr_type == VR_ANTI_RANGE)
172 /* The VR_ANTI_RANGE is equivalent to the union of the ranges
173 A: [-INF, *MIN) and B: (*MAX, +INF]. First use NONZERO_BITS
174 to create an inclusive upper bound for A and an inclusive lower
175 bound for B. */
176 wide_int a_max = wi::round_down_for_mask (*min - 1, nonzero_bits);
177 wide_int b_min = wi::round_up_for_mask (*max + 1, nonzero_bits);
179 /* If the calculation of A_MAX wrapped, A is effectively empty
180 and A_MAX is the highest value that satisfies NONZERO_BITS.
181 Likewise if the calculation of B_MIN wrapped, B is effectively
182 empty and B_MIN is the lowest value that satisfies NONZERO_BITS. */
183 bool a_empty = wi::ge_p (a_max, *min, sgn);
184 bool b_empty = wi::le_p (b_min, *max, sgn);
186 /* If both A and B are empty, there are no valid values. */
187 if (a_empty && b_empty)
188 return VR_UNDEFINED;
190 /* If exactly one of A or B is empty, return a VR_RANGE for the
191 other one. */
192 if (a_empty || b_empty)
194 *min = b_min;
195 *max = a_max;
196 gcc_checking_assert (wi::le_p (*min, *max, sgn));
197 return VR_RANGE;
200 /* Update the VR_ANTI_RANGE bounds. */
201 *min = a_max + 1;
202 *max = b_min - 1;
203 gcc_checking_assert (wi::le_p (*min, *max, sgn));
205 /* Now check whether the excluded range includes any values that
206 satisfy NONZERO_BITS. If not, switch to a full VR_RANGE. */
207 if (wi::round_up_for_mask (*min, nonzero_bits) == b_min)
209 unsigned int precision = min->get_precision ();
210 *min = wi::min_value (precision, sgn);
211 *max = wi::max_value (precision, sgn);
212 vr_type = VR_RANGE;
215 if (vr_type == VR_RANGE || vr_type == VR_VARYING)
217 *max = wi::round_down_for_mask (*max, nonzero_bits);
219 /* Check that the range contains at least one valid value. */
220 if (wi::gt_p (*min, *max, sgn))
221 return VR_UNDEFINED;
223 *min = wi::round_up_for_mask (*min, nonzero_bits);
224 gcc_checking_assert (wi::le_p (*min, *max, sgn));
226 return vr_type;
229 /* Return true if max and min of VR are INTEGER_CST. It's not necessary
230 a singleton. */
232 bool
233 range_int_cst_p (const value_range *vr)
235 return (vr->kind () == VR_RANGE && range_has_numeric_bounds_p (vr));
238 /* Return the single symbol (an SSA_NAME) contained in T if any, or NULL_TREE
239 otherwise. We only handle additive operations and set NEG to true if the
240 symbol is negated and INV to the invariant part, if any. */
242 tree
243 get_single_symbol (tree t, bool *neg, tree *inv)
245 bool neg_;
246 tree inv_;
248 *inv = NULL_TREE;
249 *neg = false;
251 if (TREE_CODE (t) == PLUS_EXPR
252 || TREE_CODE (t) == POINTER_PLUS_EXPR
253 || TREE_CODE (t) == MINUS_EXPR)
255 if (is_gimple_min_invariant (TREE_OPERAND (t, 0)))
257 neg_ = (TREE_CODE (t) == MINUS_EXPR);
258 inv_ = TREE_OPERAND (t, 0);
259 t = TREE_OPERAND (t, 1);
261 else if (is_gimple_min_invariant (TREE_OPERAND (t, 1)))
263 neg_ = false;
264 inv_ = TREE_OPERAND (t, 1);
265 t = TREE_OPERAND (t, 0);
267 else
268 return NULL_TREE;
270 else
272 neg_ = false;
273 inv_ = NULL_TREE;
276 if (TREE_CODE (t) == NEGATE_EXPR)
278 t = TREE_OPERAND (t, 0);
279 neg_ = !neg_;
282 if (TREE_CODE (t) != SSA_NAME)
283 return NULL_TREE;
285 if (inv_ && TREE_OVERFLOW_P (inv_))
286 inv_ = drop_tree_overflow (inv_);
288 *neg = neg_;
289 *inv = inv_;
290 return t;
293 /* The reverse operation: build a symbolic expression with TYPE
294 from symbol SYM, negated according to NEG, and invariant INV. */
296 static tree
297 build_symbolic_expr (tree type, tree sym, bool neg, tree inv)
299 const bool pointer_p = POINTER_TYPE_P (type);
300 tree t = sym;
302 if (neg)
303 t = build1 (NEGATE_EXPR, type, t);
305 if (integer_zerop (inv))
306 return t;
308 return build2 (pointer_p ? POINTER_PLUS_EXPR : PLUS_EXPR, type, t, inv);
311 /* Return
312 1 if VAL < VAL2
313 0 if !(VAL < VAL2)
314 -2 if those are incomparable. */
316 operand_less_p (tree val, tree val2)
318 /* LT is folded faster than GE and others. Inline the common case. */
319 if (TREE_CODE (val) == INTEGER_CST && TREE_CODE (val2) == INTEGER_CST)
320 return tree_int_cst_lt (val, val2);
321 else if (TREE_CODE (val) == SSA_NAME && TREE_CODE (val2) == SSA_NAME)
322 return val == val2 ? 0 : -2;
323 else
325 int cmp = compare_values (val, val2);
326 if (cmp == -1)
327 return 1;
328 else if (cmp == 0 || cmp == 1)
329 return 0;
330 else
331 return -2;
334 return 0;
337 /* Compare two values VAL1 and VAL2. Return
339 -2 if VAL1 and VAL2 cannot be compared at compile-time,
340 -1 if VAL1 < VAL2,
341 0 if VAL1 == VAL2,
342 +1 if VAL1 > VAL2, and
343 +2 if VAL1 != VAL2
345 This is similar to tree_int_cst_compare but supports pointer values
346 and values that cannot be compared at compile time.
348 If STRICT_OVERFLOW_P is not NULL, then set *STRICT_OVERFLOW_P to
349 true if the return value is only valid if we assume that signed
350 overflow is undefined. */
353 compare_values_warnv (tree val1, tree val2, bool *strict_overflow_p)
355 if (val1 == val2)
356 return 0;
358 /* Below we rely on the fact that VAL1 and VAL2 are both pointers or
359 both integers. */
360 gcc_assert (POINTER_TYPE_P (TREE_TYPE (val1))
361 == POINTER_TYPE_P (TREE_TYPE (val2)));
363 /* Convert the two values into the same type. This is needed because
364 sizetype causes sign extension even for unsigned types. */
365 if (!useless_type_conversion_p (TREE_TYPE (val1), TREE_TYPE (val2)))
366 val2 = fold_convert (TREE_TYPE (val1), val2);
368 const bool overflow_undefined
369 = INTEGRAL_TYPE_P (TREE_TYPE (val1))
370 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1));
371 tree inv1, inv2;
372 bool neg1, neg2;
373 tree sym1 = get_single_symbol (val1, &neg1, &inv1);
374 tree sym2 = get_single_symbol (val2, &neg2, &inv2);
376 /* If VAL1 and VAL2 are of the form '[-]NAME [+ CST]', return -1 or +1
377 accordingly. If VAL1 and VAL2 don't use the same name, return -2. */
378 if (sym1 && sym2)
380 /* Both values must use the same name with the same sign. */
381 if (sym1 != sym2 || neg1 != neg2)
382 return -2;
384 /* [-]NAME + CST == [-]NAME + CST. */
385 if (inv1 == inv2)
386 return 0;
388 /* If overflow is defined we cannot simplify more. */
389 if (!overflow_undefined)
390 return -2;
392 if (strict_overflow_p != NULL
393 /* Symbolic range building sets the no-warning bit to declare
394 that overflow doesn't happen. */
395 && (!inv1 || !warning_suppressed_p (val1, OPT_Woverflow))
396 && (!inv2 || !warning_suppressed_p (val2, OPT_Woverflow)))
397 *strict_overflow_p = true;
399 if (!inv1)
400 inv1 = build_int_cst (TREE_TYPE (val1), 0);
401 if (!inv2)
402 inv2 = build_int_cst (TREE_TYPE (val2), 0);
404 return wi::cmp (wi::to_wide (inv1), wi::to_wide (inv2),
405 TYPE_SIGN (TREE_TYPE (val1)));
408 const bool cst1 = is_gimple_min_invariant (val1);
409 const bool cst2 = is_gimple_min_invariant (val2);
411 /* If one is of the form '[-]NAME + CST' and the other is constant, then
412 it might be possible to say something depending on the constants. */
413 if ((sym1 && inv1 && cst2) || (sym2 && inv2 && cst1))
415 if (!overflow_undefined)
416 return -2;
418 if (strict_overflow_p != NULL
419 /* Symbolic range building sets the no-warning bit to declare
420 that overflow doesn't happen. */
421 && (!sym1 || !warning_suppressed_p (val1, OPT_Woverflow))
422 && (!sym2 || !warning_suppressed_p (val2, OPT_Woverflow)))
423 *strict_overflow_p = true;
425 const signop sgn = TYPE_SIGN (TREE_TYPE (val1));
426 tree cst = cst1 ? val1 : val2;
427 tree inv = cst1 ? inv2 : inv1;
429 /* Compute the difference between the constants. If it overflows or
430 underflows, this means that we can trivially compare the NAME with
431 it and, consequently, the two values with each other. */
432 wide_int diff = wi::to_wide (cst) - wi::to_wide (inv);
433 if (wi::cmp (0, wi::to_wide (inv), sgn)
434 != wi::cmp (diff, wi::to_wide (cst), sgn))
436 const int res = wi::cmp (wi::to_wide (cst), wi::to_wide (inv), sgn);
437 return cst1 ? res : -res;
440 return -2;
443 /* We cannot say anything more for non-constants. */
444 if (!cst1 || !cst2)
445 return -2;
447 if (!POINTER_TYPE_P (TREE_TYPE (val1)))
449 /* We cannot compare overflowed values. */
450 if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
451 return -2;
453 if (TREE_CODE (val1) == INTEGER_CST
454 && TREE_CODE (val2) == INTEGER_CST)
455 return tree_int_cst_compare (val1, val2);
457 if (poly_int_tree_p (val1) && poly_int_tree_p (val2))
459 if (known_eq (wi::to_poly_widest (val1),
460 wi::to_poly_widest (val2)))
461 return 0;
462 if (known_lt (wi::to_poly_widest (val1),
463 wi::to_poly_widest (val2)))
464 return -1;
465 if (known_gt (wi::to_poly_widest (val1),
466 wi::to_poly_widest (val2)))
467 return 1;
470 return -2;
472 else
474 if (TREE_CODE (val1) == INTEGER_CST && TREE_CODE (val2) == INTEGER_CST)
476 /* We cannot compare overflowed values. */
477 if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
478 return -2;
480 return tree_int_cst_compare (val1, val2);
483 /* First see if VAL1 and VAL2 are not the same. */
484 if (operand_equal_p (val1, val2, 0))
485 return 0;
487 fold_defer_overflow_warnings ();
489 /* If VAL1 is a lower address than VAL2, return -1. */
490 tree t = fold_binary_to_constant (LT_EXPR, boolean_type_node, val1, val2);
491 if (t && integer_onep (t))
493 fold_undefer_and_ignore_overflow_warnings ();
494 return -1;
497 /* If VAL1 is a higher address than VAL2, return +1. */
498 t = fold_binary_to_constant (LT_EXPR, boolean_type_node, val2, val1);
499 if (t && integer_onep (t))
501 fold_undefer_and_ignore_overflow_warnings ();
502 return 1;
505 /* If VAL1 is different than VAL2, return +2. */
506 t = fold_binary_to_constant (NE_EXPR, boolean_type_node, val1, val2);
507 fold_undefer_and_ignore_overflow_warnings ();
508 if (t && integer_onep (t))
509 return 2;
511 return -2;
515 /* Compare values like compare_values_warnv. */
518 compare_values (tree val1, tree val2)
520 bool sop;
521 return compare_values_warnv (val1, val2, &sop);
524 /* If BOUND will include a symbolic bound, adjust it accordingly,
525 otherwise leave it as is.
527 CODE is the original operation that combined the bounds (PLUS_EXPR
528 or MINUS_EXPR).
530 TYPE is the type of the original operation.
532 SYM_OPn is the symbolic for OPn if it has a symbolic.
534 NEG_OPn is TRUE if the OPn was negated. */
536 static void
537 adjust_symbolic_bound (tree &bound, enum tree_code code, tree type,
538 tree sym_op0, tree sym_op1,
539 bool neg_op0, bool neg_op1)
541 bool minus_p = (code == MINUS_EXPR);
542 /* If the result bound is constant, we're done; otherwise, build the
543 symbolic lower bound. */
544 if (sym_op0 == sym_op1)
546 else if (sym_op0)
547 bound = build_symbolic_expr (type, sym_op0,
548 neg_op0, bound);
549 else if (sym_op1)
551 /* We may not negate if that might introduce
552 undefined overflow. */
553 if (!minus_p
554 || neg_op1
555 || TYPE_OVERFLOW_WRAPS (type))
556 bound = build_symbolic_expr (type, sym_op1,
557 neg_op1 ^ minus_p, bound);
558 else
559 bound = NULL_TREE;
563 /* Combine OP1 and OP1, which are two parts of a bound, into one wide
564 int bound according to CODE. CODE is the operation combining the
565 bound (either a PLUS_EXPR or a MINUS_EXPR).
567 TYPE is the type of the combine operation.
569 WI is the wide int to store the result.
571 OVF is -1 if an underflow occurred, +1 if an overflow occurred or 0
572 if over/underflow occurred. */
574 static void
575 combine_bound (enum tree_code code, wide_int &wi, wi::overflow_type &ovf,
576 tree type, tree op0, tree op1)
578 bool minus_p = (code == MINUS_EXPR);
579 const signop sgn = TYPE_SIGN (type);
580 const unsigned int prec = TYPE_PRECISION (type);
582 /* Combine the bounds, if any. */
583 if (op0 && op1)
585 if (minus_p)
586 wi = wi::sub (wi::to_wide (op0), wi::to_wide (op1), sgn, &ovf);
587 else
588 wi = wi::add (wi::to_wide (op0), wi::to_wide (op1), sgn, &ovf);
590 else if (op0)
591 wi = wi::to_wide (op0);
592 else if (op1)
594 if (minus_p)
595 wi = wi::neg (wi::to_wide (op1), &ovf);
596 else
597 wi = wi::to_wide (op1);
599 else
600 wi = wi::shwi (0, prec);
603 /* Given a range in [WMIN, WMAX], adjust it for possible overflow and
604 put the result in VR.
606 TYPE is the type of the range.
608 MIN_OVF and MAX_OVF indicate what type of overflow, if any,
609 occurred while originally calculating WMIN or WMAX. -1 indicates
610 underflow. +1 indicates overflow. 0 indicates neither. */
612 static void
613 set_value_range_with_overflow (value_range_kind &kind, tree &min, tree &max,
614 tree type,
615 const wide_int &wmin, const wide_int &wmax,
616 wi::overflow_type min_ovf,
617 wi::overflow_type max_ovf)
619 const signop sgn = TYPE_SIGN (type);
620 const unsigned int prec = TYPE_PRECISION (type);
622 /* For one bit precision if max < min, then the swapped
623 range covers all values. */
624 if (prec == 1 && wi::lt_p (wmax, wmin, sgn))
626 kind = VR_VARYING;
627 return;
630 if (TYPE_OVERFLOW_WRAPS (type))
632 /* If overflow wraps, truncate the values and adjust the
633 range kind and bounds appropriately. */
634 wide_int tmin = wide_int::from (wmin, prec, sgn);
635 wide_int tmax = wide_int::from (wmax, prec, sgn);
636 if ((min_ovf != wi::OVF_NONE) == (max_ovf != wi::OVF_NONE))
638 /* If the limits are swapped, we wrapped around and cover
639 the entire range. */
640 if (wi::gt_p (tmin, tmax, sgn))
641 kind = VR_VARYING;
642 else
644 kind = VR_RANGE;
645 /* No overflow or both overflow or underflow. The
646 range kind stays VR_RANGE. */
647 min = wide_int_to_tree (type, tmin);
648 max = wide_int_to_tree (type, tmax);
650 return;
652 else if ((min_ovf == wi::OVF_UNDERFLOW && max_ovf == wi::OVF_NONE)
653 || (max_ovf == wi::OVF_OVERFLOW && min_ovf == wi::OVF_NONE))
655 /* Min underflow or max overflow. The range kind
656 changes to VR_ANTI_RANGE. */
657 bool covers = false;
658 wide_int tem = tmin;
659 tmin = tmax + 1;
660 if (wi::cmp (tmin, tmax, sgn) < 0)
661 covers = true;
662 tmax = tem - 1;
663 if (wi::cmp (tmax, tem, sgn) > 0)
664 covers = true;
665 /* If the anti-range would cover nothing, drop to varying.
666 Likewise if the anti-range bounds are outside of the
667 types values. */
668 if (covers || wi::cmp (tmin, tmax, sgn) > 0)
670 kind = VR_VARYING;
671 return;
673 kind = VR_ANTI_RANGE;
674 min = wide_int_to_tree (type, tmin);
675 max = wide_int_to_tree (type, tmax);
676 return;
678 else
680 /* Other underflow and/or overflow, drop to VR_VARYING. */
681 kind = VR_VARYING;
682 return;
685 else
687 /* If overflow does not wrap, saturate to the types min/max
688 value. */
689 wide_int type_min = wi::min_value (prec, sgn);
690 wide_int type_max = wi::max_value (prec, sgn);
691 kind = VR_RANGE;
692 if (min_ovf == wi::OVF_UNDERFLOW)
693 min = wide_int_to_tree (type, type_min);
694 else if (min_ovf == wi::OVF_OVERFLOW)
695 min = wide_int_to_tree (type, type_max);
696 else
697 min = wide_int_to_tree (type, wmin);
699 if (max_ovf == wi::OVF_UNDERFLOW)
700 max = wide_int_to_tree (type, type_min);
701 else if (max_ovf == wi::OVF_OVERFLOW)
702 max = wide_int_to_tree (type, type_max);
703 else
704 max = wide_int_to_tree (type, wmax);
708 /* Fold two value range's of a POINTER_PLUS_EXPR into VR. */
710 static void
711 extract_range_from_pointer_plus_expr (value_range *vr,
712 enum tree_code code,
713 tree expr_type,
714 const value_range *vr0,
715 const value_range *vr1)
717 gcc_checking_assert (POINTER_TYPE_P (expr_type)
718 && code == POINTER_PLUS_EXPR);
719 /* For pointer types, we are really only interested in asserting
720 whether the expression evaluates to non-NULL.
721 With -fno-delete-null-pointer-checks we need to be more
722 conservative. As some object might reside at address 0,
723 then some offset could be added to it and the same offset
724 subtracted again and the result would be NULL.
725 E.g.
726 static int a[12]; where &a[0] is NULL and
727 ptr = &a[6];
728 ptr -= 6;
729 ptr will be NULL here, even when there is POINTER_PLUS_EXPR
730 where the first range doesn't include zero and the second one
731 doesn't either. As the second operand is sizetype (unsigned),
732 consider all ranges where the MSB could be set as possible
733 subtractions where the result might be NULL. */
734 if ((!range_includes_zero_p (vr0)
735 || !range_includes_zero_p (vr1))
736 && !TYPE_OVERFLOW_WRAPS (expr_type)
737 && (flag_delete_null_pointer_checks
738 || (range_int_cst_p (vr1)
739 && !tree_int_cst_sign_bit (vr1->max ()))))
740 vr->set_nonzero (expr_type);
741 else if (vr0->zero_p () && vr1->zero_p ())
742 vr->set_zero (expr_type);
743 else
744 vr->set_varying (expr_type);
747 /* Extract range information from a PLUS/MINUS_EXPR and store the
748 result in *VR. */
750 static void
751 extract_range_from_plus_minus_expr (value_range *vr,
752 enum tree_code code,
753 tree expr_type,
754 const value_range *vr0_,
755 const value_range *vr1_)
757 gcc_checking_assert (code == PLUS_EXPR || code == MINUS_EXPR);
759 value_range vr0 = *vr0_, vr1 = *vr1_;
760 value_range vrtem0, vrtem1;
762 /* Now canonicalize anti-ranges to ranges when they are not symbolic
763 and express ~[] op X as ([]' op X) U ([]'' op X). */
764 if (vr0.kind () == VR_ANTI_RANGE
765 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
767 extract_range_from_plus_minus_expr (vr, code, expr_type, &vrtem0, vr1_);
768 if (!vrtem1.undefined_p ())
770 value_range vrres;
771 extract_range_from_plus_minus_expr (&vrres, code, expr_type,
772 &vrtem1, vr1_);
773 vr->union_ (&vrres);
775 return;
777 /* Likewise for X op ~[]. */
778 if (vr1.kind () == VR_ANTI_RANGE
779 && ranges_from_anti_range (&vr1, &vrtem0, &vrtem1))
781 extract_range_from_plus_minus_expr (vr, code, expr_type, vr0_, &vrtem0);
782 if (!vrtem1.undefined_p ())
784 value_range vrres;
785 extract_range_from_plus_minus_expr (&vrres, code, expr_type,
786 vr0_, &vrtem1);
787 vr->union_ (&vrres);
789 return;
792 value_range_kind kind;
793 value_range_kind vr0_kind = vr0.kind (), vr1_kind = vr1.kind ();
794 tree vr0_min = vr0.min (), vr0_max = vr0.max ();
795 tree vr1_min = vr1.min (), vr1_max = vr1.max ();
796 tree min = NULL_TREE, max = NULL_TREE;
798 /* This will normalize things such that calculating
799 [0,0] - VR_VARYING is not dropped to varying, but is
800 calculated as [MIN+1, MAX]. */
801 if (vr0.varying_p ())
803 vr0_kind = VR_RANGE;
804 vr0_min = vrp_val_min (expr_type);
805 vr0_max = vrp_val_max (expr_type);
807 if (vr1.varying_p ())
809 vr1_kind = VR_RANGE;
810 vr1_min = vrp_val_min (expr_type);
811 vr1_max = vrp_val_max (expr_type);
814 const bool minus_p = (code == MINUS_EXPR);
815 tree min_op0 = vr0_min;
816 tree min_op1 = minus_p ? vr1_max : vr1_min;
817 tree max_op0 = vr0_max;
818 tree max_op1 = minus_p ? vr1_min : vr1_max;
819 tree sym_min_op0 = NULL_TREE;
820 tree sym_min_op1 = NULL_TREE;
821 tree sym_max_op0 = NULL_TREE;
822 tree sym_max_op1 = NULL_TREE;
823 bool neg_min_op0, neg_min_op1, neg_max_op0, neg_max_op1;
825 neg_min_op0 = neg_min_op1 = neg_max_op0 = neg_max_op1 = false;
827 /* If we have a PLUS or MINUS with two VR_RANGEs, either constant or
828 single-symbolic ranges, try to compute the precise resulting range,
829 but only if we know that this resulting range will also be constant
830 or single-symbolic. */
831 if (vr0_kind == VR_RANGE && vr1_kind == VR_RANGE
832 && (TREE_CODE (min_op0) == INTEGER_CST
833 || (sym_min_op0
834 = get_single_symbol (min_op0, &neg_min_op0, &min_op0)))
835 && (TREE_CODE (min_op1) == INTEGER_CST
836 || (sym_min_op1
837 = get_single_symbol (min_op1, &neg_min_op1, &min_op1)))
838 && (!(sym_min_op0 && sym_min_op1)
839 || (sym_min_op0 == sym_min_op1
840 && neg_min_op0 == (minus_p ? neg_min_op1 : !neg_min_op1)))
841 && (TREE_CODE (max_op0) == INTEGER_CST
842 || (sym_max_op0
843 = get_single_symbol (max_op0, &neg_max_op0, &max_op0)))
844 && (TREE_CODE (max_op1) == INTEGER_CST
845 || (sym_max_op1
846 = get_single_symbol (max_op1, &neg_max_op1, &max_op1)))
847 && (!(sym_max_op0 && sym_max_op1)
848 || (sym_max_op0 == sym_max_op1
849 && neg_max_op0 == (minus_p ? neg_max_op1 : !neg_max_op1))))
851 wide_int wmin, wmax;
852 wi::overflow_type min_ovf = wi::OVF_NONE;
853 wi::overflow_type max_ovf = wi::OVF_NONE;
855 /* Build the bounds. */
856 combine_bound (code, wmin, min_ovf, expr_type, min_op0, min_op1);
857 combine_bound (code, wmax, max_ovf, expr_type, max_op0, max_op1);
859 /* If the resulting range will be symbolic, we need to eliminate any
860 explicit or implicit overflow introduced in the above computation
861 because compare_values could make an incorrect use of it. That's
862 why we require one of the ranges to be a singleton. */
863 if ((sym_min_op0 != sym_min_op1 || sym_max_op0 != sym_max_op1)
864 && ((bool)min_ovf || (bool)max_ovf
865 || (min_op0 != max_op0 && min_op1 != max_op1)))
867 vr->set_varying (expr_type);
868 return;
871 /* Adjust the range for possible overflow. */
872 set_value_range_with_overflow (kind, min, max, expr_type,
873 wmin, wmax, min_ovf, max_ovf);
874 if (kind == VR_VARYING)
876 vr->set_varying (expr_type);
877 return;
880 /* Build the symbolic bounds if needed. */
881 adjust_symbolic_bound (min, code, expr_type,
882 sym_min_op0, sym_min_op1,
883 neg_min_op0, neg_min_op1);
884 adjust_symbolic_bound (max, code, expr_type,
885 sym_max_op0, sym_max_op1,
886 neg_max_op0, neg_max_op1);
888 else
890 /* For other cases, for example if we have a PLUS_EXPR with two
891 VR_ANTI_RANGEs, drop to VR_VARYING. It would take more effort
892 to compute a precise range for such a case.
893 ??? General even mixed range kind operations can be expressed
894 by for example transforming ~[3, 5] + [1, 2] to range-only
895 operations and a union primitive:
896 [-INF, 2] + [1, 2] U [5, +INF] + [1, 2]
897 [-INF+1, 4] U [6, +INF(OVF)]
898 though usually the union is not exactly representable with
899 a single range or anti-range as the above is
900 [-INF+1, +INF(OVF)] intersected with ~[5, 5]
901 but one could use a scheme similar to equivalences for this. */
902 vr->set_varying (expr_type);
903 return;
906 /* If either MIN or MAX overflowed, then set the resulting range to
907 VARYING. */
908 if (min == NULL_TREE
909 || TREE_OVERFLOW_P (min)
910 || max == NULL_TREE
911 || TREE_OVERFLOW_P (max))
913 vr->set_varying (expr_type);
914 return;
917 int cmp = compare_values (min, max);
918 if (cmp == -2 || cmp == 1)
920 /* If the new range has its limits swapped around (MIN > MAX),
921 then the operation caused one of them to wrap around, mark
922 the new range VARYING. */
923 vr->set_varying (expr_type);
925 else
926 vr->set (min, max, kind);
929 /* Return the range-ops handler for CODE and EXPR_TYPE. If no
930 suitable operator is found, return NULL and set VR to VARYING. */
932 static const range_operator *
933 get_range_op_handler (value_range *vr,
934 enum tree_code code,
935 tree expr_type)
937 const range_operator *op = range_op_handler (code, expr_type);
938 if (!op)
939 vr->set_varying (expr_type);
940 return op;
943 /* If the types passed are supported, return TRUE, otherwise set VR to
944 VARYING and return FALSE. */
946 static bool
947 supported_types_p (value_range *vr,
948 tree type0,
949 tree type1 = NULL)
951 if (!value_range::supports_type_p (type0)
952 || (type1 && !value_range::supports_type_p (type1)))
954 vr->set_varying (type0);
955 return false;
957 return true;
960 /* If any of the ranges passed are defined, return TRUE, otherwise set
961 VR to UNDEFINED and return FALSE. */
963 static bool
964 defined_ranges_p (value_range *vr,
965 const value_range *vr0, const value_range *vr1 = NULL)
967 if (vr0->undefined_p () && (!vr1 || vr1->undefined_p ()))
969 vr->set_undefined ();
970 return false;
972 return true;
975 static value_range
976 drop_undefines_to_varying (const value_range *vr, tree expr_type)
978 if (vr->undefined_p ())
979 return value_range (expr_type);
980 else
981 return *vr;
984 /* If any operand is symbolic, perform a binary operation on them and
985 return TRUE, otherwise return FALSE. */
987 static bool
988 range_fold_binary_symbolics_p (value_range *vr,
989 tree_code code,
990 tree expr_type,
991 const value_range *vr0_,
992 const value_range *vr1_)
994 if (vr0_->symbolic_p () || vr1_->symbolic_p ())
996 value_range vr0 = drop_undefines_to_varying (vr0_, expr_type);
997 value_range vr1 = drop_undefines_to_varying (vr1_, expr_type);
998 if ((code == PLUS_EXPR || code == MINUS_EXPR))
1000 extract_range_from_plus_minus_expr (vr, code, expr_type,
1001 &vr0, &vr1);
1002 return true;
1004 if (POINTER_TYPE_P (expr_type) && code == POINTER_PLUS_EXPR)
1006 extract_range_from_pointer_plus_expr (vr, code, expr_type,
1007 &vr0, &vr1);
1008 return true;
1010 const range_operator *op = get_range_op_handler (vr, code, expr_type);
1011 vr0.normalize_symbolics ();
1012 vr1.normalize_symbolics ();
1013 return op->fold_range (*vr, expr_type, vr0, vr1);
1015 return false;
1018 /* If operand is symbolic, perform a unary operation on it and return
1019 TRUE, otherwise return FALSE. */
1021 static bool
1022 range_fold_unary_symbolics_p (value_range *vr,
1023 tree_code code,
1024 tree expr_type,
1025 const value_range *vr0)
1027 if (vr0->symbolic_p ())
1029 if (code == NEGATE_EXPR)
1031 /* -X is simply 0 - X. */
1032 value_range zero;
1033 zero.set_zero (vr0->type ());
1034 range_fold_binary_expr (vr, MINUS_EXPR, expr_type, &zero, vr0);
1035 return true;
1037 if (code == BIT_NOT_EXPR)
1039 /* ~X is simply -1 - X. */
1040 value_range minusone;
1041 minusone.set (build_int_cst (vr0->type (), -1));
1042 range_fold_binary_expr (vr, MINUS_EXPR, expr_type, &minusone, vr0);
1043 return true;
1045 const range_operator *op = get_range_op_handler (vr, code, expr_type);
1046 value_range vr0_cst (*vr0);
1047 vr0_cst.normalize_symbolics ();
1048 return op->fold_range (*vr, expr_type, vr0_cst, value_range (expr_type));
1050 return false;
1053 /* Perform a binary operation on a pair of ranges. */
1055 void
1056 range_fold_binary_expr (value_range *vr,
1057 enum tree_code code,
1058 tree expr_type,
1059 const value_range *vr0_,
1060 const value_range *vr1_)
1062 if (!supported_types_p (vr, expr_type)
1063 || !defined_ranges_p (vr, vr0_, vr1_))
1064 return;
1065 const range_operator *op = get_range_op_handler (vr, code, expr_type);
1066 if (!op)
1067 return;
1069 if (range_fold_binary_symbolics_p (vr, code, expr_type, vr0_, vr1_))
1070 return;
1072 value_range vr0 (*vr0_);
1073 value_range vr1 (*vr1_);
1074 if (vr0.undefined_p ())
1075 vr0.set_varying (expr_type);
1076 if (vr1.undefined_p ())
1077 vr1.set_varying (expr_type);
1078 vr0.normalize_addresses ();
1079 vr1.normalize_addresses ();
1080 op->fold_range (*vr, expr_type, vr0, vr1);
1083 /* Perform a unary operation on a range. */
1085 void
1086 range_fold_unary_expr (value_range *vr,
1087 enum tree_code code, tree expr_type,
1088 const value_range *vr0,
1089 tree vr0_type)
1091 if (!supported_types_p (vr, expr_type, vr0_type)
1092 || !defined_ranges_p (vr, vr0))
1093 return;
1094 const range_operator *op = get_range_op_handler (vr, code, expr_type);
1095 if (!op)
1096 return;
1098 if (range_fold_unary_symbolics_p (vr, code, expr_type, vr0))
1099 return;
1101 value_range vr0_cst (*vr0);
1102 vr0_cst.normalize_addresses ();
1103 op->fold_range (*vr, expr_type, vr0_cst, value_range (expr_type));
1106 /* If the range of values taken by OP can be inferred after STMT executes,
1107 return the comparison code (COMP_CODE_P) and value (VAL_P) that
1108 describes the inferred range. Return true if a range could be
1109 inferred. */
1111 bool
1112 infer_value_range (gimple *stmt, tree op, tree_code *comp_code_p, tree *val_p)
1114 *val_p = NULL_TREE;
1115 *comp_code_p = ERROR_MARK;
1117 /* Do not attempt to infer anything in names that flow through
1118 abnormal edges. */
1119 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
1120 return false;
1122 /* If STMT is the last statement of a basic block with no normal
1123 successors, there is no point inferring anything about any of its
1124 operands. We would not be able to find a proper insertion point
1125 for the assertion, anyway. */
1126 if (stmt_ends_bb_p (stmt))
1128 edge_iterator ei;
1129 edge e;
1131 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
1132 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
1133 break;
1134 if (e == NULL)
1135 return false;
1138 if (infer_nonnull_range (stmt, op))
1140 *val_p = build_int_cst (TREE_TYPE (op), 0);
1141 *comp_code_p = NE_EXPR;
1142 return true;
1145 return false;
1148 /* Dump assert_info structure. */
1150 void
1151 dump_assert_info (FILE *file, const assert_info &assert)
1153 fprintf (file, "Assert for: ");
1154 print_generic_expr (file, assert.name);
1155 fprintf (file, "\n\tPREDICATE: expr=[");
1156 print_generic_expr (file, assert.expr);
1157 fprintf (file, "] %s ", get_tree_code_name (assert.comp_code));
1158 fprintf (file, "val=[");
1159 print_generic_expr (file, assert.val);
1160 fprintf (file, "]\n\n");
1163 DEBUG_FUNCTION void
1164 debug (const assert_info &assert)
1166 dump_assert_info (stderr, assert);
1169 /* Dump a vector of assert_info's. */
1171 void
1172 dump_asserts_info (FILE *file, const vec<assert_info> &asserts)
1174 for (unsigned i = 0; i < asserts.length (); ++i)
1176 dump_assert_info (file, asserts[i]);
1177 fprintf (file, "\n");
1181 DEBUG_FUNCTION void
1182 debug (const vec<assert_info> &asserts)
1184 dump_asserts_info (stderr, asserts);
1187 /* Push the assert info for NAME, EXPR, COMP_CODE and VAL to ASSERTS. */
1189 static void
1190 add_assert_info (vec<assert_info> &asserts,
1191 tree name, tree expr, enum tree_code comp_code, tree val)
1193 assert_info info;
1194 info.comp_code = comp_code;
1195 info.name = name;
1196 if (TREE_OVERFLOW_P (val))
1197 val = drop_tree_overflow (val);
1198 info.val = val;
1199 info.expr = expr;
1200 asserts.safe_push (info);
1201 if (dump_enabled_p ())
1202 dump_printf (MSG_NOTE | MSG_PRIORITY_INTERNALS,
1203 "Adding assert for %T from %T %s %T\n",
1204 name, expr, op_symbol_code (comp_code), val);
1207 /* (COND_OP0 COND_CODE COND_OP1) is a predicate which uses NAME.
1208 Extract a suitable test code and value and store them into *CODE_P and
1209 *VAL_P so the predicate is normalized to NAME *CODE_P *VAL_P.
1211 If no extraction was possible, return FALSE, otherwise return TRUE.
1213 If INVERT is true, then we invert the result stored into *CODE_P. */
1215 static bool
1216 extract_code_and_val_from_cond_with_ops (tree name, enum tree_code cond_code,
1217 tree cond_op0, tree cond_op1,
1218 bool invert, enum tree_code *code_p,
1219 tree *val_p)
1221 enum tree_code comp_code;
1222 tree val;
1224 /* Otherwise, we have a comparison of the form NAME COMP VAL
1225 or VAL COMP NAME. */
1226 if (name == cond_op1)
1228 /* If the predicate is of the form VAL COMP NAME, flip
1229 COMP around because we need to register NAME as the
1230 first operand in the predicate. */
1231 comp_code = swap_tree_comparison (cond_code);
1232 val = cond_op0;
1234 else if (name == cond_op0)
1236 /* The comparison is of the form NAME COMP VAL, so the
1237 comparison code remains unchanged. */
1238 comp_code = cond_code;
1239 val = cond_op1;
1241 else
1242 gcc_unreachable ();
1244 /* Invert the comparison code as necessary. */
1245 if (invert)
1246 comp_code = invert_tree_comparison (comp_code, 0);
1248 /* VRP only handles integral and pointer types. */
1249 if (! INTEGRAL_TYPE_P (TREE_TYPE (val))
1250 && ! POINTER_TYPE_P (TREE_TYPE (val)))
1251 return false;
1253 /* Do not register always-false predicates.
1254 FIXME: this works around a limitation in fold() when dealing with
1255 enumerations. Given 'enum { N1, N2 } x;', fold will not
1256 fold 'if (x > N2)' to 'if (0)'. */
1257 if ((comp_code == GT_EXPR || comp_code == LT_EXPR)
1258 && INTEGRAL_TYPE_P (TREE_TYPE (val)))
1260 tree min = TYPE_MIN_VALUE (TREE_TYPE (val));
1261 tree max = TYPE_MAX_VALUE (TREE_TYPE (val));
1263 if (comp_code == GT_EXPR
1264 && (!max
1265 || compare_values (val, max) == 0))
1266 return false;
1268 if (comp_code == LT_EXPR
1269 && (!min
1270 || compare_values (val, min) == 0))
1271 return false;
1273 *code_p = comp_code;
1274 *val_p = val;
1275 return true;
1278 /* Find out smallest RES where RES > VAL && (RES & MASK) == RES, if any
1279 (otherwise return VAL). VAL and MASK must be zero-extended for
1280 precision PREC. If SGNBIT is non-zero, first xor VAL with SGNBIT
1281 (to transform signed values into unsigned) and at the end xor
1282 SGNBIT back. */
1284 wide_int
1285 masked_increment (const wide_int &val_in, const wide_int &mask,
1286 const wide_int &sgnbit, unsigned int prec)
1288 wide_int bit = wi::one (prec), res;
1289 unsigned int i;
1291 wide_int val = val_in ^ sgnbit;
1292 for (i = 0; i < prec; i++, bit += bit)
1294 res = mask;
1295 if ((res & bit) == 0)
1296 continue;
1297 res = bit - 1;
1298 res = wi::bit_and_not (val + bit, res);
1299 res &= mask;
1300 if (wi::gtu_p (res, val))
1301 return res ^ sgnbit;
1303 return val ^ sgnbit;
1306 /* Helper for overflow_comparison_p
1308 OP0 CODE OP1 is a comparison. Examine the comparison and potentially
1309 OP1's defining statement to see if it ultimately has the form
1310 OP0 CODE (OP0 PLUS INTEGER_CST)
1312 If so, return TRUE indicating this is an overflow test and store into
1313 *NEW_CST an updated constant that can be used in a narrowed range test.
1315 REVERSED indicates if the comparison was originally:
1317 OP1 CODE' OP0.
1319 This affects how we build the updated constant. */
1321 static bool
1322 overflow_comparison_p_1 (enum tree_code code, tree op0, tree op1,
1323 bool follow_assert_exprs, bool reversed, tree *new_cst)
1325 /* See if this is a relational operation between two SSA_NAMES with
1326 unsigned, overflow wrapping values. If so, check it more deeply. */
1327 if ((code == LT_EXPR || code == LE_EXPR
1328 || code == GE_EXPR || code == GT_EXPR)
1329 && TREE_CODE (op0) == SSA_NAME
1330 && TREE_CODE (op1) == SSA_NAME
1331 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
1332 && TYPE_UNSIGNED (TREE_TYPE (op0))
1333 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0)))
1335 gimple *op1_def = SSA_NAME_DEF_STMT (op1);
1337 /* If requested, follow any ASSERT_EXPRs backwards for OP1. */
1338 if (follow_assert_exprs)
1340 while (gimple_assign_single_p (op1_def)
1341 && TREE_CODE (gimple_assign_rhs1 (op1_def)) == ASSERT_EXPR)
1343 op1 = TREE_OPERAND (gimple_assign_rhs1 (op1_def), 0);
1344 if (TREE_CODE (op1) != SSA_NAME)
1345 break;
1346 op1_def = SSA_NAME_DEF_STMT (op1);
1350 /* Now look at the defining statement of OP1 to see if it adds
1351 or subtracts a nonzero constant from another operand. */
1352 if (op1_def
1353 && is_gimple_assign (op1_def)
1354 && gimple_assign_rhs_code (op1_def) == PLUS_EXPR
1355 && TREE_CODE (gimple_assign_rhs2 (op1_def)) == INTEGER_CST
1356 && !integer_zerop (gimple_assign_rhs2 (op1_def)))
1358 tree target = gimple_assign_rhs1 (op1_def);
1360 /* If requested, follow ASSERT_EXPRs backwards for op0 looking
1361 for one where TARGET appears on the RHS. */
1362 if (follow_assert_exprs)
1364 /* Now see if that "other operand" is op0, following the chain
1365 of ASSERT_EXPRs if necessary. */
1366 gimple *op0_def = SSA_NAME_DEF_STMT (op0);
1367 while (op0 != target
1368 && gimple_assign_single_p (op0_def)
1369 && TREE_CODE (gimple_assign_rhs1 (op0_def)) == ASSERT_EXPR)
1371 op0 = TREE_OPERAND (gimple_assign_rhs1 (op0_def), 0);
1372 if (TREE_CODE (op0) != SSA_NAME)
1373 break;
1374 op0_def = SSA_NAME_DEF_STMT (op0);
1378 /* If we did not find our target SSA_NAME, then this is not
1379 an overflow test. */
1380 if (op0 != target)
1381 return false;
1383 tree type = TREE_TYPE (op0);
1384 wide_int max = wi::max_value (TYPE_PRECISION (type), UNSIGNED);
1385 tree inc = gimple_assign_rhs2 (op1_def);
1386 if (reversed)
1387 *new_cst = wide_int_to_tree (type, max + wi::to_wide (inc));
1388 else
1389 *new_cst = wide_int_to_tree (type, max - wi::to_wide (inc));
1390 return true;
1393 return false;
1396 /* OP0 CODE OP1 is a comparison. Examine the comparison and potentially
1397 OP1's defining statement to see if it ultimately has the form
1398 OP0 CODE (OP0 PLUS INTEGER_CST)
1400 If so, return TRUE indicating this is an overflow test and store into
1401 *NEW_CST an updated constant that can be used in a narrowed range test.
1403 These statements are left as-is in the IL to facilitate discovery of
1404 {ADD,SUB}_OVERFLOW sequences later in the optimizer pipeline. But
1405 the alternate range representation is often useful within VRP. */
1407 bool
1408 overflow_comparison_p (tree_code code, tree name, tree val,
1409 bool use_equiv_p, tree *new_cst)
1411 if (overflow_comparison_p_1 (code, name, val, use_equiv_p, false, new_cst))
1412 return true;
1413 return overflow_comparison_p_1 (swap_tree_comparison (code), val, name,
1414 use_equiv_p, true, new_cst);
1418 /* Try to register an edge assertion for SSA name NAME on edge E for
1419 the condition COND contributing to the conditional jump pointed to by BSI.
1420 Invert the condition COND if INVERT is true. */
1422 static void
1423 register_edge_assert_for_2 (tree name, edge e,
1424 enum tree_code cond_code,
1425 tree cond_op0, tree cond_op1, bool invert,
1426 vec<assert_info> &asserts)
1428 tree val;
1429 enum tree_code comp_code;
1431 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
1432 cond_op0,
1433 cond_op1,
1434 invert, &comp_code, &val))
1435 return;
1437 /* Queue the assert. */
1438 tree x;
1439 if (overflow_comparison_p (comp_code, name, val, false, &x))
1441 enum tree_code new_code = ((comp_code == GT_EXPR || comp_code == GE_EXPR)
1442 ? GT_EXPR : LE_EXPR);
1443 add_assert_info (asserts, name, name, new_code, x);
1445 add_assert_info (asserts, name, name, comp_code, val);
1447 /* In the case of NAME <= CST and NAME being defined as
1448 NAME = (unsigned) NAME2 + CST2 we can assert NAME2 >= -CST2
1449 and NAME2 <= CST - CST2. We can do the same for NAME > CST.
1450 This catches range and anti-range tests. */
1451 if ((comp_code == LE_EXPR
1452 || comp_code == GT_EXPR)
1453 && TREE_CODE (val) == INTEGER_CST
1454 && TYPE_UNSIGNED (TREE_TYPE (val)))
1456 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
1457 tree cst2 = NULL_TREE, name2 = NULL_TREE, name3 = NULL_TREE;
1459 /* Extract CST2 from the (optional) addition. */
1460 if (is_gimple_assign (def_stmt)
1461 && gimple_assign_rhs_code (def_stmt) == PLUS_EXPR)
1463 name2 = gimple_assign_rhs1 (def_stmt);
1464 cst2 = gimple_assign_rhs2 (def_stmt);
1465 if (TREE_CODE (name2) == SSA_NAME
1466 && TREE_CODE (cst2) == INTEGER_CST)
1467 def_stmt = SSA_NAME_DEF_STMT (name2);
1470 /* Extract NAME2 from the (optional) sign-changing cast. */
1471 if (gassign *ass = dyn_cast <gassign *> (def_stmt))
1473 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (ass))
1474 && ! TYPE_UNSIGNED (TREE_TYPE (gimple_assign_rhs1 (ass)))
1475 && (TYPE_PRECISION (TREE_TYPE (gimple_assign_lhs (ass)))
1476 == TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (ass)))))
1477 name3 = gimple_assign_rhs1 (ass);
1480 /* If name3 is used later, create an ASSERT_EXPR for it. */
1481 if (name3 != NULL_TREE
1482 && TREE_CODE (name3) == SSA_NAME
1483 && (cst2 == NULL_TREE
1484 || TREE_CODE (cst2) == INTEGER_CST)
1485 && INTEGRAL_TYPE_P (TREE_TYPE (name3)))
1487 tree tmp;
1489 /* Build an expression for the range test. */
1490 tmp = build1 (NOP_EXPR, TREE_TYPE (name), name3);
1491 if (cst2 != NULL_TREE)
1492 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
1493 add_assert_info (asserts, name3, tmp, comp_code, val);
1496 /* If name2 is used later, create an ASSERT_EXPR for it. */
1497 if (name2 != NULL_TREE
1498 && TREE_CODE (name2) == SSA_NAME
1499 && TREE_CODE (cst2) == INTEGER_CST
1500 && INTEGRAL_TYPE_P (TREE_TYPE (name2)))
1502 tree tmp;
1504 /* Build an expression for the range test. */
1505 tmp = name2;
1506 if (TREE_TYPE (name) != TREE_TYPE (name2))
1507 tmp = build1 (NOP_EXPR, TREE_TYPE (name), tmp);
1508 if (cst2 != NULL_TREE)
1509 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
1510 add_assert_info (asserts, name2, tmp, comp_code, val);
1514 /* In the case of post-in/decrement tests like if (i++) ... and uses
1515 of the in/decremented value on the edge the extra name we want to
1516 assert for is not on the def chain of the name compared. Instead
1517 it is in the set of use stmts.
1518 Similar cases happen for conversions that were simplified through
1519 fold_{sign_changed,widened}_comparison. */
1520 if ((comp_code == NE_EXPR
1521 || comp_code == EQ_EXPR)
1522 && TREE_CODE (val) == INTEGER_CST)
1524 imm_use_iterator ui;
1525 gimple *use_stmt;
1526 FOR_EACH_IMM_USE_STMT (use_stmt, ui, name)
1528 if (!is_gimple_assign (use_stmt))
1529 continue;
1531 /* Cut off to use-stmts that are dominating the predecessor. */
1532 if (!dominated_by_p (CDI_DOMINATORS, e->src, gimple_bb (use_stmt)))
1533 continue;
1535 tree name2 = gimple_assign_lhs (use_stmt);
1536 if (TREE_CODE (name2) != SSA_NAME)
1537 continue;
1539 enum tree_code code = gimple_assign_rhs_code (use_stmt);
1540 tree cst;
1541 if (code == PLUS_EXPR
1542 || code == MINUS_EXPR)
1544 cst = gimple_assign_rhs2 (use_stmt);
1545 if (TREE_CODE (cst) != INTEGER_CST)
1546 continue;
1547 cst = int_const_binop (code, val, cst);
1549 else if (CONVERT_EXPR_CODE_P (code))
1551 /* For truncating conversions we cannot record
1552 an inequality. */
1553 if (comp_code == NE_EXPR
1554 && (TYPE_PRECISION (TREE_TYPE (name2))
1555 < TYPE_PRECISION (TREE_TYPE (name))))
1556 continue;
1557 cst = fold_convert (TREE_TYPE (name2), val);
1559 else
1560 continue;
1562 if (TREE_OVERFLOW_P (cst))
1563 cst = drop_tree_overflow (cst);
1564 add_assert_info (asserts, name2, name2, comp_code, cst);
1568 if (TREE_CODE_CLASS (comp_code) == tcc_comparison
1569 && TREE_CODE (val) == INTEGER_CST)
1571 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
1572 tree name2 = NULL_TREE, names[2], cst2 = NULL_TREE;
1573 tree val2 = NULL_TREE;
1574 unsigned int prec = TYPE_PRECISION (TREE_TYPE (val));
1575 wide_int mask = wi::zero (prec);
1576 unsigned int nprec = prec;
1577 enum tree_code rhs_code = ERROR_MARK;
1579 if (is_gimple_assign (def_stmt))
1580 rhs_code = gimple_assign_rhs_code (def_stmt);
1582 /* In the case of NAME != CST1 where NAME = A +- CST2 we can
1583 assert that A != CST1 -+ CST2. */
1584 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
1585 && (rhs_code == PLUS_EXPR || rhs_code == MINUS_EXPR))
1587 tree op0 = gimple_assign_rhs1 (def_stmt);
1588 tree op1 = gimple_assign_rhs2 (def_stmt);
1589 if (TREE_CODE (op0) == SSA_NAME
1590 && TREE_CODE (op1) == INTEGER_CST)
1592 enum tree_code reverse_op = (rhs_code == PLUS_EXPR
1593 ? MINUS_EXPR : PLUS_EXPR);
1594 op1 = int_const_binop (reverse_op, val, op1);
1595 if (TREE_OVERFLOW (op1))
1596 op1 = drop_tree_overflow (op1);
1597 add_assert_info (asserts, op0, op0, comp_code, op1);
1601 /* Add asserts for NAME cmp CST and NAME being defined
1602 as NAME = (int) NAME2. */
1603 if (!TYPE_UNSIGNED (TREE_TYPE (val))
1604 && (comp_code == LE_EXPR || comp_code == LT_EXPR
1605 || comp_code == GT_EXPR || comp_code == GE_EXPR)
1606 && gimple_assign_cast_p (def_stmt))
1608 name2 = gimple_assign_rhs1 (def_stmt);
1609 if (CONVERT_EXPR_CODE_P (rhs_code)
1610 && TREE_CODE (name2) == SSA_NAME
1611 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
1612 && TYPE_UNSIGNED (TREE_TYPE (name2))
1613 && prec == TYPE_PRECISION (TREE_TYPE (name2))
1614 && (comp_code == LE_EXPR || comp_code == GT_EXPR
1615 || !tree_int_cst_equal (val,
1616 TYPE_MIN_VALUE (TREE_TYPE (val)))))
1618 tree tmp, cst;
1619 enum tree_code new_comp_code = comp_code;
1621 cst = fold_convert (TREE_TYPE (name2),
1622 TYPE_MIN_VALUE (TREE_TYPE (val)));
1623 /* Build an expression for the range test. */
1624 tmp = build2 (PLUS_EXPR, TREE_TYPE (name2), name2, cst);
1625 cst = fold_build2 (PLUS_EXPR, TREE_TYPE (name2), cst,
1626 fold_convert (TREE_TYPE (name2), val));
1627 if (comp_code == LT_EXPR || comp_code == GE_EXPR)
1629 new_comp_code = comp_code == LT_EXPR ? LE_EXPR : GT_EXPR;
1630 cst = fold_build2 (MINUS_EXPR, TREE_TYPE (name2), cst,
1631 build_int_cst (TREE_TYPE (name2), 1));
1633 add_assert_info (asserts, name2, tmp, new_comp_code, cst);
1637 /* Add asserts for NAME cmp CST and NAME being defined as
1638 NAME = NAME2 >> CST2.
1640 Extract CST2 from the right shift. */
1641 if (rhs_code == RSHIFT_EXPR)
1643 name2 = gimple_assign_rhs1 (def_stmt);
1644 cst2 = gimple_assign_rhs2 (def_stmt);
1645 if (TREE_CODE (name2) == SSA_NAME
1646 && tree_fits_uhwi_p (cst2)
1647 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
1648 && IN_RANGE (tree_to_uhwi (cst2), 1, prec - 1)
1649 && type_has_mode_precision_p (TREE_TYPE (val)))
1651 mask = wi::mask (tree_to_uhwi (cst2), false, prec);
1652 val2 = fold_binary (LSHIFT_EXPR, TREE_TYPE (val), val, cst2);
1655 if (val2 != NULL_TREE
1656 && TREE_CODE (val2) == INTEGER_CST
1657 && simple_cst_equal (fold_build2 (RSHIFT_EXPR,
1658 TREE_TYPE (val),
1659 val2, cst2), val))
1661 enum tree_code new_comp_code = comp_code;
1662 tree tmp, new_val;
1664 tmp = name2;
1665 if (comp_code == EQ_EXPR || comp_code == NE_EXPR)
1667 if (!TYPE_UNSIGNED (TREE_TYPE (val)))
1669 tree type = build_nonstandard_integer_type (prec, 1);
1670 tmp = build1 (NOP_EXPR, type, name2);
1671 val2 = fold_convert (type, val2);
1673 tmp = fold_build2 (MINUS_EXPR, TREE_TYPE (tmp), tmp, val2);
1674 new_val = wide_int_to_tree (TREE_TYPE (tmp), mask);
1675 new_comp_code = comp_code == EQ_EXPR ? LE_EXPR : GT_EXPR;
1677 else if (comp_code == LT_EXPR || comp_code == GE_EXPR)
1679 wide_int minval
1680 = wi::min_value (prec, TYPE_SIGN (TREE_TYPE (val)));
1681 new_val = val2;
1682 if (minval == wi::to_wide (new_val))
1683 new_val = NULL_TREE;
1685 else
1687 wide_int maxval
1688 = wi::max_value (prec, TYPE_SIGN (TREE_TYPE (val)));
1689 mask |= wi::to_wide (val2);
1690 if (wi::eq_p (mask, maxval))
1691 new_val = NULL_TREE;
1692 else
1693 new_val = wide_int_to_tree (TREE_TYPE (val2), mask);
1696 if (new_val)
1697 add_assert_info (asserts, name2, tmp, new_comp_code, new_val);
1700 /* If we have a conversion that doesn't change the value of the source
1701 simply register the same assert for it. */
1702 if (CONVERT_EXPR_CODE_P (rhs_code))
1704 value_range vr;
1705 tree rhs1 = gimple_assign_rhs1 (def_stmt);
1706 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1))
1707 && TREE_CODE (rhs1) == SSA_NAME
1708 /* Make sure the relation preserves the upper/lower boundary of
1709 the range conservatively. */
1710 && (comp_code == NE_EXPR
1711 || comp_code == EQ_EXPR
1712 || (TYPE_SIGN (TREE_TYPE (name))
1713 == TYPE_SIGN (TREE_TYPE (rhs1)))
1714 || ((comp_code == LE_EXPR
1715 || comp_code == LT_EXPR)
1716 && !TYPE_UNSIGNED (TREE_TYPE (rhs1)))
1717 || ((comp_code == GE_EXPR
1718 || comp_code == GT_EXPR)
1719 && TYPE_UNSIGNED (TREE_TYPE (rhs1))))
1720 /* And the conversion does not alter the value we compare
1721 against and all values in rhs1 can be represented in
1722 the converted to type. */
1723 && int_fits_type_p (val, TREE_TYPE (rhs1))
1724 && ((TYPE_PRECISION (TREE_TYPE (name))
1725 > TYPE_PRECISION (TREE_TYPE (rhs1)))
1726 || ((get_range_query (cfun)->range_of_expr (vr, rhs1)
1727 && vr.kind () == VR_RANGE)
1728 && wi::fits_to_tree_p
1729 (widest_int::from (vr.lower_bound (),
1730 TYPE_SIGN (TREE_TYPE (rhs1))),
1731 TREE_TYPE (name))
1732 && wi::fits_to_tree_p
1733 (widest_int::from (vr.upper_bound (),
1734 TYPE_SIGN (TREE_TYPE (rhs1))),
1735 TREE_TYPE (name)))))
1736 add_assert_info (asserts, rhs1, rhs1,
1737 comp_code, fold_convert (TREE_TYPE (rhs1), val));
1740 /* Add asserts for NAME cmp CST and NAME being defined as
1741 NAME = NAME2 & CST2.
1743 Extract CST2 from the and.
1745 Also handle
1746 NAME = (unsigned) NAME2;
1747 casts where NAME's type is unsigned and has smaller precision
1748 than NAME2's type as if it was NAME = NAME2 & MASK. */
1749 names[0] = NULL_TREE;
1750 names[1] = NULL_TREE;
1751 cst2 = NULL_TREE;
1752 if (rhs_code == BIT_AND_EXPR
1753 || (CONVERT_EXPR_CODE_P (rhs_code)
1754 && INTEGRAL_TYPE_P (TREE_TYPE (val))
1755 && TYPE_UNSIGNED (TREE_TYPE (val))
1756 && TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
1757 > prec))
1759 name2 = gimple_assign_rhs1 (def_stmt);
1760 if (rhs_code == BIT_AND_EXPR)
1761 cst2 = gimple_assign_rhs2 (def_stmt);
1762 else
1764 cst2 = TYPE_MAX_VALUE (TREE_TYPE (val));
1765 nprec = TYPE_PRECISION (TREE_TYPE (name2));
1767 if (TREE_CODE (name2) == SSA_NAME
1768 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
1769 && TREE_CODE (cst2) == INTEGER_CST
1770 && !integer_zerop (cst2)
1771 && (nprec > 1
1772 || TYPE_UNSIGNED (TREE_TYPE (val))))
1774 gimple *def_stmt2 = SSA_NAME_DEF_STMT (name2);
1775 if (gimple_assign_cast_p (def_stmt2))
1777 names[1] = gimple_assign_rhs1 (def_stmt2);
1778 if (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt2))
1779 || TREE_CODE (names[1]) != SSA_NAME
1780 || !INTEGRAL_TYPE_P (TREE_TYPE (names[1]))
1781 || (TYPE_PRECISION (TREE_TYPE (name2))
1782 != TYPE_PRECISION (TREE_TYPE (names[1]))))
1783 names[1] = NULL_TREE;
1785 names[0] = name2;
1788 if (names[0] || names[1])
1790 wide_int minv, maxv, valv, cst2v;
1791 wide_int tem, sgnbit;
1792 bool valid_p = false, valn, cst2n;
1793 enum tree_code ccode = comp_code;
1795 valv = wide_int::from (wi::to_wide (val), nprec, UNSIGNED);
1796 cst2v = wide_int::from (wi::to_wide (cst2), nprec, UNSIGNED);
1797 valn = wi::neg_p (valv, TYPE_SIGN (TREE_TYPE (val)));
1798 cst2n = wi::neg_p (cst2v, TYPE_SIGN (TREE_TYPE (val)));
1799 /* If CST2 doesn't have most significant bit set,
1800 but VAL is negative, we have comparison like
1801 if ((x & 0x123) > -4) (always true). Just give up. */
1802 if (!cst2n && valn)
1803 ccode = ERROR_MARK;
1804 if (cst2n)
1805 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
1806 else
1807 sgnbit = wi::zero (nprec);
1808 minv = valv & cst2v;
1809 switch (ccode)
1811 case EQ_EXPR:
1812 /* Minimum unsigned value for equality is VAL & CST2
1813 (should be equal to VAL, otherwise we probably should
1814 have folded the comparison into false) and
1815 maximum unsigned value is VAL | ~CST2. */
1816 maxv = valv | ~cst2v;
1817 valid_p = true;
1818 break;
1820 case NE_EXPR:
1821 tem = valv | ~cst2v;
1822 /* If VAL is 0, handle (X & CST2) != 0 as (X & CST2) > 0U. */
1823 if (valv == 0)
1825 cst2n = false;
1826 sgnbit = wi::zero (nprec);
1827 goto gt_expr;
1829 /* If (VAL | ~CST2) is all ones, handle it as
1830 (X & CST2) < VAL. */
1831 if (tem == -1)
1833 cst2n = false;
1834 valn = false;
1835 sgnbit = wi::zero (nprec);
1836 goto lt_expr;
1838 if (!cst2n && wi::neg_p (cst2v))
1839 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
1840 if (sgnbit != 0)
1842 if (valv == sgnbit)
1844 cst2n = true;
1845 valn = true;
1846 goto gt_expr;
1848 if (tem == wi::mask (nprec - 1, false, nprec))
1850 cst2n = true;
1851 goto lt_expr;
1853 if (!cst2n)
1854 sgnbit = wi::zero (nprec);
1856 break;
1858 case GE_EXPR:
1859 /* Minimum unsigned value for >= if (VAL & CST2) == VAL
1860 is VAL and maximum unsigned value is ~0. For signed
1861 comparison, if CST2 doesn't have most significant bit
1862 set, handle it similarly. If CST2 has MSB set,
1863 the minimum is the same, and maximum is ~0U/2. */
1864 if (minv != valv)
1866 /* If (VAL & CST2) != VAL, X & CST2 can't be equal to
1867 VAL. */
1868 minv = masked_increment (valv, cst2v, sgnbit, nprec);
1869 if (minv == valv)
1870 break;
1872 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
1873 valid_p = true;
1874 break;
1876 case GT_EXPR:
1877 gt_expr:
1878 /* Find out smallest MINV where MINV > VAL
1879 && (MINV & CST2) == MINV, if any. If VAL is signed and
1880 CST2 has MSB set, compute it biased by 1 << (nprec - 1). */
1881 minv = masked_increment (valv, cst2v, sgnbit, nprec);
1882 if (minv == valv)
1883 break;
1884 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
1885 valid_p = true;
1886 break;
1888 case LE_EXPR:
1889 /* Minimum unsigned value for <= is 0 and maximum
1890 unsigned value is VAL | ~CST2 if (VAL & CST2) == VAL.
1891 Otherwise, find smallest VAL2 where VAL2 > VAL
1892 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
1893 as maximum.
1894 For signed comparison, if CST2 doesn't have most
1895 significant bit set, handle it similarly. If CST2 has
1896 MSB set, the maximum is the same and minimum is INT_MIN. */
1897 if (minv == valv)
1898 maxv = valv;
1899 else
1901 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
1902 if (maxv == valv)
1903 break;
1904 maxv -= 1;
1906 maxv |= ~cst2v;
1907 minv = sgnbit;
1908 valid_p = true;
1909 break;
1911 case LT_EXPR:
1912 lt_expr:
1913 /* Minimum unsigned value for < is 0 and maximum
1914 unsigned value is (VAL-1) | ~CST2 if (VAL & CST2) == VAL.
1915 Otherwise, find smallest VAL2 where VAL2 > VAL
1916 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
1917 as maximum.
1918 For signed comparison, if CST2 doesn't have most
1919 significant bit set, handle it similarly. If CST2 has
1920 MSB set, the maximum is the same and minimum is INT_MIN. */
1921 if (minv == valv)
1923 if (valv == sgnbit)
1924 break;
1925 maxv = valv;
1927 else
1929 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
1930 if (maxv == valv)
1931 break;
1933 maxv -= 1;
1934 maxv |= ~cst2v;
1935 minv = sgnbit;
1936 valid_p = true;
1937 break;
1939 default:
1940 break;
1942 if (valid_p
1943 && (maxv - minv) != -1)
1945 tree tmp, new_val, type;
1946 int i;
1948 for (i = 0; i < 2; i++)
1949 if (names[i])
1951 wide_int maxv2 = maxv;
1952 tmp = names[i];
1953 type = TREE_TYPE (names[i]);
1954 if (!TYPE_UNSIGNED (type))
1956 type = build_nonstandard_integer_type (nprec, 1);
1957 tmp = build1 (NOP_EXPR, type, names[i]);
1959 if (minv != 0)
1961 tmp = build2 (PLUS_EXPR, type, tmp,
1962 wide_int_to_tree (type, -minv));
1963 maxv2 = maxv - minv;
1965 new_val = wide_int_to_tree (type, maxv2);
1966 add_assert_info (asserts, names[i], tmp, LE_EXPR, new_val);
1973 /* OP is an operand of a truth value expression which is known to have
1974 a particular value. Register any asserts for OP and for any
1975 operands in OP's defining statement.
1977 If CODE is EQ_EXPR, then we want to register OP is zero (false),
1978 if CODE is NE_EXPR, then we want to register OP is nonzero (true). */
1980 static void
1981 register_edge_assert_for_1 (tree op, enum tree_code code,
1982 edge e, vec<assert_info> &asserts)
1984 gimple *op_def;
1985 tree val;
1986 enum tree_code rhs_code;
1988 /* We only care about SSA_NAMEs. */
1989 if (TREE_CODE (op) != SSA_NAME)
1990 return;
1992 /* We know that OP will have a zero or nonzero value. */
1993 val = build_int_cst (TREE_TYPE (op), 0);
1994 add_assert_info (asserts, op, op, code, val);
1996 /* Now look at how OP is set. If it's set from a comparison,
1997 a truth operation or some bit operations, then we may be able
1998 to register information about the operands of that assignment. */
1999 op_def = SSA_NAME_DEF_STMT (op);
2000 if (gimple_code (op_def) != GIMPLE_ASSIGN)
2001 return;
2003 rhs_code = gimple_assign_rhs_code (op_def);
2005 if (TREE_CODE_CLASS (rhs_code) == tcc_comparison)
2007 bool invert = (code == EQ_EXPR ? true : false);
2008 tree op0 = gimple_assign_rhs1 (op_def);
2009 tree op1 = gimple_assign_rhs2 (op_def);
2011 if (TREE_CODE (op0) == SSA_NAME)
2012 register_edge_assert_for_2 (op0, e, rhs_code, op0, op1, invert, asserts);
2013 if (TREE_CODE (op1) == SSA_NAME)
2014 register_edge_assert_for_2 (op1, e, rhs_code, op0, op1, invert, asserts);
2016 else if ((code == NE_EXPR
2017 && gimple_assign_rhs_code (op_def) == BIT_AND_EXPR)
2018 || (code == EQ_EXPR
2019 && gimple_assign_rhs_code (op_def) == BIT_IOR_EXPR))
2021 /* Recurse on each operand. */
2022 tree op0 = gimple_assign_rhs1 (op_def);
2023 tree op1 = gimple_assign_rhs2 (op_def);
2024 if (TREE_CODE (op0) == SSA_NAME
2025 && has_single_use (op0))
2026 register_edge_assert_for_1 (op0, code, e, asserts);
2027 if (TREE_CODE (op1) == SSA_NAME
2028 && has_single_use (op1))
2029 register_edge_assert_for_1 (op1, code, e, asserts);
2031 else if (gimple_assign_rhs_code (op_def) == BIT_NOT_EXPR
2032 && TYPE_PRECISION (TREE_TYPE (gimple_assign_lhs (op_def))) == 1)
2034 /* Recurse, flipping CODE. */
2035 code = invert_tree_comparison (code, false);
2036 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
2038 else if (gimple_assign_rhs_code (op_def) == SSA_NAME)
2040 /* Recurse through the copy. */
2041 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
2043 else if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (op_def)))
2045 /* Recurse through the type conversion, unless it is a narrowing
2046 conversion or conversion from non-integral type. */
2047 tree rhs = gimple_assign_rhs1 (op_def);
2048 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs))
2049 && (TYPE_PRECISION (TREE_TYPE (rhs))
2050 <= TYPE_PRECISION (TREE_TYPE (op))))
2051 register_edge_assert_for_1 (rhs, code, e, asserts);
2055 /* Check if comparison
2056 NAME COND_OP INTEGER_CST
2057 has a form of
2058 (X & 11...100..0) COND_OP XX...X00...0
2059 Such comparison can yield assertions like
2060 X >= XX...X00...0
2061 X <= XX...X11...1
2062 in case of COND_OP being EQ_EXPR or
2063 X < XX...X00...0
2064 X > XX...X11...1
2065 in case of NE_EXPR. */
2067 static bool
2068 is_masked_range_test (tree name, tree valt, enum tree_code cond_code,
2069 tree *new_name, tree *low, enum tree_code *low_code,
2070 tree *high, enum tree_code *high_code)
2072 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
2074 if (!is_gimple_assign (def_stmt)
2075 || gimple_assign_rhs_code (def_stmt) != BIT_AND_EXPR)
2076 return false;
2078 tree t = gimple_assign_rhs1 (def_stmt);
2079 tree maskt = gimple_assign_rhs2 (def_stmt);
2080 if (TREE_CODE (t) != SSA_NAME || TREE_CODE (maskt) != INTEGER_CST)
2081 return false;
2083 wi::tree_to_wide_ref mask = wi::to_wide (maskt);
2084 wide_int inv_mask = ~mask;
2085 /* Must have been removed by now so don't bother optimizing. */
2086 if (mask == 0 || inv_mask == 0)
2087 return false;
2089 /* Assume VALT is INTEGER_CST. */
2090 wi::tree_to_wide_ref val = wi::to_wide (valt);
2092 if ((inv_mask & (inv_mask + 1)) != 0
2093 || (val & mask) != val)
2094 return false;
2096 bool is_range = cond_code == EQ_EXPR;
2098 tree type = TREE_TYPE (t);
2099 wide_int min = wi::min_value (type),
2100 max = wi::max_value (type);
2102 if (is_range)
2104 *low_code = val == min ? ERROR_MARK : GE_EXPR;
2105 *high_code = val == max ? ERROR_MARK : LE_EXPR;
2107 else
2109 /* We can still generate assertion if one of alternatives
2110 is known to always be false. */
2111 if (val == min)
2113 *low_code = (enum tree_code) 0;
2114 *high_code = GT_EXPR;
2116 else if ((val | inv_mask) == max)
2118 *low_code = LT_EXPR;
2119 *high_code = (enum tree_code) 0;
2121 else
2122 return false;
2125 *new_name = t;
2126 *low = wide_int_to_tree (type, val);
2127 *high = wide_int_to_tree (type, val | inv_mask);
2129 return true;
2132 /* Try to register an edge assertion for SSA name NAME on edge E for
2133 the condition COND contributing to the conditional jump pointed to by
2134 SI. */
2136 void
2137 register_edge_assert_for (tree name, edge e,
2138 enum tree_code cond_code, tree cond_op0,
2139 tree cond_op1, vec<assert_info> &asserts)
2141 tree val;
2142 enum tree_code comp_code;
2143 bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
2145 /* Do not attempt to infer anything in names that flow through
2146 abnormal edges. */
2147 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
2148 return;
2150 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
2151 cond_op0, cond_op1,
2152 is_else_edge,
2153 &comp_code, &val))
2154 return;
2156 /* Register ASSERT_EXPRs for name. */
2157 register_edge_assert_for_2 (name, e, cond_code, cond_op0,
2158 cond_op1, is_else_edge, asserts);
2161 /* If COND is effectively an equality test of an SSA_NAME against
2162 the value zero or one, then we may be able to assert values
2163 for SSA_NAMEs which flow into COND. */
2165 /* In the case of NAME == 1 or NAME != 0, for BIT_AND_EXPR defining
2166 statement of NAME we can assert both operands of the BIT_AND_EXPR
2167 have nonzero value. */
2168 if ((comp_code == EQ_EXPR && integer_onep (val))
2169 || (comp_code == NE_EXPR && integer_zerop (val)))
2171 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
2173 if (is_gimple_assign (def_stmt)
2174 && gimple_assign_rhs_code (def_stmt) == BIT_AND_EXPR)
2176 tree op0 = gimple_assign_rhs1 (def_stmt);
2177 tree op1 = gimple_assign_rhs2 (def_stmt);
2178 register_edge_assert_for_1 (op0, NE_EXPR, e, asserts);
2179 register_edge_assert_for_1 (op1, NE_EXPR, e, asserts);
2181 else if (is_gimple_assign (def_stmt)
2182 && (TREE_CODE_CLASS (gimple_assign_rhs_code (def_stmt))
2183 == tcc_comparison))
2184 register_edge_assert_for_1 (name, NE_EXPR, e, asserts);
2187 /* In the case of NAME == 0 or NAME != 1, for BIT_IOR_EXPR defining
2188 statement of NAME we can assert both operands of the BIT_IOR_EXPR
2189 have zero value. */
2190 if ((comp_code == EQ_EXPR && integer_zerop (val))
2191 || (comp_code == NE_EXPR
2192 && integer_onep (val)
2193 && TYPE_PRECISION (TREE_TYPE (name)) == 1))
2195 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
2197 /* For BIT_IOR_EXPR only if NAME == 0 both operands have
2198 necessarily zero value, or if type-precision is one. */
2199 if (is_gimple_assign (def_stmt)
2200 && gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR)
2202 tree op0 = gimple_assign_rhs1 (def_stmt);
2203 tree op1 = gimple_assign_rhs2 (def_stmt);
2204 register_edge_assert_for_1 (op0, EQ_EXPR, e, asserts);
2205 register_edge_assert_for_1 (op1, EQ_EXPR, e, asserts);
2207 else if (is_gimple_assign (def_stmt)
2208 && (TREE_CODE_CLASS (gimple_assign_rhs_code (def_stmt))
2209 == tcc_comparison))
2210 register_edge_assert_for_1 (name, EQ_EXPR, e, asserts);
2213 /* Sometimes we can infer ranges from (NAME & MASK) == VALUE. */
2214 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
2215 && TREE_CODE (val) == INTEGER_CST)
2217 enum tree_code low_code, high_code;
2218 tree low, high;
2219 if (is_masked_range_test (name, val, comp_code, &name, &low,
2220 &low_code, &high, &high_code))
2222 if (low_code != ERROR_MARK)
2223 register_edge_assert_for_2 (name, e, low_code, name,
2224 low, /*invert*/false, asserts);
2225 if (high_code != ERROR_MARK)
2226 register_edge_assert_for_2 (name, e, high_code, name,
2227 high, /*invert*/false, asserts);
2232 /* Handle
2233 _4 = x_3 & 31;
2234 if (_4 != 0)
2235 goto <bb 6>;
2236 else
2237 goto <bb 7>;
2238 <bb 6>:
2239 __builtin_unreachable ();
2240 <bb 7>:
2241 x_5 = ASSERT_EXPR <x_3, ...>;
2242 If x_3 has no other immediate uses (checked by caller),
2243 var is the x_3 var from ASSERT_EXPR, we can clear low 5 bits
2244 from the non-zero bitmask. */
2246 void
2247 maybe_set_nonzero_bits (edge e, tree var)
2249 basic_block cond_bb = e->src;
2250 gimple *stmt = last_stmt (cond_bb);
2251 tree cst;
2253 if (stmt == NULL
2254 || gimple_code (stmt) != GIMPLE_COND
2255 || gimple_cond_code (stmt) != ((e->flags & EDGE_TRUE_VALUE)
2256 ? EQ_EXPR : NE_EXPR)
2257 || TREE_CODE (gimple_cond_lhs (stmt)) != SSA_NAME
2258 || !integer_zerop (gimple_cond_rhs (stmt)))
2259 return;
2261 stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt));
2262 if (!is_gimple_assign (stmt)
2263 || gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
2264 || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
2265 return;
2266 if (gimple_assign_rhs1 (stmt) != var)
2268 gimple *stmt2;
2270 if (TREE_CODE (gimple_assign_rhs1 (stmt)) != SSA_NAME)
2271 return;
2272 stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
2273 if (!gimple_assign_cast_p (stmt2)
2274 || gimple_assign_rhs1 (stmt2) != var
2275 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt2))
2276 || (TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (stmt)))
2277 != TYPE_PRECISION (TREE_TYPE (var))))
2278 return;
2280 cst = gimple_assign_rhs2 (stmt);
2281 set_nonzero_bits (var, wi::bit_and_not (get_nonzero_bits (var),
2282 wi::to_wide (cst)));
2285 /* Return true if STMT is interesting for VRP. */
2287 bool
2288 stmt_interesting_for_vrp (gimple *stmt)
2290 if (gimple_code (stmt) == GIMPLE_PHI)
2292 tree res = gimple_phi_result (stmt);
2293 return (!virtual_operand_p (res)
2294 && (INTEGRAL_TYPE_P (TREE_TYPE (res))
2295 || POINTER_TYPE_P (TREE_TYPE (res))));
2297 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
2299 tree lhs = gimple_get_lhs (stmt);
2301 /* In general, assignments with virtual operands are not useful
2302 for deriving ranges, with the obvious exception of calls to
2303 builtin functions. */
2304 if (lhs && TREE_CODE (lhs) == SSA_NAME
2305 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
2306 || POINTER_TYPE_P (TREE_TYPE (lhs)))
2307 && (is_gimple_call (stmt)
2308 || !gimple_vuse (stmt)))
2309 return true;
2310 else if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
2311 switch (gimple_call_internal_fn (stmt))
2313 case IFN_ADD_OVERFLOW:
2314 case IFN_SUB_OVERFLOW:
2315 case IFN_MUL_OVERFLOW:
2316 case IFN_ATOMIC_COMPARE_EXCHANGE:
2317 /* These internal calls return _Complex integer type,
2318 but are interesting to VRP nevertheless. */
2319 if (lhs && TREE_CODE (lhs) == SSA_NAME)
2320 return true;
2321 break;
2322 default:
2323 break;
2326 else if (gimple_code (stmt) == GIMPLE_COND
2327 || gimple_code (stmt) == GIMPLE_SWITCH)
2328 return true;
2330 return false;
2333 /* Searches the case label vector VEC for the index *IDX of the CASE_LABEL
2334 that includes the value VAL. The search is restricted to the range
2335 [START_IDX, n - 1] where n is the size of VEC.
2337 If there is a CASE_LABEL for VAL, its index is placed in IDX and true is
2338 returned.
2340 If there is no CASE_LABEL for VAL and there is one that is larger than VAL,
2341 it is placed in IDX and false is returned.
2343 If VAL is larger than any CASE_LABEL, n is placed on IDX and false is
2344 returned. */
2346 bool
2347 find_case_label_index (gswitch *stmt, size_t start_idx, tree val, size_t *idx)
2349 size_t n = gimple_switch_num_labels (stmt);
2350 size_t low, high;
2352 /* Find case label for minimum of the value range or the next one.
2353 At each iteration we are searching in [low, high - 1]. */
2355 for (low = start_idx, high = n; high != low; )
2357 tree t;
2358 int cmp;
2359 /* Note that i != high, so we never ask for n. */
2360 size_t i = (high + low) / 2;
2361 t = gimple_switch_label (stmt, i);
2363 /* Cache the result of comparing CASE_LOW and val. */
2364 cmp = tree_int_cst_compare (CASE_LOW (t), val);
2366 if (cmp == 0)
2368 /* Ranges cannot be empty. */
2369 *idx = i;
2370 return true;
2372 else if (cmp > 0)
2373 high = i;
2374 else
2376 low = i + 1;
2377 if (CASE_HIGH (t) != NULL
2378 && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
2380 *idx = i;
2381 return true;
2386 *idx = high;
2387 return false;
2390 /* Searches the case label vector VEC for the range of CASE_LABELs that is used
2391 for values between MIN and MAX. The first index is placed in MIN_IDX. The
2392 last index is placed in MAX_IDX. If the range of CASE_LABELs is empty
2393 then MAX_IDX < MIN_IDX.
2394 Returns true if the default label is not needed. */
2396 bool
2397 find_case_label_range (gswitch *stmt, tree min, tree max, size_t *min_idx,
2398 size_t *max_idx)
2400 size_t i, j;
2401 bool min_take_default = !find_case_label_index (stmt, 1, min, &i);
2402 bool max_take_default = !find_case_label_index (stmt, i, max, &j);
2404 if (i == j
2405 && min_take_default
2406 && max_take_default)
2408 /* Only the default case label reached.
2409 Return an empty range. */
2410 *min_idx = 1;
2411 *max_idx = 0;
2412 return false;
2414 else
2416 bool take_default = min_take_default || max_take_default;
2417 tree low, high;
2418 size_t k;
2420 if (max_take_default)
2421 j--;
2423 /* If the case label range is continuous, we do not need
2424 the default case label. Verify that. */
2425 high = CASE_LOW (gimple_switch_label (stmt, i));
2426 if (CASE_HIGH (gimple_switch_label (stmt, i)))
2427 high = CASE_HIGH (gimple_switch_label (stmt, i));
2428 for (k = i + 1; k <= j; ++k)
2430 low = CASE_LOW (gimple_switch_label (stmt, k));
2431 if (!integer_onep (int_const_binop (MINUS_EXPR, low, high)))
2433 take_default = true;
2434 break;
2436 high = low;
2437 if (CASE_HIGH (gimple_switch_label (stmt, k)))
2438 high = CASE_HIGH (gimple_switch_label (stmt, k));
2441 *min_idx = i;
2442 *max_idx = j;
2443 return !take_default;
2447 /* Given a SWITCH_STMT, return the case label that encompasses the
2448 known possible values for the switch operand. RANGE_OF_OP is a
2449 range for the known values of the switch operand. */
2451 tree
2452 find_case_label_range (gswitch *switch_stmt, const irange *range_of_op)
2454 if (range_of_op->undefined_p ()
2455 || range_of_op->varying_p ()
2456 || range_of_op->symbolic_p ())
2457 return NULL_TREE;
2459 size_t i, j;
2460 tree op = gimple_switch_index (switch_stmt);
2461 tree type = TREE_TYPE (op);
2462 tree tmin = wide_int_to_tree (type, range_of_op->lower_bound ());
2463 tree tmax = wide_int_to_tree (type, range_of_op->upper_bound ());
2464 find_case_label_range (switch_stmt, tmin, tmax, &i, &j);
2465 if (i == j)
2467 /* Look for exactly one label that encompasses the range of
2468 the operand. */
2469 tree label = gimple_switch_label (switch_stmt, i);
2470 tree case_high
2471 = CASE_HIGH (label) ? CASE_HIGH (label) : CASE_LOW (label);
2472 int_range_max label_range (CASE_LOW (label), case_high);
2473 if (!types_compatible_p (label_range.type (), range_of_op->type ()))
2474 range_cast (label_range, range_of_op->type ());
2475 label_range.intersect (range_of_op);
2476 if (label_range == *range_of_op)
2477 return label;
2479 else if (i > j)
2481 /* If there are no labels at all, take the default. */
2482 return gimple_switch_label (switch_stmt, 0);
2484 else
2486 /* Otherwise, there are various labels that can encompass
2487 the range of operand. In which case, see if the range of
2488 the operand is entirely *outside* the bounds of all the
2489 (non-default) case labels. If so, take the default. */
2490 unsigned n = gimple_switch_num_labels (switch_stmt);
2491 tree min_label = gimple_switch_label (switch_stmt, 1);
2492 tree max_label = gimple_switch_label (switch_stmt, n - 1);
2493 tree case_high = CASE_HIGH (max_label);
2494 if (!case_high)
2495 case_high = CASE_LOW (max_label);
2496 int_range_max label_range (CASE_LOW (min_label), case_high);
2497 if (!types_compatible_p (label_range.type (), range_of_op->type ()))
2498 range_cast (label_range, range_of_op->type ());
2499 label_range.intersect (range_of_op);
2500 if (label_range.undefined_p ())
2501 return gimple_switch_label (switch_stmt, 0);
2503 return NULL_TREE;
2506 struct case_info
2508 tree expr;
2509 basic_block bb;
2512 /* Location information for ASSERT_EXPRs. Each instance of this
2513 structure describes an ASSERT_EXPR for an SSA name. Since a single
2514 SSA name may have more than one assertion associated with it, these
2515 locations are kept in a linked list attached to the corresponding
2516 SSA name. */
2517 struct assert_locus
2519 /* Basic block where the assertion would be inserted. */
2520 basic_block bb;
2522 /* Some assertions need to be inserted on an edge (e.g., assertions
2523 generated by COND_EXPRs). In those cases, BB will be NULL. */
2524 edge e;
2526 /* Pointer to the statement that generated this assertion. */
2527 gimple_stmt_iterator si;
2529 /* Predicate code for the ASSERT_EXPR. Must be COMPARISON_CLASS_P. */
2530 enum tree_code comp_code;
2532 /* Value being compared against. */
2533 tree val;
2535 /* Expression to compare. */
2536 tree expr;
2538 /* Next node in the linked list. */
2539 assert_locus *next;
2542 /* Class to traverse the flowgraph looking for conditional jumps to
2543 insert ASSERT_EXPR range expressions. These range expressions are
2544 meant to provide information to optimizations that need to reason
2545 in terms of value ranges. They will not be expanded into RTL. */
2547 class vrp_asserts
2549 public:
2550 vrp_asserts (struct function *fn) : fun (fn) { }
2552 void insert_range_assertions ();
2554 /* Convert range assertion expressions into the implied copies and
2555 copy propagate away the copies. */
2556 void remove_range_assertions ();
2558 /* Dump all the registered assertions for all the names to FILE. */
2559 void dump (FILE *);
2561 /* Dump all the registered assertions for NAME to FILE. */
2562 void dump (FILE *file, tree name);
2564 /* Dump all the registered assertions for NAME to stderr. */
2565 void debug (tree name)
2567 dump (stderr, name);
2570 /* Dump all the registered assertions for all the names to stderr. */
2571 void debug ()
2573 dump (stderr);
2576 private:
2577 /* Set of SSA names found live during the RPO traversal of the function
2578 for still active basic-blocks. */
2579 live_names live;
2581 /* Function to work on. */
2582 struct function *fun;
2584 /* If bit I is present, it means that SSA name N_i has a list of
2585 assertions that should be inserted in the IL. */
2586 bitmap need_assert_for;
2588 /* Array of locations lists where to insert assertions. ASSERTS_FOR[I]
2589 holds a list of ASSERT_LOCUS_T nodes that describe where
2590 ASSERT_EXPRs for SSA name N_I should be inserted. */
2591 assert_locus **asserts_for;
2593 /* Finish found ASSERTS for E and register them at GSI. */
2594 void finish_register_edge_assert_for (edge e, gimple_stmt_iterator gsi,
2595 vec<assert_info> &asserts);
2597 /* Determine whether the outgoing edges of BB should receive an
2598 ASSERT_EXPR for each of the operands of BB's LAST statement. The
2599 last statement of BB must be a SWITCH_EXPR.
2601 If any of the sub-graphs rooted at BB have an interesting use of
2602 the predicate operands, an assert location node is added to the
2603 list of assertions for the corresponding operands. */
2604 void find_switch_asserts (basic_block bb, gswitch *last);
2606 /* Do an RPO walk over the function computing SSA name liveness
2607 on-the-fly and deciding on assert expressions to insert. */
2608 void find_assert_locations ();
2610 /* Traverse all the statements in block BB looking for statements that
2611 may generate useful assertions for the SSA names in their operand.
2612 See method implementation comentary for more information. */
2613 void find_assert_locations_in_bb (basic_block bb);
2615 /* Determine whether the outgoing edges of BB should receive an
2616 ASSERT_EXPR for each of the operands of BB's LAST statement.
2617 The last statement of BB must be a COND_EXPR.
2619 If any of the sub-graphs rooted at BB have an interesting use of
2620 the predicate operands, an assert location node is added to the
2621 list of assertions for the corresponding operands. */
2622 void find_conditional_asserts (basic_block bb, gcond *last);
2624 /* Process all the insertions registered for every name N_i registered
2625 in NEED_ASSERT_FOR. The list of assertions to be inserted are
2626 found in ASSERTS_FOR[i]. */
2627 void process_assert_insertions ();
2629 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
2630 'EXPR COMP_CODE VAL' at a location that dominates block BB or
2631 E->DEST, then register this location as a possible insertion point
2632 for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
2634 BB, E and SI provide the exact insertion point for the new
2635 ASSERT_EXPR. If BB is NULL, then the ASSERT_EXPR is to be inserted
2636 on edge E. Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
2637 BB. If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
2638 must not be NULL. */
2639 void register_new_assert_for (tree name, tree expr,
2640 enum tree_code comp_code,
2641 tree val, basic_block bb,
2642 edge e, gimple_stmt_iterator si);
2644 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
2645 create a new SSA name N and return the assertion assignment
2646 'N = ASSERT_EXPR <V, V OP W>'. */
2647 gimple *build_assert_expr_for (tree cond, tree v);
2649 /* Create an ASSERT_EXPR for NAME and insert it in the location
2650 indicated by LOC. Return true if we made any edge insertions. */
2651 bool process_assert_insertions_for (tree name, assert_locus *loc);
2653 /* Qsort callback for sorting assert locations. */
2654 template <bool stable> static int compare_assert_loc (const void *,
2655 const void *);
2657 /* Return false if EXPR is a predicate expression involving floating
2658 point values. */
2659 bool fp_predicate (gimple *stmt)
2661 GIMPLE_CHECK (stmt, GIMPLE_COND);
2662 return FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)));
2665 bool all_imm_uses_in_stmt_or_feed_cond (tree var, gimple *stmt,
2666 basic_block cond_bb);
2668 static int compare_case_labels (const void *, const void *);
2671 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
2672 create a new SSA name N and return the assertion assignment
2673 'N = ASSERT_EXPR <V, V OP W>'. */
2675 gimple *
2676 vrp_asserts::build_assert_expr_for (tree cond, tree v)
2678 tree a;
2679 gassign *assertion;
2681 gcc_assert (TREE_CODE (v) == SSA_NAME
2682 && COMPARISON_CLASS_P (cond));
2684 a = build2 (ASSERT_EXPR, TREE_TYPE (v), v, cond);
2685 assertion = gimple_build_assign (NULL_TREE, a);
2687 /* The new ASSERT_EXPR, creates a new SSA name that replaces the
2688 operand of the ASSERT_EXPR. Create it so the new name and the old one
2689 are registered in the replacement table so that we can fix the SSA web
2690 after adding all the ASSERT_EXPRs. */
2691 tree new_def = create_new_def_for (v, assertion, NULL);
2692 /* Make sure we preserve abnormalness throughout an ASSERT_EXPR chain
2693 given we have to be able to fully propagate those out to re-create
2694 valid SSA when removing the asserts. */
2695 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (v))
2696 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_def) = 1;
2698 return assertion;
2701 /* Dump all the registered assertions for NAME to FILE. */
2703 void
2704 vrp_asserts::dump (FILE *file, tree name)
2706 assert_locus *loc;
2708 fprintf (file, "Assertions to be inserted for ");
2709 print_generic_expr (file, name);
2710 fprintf (file, "\n");
2712 loc = asserts_for[SSA_NAME_VERSION (name)];
2713 while (loc)
2715 fprintf (file, "\t");
2716 print_gimple_stmt (file, gsi_stmt (loc->si), 0);
2717 fprintf (file, "\n\tBB #%d", loc->bb->index);
2718 if (loc->e)
2720 fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
2721 loc->e->dest->index);
2722 dump_edge_info (file, loc->e, dump_flags, 0);
2724 fprintf (file, "\n\tPREDICATE: ");
2725 print_generic_expr (file, loc->expr);
2726 fprintf (file, " %s ", get_tree_code_name (loc->comp_code));
2727 print_generic_expr (file, loc->val);
2728 fprintf (file, "\n\n");
2729 loc = loc->next;
2732 fprintf (file, "\n");
2735 /* Dump all the registered assertions for all the names to FILE. */
2737 void
2738 vrp_asserts::dump (FILE *file)
2740 unsigned i;
2741 bitmap_iterator bi;
2743 fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
2744 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
2745 dump (file, ssa_name (i));
2746 fprintf (file, "\n");
2749 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
2750 'EXPR COMP_CODE VAL' at a location that dominates block BB or
2751 E->DEST, then register this location as a possible insertion point
2752 for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
2754 BB, E and SI provide the exact insertion point for the new
2755 ASSERT_EXPR. If BB is NULL, then the ASSERT_EXPR is to be inserted
2756 on edge E. Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
2757 BB. If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
2758 must not be NULL. */
2760 void
2761 vrp_asserts::register_new_assert_for (tree name, tree expr,
2762 enum tree_code comp_code,
2763 tree val,
2764 basic_block bb,
2765 edge e,
2766 gimple_stmt_iterator si)
2768 assert_locus *n, *loc, *last_loc;
2769 basic_block dest_bb;
2771 gcc_checking_assert (bb == NULL || e == NULL);
2773 if (e == NULL)
2774 gcc_checking_assert (gimple_code (gsi_stmt (si)) != GIMPLE_COND
2775 && gimple_code (gsi_stmt (si)) != GIMPLE_SWITCH);
2777 /* Never build an assert comparing against an integer constant with
2778 TREE_OVERFLOW set. This confuses our undefined overflow warning
2779 machinery. */
2780 if (TREE_OVERFLOW_P (val))
2781 val = drop_tree_overflow (val);
2783 /* The new assertion A will be inserted at BB or E. We need to
2784 determine if the new location is dominated by a previously
2785 registered location for A. If we are doing an edge insertion,
2786 assume that A will be inserted at E->DEST. Note that this is not
2787 necessarily true.
2789 If E is a critical edge, it will be split. But even if E is
2790 split, the new block will dominate the same set of blocks that
2791 E->DEST dominates.
2793 The reverse, however, is not true, blocks dominated by E->DEST
2794 will not be dominated by the new block created to split E. So,
2795 if the insertion location is on a critical edge, we will not use
2796 the new location to move another assertion previously registered
2797 at a block dominated by E->DEST. */
2798 dest_bb = (bb) ? bb : e->dest;
2800 /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
2801 VAL at a block dominating DEST_BB, then we don't need to insert a new
2802 one. Similarly, if the same assertion already exists at a block
2803 dominated by DEST_BB and the new location is not on a critical
2804 edge, then update the existing location for the assertion (i.e.,
2805 move the assertion up in the dominance tree).
2807 Note, this is implemented as a simple linked list because there
2808 should not be more than a handful of assertions registered per
2809 name. If this becomes a performance problem, a table hashed by
2810 COMP_CODE and VAL could be implemented. */
2811 loc = asserts_for[SSA_NAME_VERSION (name)];
2812 last_loc = loc;
2813 while (loc)
2815 if (loc->comp_code == comp_code
2816 && (loc->val == val
2817 || operand_equal_p (loc->val, val, 0))
2818 && (loc->expr == expr
2819 || operand_equal_p (loc->expr, expr, 0)))
2821 /* If E is not a critical edge and DEST_BB
2822 dominates the existing location for the assertion, move
2823 the assertion up in the dominance tree by updating its
2824 location information. */
2825 if ((e == NULL || !EDGE_CRITICAL_P (e))
2826 && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
2828 loc->bb = dest_bb;
2829 loc->e = e;
2830 loc->si = si;
2831 return;
2835 /* Update the last node of the list and move to the next one. */
2836 last_loc = loc;
2837 loc = loc->next;
2840 /* If we didn't find an assertion already registered for
2841 NAME COMP_CODE VAL, add a new one at the end of the list of
2842 assertions associated with NAME. */
2843 n = XNEW (struct assert_locus);
2844 n->bb = dest_bb;
2845 n->e = e;
2846 n->si = si;
2847 n->comp_code = comp_code;
2848 n->val = val;
2849 n->expr = expr;
2850 n->next = NULL;
2852 if (last_loc)
2853 last_loc->next = n;
2854 else
2855 asserts_for[SSA_NAME_VERSION (name)] = n;
2857 bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
2860 /* Finish found ASSERTS for E and register them at GSI. */
2862 void
2863 vrp_asserts::finish_register_edge_assert_for (edge e,
2864 gimple_stmt_iterator gsi,
2865 vec<assert_info> &asserts)
2867 for (unsigned i = 0; i < asserts.length (); ++i)
2868 /* Only register an ASSERT_EXPR if NAME was found in the sub-graph
2869 reachable from E. */
2870 if (live.live_on_edge_p (asserts[i].name, e))
2871 register_new_assert_for (asserts[i].name, asserts[i].expr,
2872 asserts[i].comp_code, asserts[i].val,
2873 NULL, e, gsi);
2876 /* Determine whether the outgoing edges of BB should receive an
2877 ASSERT_EXPR for each of the operands of BB's LAST statement.
2878 The last statement of BB must be a COND_EXPR.
2880 If any of the sub-graphs rooted at BB have an interesting use of
2881 the predicate operands, an assert location node is added to the
2882 list of assertions for the corresponding operands. */
2884 void
2885 vrp_asserts::find_conditional_asserts (basic_block bb, gcond *last)
2887 gimple_stmt_iterator bsi;
2888 tree op;
2889 edge_iterator ei;
2890 edge e;
2891 ssa_op_iter iter;
2893 bsi = gsi_for_stmt (last);
2895 /* Look for uses of the operands in each of the sub-graphs
2896 rooted at BB. We need to check each of the outgoing edges
2897 separately, so that we know what kind of ASSERT_EXPR to
2898 insert. */
2899 FOR_EACH_EDGE (e, ei, bb->succs)
2901 if (e->dest == bb)
2902 continue;
2904 /* Register the necessary assertions for each operand in the
2905 conditional predicate. */
2906 auto_vec<assert_info, 8> asserts;
2907 FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
2908 register_edge_assert_for (op, e,
2909 gimple_cond_code (last),
2910 gimple_cond_lhs (last),
2911 gimple_cond_rhs (last), asserts);
2912 finish_register_edge_assert_for (e, bsi, asserts);
2916 /* Compare two case labels sorting first by the destination bb index
2917 and then by the case value. */
2920 vrp_asserts::compare_case_labels (const void *p1, const void *p2)
2922 const struct case_info *ci1 = (const struct case_info *) p1;
2923 const struct case_info *ci2 = (const struct case_info *) p2;
2924 int idx1 = ci1->bb->index;
2925 int idx2 = ci2->bb->index;
2927 if (idx1 < idx2)
2928 return -1;
2929 else if (idx1 == idx2)
2931 /* Make sure the default label is first in a group. */
2932 if (!CASE_LOW (ci1->expr))
2933 return -1;
2934 else if (!CASE_LOW (ci2->expr))
2935 return 1;
2936 else
2937 return tree_int_cst_compare (CASE_LOW (ci1->expr),
2938 CASE_LOW (ci2->expr));
2940 else
2941 return 1;
2944 /* Determine whether the outgoing edges of BB should receive an
2945 ASSERT_EXPR for each of the operands of BB's LAST statement.
2946 The last statement of BB must be a SWITCH_EXPR.
2948 If any of the sub-graphs rooted at BB have an interesting use of
2949 the predicate operands, an assert location node is added to the
2950 list of assertions for the corresponding operands. */
2952 void
2953 vrp_asserts::find_switch_asserts (basic_block bb, gswitch *last)
2955 gimple_stmt_iterator bsi;
2956 tree op;
2957 edge e;
2958 struct case_info *ci;
2959 size_t n = gimple_switch_num_labels (last);
2960 #if GCC_VERSION >= 4000
2961 unsigned int idx;
2962 #else
2963 /* Work around GCC 3.4 bug (PR 37086). */
2964 volatile unsigned int idx;
2965 #endif
2967 bsi = gsi_for_stmt (last);
2968 op = gimple_switch_index (last);
2969 if (TREE_CODE (op) != SSA_NAME)
2970 return;
2972 /* Build a vector of case labels sorted by destination label. */
2973 ci = XNEWVEC (struct case_info, n);
2974 for (idx = 0; idx < n; ++idx)
2976 ci[idx].expr = gimple_switch_label (last, idx);
2977 ci[idx].bb = label_to_block (fun, CASE_LABEL (ci[idx].expr));
2979 edge default_edge = find_edge (bb, ci[0].bb);
2980 qsort (ci, n, sizeof (struct case_info), compare_case_labels);
2982 for (idx = 0; idx < n; ++idx)
2984 tree min, max;
2985 tree cl = ci[idx].expr;
2986 basic_block cbb = ci[idx].bb;
2988 min = CASE_LOW (cl);
2989 max = CASE_HIGH (cl);
2991 /* If there are multiple case labels with the same destination
2992 we need to combine them to a single value range for the edge. */
2993 if (idx + 1 < n && cbb == ci[idx + 1].bb)
2995 /* Skip labels until the last of the group. */
2996 do {
2997 ++idx;
2998 } while (idx < n && cbb == ci[idx].bb);
2999 --idx;
3001 /* Pick up the maximum of the case label range. */
3002 if (CASE_HIGH (ci[idx].expr))
3003 max = CASE_HIGH (ci[idx].expr);
3004 else
3005 max = CASE_LOW (ci[idx].expr);
3008 /* Can't extract a useful assertion out of a range that includes the
3009 default label. */
3010 if (min == NULL_TREE)
3011 continue;
3013 /* Find the edge to register the assert expr on. */
3014 e = find_edge (bb, cbb);
3016 /* Register the necessary assertions for the operand in the
3017 SWITCH_EXPR. */
3018 auto_vec<assert_info, 8> asserts;
3019 register_edge_assert_for (op, e,
3020 max ? GE_EXPR : EQ_EXPR,
3021 op, fold_convert (TREE_TYPE (op), min),
3022 asserts);
3023 if (max)
3024 register_edge_assert_for (op, e, LE_EXPR, op,
3025 fold_convert (TREE_TYPE (op), max),
3026 asserts);
3027 finish_register_edge_assert_for (e, bsi, asserts);
3030 XDELETEVEC (ci);
3032 if (!live.live_on_edge_p (op, default_edge))
3033 return;
3035 /* Now register along the default label assertions that correspond to the
3036 anti-range of each label. */
3037 int insertion_limit = param_max_vrp_switch_assertions;
3038 if (insertion_limit == 0)
3039 return;
3041 /* We can't do this if the default case shares a label with another case. */
3042 tree default_cl = gimple_switch_default_label (last);
3043 for (idx = 1; idx < n; idx++)
3045 tree min, max;
3046 tree cl = gimple_switch_label (last, idx);
3047 if (CASE_LABEL (cl) == CASE_LABEL (default_cl))
3048 continue;
3050 min = CASE_LOW (cl);
3051 max = CASE_HIGH (cl);
3053 /* Combine contiguous case ranges to reduce the number of assertions
3054 to insert. */
3055 for (idx = idx + 1; idx < n; idx++)
3057 tree next_min, next_max;
3058 tree next_cl = gimple_switch_label (last, idx);
3059 if (CASE_LABEL (next_cl) == CASE_LABEL (default_cl))
3060 break;
3062 next_min = CASE_LOW (next_cl);
3063 next_max = CASE_HIGH (next_cl);
3065 wide_int difference = (wi::to_wide (next_min)
3066 - wi::to_wide (max ? max : min));
3067 if (wi::eq_p (difference, 1))
3068 max = next_max ? next_max : next_min;
3069 else
3070 break;
3072 idx--;
3074 if (max == NULL_TREE)
3076 /* Register the assertion OP != MIN. */
3077 auto_vec<assert_info, 8> asserts;
3078 min = fold_convert (TREE_TYPE (op), min);
3079 register_edge_assert_for (op, default_edge, NE_EXPR, op, min,
3080 asserts);
3081 finish_register_edge_assert_for (default_edge, bsi, asserts);
3083 else
3085 /* Register the assertion (unsigned)OP - MIN > (MAX - MIN),
3086 which will give OP the anti-range ~[MIN,MAX]. */
3087 tree uop = fold_convert (unsigned_type_for (TREE_TYPE (op)), op);
3088 min = fold_convert (TREE_TYPE (uop), min);
3089 max = fold_convert (TREE_TYPE (uop), max);
3091 tree lhs = fold_build2 (MINUS_EXPR, TREE_TYPE (uop), uop, min);
3092 tree rhs = int_const_binop (MINUS_EXPR, max, min);
3093 register_new_assert_for (op, lhs, GT_EXPR, rhs,
3094 NULL, default_edge, bsi);
3097 if (--insertion_limit == 0)
3098 break;
3102 /* Traverse all the statements in block BB looking for statements that
3103 may generate useful assertions for the SSA names in their operand.
3104 If a statement produces a useful assertion A for name N_i, then the
3105 list of assertions already generated for N_i is scanned to
3106 determine if A is actually needed.
3108 If N_i already had the assertion A at a location dominating the
3109 current location, then nothing needs to be done. Otherwise, the
3110 new location for A is recorded instead.
3112 1- For every statement S in BB, all the variables used by S are
3113 added to bitmap FOUND_IN_SUBGRAPH.
3115 2- If statement S uses an operand N in a way that exposes a known
3116 value range for N, then if N was not already generated by an
3117 ASSERT_EXPR, create a new assert location for N. For instance,
3118 if N is a pointer and the statement dereferences it, we can
3119 assume that N is not NULL.
3121 3- COND_EXPRs are a special case of #2. We can derive range
3122 information from the predicate but need to insert different
3123 ASSERT_EXPRs for each of the sub-graphs rooted at the
3124 conditional block. If the last statement of BB is a conditional
3125 expression of the form 'X op Y', then
3127 a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
3129 b) If the conditional is the only entry point to the sub-graph
3130 corresponding to the THEN_CLAUSE, recurse into it. On
3131 return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
3132 an ASSERT_EXPR is added for the corresponding variable.
3134 c) Repeat step (b) on the ELSE_CLAUSE.
3136 d) Mark X and Y in FOUND_IN_SUBGRAPH.
3138 For instance,
3140 if (a == 9)
3141 b = a;
3142 else
3143 b = c + 1;
3145 In this case, an assertion on the THEN clause is useful to
3146 determine that 'a' is always 9 on that edge. However, an assertion
3147 on the ELSE clause would be unnecessary.
3149 4- If BB does not end in a conditional expression, then we recurse
3150 into BB's dominator children.
3152 At the end of the recursive traversal, every SSA name will have a
3153 list of locations where ASSERT_EXPRs should be added. When a new
3154 location for name N is found, it is registered by calling
3155 register_new_assert_for. That function keeps track of all the
3156 registered assertions to prevent adding unnecessary assertions.
3157 For instance, if a pointer P_4 is dereferenced more than once in a
3158 dominator tree, only the location dominating all the dereference of
3159 P_4 will receive an ASSERT_EXPR. */
3161 void
3162 vrp_asserts::find_assert_locations_in_bb (basic_block bb)
3164 gimple *last;
3166 last = last_stmt (bb);
3168 /* If BB's last statement is a conditional statement involving integer
3169 operands, determine if we need to add ASSERT_EXPRs. */
3170 if (last
3171 && gimple_code (last) == GIMPLE_COND
3172 && !fp_predicate (last)
3173 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
3174 find_conditional_asserts (bb, as_a <gcond *> (last));
3176 /* If BB's last statement is a switch statement involving integer
3177 operands, determine if we need to add ASSERT_EXPRs. */
3178 if (last
3179 && gimple_code (last) == GIMPLE_SWITCH
3180 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
3181 find_switch_asserts (bb, as_a <gswitch *> (last));
3183 /* Traverse all the statements in BB marking used names and looking
3184 for statements that may infer assertions for their used operands. */
3185 for (gimple_stmt_iterator si = gsi_last_bb (bb); !gsi_end_p (si);
3186 gsi_prev (&si))
3188 gimple *stmt;
3189 tree op;
3190 ssa_op_iter i;
3192 stmt = gsi_stmt (si);
3194 if (is_gimple_debug (stmt))
3195 continue;
3197 /* See if we can derive an assertion for any of STMT's operands. */
3198 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
3200 tree value;
3201 enum tree_code comp_code;
3203 /* If op is not live beyond this stmt, do not bother to insert
3204 asserts for it. */
3205 if (!live.live_on_block_p (op, bb))
3206 continue;
3208 /* If OP is used in such a way that we can infer a value
3209 range for it, and we don't find a previous assertion for
3210 it, create a new assertion location node for OP. */
3211 if (infer_value_range (stmt, op, &comp_code, &value))
3213 /* If we are able to infer a nonzero value range for OP,
3214 then walk backwards through the use-def chain to see if OP
3215 was set via a typecast.
3217 If so, then we can also infer a nonzero value range
3218 for the operand of the NOP_EXPR. */
3219 if (comp_code == NE_EXPR && integer_zerop (value))
3221 tree t = op;
3222 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
3224 while (is_gimple_assign (def_stmt)
3225 && CONVERT_EXPR_CODE_P
3226 (gimple_assign_rhs_code (def_stmt))
3227 && TREE_CODE
3228 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
3229 && POINTER_TYPE_P
3230 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
3232 t = gimple_assign_rhs1 (def_stmt);
3233 def_stmt = SSA_NAME_DEF_STMT (t);
3235 /* Note we want to register the assert for the
3236 operand of the NOP_EXPR after SI, not after the
3237 conversion. */
3238 if (live.live_on_block_p (t, bb))
3239 register_new_assert_for (t, t, comp_code, value,
3240 bb, NULL, si);
3244 register_new_assert_for (op, op, comp_code, value, bb, NULL, si);
3248 /* Update live. */
3249 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
3250 live.set (op, bb);
3251 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_DEF)
3252 live.clear (op, bb);
3255 /* Traverse all PHI nodes in BB, updating live. */
3256 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
3257 gsi_next (&si))
3259 use_operand_p arg_p;
3260 ssa_op_iter i;
3261 gphi *phi = si.phi ();
3262 tree res = gimple_phi_result (phi);
3264 if (virtual_operand_p (res))
3265 continue;
3267 FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
3269 tree arg = USE_FROM_PTR (arg_p);
3270 if (TREE_CODE (arg) == SSA_NAME)
3271 live.set (arg, bb);
3274 live.clear (res, bb);
3278 /* Do an RPO walk over the function computing SSA name liveness
3279 on-the-fly and deciding on assert expressions to insert. */
3281 void
3282 vrp_asserts::find_assert_locations (void)
3284 int *rpo = XNEWVEC (int, last_basic_block_for_fn (fun));
3285 int *bb_rpo = XNEWVEC (int, last_basic_block_for_fn (fun));
3286 int *last_rpo = XCNEWVEC (int, last_basic_block_for_fn (fun));
3287 int rpo_cnt, i;
3289 rpo_cnt = pre_and_rev_post_order_compute (NULL, rpo, false);
3290 for (i = 0; i < rpo_cnt; ++i)
3291 bb_rpo[rpo[i]] = i;
3293 /* Pre-seed loop latch liveness from loop header PHI nodes. Due to
3294 the order we compute liveness and insert asserts we otherwise
3295 fail to insert asserts into the loop latch. */
3296 for (auto loop : loops_list (cfun, 0))
3298 i = loop->latch->index;
3299 unsigned int j = single_succ_edge (loop->latch)->dest_idx;
3300 for (gphi_iterator gsi = gsi_start_phis (loop->header);
3301 !gsi_end_p (gsi); gsi_next (&gsi))
3303 gphi *phi = gsi.phi ();
3304 if (virtual_operand_p (gimple_phi_result (phi)))
3305 continue;
3306 tree arg = gimple_phi_arg_def (phi, j);
3307 if (TREE_CODE (arg) == SSA_NAME)
3308 live.set (arg, loop->latch);
3312 for (i = rpo_cnt - 1; i >= 0; --i)
3314 basic_block bb = BASIC_BLOCK_FOR_FN (fun, rpo[i]);
3315 edge e;
3316 edge_iterator ei;
3318 /* Process BB and update the live information with uses in
3319 this block. */
3320 find_assert_locations_in_bb (bb);
3322 /* Merge liveness into the predecessor blocks and free it. */
3323 if (!live.block_has_live_names_p (bb))
3325 int pred_rpo = i;
3326 FOR_EACH_EDGE (e, ei, bb->preds)
3328 int pred = e->src->index;
3329 if ((e->flags & EDGE_DFS_BACK) || pred == ENTRY_BLOCK)
3330 continue;
3332 live.merge (e->src, bb);
3334 if (bb_rpo[pred] < pred_rpo)
3335 pred_rpo = bb_rpo[pred];
3338 /* Record the RPO number of the last visited block that needs
3339 live information from this block. */
3340 last_rpo[rpo[i]] = pred_rpo;
3342 else
3343 live.clear_block (bb);
3345 /* We can free all successors live bitmaps if all their
3346 predecessors have been visited already. */
3347 FOR_EACH_EDGE (e, ei, bb->succs)
3348 if (last_rpo[e->dest->index] == i)
3349 live.clear_block (e->dest);
3352 XDELETEVEC (rpo);
3353 XDELETEVEC (bb_rpo);
3354 XDELETEVEC (last_rpo);
3357 /* Create an ASSERT_EXPR for NAME and insert it in the location
3358 indicated by LOC. Return true if we made any edge insertions. */
3360 bool
3361 vrp_asserts::process_assert_insertions_for (tree name, assert_locus *loc)
3363 /* Build the comparison expression NAME_i COMP_CODE VAL. */
3364 gimple *stmt;
3365 tree cond;
3366 gimple *assert_stmt;
3367 edge_iterator ei;
3368 edge e;
3370 /* If we have X <=> X do not insert an assert expr for that. */
3371 if (loc->expr == loc->val)
3372 return false;
3374 cond = build2 (loc->comp_code, boolean_type_node, loc->expr, loc->val);
3375 assert_stmt = build_assert_expr_for (cond, name);
3376 if (loc->e)
3378 /* We have been asked to insert the assertion on an edge. This
3379 is used only by COND_EXPR and SWITCH_EXPR assertions. */
3380 gcc_checking_assert (gimple_code (gsi_stmt (loc->si)) == GIMPLE_COND
3381 || (gimple_code (gsi_stmt (loc->si))
3382 == GIMPLE_SWITCH));
3384 gsi_insert_on_edge (loc->e, assert_stmt);
3385 return true;
3388 /* If the stmt iterator points at the end then this is an insertion
3389 at the beginning of a block. */
3390 if (gsi_end_p (loc->si))
3392 gimple_stmt_iterator si = gsi_after_labels (loc->bb);
3393 gsi_insert_before (&si, assert_stmt, GSI_SAME_STMT);
3394 return false;
3397 /* Otherwise, we can insert right after LOC->SI iff the
3398 statement must not be the last statement in the block. */
3399 stmt = gsi_stmt (loc->si);
3400 if (!stmt_ends_bb_p (stmt))
3402 gsi_insert_after (&loc->si, assert_stmt, GSI_SAME_STMT);
3403 return false;
3406 /* If STMT must be the last statement in BB, we can only insert new
3407 assertions on the non-abnormal edge out of BB. Note that since
3408 STMT is not control flow, there may only be one non-abnormal/eh edge
3409 out of BB. */
3410 FOR_EACH_EDGE (e, ei, loc->bb->succs)
3411 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
3413 gsi_insert_on_edge (e, assert_stmt);
3414 return true;
3417 gcc_unreachable ();
3420 /* Qsort helper for sorting assert locations. If stable is true, don't
3421 use iterative_hash_expr because it can be unstable for -fcompare-debug,
3422 on the other side some pointers might be NULL. */
3424 template <bool stable>
3426 vrp_asserts::compare_assert_loc (const void *pa, const void *pb)
3428 assert_locus * const a = *(assert_locus * const *)pa;
3429 assert_locus * const b = *(assert_locus * const *)pb;
3431 /* If stable, some asserts might be optimized away already, sort
3432 them last. */
3433 if (stable)
3435 if (a == NULL)
3436 return b != NULL;
3437 else if (b == NULL)
3438 return -1;
3441 if (a->e == NULL && b->e != NULL)
3442 return 1;
3443 else if (a->e != NULL && b->e == NULL)
3444 return -1;
3446 /* After the above checks, we know that (a->e == NULL) == (b->e == NULL),
3447 no need to test both a->e and b->e. */
3449 /* Sort after destination index. */
3450 if (a->e == NULL)
3452 else if (a->e->dest->index > b->e->dest->index)
3453 return 1;
3454 else if (a->e->dest->index < b->e->dest->index)
3455 return -1;
3457 /* Sort after comp_code. */
3458 if (a->comp_code > b->comp_code)
3459 return 1;
3460 else if (a->comp_code < b->comp_code)
3461 return -1;
3463 hashval_t ha, hb;
3465 /* E.g. if a->val is ADDR_EXPR of a VAR_DECL, iterative_hash_expr
3466 uses DECL_UID of the VAR_DECL, so sorting might differ between
3467 -g and -g0. When doing the removal of redundant assert exprs
3468 and commonization to successors, this does not matter, but for
3469 the final sort needs to be stable. */
3470 if (stable)
3472 ha = 0;
3473 hb = 0;
3475 else
3477 ha = iterative_hash_expr (a->expr, iterative_hash_expr (a->val, 0));
3478 hb = iterative_hash_expr (b->expr, iterative_hash_expr (b->val, 0));
3481 /* Break the tie using hashing and source/bb index. */
3482 if (ha == hb)
3483 return (a->e != NULL
3484 ? a->e->src->index - b->e->src->index
3485 : a->bb->index - b->bb->index);
3486 return ha > hb ? 1 : -1;
3489 /* Process all the insertions registered for every name N_i registered
3490 in NEED_ASSERT_FOR. The list of assertions to be inserted are
3491 found in ASSERTS_FOR[i]. */
3493 void
3494 vrp_asserts::process_assert_insertions ()
3496 unsigned i;
3497 bitmap_iterator bi;
3498 bool update_edges_p = false;
3499 int num_asserts = 0;
3501 if (dump_file && (dump_flags & TDF_DETAILS))
3502 dump (dump_file);
3504 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
3506 assert_locus *loc = asserts_for[i];
3507 gcc_assert (loc);
3509 auto_vec<assert_locus *, 16> asserts;
3510 for (; loc; loc = loc->next)
3511 asserts.safe_push (loc);
3512 asserts.qsort (compare_assert_loc<false>);
3514 /* Push down common asserts to successors and remove redundant ones. */
3515 unsigned ecnt = 0;
3516 assert_locus *common = NULL;
3517 unsigned commonj = 0;
3518 for (unsigned j = 0; j < asserts.length (); ++j)
3520 loc = asserts[j];
3521 if (! loc->e)
3522 common = NULL;
3523 else if (! common
3524 || loc->e->dest != common->e->dest
3525 || loc->comp_code != common->comp_code
3526 || ! operand_equal_p (loc->val, common->val, 0)
3527 || ! operand_equal_p (loc->expr, common->expr, 0))
3529 commonj = j;
3530 common = loc;
3531 ecnt = 1;
3533 else if (loc->e == asserts[j-1]->e)
3535 /* Remove duplicate asserts. */
3536 if (commonj == j - 1)
3538 commonj = j;
3539 common = loc;
3541 free (asserts[j-1]);
3542 asserts[j-1] = NULL;
3544 else
3546 ecnt++;
3547 if (EDGE_COUNT (common->e->dest->preds) == ecnt)
3549 /* We have the same assertion on all incoming edges of a BB.
3550 Insert it at the beginning of that block. */
3551 loc->bb = loc->e->dest;
3552 loc->e = NULL;
3553 loc->si = gsi_none ();
3554 common = NULL;
3555 /* Clear asserts commoned. */
3556 for (; commonj != j; ++commonj)
3557 if (asserts[commonj])
3559 free (asserts[commonj]);
3560 asserts[commonj] = NULL;
3566 /* The asserts vector sorting above might be unstable for
3567 -fcompare-debug, sort again to ensure a stable sort. */
3568 asserts.qsort (compare_assert_loc<true>);
3569 for (unsigned j = 0; j < asserts.length (); ++j)
3571 loc = asserts[j];
3572 if (! loc)
3573 break;
3574 update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
3575 num_asserts++;
3576 free (loc);
3580 if (update_edges_p)
3581 gsi_commit_edge_inserts ();
3583 statistics_counter_event (fun, "Number of ASSERT_EXPR expressions inserted",
3584 num_asserts);
3587 /* Traverse the flowgraph looking for conditional jumps to insert range
3588 expressions. These range expressions are meant to provide information
3589 to optimizations that need to reason in terms of value ranges. They
3590 will not be expanded into RTL. For instance, given:
3592 x = ...
3593 y = ...
3594 if (x < y)
3595 y = x - 2;
3596 else
3597 x = y + 3;
3599 this pass will transform the code into:
3601 x = ...
3602 y = ...
3603 if (x < y)
3605 x = ASSERT_EXPR <x, x < y>
3606 y = x - 2
3608 else
3610 y = ASSERT_EXPR <y, x >= y>
3611 x = y + 3
3614 The idea is that once copy and constant propagation have run, other
3615 optimizations will be able to determine what ranges of values can 'x'
3616 take in different paths of the code, simply by checking the reaching
3617 definition of 'x'. */
3619 void
3620 vrp_asserts::insert_range_assertions (void)
3622 need_assert_for = BITMAP_ALLOC (NULL);
3623 asserts_for = XCNEWVEC (assert_locus *, num_ssa_names);
3625 calculate_dominance_info (CDI_DOMINATORS);
3627 find_assert_locations ();
3628 if (!bitmap_empty_p (need_assert_for))
3630 process_assert_insertions ();
3631 update_ssa (TODO_update_ssa_no_phi);
3634 if (dump_file && (dump_flags & TDF_DETAILS))
3636 fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
3637 dump_function_to_file (current_function_decl, dump_file, dump_flags);
3640 free (asserts_for);
3641 BITMAP_FREE (need_assert_for);
3644 /* Return true if all imm uses of VAR are either in STMT, or
3645 feed (optionally through a chain of single imm uses) GIMPLE_COND
3646 in basic block COND_BB. */
3648 bool
3649 vrp_asserts::all_imm_uses_in_stmt_or_feed_cond (tree var,
3650 gimple *stmt,
3651 basic_block cond_bb)
3653 use_operand_p use_p, use2_p;
3654 imm_use_iterator iter;
3656 FOR_EACH_IMM_USE_FAST (use_p, iter, var)
3657 if (USE_STMT (use_p) != stmt)
3659 gimple *use_stmt = USE_STMT (use_p), *use_stmt2;
3660 if (is_gimple_debug (use_stmt))
3661 continue;
3662 while (is_gimple_assign (use_stmt)
3663 && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
3664 && single_imm_use (gimple_assign_lhs (use_stmt),
3665 &use2_p, &use_stmt2))
3666 use_stmt = use_stmt2;
3667 if (gimple_code (use_stmt) != GIMPLE_COND
3668 || gimple_bb (use_stmt) != cond_bb)
3669 return false;
3671 return true;
3674 /* Convert range assertion expressions into the implied copies and
3675 copy propagate away the copies. Doing the trivial copy propagation
3676 here avoids the need to run the full copy propagation pass after
3677 VRP.
3679 FIXME, this will eventually lead to copy propagation removing the
3680 names that had useful range information attached to them. For
3681 instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
3682 then N_i will have the range [3, +INF].
3684 However, by converting the assertion into the implied copy
3685 operation N_i = N_j, we will then copy-propagate N_j into the uses
3686 of N_i and lose the range information.
3688 The problem with keeping ASSERT_EXPRs around is that passes after
3689 VRP need to handle them appropriately.
3691 Another approach would be to make the range information a first
3692 class property of the SSA_NAME so that it can be queried from
3693 any pass. This is made somewhat more complex by the need for
3694 multiple ranges to be associated with one SSA_NAME. */
3696 void
3697 vrp_asserts::remove_range_assertions ()
3699 basic_block bb;
3700 gimple_stmt_iterator si;
3701 /* 1 if looking at ASSERT_EXPRs immediately at the beginning of
3702 a basic block preceeded by GIMPLE_COND branching to it and
3703 __builtin_trap, -1 if not yet checked, 0 otherwise. */
3704 int is_unreachable;
3706 /* Note that the BSI iterator bump happens at the bottom of the
3707 loop and no bump is necessary if we're removing the statement
3708 referenced by the current BSI. */
3709 FOR_EACH_BB_FN (bb, fun)
3710 for (si = gsi_after_labels (bb), is_unreachable = -1; !gsi_end_p (si);)
3712 gimple *stmt = gsi_stmt (si);
3714 if (is_gimple_assign (stmt)
3715 && gimple_assign_rhs_code (stmt) == ASSERT_EXPR)
3717 tree lhs = gimple_assign_lhs (stmt);
3718 tree rhs = gimple_assign_rhs1 (stmt);
3719 tree var;
3721 var = ASSERT_EXPR_VAR (rhs);
3723 if (TREE_CODE (var) == SSA_NAME
3724 && !POINTER_TYPE_P (TREE_TYPE (lhs))
3725 && SSA_NAME_RANGE_INFO (lhs))
3727 if (is_unreachable == -1)
3729 is_unreachable = 0;
3730 if (single_pred_p (bb)
3731 && assert_unreachable_fallthru_edge_p
3732 (single_pred_edge (bb)))
3733 is_unreachable = 1;
3735 /* Handle
3736 if (x_7 >= 10 && x_7 < 20)
3737 __builtin_unreachable ();
3738 x_8 = ASSERT_EXPR <x_7, ...>;
3739 if the only uses of x_7 are in the ASSERT_EXPR and
3740 in the condition. In that case, we can copy the
3741 range info from x_8 computed in this pass also
3742 for x_7. */
3743 if (is_unreachable
3744 && all_imm_uses_in_stmt_or_feed_cond (var, stmt,
3745 single_pred (bb)))
3747 set_range_info (var, SSA_NAME_RANGE_TYPE (lhs),
3748 SSA_NAME_RANGE_INFO (lhs)->get_min (),
3749 SSA_NAME_RANGE_INFO (lhs)->get_max ());
3750 maybe_set_nonzero_bits (single_pred_edge (bb), var);
3754 /* Propagate the RHS into every use of the LHS. For SSA names
3755 also propagate abnormals as it merely restores the original
3756 IL in this case (an replace_uses_by would assert). */
3757 if (TREE_CODE (var) == SSA_NAME)
3759 imm_use_iterator iter;
3760 use_operand_p use_p;
3761 gimple *use_stmt;
3762 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
3763 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
3764 SET_USE (use_p, var);
3766 else
3767 replace_uses_by (lhs, var);
3769 /* And finally, remove the copy, it is not needed. */
3770 gsi_remove (&si, true);
3771 release_defs (stmt);
3773 else
3775 if (!is_gimple_debug (gsi_stmt (si)))
3776 is_unreachable = 0;
3777 gsi_next (&si);
3782 class vrp_prop : public ssa_propagation_engine
3784 public:
3785 vrp_prop (vr_values *v)
3786 : ssa_propagation_engine (),
3787 m_vr_values (v) { }
3789 void initialize (struct function *);
3790 void finalize ();
3792 private:
3793 enum ssa_prop_result visit_stmt (gimple *, edge *, tree *) FINAL OVERRIDE;
3794 enum ssa_prop_result visit_phi (gphi *) FINAL OVERRIDE;
3796 struct function *fun;
3797 vr_values *m_vr_values;
3800 /* Initialization required by ssa_propagate engine. */
3802 void
3803 vrp_prop::initialize (struct function *fn)
3805 basic_block bb;
3806 fun = fn;
3808 FOR_EACH_BB_FN (bb, fun)
3810 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
3811 gsi_next (&si))
3813 gphi *phi = si.phi ();
3814 if (!stmt_interesting_for_vrp (phi))
3816 tree lhs = PHI_RESULT (phi);
3817 m_vr_values->set_def_to_varying (lhs);
3818 prop_set_simulate_again (phi, false);
3820 else
3821 prop_set_simulate_again (phi, true);
3824 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
3825 gsi_next (&si))
3827 gimple *stmt = gsi_stmt (si);
3829 /* If the statement is a control insn, then we do not
3830 want to avoid simulating the statement once. Failure
3831 to do so means that those edges will never get added. */
3832 if (stmt_ends_bb_p (stmt))
3833 prop_set_simulate_again (stmt, true);
3834 else if (!stmt_interesting_for_vrp (stmt))
3836 m_vr_values->set_defs_to_varying (stmt);
3837 prop_set_simulate_again (stmt, false);
3839 else
3840 prop_set_simulate_again (stmt, true);
3845 /* Evaluate statement STMT. If the statement produces a useful range,
3846 return SSA_PROP_INTERESTING and record the SSA name with the
3847 interesting range into *OUTPUT_P.
3849 If STMT is a conditional branch and we can determine its truth
3850 value, the taken edge is recorded in *TAKEN_EDGE_P.
3852 If STMT produces a varying value, return SSA_PROP_VARYING. */
3854 enum ssa_prop_result
3855 vrp_prop::visit_stmt (gimple *stmt, edge *taken_edge_p, tree *output_p)
3857 tree lhs = gimple_get_lhs (stmt);
3858 value_range_equiv vr;
3859 m_vr_values->extract_range_from_stmt (stmt, taken_edge_p, output_p, &vr);
3861 if (*output_p)
3863 if (m_vr_values->update_value_range (*output_p, &vr))
3865 if (dump_file && (dump_flags & TDF_DETAILS))
3867 fprintf (dump_file, "Found new range for ");
3868 print_generic_expr (dump_file, *output_p);
3869 fprintf (dump_file, ": ");
3870 dump_value_range (dump_file, &vr);
3871 fprintf (dump_file, "\n");
3874 if (vr.varying_p ())
3875 return SSA_PROP_VARYING;
3877 return SSA_PROP_INTERESTING;
3879 return SSA_PROP_NOT_INTERESTING;
3882 if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
3883 switch (gimple_call_internal_fn (stmt))
3885 case IFN_ADD_OVERFLOW:
3886 case IFN_SUB_OVERFLOW:
3887 case IFN_MUL_OVERFLOW:
3888 case IFN_ATOMIC_COMPARE_EXCHANGE:
3889 /* These internal calls return _Complex integer type,
3890 which VRP does not track, but the immediate uses
3891 thereof might be interesting. */
3892 if (lhs && TREE_CODE (lhs) == SSA_NAME)
3894 imm_use_iterator iter;
3895 use_operand_p use_p;
3896 enum ssa_prop_result res = SSA_PROP_VARYING;
3898 m_vr_values->set_def_to_varying (lhs);
3900 FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
3902 gimple *use_stmt = USE_STMT (use_p);
3903 if (!is_gimple_assign (use_stmt))
3904 continue;
3905 enum tree_code rhs_code = gimple_assign_rhs_code (use_stmt);
3906 if (rhs_code != REALPART_EXPR && rhs_code != IMAGPART_EXPR)
3907 continue;
3908 tree rhs1 = gimple_assign_rhs1 (use_stmt);
3909 tree use_lhs = gimple_assign_lhs (use_stmt);
3910 if (TREE_CODE (rhs1) != rhs_code
3911 || TREE_OPERAND (rhs1, 0) != lhs
3912 || TREE_CODE (use_lhs) != SSA_NAME
3913 || !stmt_interesting_for_vrp (use_stmt)
3914 || (!INTEGRAL_TYPE_P (TREE_TYPE (use_lhs))
3915 || !TYPE_MIN_VALUE (TREE_TYPE (use_lhs))
3916 || !TYPE_MAX_VALUE (TREE_TYPE (use_lhs))))
3917 continue;
3919 /* If there is a change in the value range for any of the
3920 REALPART_EXPR/IMAGPART_EXPR immediate uses, return
3921 SSA_PROP_INTERESTING. If there are any REALPART_EXPR
3922 or IMAGPART_EXPR immediate uses, but none of them have
3923 a change in their value ranges, return
3924 SSA_PROP_NOT_INTERESTING. If there are no
3925 {REAL,IMAG}PART_EXPR uses at all,
3926 return SSA_PROP_VARYING. */
3927 value_range_equiv new_vr;
3928 m_vr_values->extract_range_basic (&new_vr, use_stmt);
3929 const value_range_equiv *old_vr
3930 = m_vr_values->get_value_range (use_lhs);
3931 if (!old_vr->equal_p (new_vr, /*ignore_equivs=*/false))
3932 res = SSA_PROP_INTERESTING;
3933 else
3934 res = SSA_PROP_NOT_INTERESTING;
3935 new_vr.equiv_clear ();
3936 if (res == SSA_PROP_INTERESTING)
3938 *output_p = lhs;
3939 return res;
3943 return res;
3945 break;
3946 default:
3947 break;
3950 /* All other statements produce nothing of interest for VRP, so mark
3951 their outputs varying and prevent further simulation. */
3952 m_vr_values->set_defs_to_varying (stmt);
3954 return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
3957 /* Visit all arguments for PHI node PHI that flow through executable
3958 edges. If a valid value range can be derived from all the incoming
3959 value ranges, set a new range for the LHS of PHI. */
3961 enum ssa_prop_result
3962 vrp_prop::visit_phi (gphi *phi)
3964 tree lhs = PHI_RESULT (phi);
3965 value_range_equiv vr_result;
3966 m_vr_values->extract_range_from_phi_node (phi, &vr_result);
3967 if (m_vr_values->update_value_range (lhs, &vr_result))
3969 if (dump_file && (dump_flags & TDF_DETAILS))
3971 fprintf (dump_file, "Found new range for ");
3972 print_generic_expr (dump_file, lhs);
3973 fprintf (dump_file, ": ");
3974 dump_value_range (dump_file, &vr_result);
3975 fprintf (dump_file, "\n");
3978 if (vr_result.varying_p ())
3979 return SSA_PROP_VARYING;
3981 return SSA_PROP_INTERESTING;
3984 /* Nothing changed, don't add outgoing edges. */
3985 return SSA_PROP_NOT_INTERESTING;
3988 /* Traverse all the blocks folding conditionals with known ranges. */
3990 void
3991 vrp_prop::finalize ()
3993 size_t i;
3995 /* We have completed propagating through the lattice. */
3996 m_vr_values->set_lattice_propagation_complete ();
3998 if (dump_file)
4000 fprintf (dump_file, "\nValue ranges after VRP:\n\n");
4001 m_vr_values->dump (dump_file);
4002 fprintf (dump_file, "\n");
4005 /* Set value range to non pointer SSA_NAMEs. */
4006 for (i = 0; i < num_ssa_names; i++)
4008 tree name = ssa_name (i);
4009 if (!name)
4010 continue;
4012 const value_range_equiv *vr = m_vr_values->get_value_range (name);
4013 if (!name || vr->varying_p () || !vr->constant_p ())
4014 continue;
4016 if (POINTER_TYPE_P (TREE_TYPE (name))
4017 && range_includes_zero_p (vr) == 0)
4018 set_ptr_nonnull (name);
4019 else if (!POINTER_TYPE_P (TREE_TYPE (name)))
4020 set_range_info (name, *vr);
4024 class vrp_folder : public substitute_and_fold_engine
4026 public:
4027 vrp_folder (vr_values *v)
4028 : substitute_and_fold_engine (/* Fold all stmts. */ true),
4029 m_vr_values (v), simplifier (v)
4031 void simplify_casted_conds (function *fun);
4033 private:
4034 tree value_of_expr (tree name, gimple *stmt) OVERRIDE
4036 return m_vr_values->value_of_expr (name, stmt);
4038 bool fold_stmt (gimple_stmt_iterator *) FINAL OVERRIDE;
4039 bool fold_predicate_in (gimple_stmt_iterator *);
4041 vr_values *m_vr_values;
4042 simplify_using_ranges simplifier;
4045 /* If the statement pointed by SI has a predicate whose value can be
4046 computed using the value range information computed by VRP, compute
4047 its value and return true. Otherwise, return false. */
4049 bool
4050 vrp_folder::fold_predicate_in (gimple_stmt_iterator *si)
4052 bool assignment_p = false;
4053 tree val;
4054 gimple *stmt = gsi_stmt (*si);
4056 if (is_gimple_assign (stmt)
4057 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
4059 assignment_p = true;
4060 val = simplifier.vrp_evaluate_conditional (gimple_assign_rhs_code (stmt),
4061 gimple_assign_rhs1 (stmt),
4062 gimple_assign_rhs2 (stmt),
4063 stmt);
4065 else if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
4066 val = simplifier.vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
4067 gimple_cond_lhs (cond_stmt),
4068 gimple_cond_rhs (cond_stmt),
4069 stmt);
4070 else
4071 return false;
4073 if (val)
4075 if (assignment_p)
4076 val = fold_convert (TREE_TYPE (gimple_assign_lhs (stmt)), val);
4078 if (dump_file)
4080 fprintf (dump_file, "Folding predicate ");
4081 print_gimple_expr (dump_file, stmt, 0);
4082 fprintf (dump_file, " to ");
4083 print_generic_expr (dump_file, val);
4084 fprintf (dump_file, "\n");
4087 if (is_gimple_assign (stmt))
4088 gimple_assign_set_rhs_from_tree (si, val);
4089 else
4091 gcc_assert (gimple_code (stmt) == GIMPLE_COND);
4092 gcond *cond_stmt = as_a <gcond *> (stmt);
4093 if (integer_zerop (val))
4094 gimple_cond_make_false (cond_stmt);
4095 else if (integer_onep (val))
4096 gimple_cond_make_true (cond_stmt);
4097 else
4098 gcc_unreachable ();
4101 return true;
4104 return false;
4107 /* Callback for substitute_and_fold folding the stmt at *SI. */
4109 bool
4110 vrp_folder::fold_stmt (gimple_stmt_iterator *si)
4112 if (fold_predicate_in (si))
4113 return true;
4115 return simplifier.simplify (si);
4118 /* A comparison of an SSA_NAME against a constant where the SSA_NAME
4119 was set by a type conversion can often be rewritten to use the RHS
4120 of the type conversion. Do this optimization for all conditionals
4121 in FUN. */
4123 void
4124 vrp_folder::simplify_casted_conds (function *fun)
4126 basic_block bb;
4127 FOR_EACH_BB_FN (bb, fun)
4129 gimple *last = last_stmt (bb);
4130 if (last && gimple_code (last) == GIMPLE_COND)
4132 if (simplifier.simplify_casted_cond (as_a <gcond *> (last)))
4134 if (dump_file && (dump_flags & TDF_DETAILS))
4136 fprintf (dump_file, "Folded into: ");
4137 print_gimple_stmt (dump_file, last, 0, TDF_SLIM);
4138 fprintf (dump_file, "\n");
4145 /* Main entry point to VRP (Value Range Propagation). This pass is
4146 loosely based on J. R. C. Patterson, ``Accurate Static Branch
4147 Prediction by Value Range Propagation,'' in SIGPLAN Conference on
4148 Programming Language Design and Implementation, pp. 67-78, 1995.
4149 Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
4151 This is essentially an SSA-CCP pass modified to deal with ranges
4152 instead of constants.
4154 While propagating ranges, we may find that two or more SSA name
4155 have equivalent, though distinct ranges. For instance,
4157 1 x_9 = p_3->a;
4158 2 p_4 = ASSERT_EXPR <p_3, p_3 != 0>
4159 3 if (p_4 == q_2)
4160 4 p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
4161 5 endif
4162 6 if (q_2)
4164 In the code above, pointer p_5 has range [q_2, q_2], but from the
4165 code we can also determine that p_5 cannot be NULL and, if q_2 had
4166 a non-varying range, p_5's range should also be compatible with it.
4168 These equivalences are created by two expressions: ASSERT_EXPR and
4169 copy operations. Since p_5 is an assertion on p_4, and p_4 was the
4170 result of another assertion, then we can use the fact that p_5 and
4171 p_4 are equivalent when evaluating p_5's range.
4173 Together with value ranges, we also propagate these equivalences
4174 between names so that we can take advantage of information from
4175 multiple ranges when doing final replacement. Note that this
4176 equivalency relation is transitive but not symmetric.
4178 In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
4179 cannot assert that q_2 is equivalent to p_5 because q_2 may be used
4180 in contexts where that assertion does not hold (e.g., in line 6).
4182 TODO, the main difference between this pass and Patterson's is that
4183 we do not propagate edge probabilities. We only compute whether
4184 edges can be taken or not. That is, instead of having a spectrum
4185 of jump probabilities between 0 and 1, we only deal with 0, 1 and
4186 DON'T KNOW. In the future, it may be worthwhile to propagate
4187 probabilities to aid branch prediction. */
4189 static unsigned int
4190 execute_vrp (struct function *fun, bool warn_array_bounds_p)
4192 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
4193 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
4194 scev_initialize ();
4196 /* ??? This ends up using stale EDGE_DFS_BACK for liveness computation.
4197 Inserting assertions may split edges which will invalidate
4198 EDGE_DFS_BACK. */
4199 vrp_asserts assert_engine (fun);
4200 assert_engine.insert_range_assertions ();
4202 /* For visiting PHI nodes we need EDGE_DFS_BACK computed. */
4203 mark_dfs_back_edges ();
4205 vr_values vrp_vr_values;
4207 class vrp_prop vrp_prop (&vrp_vr_values);
4208 vrp_prop.initialize (fun);
4209 vrp_prop.ssa_propagate ();
4211 /* Instantiate the folder here, so that edge cleanups happen at the
4212 end of this function. */
4213 vrp_folder folder (&vrp_vr_values);
4214 vrp_prop.finalize ();
4216 /* If we're checking array refs, we want to merge information on
4217 the executability of each edge between vrp_folder and the
4218 check_array_bounds_dom_walker: each can clear the
4219 EDGE_EXECUTABLE flag on edges, in different ways.
4221 Hence, if we're going to call check_all_array_refs, set
4222 the flag on every edge now, rather than in
4223 check_array_bounds_dom_walker's ctor; vrp_folder may clear
4224 it from some edges. */
4225 if (warn_array_bounds && warn_array_bounds_p)
4226 set_all_edges_as_executable (fun);
4228 folder.substitute_and_fold ();
4230 if (warn_array_bounds && warn_array_bounds_p)
4232 array_bounds_checker array_checker (fun, &vrp_vr_values);
4233 array_checker.check ();
4236 folder.simplify_casted_conds (fun);
4238 free_numbers_of_iterations_estimates (fun);
4240 assert_engine.remove_range_assertions ();
4242 scev_finalize ();
4243 loop_optimizer_finalize ();
4244 return 0;
4247 // This is a ranger based folder which continues to use the dominator
4248 // walk to access the substitute and fold machinery. Ranges are calculated
4249 // on demand.
4251 class rvrp_folder : public substitute_and_fold_engine
4253 public:
4255 rvrp_folder (gimple_ranger *r) : substitute_and_fold_engine (),
4256 m_simplifier (r, r->non_executable_edge_flag)
4258 m_ranger = r;
4259 m_pta = new pointer_equiv_analyzer (m_ranger);
4262 ~rvrp_folder ()
4264 delete m_pta;
4267 tree value_of_expr (tree name, gimple *s = NULL) OVERRIDE
4269 // Shortcircuit subst_and_fold callbacks for abnormal ssa_names.
4270 if (TREE_CODE (name) == SSA_NAME && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
4271 return NULL;
4272 tree ret = m_ranger->value_of_expr (name, s);
4273 if (!ret && supported_pointer_equiv_p (name))
4274 ret = m_pta->get_equiv (name);
4275 return ret;
4278 tree value_on_edge (edge e, tree name) OVERRIDE
4280 // Shortcircuit subst_and_fold callbacks for abnormal ssa_names.
4281 if (TREE_CODE (name) == SSA_NAME && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
4282 return NULL;
4283 tree ret = m_ranger->value_on_edge (e, name);
4284 if (!ret && supported_pointer_equiv_p (name))
4285 ret = m_pta->get_equiv (name);
4286 return ret;
4289 tree value_of_stmt (gimple *s, tree name = NULL) OVERRIDE
4291 // Shortcircuit subst_and_fold callbacks for abnormal ssa_names.
4292 if (TREE_CODE (name) == SSA_NAME && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
4293 return NULL;
4294 return m_ranger->value_of_stmt (s, name);
4297 void pre_fold_bb (basic_block bb) OVERRIDE
4299 m_pta->enter (bb);
4302 void post_fold_bb (basic_block bb) OVERRIDE
4304 m_pta->leave (bb);
4307 void pre_fold_stmt (gimple *stmt) OVERRIDE
4309 m_pta->visit_stmt (stmt);
4312 bool fold_stmt (gimple_stmt_iterator *gsi) OVERRIDE
4314 if (m_simplifier.simplify (gsi))
4315 return true;
4316 return m_ranger->fold_stmt (gsi, follow_single_use_edges);
4319 private:
4320 DISABLE_COPY_AND_ASSIGN (rvrp_folder);
4321 gimple_ranger *m_ranger;
4322 simplify_using_ranges m_simplifier;
4323 pointer_equiv_analyzer *m_pta;
4326 /* Main entry point for a VRP pass using just ranger. This can be called
4327 from anywhere to perform a VRP pass, including from EVRP. */
4329 unsigned int
4330 execute_ranger_vrp (struct function *fun, bool warn_array_bounds_p)
4332 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
4333 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
4334 scev_initialize ();
4335 calculate_dominance_info (CDI_DOMINATORS);
4337 gimple_ranger *ranger = enable_ranger (fun);
4338 rvrp_folder folder (ranger);
4339 folder.substitute_and_fold ();
4340 ranger->export_global_ranges ();
4341 if (dump_file && (dump_flags & TDF_DETAILS))
4342 ranger->dump (dump_file);
4344 if (warn_array_bounds && warn_array_bounds_p)
4346 // Set all edges as executable, except those ranger says aren't.
4347 int non_exec_flag = ranger->non_executable_edge_flag;
4348 basic_block bb;
4349 FOR_ALL_BB_FN (bb, fun)
4351 edge_iterator ei;
4352 edge e;
4353 FOR_EACH_EDGE (e, ei, bb->succs)
4354 if (e->flags & non_exec_flag)
4355 e->flags &= ~EDGE_EXECUTABLE;
4356 else
4357 e->flags |= EDGE_EXECUTABLE;
4359 scev_reset ();
4360 array_bounds_checker array_checker (fun, ranger);
4361 array_checker.check ();
4364 disable_ranger (fun);
4365 scev_finalize ();
4366 loop_optimizer_finalize ();
4367 return 0;
4370 namespace {
4372 const pass_data pass_data_vrp =
4374 GIMPLE_PASS, /* type */
4375 "vrp", /* name */
4376 OPTGROUP_NONE, /* optinfo_flags */
4377 TV_TREE_VRP, /* tv_id */
4378 PROP_ssa, /* properties_required */
4379 0, /* properties_provided */
4380 0, /* properties_destroyed */
4381 0, /* todo_flags_start */
4382 ( TODO_cleanup_cfg | TODO_update_ssa ), /* todo_flags_finish */
4385 static int vrp_pass_num = 0;
4386 class pass_vrp : public gimple_opt_pass
4388 public:
4389 pass_vrp (gcc::context *ctxt)
4390 : gimple_opt_pass (pass_data_vrp, ctxt), warn_array_bounds_p (false),
4391 my_pass (++vrp_pass_num)
4394 /* opt_pass methods: */
4395 opt_pass * clone () { return new pass_vrp (m_ctxt); }
4396 void set_pass_param (unsigned int n, bool param)
4398 gcc_assert (n == 0);
4399 warn_array_bounds_p = param;
4401 virtual bool gate (function *) { return flag_tree_vrp != 0; }
4402 virtual unsigned int execute (function *fun)
4404 if ((my_pass == 1 && param_vrp1_mode == VRP_MODE_RANGER)
4405 || (my_pass == 2 && param_vrp2_mode == VRP_MODE_RANGER))
4406 return execute_ranger_vrp (fun, warn_array_bounds_p);
4407 return execute_vrp (fun, warn_array_bounds_p);
4410 private:
4411 bool warn_array_bounds_p;
4412 int my_pass;
4413 }; // class pass_vrp
4415 } // anon namespace
4417 gimple_opt_pass *
4418 make_pass_vrp (gcc::context *ctxt)
4420 return new pass_vrp (ctxt);