1 /* Support routines for Value Range Propagation (VRP).
2 Copyright (C) 2005-2020 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)
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/>. */
23 #include "coretypes.h"
25 #include "insn-codes.h"
30 #include "tree-pass.h"
32 #include "optabs-tree.h"
33 #include "gimple-pretty-print.h"
34 #include "diagnostic-core.h"
36 #include "fold-const.h"
37 #include "stor-layout.h"
40 #include "gimple-fold.h"
42 #include "gimple-iterator.h"
43 #include "gimple-walk.h"
46 #include "tree-ssa-loop-manip.h"
47 #include "tree-ssa-loop-niter.h"
48 #include "tree-ssa-loop.h"
49 #include "tree-into-ssa.h"
53 #include "tree-scalar-evolution.h"
54 #include "tree-ssa-propagate.h"
55 #include "tree-chrec.h"
56 #include "tree-ssa-threadupdate.h"
57 #include "tree-ssa-scopedtables.h"
58 #include "tree-ssa-threadedge.h"
59 #include "omp-general.h"
61 #include "case-cfn-macros.h"
62 #include "alloc-pool.h"
64 #include "tree-cfgcleanup.h"
65 #include "stringpool.h"
67 #include "vr-values.h"
70 #include "value-range-equiv.h"
72 /* Set of SSA names found live during the RPO traversal of the function
73 for still active basic-blocks. */
79 void set (tree
, basic_block
);
80 void clear (tree
, basic_block
);
81 void merge (basic_block dest
, basic_block src
);
82 bool live_on_block_p (tree
, basic_block
);
83 bool live_on_edge_p (tree
, edge
);
84 bool block_has_live_names_p (basic_block
);
85 void clear_block (basic_block
);
90 void init_bitmap_if_needed (basic_block
);
94 live_names::init_bitmap_if_needed (basic_block bb
)
96 unsigned i
= bb
->index
;
99 live
[i
] = sbitmap_alloc (num_ssa_names
);
100 bitmap_clear (live
[i
]);
105 live_names::block_has_live_names_p (basic_block bb
)
107 unsigned i
= bb
->index
;
108 return live
[i
] && bitmap_empty_p (live
[i
]);
112 live_names::clear_block (basic_block bb
)
114 unsigned i
= bb
->index
;
117 sbitmap_free (live
[i
]);
123 live_names::merge (basic_block dest
, basic_block src
)
125 init_bitmap_if_needed (dest
);
126 init_bitmap_if_needed (src
);
127 bitmap_ior (live
[dest
->index
], live
[dest
->index
], live
[src
->index
]);
131 live_names::set (tree name
, basic_block bb
)
133 init_bitmap_if_needed (bb
);
134 bitmap_set_bit (live
[bb
->index
], SSA_NAME_VERSION (name
));
138 live_names::clear (tree name
, basic_block bb
)
140 unsigned i
= bb
->index
;
142 bitmap_clear_bit (live
[i
], SSA_NAME_VERSION (name
));
145 live_names::live_names ()
147 num_blocks
= last_basic_block_for_fn (cfun
);
148 live
= XCNEWVEC (sbitmap
, num_blocks
);
151 live_names::~live_names ()
153 for (unsigned i
= 0; i
< num_blocks
; ++i
)
155 sbitmap_free (live
[i
]);
160 live_names::live_on_block_p (tree name
, basic_block bb
)
162 return (live
[bb
->index
]
163 && bitmap_bit_p (live
[bb
->index
], SSA_NAME_VERSION (name
)));
167 /* Location information for ASSERT_EXPRs. Each instance of this
168 structure describes an ASSERT_EXPR for an SSA name. Since a single
169 SSA name may have more than one assertion associated with it, these
170 locations are kept in a linked list attached to the corresponding
174 /* Basic block where the assertion would be inserted. */
177 /* Some assertions need to be inserted on an edge (e.g., assertions
178 generated by COND_EXPRs). In those cases, BB will be NULL. */
181 /* Pointer to the statement that generated this assertion. */
182 gimple_stmt_iterator si
;
184 /* Predicate code for the ASSERT_EXPR. Must be COMPARISON_CLASS_P. */
185 enum tree_code comp_code
;
187 /* Value being compared against. */
190 /* Expression to compare. */
193 /* Next node in the linked list. */
200 vrp_insert (struct function
*fn
) : fun (fn
) { }
202 /* Traverse the flowgraph looking for conditional jumps to insert range
203 expressions. These range expressions are meant to provide information
204 to optimizations that need to reason in terms of value ranges. They
205 will not be expanded into RTL. See method implementation comment
207 void insert_range_assertions ();
209 /* Convert range assertion expressions into the implied copies and
210 copy propagate away the copies. */
211 void remove_range_assertions ();
213 /* Dump all the registered assertions for all the names to FILE. */
216 /* Dump all the registered assertions for NAME to FILE. */
217 void dump (FILE *file
, tree name
);
219 /* Dump all the registered assertions for NAME to stderr. */
220 void debug (tree name
)
225 /* Dump all the registered assertions for all the names to stderr. */
232 /* Set of SSA names found live during the RPO traversal of the function
233 for still active basic-blocks. */
236 /* Function to work on. */
237 struct function
*fun
;
239 /* If bit I is present, it means that SSA name N_i has a list of
240 assertions that should be inserted in the IL. */
241 bitmap need_assert_for
;
243 /* Array of locations lists where to insert assertions. ASSERTS_FOR[I]
244 holds a list of ASSERT_LOCUS_T nodes that describe where
245 ASSERT_EXPRs for SSA name N_I should be inserted. */
246 assert_locus
**asserts_for
;
248 /* Finish found ASSERTS for E and register them at GSI. */
249 void finish_register_edge_assert_for (edge e
, gimple_stmt_iterator gsi
,
250 vec
<assert_info
> &asserts
);
252 /* Determine whether the outgoing edges of BB should receive an
253 ASSERT_EXPR for each of the operands of BB's LAST statement. The
254 last statement of BB must be a SWITCH_EXPR.
256 If any of the sub-graphs rooted at BB have an interesting use of
257 the predicate operands, an assert location node is added to the
258 list of assertions for the corresponding operands. */
259 void find_switch_asserts (basic_block bb
, gswitch
*last
);
261 /* Do an RPO walk over the function computing SSA name liveness
262 on-the-fly and deciding on assert expressions to insert. */
263 void find_assert_locations ();
265 /* Traverse all the statements in block BB looking for statements that
266 may generate useful assertions for the SSA names in their operand.
267 See method implementation comentary for more information. */
268 void find_assert_locations_in_bb (basic_block bb
);
270 /* Determine whether the outgoing edges of BB should receive an
271 ASSERT_EXPR for each of the operands of BB's LAST statement.
272 The last statement of BB must be a COND_EXPR.
274 If any of the sub-graphs rooted at BB have an interesting use of
275 the predicate operands, an assert location node is added to the
276 list of assertions for the corresponding operands. */
277 void find_conditional_asserts (basic_block bb
, gcond
*last
);
279 /* Process all the insertions registered for every name N_i registered
280 in NEED_ASSERT_FOR. The list of assertions to be inserted are
281 found in ASSERTS_FOR[i]. */
282 void process_assert_insertions ();
284 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
285 'EXPR COMP_CODE VAL' at a location that dominates block BB or
286 E->DEST, then register this location as a possible insertion point
287 for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
289 BB, E and SI provide the exact insertion point for the new
290 ASSERT_EXPR. If BB is NULL, then the ASSERT_EXPR is to be inserted
291 on edge E. Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
292 BB. If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
294 void register_new_assert_for (tree name
, tree expr
,
295 enum tree_code comp_code
,
296 tree val
, basic_block bb
,
297 edge e
, gimple_stmt_iterator si
);
299 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
300 create a new SSA name N and return the assertion assignment
301 'N = ASSERT_EXPR <V, V OP W>'. */
302 gimple
*build_assert_expr_for (tree cond
, tree v
);
304 /* Create an ASSERT_EXPR for NAME and insert it in the location
305 indicated by LOC. Return true if we made any edge insertions. */
306 bool process_assert_insertions_for (tree name
, assert_locus
*loc
);
308 /* Qsort callback for sorting assert locations. */
309 template <bool stable
> static int compare_assert_loc (const void *,
313 /* Return true if the SSA name NAME is live on the edge E. */
316 live_names::live_on_edge_p (tree name
, edge e
)
318 return live_on_block_p (name
, e
->dest
);
322 /* VR_TYPE describes a range with mininum value *MIN and maximum
323 value *MAX. Restrict the range to the set of values that have
324 no bits set outside NONZERO_BITS. Update *MIN and *MAX and
325 return the new range type.
327 SGN gives the sign of the values described by the range. */
329 enum value_range_kind
330 intersect_range_with_nonzero_bits (enum value_range_kind vr_type
,
331 wide_int
*min
, wide_int
*max
,
332 const wide_int
&nonzero_bits
,
335 if (vr_type
== VR_ANTI_RANGE
)
337 /* The VR_ANTI_RANGE is equivalent to the union of the ranges
338 A: [-INF, *MIN) and B: (*MAX, +INF]. First use NONZERO_BITS
339 to create an inclusive upper bound for A and an inclusive lower
341 wide_int a_max
= wi::round_down_for_mask (*min
- 1, nonzero_bits
);
342 wide_int b_min
= wi::round_up_for_mask (*max
+ 1, nonzero_bits
);
344 /* If the calculation of A_MAX wrapped, A is effectively empty
345 and A_MAX is the highest value that satisfies NONZERO_BITS.
346 Likewise if the calculation of B_MIN wrapped, B is effectively
347 empty and B_MIN is the lowest value that satisfies NONZERO_BITS. */
348 bool a_empty
= wi::ge_p (a_max
, *min
, sgn
);
349 bool b_empty
= wi::le_p (b_min
, *max
, sgn
);
351 /* If both A and B are empty, there are no valid values. */
352 if (a_empty
&& b_empty
)
355 /* If exactly one of A or B is empty, return a VR_RANGE for the
357 if (a_empty
|| b_empty
)
361 gcc_checking_assert (wi::le_p (*min
, *max
, sgn
));
365 /* Update the VR_ANTI_RANGE bounds. */
368 gcc_checking_assert (wi::le_p (*min
, *max
, sgn
));
370 /* Now check whether the excluded range includes any values that
371 satisfy NONZERO_BITS. If not, switch to a full VR_RANGE. */
372 if (wi::round_up_for_mask (*min
, nonzero_bits
) == b_min
)
374 unsigned int precision
= min
->get_precision ();
375 *min
= wi::min_value (precision
, sgn
);
376 *max
= wi::max_value (precision
, sgn
);
380 if (vr_type
== VR_RANGE
)
382 *max
= wi::round_down_for_mask (*max
, nonzero_bits
);
384 /* Check that the range contains at least one valid value. */
385 if (wi::gt_p (*min
, *max
, sgn
))
388 *min
= wi::round_up_for_mask (*min
, nonzero_bits
);
389 gcc_checking_assert (wi::le_p (*min
, *max
, sgn
));
394 /* Return true if max and min of VR are INTEGER_CST. It's not necessary
398 range_int_cst_p (const value_range
*vr
)
400 return (vr
->kind () == VR_RANGE
&& range_has_numeric_bounds_p (vr
));
403 /* Return the single symbol (an SSA_NAME) contained in T if any, or NULL_TREE
404 otherwise. We only handle additive operations and set NEG to true if the
405 symbol is negated and INV to the invariant part, if any. */
408 get_single_symbol (tree t
, bool *neg
, tree
*inv
)
416 if (TREE_CODE (t
) == PLUS_EXPR
417 || TREE_CODE (t
) == POINTER_PLUS_EXPR
418 || TREE_CODE (t
) == MINUS_EXPR
)
420 if (is_gimple_min_invariant (TREE_OPERAND (t
, 0)))
422 neg_
= (TREE_CODE (t
) == MINUS_EXPR
);
423 inv_
= TREE_OPERAND (t
, 0);
424 t
= TREE_OPERAND (t
, 1);
426 else if (is_gimple_min_invariant (TREE_OPERAND (t
, 1)))
429 inv_
= TREE_OPERAND (t
, 1);
430 t
= TREE_OPERAND (t
, 0);
441 if (TREE_CODE (t
) == NEGATE_EXPR
)
443 t
= TREE_OPERAND (t
, 0);
447 if (TREE_CODE (t
) != SSA_NAME
)
450 if (inv_
&& TREE_OVERFLOW_P (inv_
))
451 inv_
= drop_tree_overflow (inv_
);
458 /* The reverse operation: build a symbolic expression with TYPE
459 from symbol SYM, negated according to NEG, and invariant INV. */
462 build_symbolic_expr (tree type
, tree sym
, bool neg
, tree inv
)
464 const bool pointer_p
= POINTER_TYPE_P (type
);
468 t
= build1 (NEGATE_EXPR
, type
, t
);
470 if (integer_zerop (inv
))
473 return build2 (pointer_p
? POINTER_PLUS_EXPR
: PLUS_EXPR
, type
, t
, inv
);
479 -2 if those are incomparable. */
481 operand_less_p (tree val
, tree val2
)
483 /* LT is folded faster than GE and others. Inline the common case. */
484 if (TREE_CODE (val
) == INTEGER_CST
&& TREE_CODE (val2
) == INTEGER_CST
)
485 return tree_int_cst_lt (val
, val2
);
486 else if (TREE_CODE (val
) == SSA_NAME
&& TREE_CODE (val2
) == SSA_NAME
)
487 return val
== val2
? 0 : -2;
490 int cmp
= compare_values (val
, val2
);
493 else if (cmp
== 0 || cmp
== 1)
502 /* Compare two values VAL1 and VAL2. Return
504 -2 if VAL1 and VAL2 cannot be compared at compile-time,
507 +1 if VAL1 > VAL2, and
510 This is similar to tree_int_cst_compare but supports pointer values
511 and values that cannot be compared at compile time.
513 If STRICT_OVERFLOW_P is not NULL, then set *STRICT_OVERFLOW_P to
514 true if the return value is only valid if we assume that signed
515 overflow is undefined. */
518 compare_values_warnv (tree val1
, tree val2
, bool *strict_overflow_p
)
523 /* Below we rely on the fact that VAL1 and VAL2 are both pointers or
525 gcc_assert (POINTER_TYPE_P (TREE_TYPE (val1
))
526 == POINTER_TYPE_P (TREE_TYPE (val2
)));
528 /* Convert the two values into the same type. This is needed because
529 sizetype causes sign extension even for unsigned types. */
530 if (!useless_type_conversion_p (TREE_TYPE (val1
), TREE_TYPE (val2
)))
531 val2
= fold_convert (TREE_TYPE (val1
), val2
);
533 const bool overflow_undefined
534 = INTEGRAL_TYPE_P (TREE_TYPE (val1
))
535 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1
));
538 tree sym1
= get_single_symbol (val1
, &neg1
, &inv1
);
539 tree sym2
= get_single_symbol (val2
, &neg2
, &inv2
);
541 /* If VAL1 and VAL2 are of the form '[-]NAME [+ CST]', return -1 or +1
542 accordingly. If VAL1 and VAL2 don't use the same name, return -2. */
545 /* Both values must use the same name with the same sign. */
546 if (sym1
!= sym2
|| neg1
!= neg2
)
549 /* [-]NAME + CST == [-]NAME + CST. */
553 /* If overflow is defined we cannot simplify more. */
554 if (!overflow_undefined
)
557 if (strict_overflow_p
!= NULL
558 /* Symbolic range building sets TREE_NO_WARNING to declare
559 that overflow doesn't happen. */
560 && (!inv1
|| !TREE_NO_WARNING (val1
))
561 && (!inv2
|| !TREE_NO_WARNING (val2
)))
562 *strict_overflow_p
= true;
565 inv1
= build_int_cst (TREE_TYPE (val1
), 0);
567 inv2
= build_int_cst (TREE_TYPE (val2
), 0);
569 return wi::cmp (wi::to_wide (inv1
), wi::to_wide (inv2
),
570 TYPE_SIGN (TREE_TYPE (val1
)));
573 const bool cst1
= is_gimple_min_invariant (val1
);
574 const bool cst2
= is_gimple_min_invariant (val2
);
576 /* If one is of the form '[-]NAME + CST' and the other is constant, then
577 it might be possible to say something depending on the constants. */
578 if ((sym1
&& inv1
&& cst2
) || (sym2
&& inv2
&& cst1
))
580 if (!overflow_undefined
)
583 if (strict_overflow_p
!= NULL
584 /* Symbolic range building sets TREE_NO_WARNING to declare
585 that overflow doesn't happen. */
586 && (!sym1
|| !TREE_NO_WARNING (val1
))
587 && (!sym2
|| !TREE_NO_WARNING (val2
)))
588 *strict_overflow_p
= true;
590 const signop sgn
= TYPE_SIGN (TREE_TYPE (val1
));
591 tree cst
= cst1
? val1
: val2
;
592 tree inv
= cst1
? inv2
: inv1
;
594 /* Compute the difference between the constants. If it overflows or
595 underflows, this means that we can trivially compare the NAME with
596 it and, consequently, the two values with each other. */
597 wide_int diff
= wi::to_wide (cst
) - wi::to_wide (inv
);
598 if (wi::cmp (0, wi::to_wide (inv
), sgn
)
599 != wi::cmp (diff
, wi::to_wide (cst
), sgn
))
601 const int res
= wi::cmp (wi::to_wide (cst
), wi::to_wide (inv
), sgn
);
602 return cst1
? res
: -res
;
608 /* We cannot say anything more for non-constants. */
612 if (!POINTER_TYPE_P (TREE_TYPE (val1
)))
614 /* We cannot compare overflowed values. */
615 if (TREE_OVERFLOW (val1
) || TREE_OVERFLOW (val2
))
618 if (TREE_CODE (val1
) == INTEGER_CST
619 && TREE_CODE (val2
) == INTEGER_CST
)
620 return tree_int_cst_compare (val1
, val2
);
622 if (poly_int_tree_p (val1
) && poly_int_tree_p (val2
))
624 if (known_eq (wi::to_poly_widest (val1
),
625 wi::to_poly_widest (val2
)))
627 if (known_lt (wi::to_poly_widest (val1
),
628 wi::to_poly_widest (val2
)))
630 if (known_gt (wi::to_poly_widest (val1
),
631 wi::to_poly_widest (val2
)))
639 if (TREE_CODE (val1
) == INTEGER_CST
&& TREE_CODE (val2
) == INTEGER_CST
)
641 /* We cannot compare overflowed values. */
642 if (TREE_OVERFLOW (val1
) || TREE_OVERFLOW (val2
))
645 return tree_int_cst_compare (val1
, val2
);
648 /* First see if VAL1 and VAL2 are not the same. */
649 if (operand_equal_p (val1
, val2
, 0))
652 fold_defer_overflow_warnings ();
654 /* If VAL1 is a lower address than VAL2, return -1. */
655 tree t
= fold_binary_to_constant (LT_EXPR
, boolean_type_node
, val1
, val2
);
656 if (t
&& integer_onep (t
))
658 fold_undefer_and_ignore_overflow_warnings ();
662 /* If VAL1 is a higher address than VAL2, return +1. */
663 t
= fold_binary_to_constant (LT_EXPR
, boolean_type_node
, val2
, val1
);
664 if (t
&& integer_onep (t
))
666 fold_undefer_and_ignore_overflow_warnings ();
670 /* If VAL1 is different than VAL2, return +2. */
671 t
= fold_binary_to_constant (NE_EXPR
, boolean_type_node
, val1
, val2
);
672 fold_undefer_and_ignore_overflow_warnings ();
673 if (t
&& integer_onep (t
))
680 /* Compare values like compare_values_warnv. */
683 compare_values (tree val1
, tree val2
)
686 return compare_values_warnv (val1
, val2
, &sop
);
689 /* If BOUND will include a symbolic bound, adjust it accordingly,
690 otherwise leave it as is.
692 CODE is the original operation that combined the bounds (PLUS_EXPR
695 TYPE is the type of the original operation.
697 SYM_OPn is the symbolic for OPn if it has a symbolic.
699 NEG_OPn is TRUE if the OPn was negated. */
702 adjust_symbolic_bound (tree
&bound
, enum tree_code code
, tree type
,
703 tree sym_op0
, tree sym_op1
,
704 bool neg_op0
, bool neg_op1
)
706 bool minus_p
= (code
== MINUS_EXPR
);
707 /* If the result bound is constant, we're done; otherwise, build the
708 symbolic lower bound. */
709 if (sym_op0
== sym_op1
)
712 bound
= build_symbolic_expr (type
, sym_op0
,
716 /* We may not negate if that might introduce
717 undefined overflow. */
720 || TYPE_OVERFLOW_WRAPS (type
))
721 bound
= build_symbolic_expr (type
, sym_op1
,
722 neg_op1
^ minus_p
, bound
);
728 /* Combine OP1 and OP1, which are two parts of a bound, into one wide
729 int bound according to CODE. CODE is the operation combining the
730 bound (either a PLUS_EXPR or a MINUS_EXPR).
732 TYPE is the type of the combine operation.
734 WI is the wide int to store the result.
736 OVF is -1 if an underflow occurred, +1 if an overflow occurred or 0
737 if over/underflow occurred. */
740 combine_bound (enum tree_code code
, wide_int
&wi
, wi::overflow_type
&ovf
,
741 tree type
, tree op0
, tree op1
)
743 bool minus_p
= (code
== MINUS_EXPR
);
744 const signop sgn
= TYPE_SIGN (type
);
745 const unsigned int prec
= TYPE_PRECISION (type
);
747 /* Combine the bounds, if any. */
751 wi
= wi::sub (wi::to_wide (op0
), wi::to_wide (op1
), sgn
, &ovf
);
753 wi
= wi::add (wi::to_wide (op0
), wi::to_wide (op1
), sgn
, &ovf
);
756 wi
= wi::to_wide (op0
);
760 wi
= wi::neg (wi::to_wide (op1
), &ovf
);
762 wi
= wi::to_wide (op1
);
765 wi
= wi::shwi (0, prec
);
768 /* Given a range in [WMIN, WMAX], adjust it for possible overflow and
769 put the result in VR.
771 TYPE is the type of the range.
773 MIN_OVF and MAX_OVF indicate what type of overflow, if any,
774 occurred while originally calculating WMIN or WMAX. -1 indicates
775 underflow. +1 indicates overflow. 0 indicates neither. */
778 set_value_range_with_overflow (value_range_kind
&kind
, tree
&min
, tree
&max
,
780 const wide_int
&wmin
, const wide_int
&wmax
,
781 wi::overflow_type min_ovf
,
782 wi::overflow_type max_ovf
)
784 const signop sgn
= TYPE_SIGN (type
);
785 const unsigned int prec
= TYPE_PRECISION (type
);
787 /* For one bit precision if max < min, then the swapped
788 range covers all values. */
789 if (prec
== 1 && wi::lt_p (wmax
, wmin
, sgn
))
795 if (TYPE_OVERFLOW_WRAPS (type
))
797 /* If overflow wraps, truncate the values and adjust the
798 range kind and bounds appropriately. */
799 wide_int tmin
= wide_int::from (wmin
, prec
, sgn
);
800 wide_int tmax
= wide_int::from (wmax
, prec
, sgn
);
801 if ((min_ovf
!= wi::OVF_NONE
) == (max_ovf
!= wi::OVF_NONE
))
803 /* If the limits are swapped, we wrapped around and cover
805 if (wi::gt_p (tmin
, tmax
, sgn
))
810 /* No overflow or both overflow or underflow. The
811 range kind stays VR_RANGE. */
812 min
= wide_int_to_tree (type
, tmin
);
813 max
= wide_int_to_tree (type
, tmax
);
817 else if ((min_ovf
== wi::OVF_UNDERFLOW
&& max_ovf
== wi::OVF_NONE
)
818 || (max_ovf
== wi::OVF_OVERFLOW
&& min_ovf
== wi::OVF_NONE
))
820 /* Min underflow or max overflow. The range kind
821 changes to VR_ANTI_RANGE. */
825 if (wi::cmp (tmin
, tmax
, sgn
) < 0)
828 if (wi::cmp (tmax
, tem
, sgn
) > 0)
830 /* If the anti-range would cover nothing, drop to varying.
831 Likewise if the anti-range bounds are outside of the
833 if (covers
|| wi::cmp (tmin
, tmax
, sgn
) > 0)
838 kind
= VR_ANTI_RANGE
;
839 min
= wide_int_to_tree (type
, tmin
);
840 max
= wide_int_to_tree (type
, tmax
);
845 /* Other underflow and/or overflow, drop to VR_VARYING. */
852 /* If overflow does not wrap, saturate to the types min/max
854 wide_int type_min
= wi::min_value (prec
, sgn
);
855 wide_int type_max
= wi::max_value (prec
, sgn
);
857 if (min_ovf
== wi::OVF_UNDERFLOW
)
858 min
= wide_int_to_tree (type
, type_min
);
859 else if (min_ovf
== wi::OVF_OVERFLOW
)
860 min
= wide_int_to_tree (type
, type_max
);
862 min
= wide_int_to_tree (type
, wmin
);
864 if (max_ovf
== wi::OVF_UNDERFLOW
)
865 max
= wide_int_to_tree (type
, type_min
);
866 else if (max_ovf
== wi::OVF_OVERFLOW
)
867 max
= wide_int_to_tree (type
, type_max
);
869 max
= wide_int_to_tree (type
, wmax
);
873 /* Fold two value range's of a POINTER_PLUS_EXPR into VR. */
876 extract_range_from_pointer_plus_expr (value_range
*vr
,
879 const value_range
*vr0
,
880 const value_range
*vr1
)
882 gcc_checking_assert (POINTER_TYPE_P (expr_type
)
883 && code
== POINTER_PLUS_EXPR
);
884 /* For pointer types, we are really only interested in asserting
885 whether the expression evaluates to non-NULL.
886 With -fno-delete-null-pointer-checks we need to be more
887 conservative. As some object might reside at address 0,
888 then some offset could be added to it and the same offset
889 subtracted again and the result would be NULL.
891 static int a[12]; where &a[0] is NULL and
894 ptr will be NULL here, even when there is POINTER_PLUS_EXPR
895 where the first range doesn't include zero and the second one
896 doesn't either. As the second operand is sizetype (unsigned),
897 consider all ranges where the MSB could be set as possible
898 subtractions where the result might be NULL. */
899 if ((!range_includes_zero_p (vr0
)
900 || !range_includes_zero_p (vr1
))
901 && !TYPE_OVERFLOW_WRAPS (expr_type
)
902 && (flag_delete_null_pointer_checks
903 || (range_int_cst_p (vr1
)
904 && !tree_int_cst_sign_bit (vr1
->max ()))))
905 vr
->set_nonzero (expr_type
);
906 else if (vr0
->zero_p () && vr1
->zero_p ())
907 vr
->set_zero (expr_type
);
909 vr
->set_varying (expr_type
);
912 /* Extract range information from a PLUS/MINUS_EXPR and store the
916 extract_range_from_plus_minus_expr (value_range
*vr
,
919 const value_range
*vr0_
,
920 const value_range
*vr1_
)
922 gcc_checking_assert (code
== PLUS_EXPR
|| code
== MINUS_EXPR
);
924 value_range vr0
= *vr0_
, vr1
= *vr1_
;
925 value_range vrtem0
, vrtem1
;
927 /* Now canonicalize anti-ranges to ranges when they are not symbolic
928 and express ~[] op X as ([]' op X) U ([]'' op X). */
929 if (vr0
.kind () == VR_ANTI_RANGE
930 && ranges_from_anti_range (&vr0
, &vrtem0
, &vrtem1
))
932 extract_range_from_plus_minus_expr (vr
, code
, expr_type
, &vrtem0
, vr1_
);
933 if (!vrtem1
.undefined_p ())
936 extract_range_from_plus_minus_expr (&vrres
, code
, expr_type
,
942 /* Likewise for X op ~[]. */
943 if (vr1
.kind () == VR_ANTI_RANGE
944 && ranges_from_anti_range (&vr1
, &vrtem0
, &vrtem1
))
946 extract_range_from_plus_minus_expr (vr
, code
, expr_type
, vr0_
, &vrtem0
);
947 if (!vrtem1
.undefined_p ())
950 extract_range_from_plus_minus_expr (&vrres
, code
, expr_type
,
957 value_range_kind kind
;
958 value_range_kind vr0_kind
= vr0
.kind (), vr1_kind
= vr1
.kind ();
959 tree vr0_min
= vr0
.min (), vr0_max
= vr0
.max ();
960 tree vr1_min
= vr1
.min (), vr1_max
= vr1
.max ();
961 tree min
= NULL_TREE
, max
= NULL_TREE
;
963 /* This will normalize things such that calculating
964 [0,0] - VR_VARYING is not dropped to varying, but is
965 calculated as [MIN+1, MAX]. */
966 if (vr0
.varying_p ())
969 vr0_min
= vrp_val_min (expr_type
);
970 vr0_max
= vrp_val_max (expr_type
);
972 if (vr1
.varying_p ())
975 vr1_min
= vrp_val_min (expr_type
);
976 vr1_max
= vrp_val_max (expr_type
);
979 const bool minus_p
= (code
== MINUS_EXPR
);
980 tree min_op0
= vr0_min
;
981 tree min_op1
= minus_p
? vr1_max
: vr1_min
;
982 tree max_op0
= vr0_max
;
983 tree max_op1
= minus_p
? vr1_min
: vr1_max
;
984 tree sym_min_op0
= NULL_TREE
;
985 tree sym_min_op1
= NULL_TREE
;
986 tree sym_max_op0
= NULL_TREE
;
987 tree sym_max_op1
= NULL_TREE
;
988 bool neg_min_op0
, neg_min_op1
, neg_max_op0
, neg_max_op1
;
990 neg_min_op0
= neg_min_op1
= neg_max_op0
= neg_max_op1
= false;
992 /* If we have a PLUS or MINUS with two VR_RANGEs, either constant or
993 single-symbolic ranges, try to compute the precise resulting range,
994 but only if we know that this resulting range will also be constant
995 or single-symbolic. */
996 if (vr0_kind
== VR_RANGE
&& vr1_kind
== VR_RANGE
997 && (TREE_CODE (min_op0
) == INTEGER_CST
999 = get_single_symbol (min_op0
, &neg_min_op0
, &min_op0
)))
1000 && (TREE_CODE (min_op1
) == INTEGER_CST
1002 = get_single_symbol (min_op1
, &neg_min_op1
, &min_op1
)))
1003 && (!(sym_min_op0
&& sym_min_op1
)
1004 || (sym_min_op0
== sym_min_op1
1005 && neg_min_op0
== (minus_p
? neg_min_op1
: !neg_min_op1
)))
1006 && (TREE_CODE (max_op0
) == INTEGER_CST
1008 = get_single_symbol (max_op0
, &neg_max_op0
, &max_op0
)))
1009 && (TREE_CODE (max_op1
) == INTEGER_CST
1011 = get_single_symbol (max_op1
, &neg_max_op1
, &max_op1
)))
1012 && (!(sym_max_op0
&& sym_max_op1
)
1013 || (sym_max_op0
== sym_max_op1
1014 && neg_max_op0
== (minus_p
? neg_max_op1
: !neg_max_op1
))))
1016 wide_int wmin
, wmax
;
1017 wi::overflow_type min_ovf
= wi::OVF_NONE
;
1018 wi::overflow_type max_ovf
= wi::OVF_NONE
;
1020 /* Build the bounds. */
1021 combine_bound (code
, wmin
, min_ovf
, expr_type
, min_op0
, min_op1
);
1022 combine_bound (code
, wmax
, max_ovf
, expr_type
, max_op0
, max_op1
);
1024 /* If the resulting range will be symbolic, we need to eliminate any
1025 explicit or implicit overflow introduced in the above computation
1026 because compare_values could make an incorrect use of it. That's
1027 why we require one of the ranges to be a singleton. */
1028 if ((sym_min_op0
!= sym_min_op1
|| sym_max_op0
!= sym_max_op1
)
1029 && ((bool)min_ovf
|| (bool)max_ovf
1030 || (min_op0
!= max_op0
&& min_op1
!= max_op1
)))
1032 vr
->set_varying (expr_type
);
1036 /* Adjust the range for possible overflow. */
1037 set_value_range_with_overflow (kind
, min
, max
, expr_type
,
1038 wmin
, wmax
, min_ovf
, max_ovf
);
1039 if (kind
== VR_VARYING
)
1041 vr
->set_varying (expr_type
);
1045 /* Build the symbolic bounds if needed. */
1046 adjust_symbolic_bound (min
, code
, expr_type
,
1047 sym_min_op0
, sym_min_op1
,
1048 neg_min_op0
, neg_min_op1
);
1049 adjust_symbolic_bound (max
, code
, expr_type
,
1050 sym_max_op0
, sym_max_op1
,
1051 neg_max_op0
, neg_max_op1
);
1055 /* For other cases, for example if we have a PLUS_EXPR with two
1056 VR_ANTI_RANGEs, drop to VR_VARYING. It would take more effort
1057 to compute a precise range for such a case.
1058 ??? General even mixed range kind operations can be expressed
1059 by for example transforming ~[3, 5] + [1, 2] to range-only
1060 operations and a union primitive:
1061 [-INF, 2] + [1, 2] U [5, +INF] + [1, 2]
1062 [-INF+1, 4] U [6, +INF(OVF)]
1063 though usually the union is not exactly representable with
1064 a single range or anti-range as the above is
1065 [-INF+1, +INF(OVF)] intersected with ~[5, 5]
1066 but one could use a scheme similar to equivalences for this. */
1067 vr
->set_varying (expr_type
);
1071 /* If either MIN or MAX overflowed, then set the resulting range to
1073 if (min
== NULL_TREE
1074 || TREE_OVERFLOW_P (min
)
1076 || TREE_OVERFLOW_P (max
))
1078 vr
->set_varying (expr_type
);
1082 int cmp
= compare_values (min
, max
);
1083 if (cmp
== -2 || cmp
== 1)
1085 /* If the new range has its limits swapped around (MIN > MAX),
1086 then the operation caused one of them to wrap around, mark
1087 the new range VARYING. */
1088 vr
->set_varying (expr_type
);
1091 vr
->set (min
, max
, kind
);
1094 /* Return the range-ops handler for CODE and EXPR_TYPE. If no
1095 suitable operator is found, return NULL and set VR to VARYING. */
1097 static const range_operator
*
1098 get_range_op_handler (value_range
*vr
,
1099 enum tree_code code
,
1102 const range_operator
*op
= range_op_handler (code
, expr_type
);
1104 vr
->set_varying (expr_type
);
1108 /* If the types passed are supported, return TRUE, otherwise set VR to
1109 VARYING and return FALSE. */
1112 supported_types_p (value_range
*vr
,
1116 if (!value_range::supports_type_p (type0
)
1117 || (type1
&& !value_range::supports_type_p (type1
)))
1119 vr
->set_varying (type0
);
1125 /* If any of the ranges passed are defined, return TRUE, otherwise set
1126 VR to UNDEFINED and return FALSE. */
1129 defined_ranges_p (value_range
*vr
,
1130 const value_range
*vr0
, const value_range
*vr1
= NULL
)
1132 if (vr0
->undefined_p () && (!vr1
|| vr1
->undefined_p ()))
1134 vr
->set_undefined ();
1141 drop_undefines_to_varying (const value_range
*vr
, tree expr_type
)
1143 if (vr
->undefined_p ())
1144 return value_range (expr_type
);
1149 /* If any operand is symbolic, perform a binary operation on them and
1150 return TRUE, otherwise return FALSE. */
1153 range_fold_binary_symbolics_p (value_range
*vr
,
1156 const value_range
*vr0
, const value_range
*vr1
)
1158 if (vr0
->symbolic_p () || vr1
->symbolic_p ())
1160 if ((code
== PLUS_EXPR
|| code
== MINUS_EXPR
))
1162 extract_range_from_plus_minus_expr (vr
, code
, expr_type
, vr0
, vr1
);
1165 if (POINTER_TYPE_P (expr_type
) && code
== POINTER_PLUS_EXPR
)
1167 extract_range_from_pointer_plus_expr (vr
, code
, expr_type
, vr0
, vr1
);
1170 const range_operator
*op
= get_range_op_handler (vr
, code
, expr_type
);
1171 value_range
vr0_cst (*vr0
), vr1_cst (*vr1
);
1172 vr0_cst
.normalize_symbolics ();
1173 vr1_cst
.normalize_symbolics ();
1174 return op
->fold_range (*vr
, expr_type
, vr0_cst
, vr1_cst
);
1179 /* If operand is symbolic, perform a unary operation on it and return
1180 TRUE, otherwise return FALSE. */
1183 range_fold_unary_symbolics_p (value_range
*vr
,
1186 const value_range
*vr0
)
1188 if (vr0
->symbolic_p ())
1190 if (code
== NEGATE_EXPR
)
1192 /* -X is simply 0 - X. */
1194 zero
.set_zero (vr0
->type ());
1195 range_fold_binary_expr (vr
, MINUS_EXPR
, expr_type
, &zero
, vr0
);
1198 if (code
== BIT_NOT_EXPR
)
1200 /* ~X is simply -1 - X. */
1201 value_range minusone
;
1202 minusone
.set (build_int_cst (vr0
->type (), -1));
1203 range_fold_binary_expr (vr
, MINUS_EXPR
, expr_type
, &minusone
, vr0
);
1206 const range_operator
*op
= get_range_op_handler (vr
, code
, expr_type
);
1207 value_range
vr0_cst (*vr0
);
1208 vr0_cst
.normalize_symbolics ();
1209 return op
->fold_range (*vr
, expr_type
, vr0_cst
, value_range (expr_type
));
1214 /* Perform a binary operation on a pair of ranges. */
1217 range_fold_binary_expr (value_range
*vr
,
1218 enum tree_code code
,
1220 const value_range
*vr0_
,
1221 const value_range
*vr1_
)
1223 if (!supported_types_p (vr
, expr_type
)
1224 || !defined_ranges_p (vr
, vr0_
, vr1_
))
1226 const range_operator
*op
= get_range_op_handler (vr
, code
, expr_type
);
1230 value_range vr0
= drop_undefines_to_varying (vr0_
, expr_type
);
1231 value_range vr1
= drop_undefines_to_varying (vr1_
, expr_type
);
1232 if (range_fold_binary_symbolics_p (vr
, code
, expr_type
, &vr0
, &vr1
))
1235 vr0
.normalize_addresses ();
1236 vr1
.normalize_addresses ();
1237 op
->fold_range (*vr
, expr_type
, vr0
, vr1
);
1240 /* Perform a unary operation on a range. */
1243 range_fold_unary_expr (value_range
*vr
,
1244 enum tree_code code
, tree expr_type
,
1245 const value_range
*vr0
,
1248 if (!supported_types_p (vr
, expr_type
, vr0_type
)
1249 || !defined_ranges_p (vr
, vr0
))
1251 const range_operator
*op
= get_range_op_handler (vr
, code
, expr_type
);
1255 if (range_fold_unary_symbolics_p (vr
, code
, expr_type
, vr0
))
1258 value_range
vr0_cst (*vr0
);
1259 vr0_cst
.normalize_addresses ();
1260 op
->fold_range (*vr
, expr_type
, vr0_cst
, value_range (expr_type
));
1263 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
1264 create a new SSA name N and return the assertion assignment
1265 'N = ASSERT_EXPR <V, V OP W>'. */
1268 vrp_insert::build_assert_expr_for (tree cond
, tree v
)
1273 gcc_assert (TREE_CODE (v
) == SSA_NAME
1274 && COMPARISON_CLASS_P (cond
));
1276 a
= build2 (ASSERT_EXPR
, TREE_TYPE (v
), v
, cond
);
1277 assertion
= gimple_build_assign (NULL_TREE
, a
);
1279 /* The new ASSERT_EXPR, creates a new SSA name that replaces the
1280 operand of the ASSERT_EXPR. Create it so the new name and the old one
1281 are registered in the replacement table so that we can fix the SSA web
1282 after adding all the ASSERT_EXPRs. */
1283 tree new_def
= create_new_def_for (v
, assertion
, NULL
);
1284 /* Make sure we preserve abnormalness throughout an ASSERT_EXPR chain
1285 given we have to be able to fully propagate those out to re-create
1286 valid SSA when removing the asserts. */
1287 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (v
))
1288 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_def
) = 1;
1294 /* Return false if EXPR is a predicate expression involving floating
1298 fp_predicate (gimple
*stmt
)
1300 GIMPLE_CHECK (stmt
, GIMPLE_COND
);
1302 return FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt
)));
1305 /* If the range of values taken by OP can be inferred after STMT executes,
1306 return the comparison code (COMP_CODE_P) and value (VAL_P) that
1307 describes the inferred range. Return true if a range could be
1311 infer_value_range (gimple
*stmt
, tree op
, tree_code
*comp_code_p
, tree
*val_p
)
1314 *comp_code_p
= ERROR_MARK
;
1316 /* Do not attempt to infer anything in names that flow through
1318 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op
))
1321 /* If STMT is the last statement of a basic block with no normal
1322 successors, there is no point inferring anything about any of its
1323 operands. We would not be able to find a proper insertion point
1324 for the assertion, anyway. */
1325 if (stmt_ends_bb_p (stmt
))
1330 FOR_EACH_EDGE (e
, ei
, gimple_bb (stmt
)->succs
)
1331 if (!(e
->flags
& (EDGE_ABNORMAL
|EDGE_EH
)))
1337 if (infer_nonnull_range (stmt
, op
))
1339 *val_p
= build_int_cst (TREE_TYPE (op
), 0);
1340 *comp_code_p
= NE_EXPR
;
1347 /* Dump all the registered assertions for NAME to FILE. */
1350 vrp_insert::dump (FILE *file
, tree name
)
1354 fprintf (file
, "Assertions to be inserted for ");
1355 print_generic_expr (file
, name
);
1356 fprintf (file
, "\n");
1358 loc
= asserts_for
[SSA_NAME_VERSION (name
)];
1361 fprintf (file
, "\t");
1362 print_gimple_stmt (file
, gsi_stmt (loc
->si
), 0);
1363 fprintf (file
, "\n\tBB #%d", loc
->bb
->index
);
1366 fprintf (file
, "\n\tEDGE %d->%d", loc
->e
->src
->index
,
1367 loc
->e
->dest
->index
);
1368 dump_edge_info (file
, loc
->e
, dump_flags
, 0);
1370 fprintf (file
, "\n\tPREDICATE: ");
1371 print_generic_expr (file
, loc
->expr
);
1372 fprintf (file
, " %s ", get_tree_code_name (loc
->comp_code
));
1373 print_generic_expr (file
, loc
->val
);
1374 fprintf (file
, "\n\n");
1378 fprintf (file
, "\n");
1381 /* Dump all the registered assertions for all the names to FILE. */
1384 vrp_insert::dump (FILE *file
)
1389 fprintf (file
, "\nASSERT_EXPRs to be inserted\n\n");
1390 EXECUTE_IF_SET_IN_BITMAP (need_assert_for
, 0, i
, bi
)
1391 dump (file
, ssa_name (i
));
1392 fprintf (file
, "\n");
1395 /* Dump assert_info structure. */
1398 dump_assert_info (FILE *file
, const assert_info
&assert)
1400 fprintf (file
, "Assert for: ");
1401 print_generic_expr (file
, assert.name
);
1402 fprintf (file
, "\n\tPREDICATE: expr=[");
1403 print_generic_expr (file
, assert.expr
);
1404 fprintf (file
, "] %s ", get_tree_code_name (assert.comp_code
));
1405 fprintf (file
, "val=[");
1406 print_generic_expr (file
, assert.val
);
1407 fprintf (file
, "]\n\n");
1411 debug (const assert_info
&assert)
1413 dump_assert_info (stderr
, assert);
1416 /* Dump a vector of assert_info's. */
1419 dump_asserts_info (FILE *file
, const vec
<assert_info
> &asserts
)
1421 for (unsigned i
= 0; i
< asserts
.length (); ++i
)
1423 dump_assert_info (file
, asserts
[i
]);
1424 fprintf (file
, "\n");
1429 debug (const vec
<assert_info
> &asserts
)
1431 dump_asserts_info (stderr
, asserts
);
1434 /* Push the assert info for NAME, EXPR, COMP_CODE and VAL to ASSERTS. */
1437 add_assert_info (vec
<assert_info
> &asserts
,
1438 tree name
, tree expr
, enum tree_code comp_code
, tree val
)
1441 info
.comp_code
= comp_code
;
1443 if (TREE_OVERFLOW_P (val
))
1444 val
= drop_tree_overflow (val
);
1447 asserts
.safe_push (info
);
1448 if (dump_enabled_p ())
1449 dump_printf (MSG_NOTE
| MSG_PRIORITY_INTERNALS
,
1450 "Adding assert for %T from %T %s %T\n",
1451 name
, expr
, op_symbol_code (comp_code
), val
);
1454 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
1455 'EXPR COMP_CODE VAL' at a location that dominates block BB or
1456 E->DEST, then register this location as a possible insertion point
1457 for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
1459 BB, E and SI provide the exact insertion point for the new
1460 ASSERT_EXPR. If BB is NULL, then the ASSERT_EXPR is to be inserted
1461 on edge E. Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
1462 BB. If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
1463 must not be NULL. */
1466 vrp_insert::register_new_assert_for (tree name
, tree expr
,
1467 enum tree_code comp_code
,
1471 gimple_stmt_iterator si
)
1473 assert_locus
*n
, *loc
, *last_loc
;
1474 basic_block dest_bb
;
1476 gcc_checking_assert (bb
== NULL
|| e
== NULL
);
1479 gcc_checking_assert (gimple_code (gsi_stmt (si
)) != GIMPLE_COND
1480 && gimple_code (gsi_stmt (si
)) != GIMPLE_SWITCH
);
1482 /* Never build an assert comparing against an integer constant with
1483 TREE_OVERFLOW set. This confuses our undefined overflow warning
1485 if (TREE_OVERFLOW_P (val
))
1486 val
= drop_tree_overflow (val
);
1488 /* The new assertion A will be inserted at BB or E. We need to
1489 determine if the new location is dominated by a previously
1490 registered location for A. If we are doing an edge insertion,
1491 assume that A will be inserted at E->DEST. Note that this is not
1494 If E is a critical edge, it will be split. But even if E is
1495 split, the new block will dominate the same set of blocks that
1498 The reverse, however, is not true, blocks dominated by E->DEST
1499 will not be dominated by the new block created to split E. So,
1500 if the insertion location is on a critical edge, we will not use
1501 the new location to move another assertion previously registered
1502 at a block dominated by E->DEST. */
1503 dest_bb
= (bb
) ? bb
: e
->dest
;
1505 /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
1506 VAL at a block dominating DEST_BB, then we don't need to insert a new
1507 one. Similarly, if the same assertion already exists at a block
1508 dominated by DEST_BB and the new location is not on a critical
1509 edge, then update the existing location for the assertion (i.e.,
1510 move the assertion up in the dominance tree).
1512 Note, this is implemented as a simple linked list because there
1513 should not be more than a handful of assertions registered per
1514 name. If this becomes a performance problem, a table hashed by
1515 COMP_CODE and VAL could be implemented. */
1516 loc
= asserts_for
[SSA_NAME_VERSION (name
)];
1520 if (loc
->comp_code
== comp_code
1522 || operand_equal_p (loc
->val
, val
, 0))
1523 && (loc
->expr
== expr
1524 || operand_equal_p (loc
->expr
, expr
, 0)))
1526 /* If E is not a critical edge and DEST_BB
1527 dominates the existing location for the assertion, move
1528 the assertion up in the dominance tree by updating its
1529 location information. */
1530 if ((e
== NULL
|| !EDGE_CRITICAL_P (e
))
1531 && dominated_by_p (CDI_DOMINATORS
, loc
->bb
, dest_bb
))
1540 /* Update the last node of the list and move to the next one. */
1545 /* If we didn't find an assertion already registered for
1546 NAME COMP_CODE VAL, add a new one at the end of the list of
1547 assertions associated with NAME. */
1548 n
= XNEW (struct assert_locus
);
1552 n
->comp_code
= comp_code
;
1560 asserts_for
[SSA_NAME_VERSION (name
)] = n
;
1562 bitmap_set_bit (need_assert_for
, SSA_NAME_VERSION (name
));
1565 /* (COND_OP0 COND_CODE COND_OP1) is a predicate which uses NAME.
1566 Extract a suitable test code and value and store them into *CODE_P and
1567 *VAL_P so the predicate is normalized to NAME *CODE_P *VAL_P.
1569 If no extraction was possible, return FALSE, otherwise return TRUE.
1571 If INVERT is true, then we invert the result stored into *CODE_P. */
1574 extract_code_and_val_from_cond_with_ops (tree name
, enum tree_code cond_code
,
1575 tree cond_op0
, tree cond_op1
,
1576 bool invert
, enum tree_code
*code_p
,
1579 enum tree_code comp_code
;
1582 /* Otherwise, we have a comparison of the form NAME COMP VAL
1583 or VAL COMP NAME. */
1584 if (name
== cond_op1
)
1586 /* If the predicate is of the form VAL COMP NAME, flip
1587 COMP around because we need to register NAME as the
1588 first operand in the predicate. */
1589 comp_code
= swap_tree_comparison (cond_code
);
1592 else if (name
== cond_op0
)
1594 /* The comparison is of the form NAME COMP VAL, so the
1595 comparison code remains unchanged. */
1596 comp_code
= cond_code
;
1602 /* Invert the comparison code as necessary. */
1604 comp_code
= invert_tree_comparison (comp_code
, 0);
1606 /* VRP only handles integral and pointer types. */
1607 if (! INTEGRAL_TYPE_P (TREE_TYPE (val
))
1608 && ! POINTER_TYPE_P (TREE_TYPE (val
)))
1611 /* Do not register always-false predicates.
1612 FIXME: this works around a limitation in fold() when dealing with
1613 enumerations. Given 'enum { N1, N2 } x;', fold will not
1614 fold 'if (x > N2)' to 'if (0)'. */
1615 if ((comp_code
== GT_EXPR
|| comp_code
== LT_EXPR
)
1616 && INTEGRAL_TYPE_P (TREE_TYPE (val
)))
1618 tree min
= TYPE_MIN_VALUE (TREE_TYPE (val
));
1619 tree max
= TYPE_MAX_VALUE (TREE_TYPE (val
));
1621 if (comp_code
== GT_EXPR
1623 || compare_values (val
, max
) == 0))
1626 if (comp_code
== LT_EXPR
1628 || compare_values (val
, min
) == 0))
1631 *code_p
= comp_code
;
1636 /* Find out smallest RES where RES > VAL && (RES & MASK) == RES, if any
1637 (otherwise return VAL). VAL and MASK must be zero-extended for
1638 precision PREC. If SGNBIT is non-zero, first xor VAL with SGNBIT
1639 (to transform signed values into unsigned) and at the end xor
1643 masked_increment (const wide_int
&val_in
, const wide_int
&mask
,
1644 const wide_int
&sgnbit
, unsigned int prec
)
1646 wide_int bit
= wi::one (prec
), res
;
1649 wide_int val
= val_in
^ sgnbit
;
1650 for (i
= 0; i
< prec
; i
++, bit
+= bit
)
1653 if ((res
& bit
) == 0)
1656 res
= wi::bit_and_not (val
+ bit
, res
);
1658 if (wi::gtu_p (res
, val
))
1659 return res
^ sgnbit
;
1661 return val
^ sgnbit
;
1664 /* Helper for overflow_comparison_p
1666 OP0 CODE OP1 is a comparison. Examine the comparison and potentially
1667 OP1's defining statement to see if it ultimately has the form
1668 OP0 CODE (OP0 PLUS INTEGER_CST)
1670 If so, return TRUE indicating this is an overflow test and store into
1671 *NEW_CST an updated constant that can be used in a narrowed range test.
1673 REVERSED indicates if the comparison was originally:
1677 This affects how we build the updated constant. */
1680 overflow_comparison_p_1 (enum tree_code code
, tree op0
, tree op1
,
1681 bool follow_assert_exprs
, bool reversed
, tree
*new_cst
)
1683 /* See if this is a relational operation between two SSA_NAMES with
1684 unsigned, overflow wrapping values. If so, check it more deeply. */
1685 if ((code
== LT_EXPR
|| code
== LE_EXPR
1686 || code
== GE_EXPR
|| code
== GT_EXPR
)
1687 && TREE_CODE (op0
) == SSA_NAME
1688 && TREE_CODE (op1
) == SSA_NAME
1689 && INTEGRAL_TYPE_P (TREE_TYPE (op0
))
1690 && TYPE_UNSIGNED (TREE_TYPE (op0
))
1691 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0
)))
1693 gimple
*op1_def
= SSA_NAME_DEF_STMT (op1
);
1695 /* If requested, follow any ASSERT_EXPRs backwards for OP1. */
1696 if (follow_assert_exprs
)
1698 while (gimple_assign_single_p (op1_def
)
1699 && TREE_CODE (gimple_assign_rhs1 (op1_def
)) == ASSERT_EXPR
)
1701 op1
= TREE_OPERAND (gimple_assign_rhs1 (op1_def
), 0);
1702 if (TREE_CODE (op1
) != SSA_NAME
)
1704 op1_def
= SSA_NAME_DEF_STMT (op1
);
1708 /* Now look at the defining statement of OP1 to see if it adds
1709 or subtracts a nonzero constant from another operand. */
1711 && is_gimple_assign (op1_def
)
1712 && gimple_assign_rhs_code (op1_def
) == PLUS_EXPR
1713 && TREE_CODE (gimple_assign_rhs2 (op1_def
)) == INTEGER_CST
1714 && !integer_zerop (gimple_assign_rhs2 (op1_def
)))
1716 tree target
= gimple_assign_rhs1 (op1_def
);
1718 /* If requested, follow ASSERT_EXPRs backwards for op0 looking
1719 for one where TARGET appears on the RHS. */
1720 if (follow_assert_exprs
)
1722 /* Now see if that "other operand" is op0, following the chain
1723 of ASSERT_EXPRs if necessary. */
1724 gimple
*op0_def
= SSA_NAME_DEF_STMT (op0
);
1725 while (op0
!= target
1726 && gimple_assign_single_p (op0_def
)
1727 && TREE_CODE (gimple_assign_rhs1 (op0_def
)) == ASSERT_EXPR
)
1729 op0
= TREE_OPERAND (gimple_assign_rhs1 (op0_def
), 0);
1730 if (TREE_CODE (op0
) != SSA_NAME
)
1732 op0_def
= SSA_NAME_DEF_STMT (op0
);
1736 /* If we did not find our target SSA_NAME, then this is not
1737 an overflow test. */
1741 tree type
= TREE_TYPE (op0
);
1742 wide_int max
= wi::max_value (TYPE_PRECISION (type
), UNSIGNED
);
1743 tree inc
= gimple_assign_rhs2 (op1_def
);
1745 *new_cst
= wide_int_to_tree (type
, max
+ wi::to_wide (inc
));
1747 *new_cst
= wide_int_to_tree (type
, max
- wi::to_wide (inc
));
1754 /* OP0 CODE OP1 is a comparison. Examine the comparison and potentially
1755 OP1's defining statement to see if it ultimately has the form
1756 OP0 CODE (OP0 PLUS INTEGER_CST)
1758 If so, return TRUE indicating this is an overflow test and store into
1759 *NEW_CST an updated constant that can be used in a narrowed range test.
1761 These statements are left as-is in the IL to facilitate discovery of
1762 {ADD,SUB}_OVERFLOW sequences later in the optimizer pipeline. But
1763 the alternate range representation is often useful within VRP. */
1766 overflow_comparison_p (tree_code code
, tree name
, tree val
,
1767 bool use_equiv_p
, tree
*new_cst
)
1769 if (overflow_comparison_p_1 (code
, name
, val
, use_equiv_p
, false, new_cst
))
1771 return overflow_comparison_p_1 (swap_tree_comparison (code
), val
, name
,
1772 use_equiv_p
, true, new_cst
);
1776 /* Try to register an edge assertion for SSA name NAME on edge E for
1777 the condition COND contributing to the conditional jump pointed to by BSI.
1778 Invert the condition COND if INVERT is true. */
1781 register_edge_assert_for_2 (tree name
, edge e
,
1782 enum tree_code cond_code
,
1783 tree cond_op0
, tree cond_op1
, bool invert
,
1784 vec
<assert_info
> &asserts
)
1787 enum tree_code comp_code
;
1789 if (!extract_code_and_val_from_cond_with_ops (name
, cond_code
,
1792 invert
, &comp_code
, &val
))
1795 /* Queue the assert. */
1797 if (overflow_comparison_p (comp_code
, name
, val
, false, &x
))
1799 enum tree_code new_code
= ((comp_code
== GT_EXPR
|| comp_code
== GE_EXPR
)
1800 ? GT_EXPR
: LE_EXPR
);
1801 add_assert_info (asserts
, name
, name
, new_code
, x
);
1803 add_assert_info (asserts
, name
, name
, comp_code
, val
);
1805 /* In the case of NAME <= CST and NAME being defined as
1806 NAME = (unsigned) NAME2 + CST2 we can assert NAME2 >= -CST2
1807 and NAME2 <= CST - CST2. We can do the same for NAME > CST.
1808 This catches range and anti-range tests. */
1809 if ((comp_code
== LE_EXPR
1810 || comp_code
== GT_EXPR
)
1811 && TREE_CODE (val
) == INTEGER_CST
1812 && TYPE_UNSIGNED (TREE_TYPE (val
)))
1814 gimple
*def_stmt
= SSA_NAME_DEF_STMT (name
);
1815 tree cst2
= NULL_TREE
, name2
= NULL_TREE
, name3
= NULL_TREE
;
1817 /* Extract CST2 from the (optional) addition. */
1818 if (is_gimple_assign (def_stmt
)
1819 && gimple_assign_rhs_code (def_stmt
) == PLUS_EXPR
)
1821 name2
= gimple_assign_rhs1 (def_stmt
);
1822 cst2
= gimple_assign_rhs2 (def_stmt
);
1823 if (TREE_CODE (name2
) == SSA_NAME
1824 && TREE_CODE (cst2
) == INTEGER_CST
)
1825 def_stmt
= SSA_NAME_DEF_STMT (name2
);
1828 /* Extract NAME2 from the (optional) sign-changing cast. */
1829 if (gimple_assign_cast_p (def_stmt
))
1831 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt
))
1832 && ! TYPE_UNSIGNED (TREE_TYPE (gimple_assign_rhs1 (def_stmt
)))
1833 && (TYPE_PRECISION (gimple_expr_type (def_stmt
))
1834 == TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt
)))))
1835 name3
= gimple_assign_rhs1 (def_stmt
);
1838 /* If name3 is used later, create an ASSERT_EXPR for it. */
1839 if (name3
!= NULL_TREE
1840 && TREE_CODE (name3
) == SSA_NAME
1841 && (cst2
== NULL_TREE
1842 || TREE_CODE (cst2
) == INTEGER_CST
)
1843 && INTEGRAL_TYPE_P (TREE_TYPE (name3
)))
1847 /* Build an expression for the range test. */
1848 tmp
= build1 (NOP_EXPR
, TREE_TYPE (name
), name3
);
1849 if (cst2
!= NULL_TREE
)
1850 tmp
= build2 (PLUS_EXPR
, TREE_TYPE (name
), tmp
, cst2
);
1851 add_assert_info (asserts
, name3
, tmp
, comp_code
, val
);
1854 /* If name2 is used later, create an ASSERT_EXPR for it. */
1855 if (name2
!= NULL_TREE
1856 && TREE_CODE (name2
) == SSA_NAME
1857 && TREE_CODE (cst2
) == INTEGER_CST
1858 && INTEGRAL_TYPE_P (TREE_TYPE (name2
)))
1862 /* Build an expression for the range test. */
1864 if (TREE_TYPE (name
) != TREE_TYPE (name2
))
1865 tmp
= build1 (NOP_EXPR
, TREE_TYPE (name
), tmp
);
1866 if (cst2
!= NULL_TREE
)
1867 tmp
= build2 (PLUS_EXPR
, TREE_TYPE (name
), tmp
, cst2
);
1868 add_assert_info (asserts
, name2
, tmp
, comp_code
, val
);
1872 /* In the case of post-in/decrement tests like if (i++) ... and uses
1873 of the in/decremented value on the edge the extra name we want to
1874 assert for is not on the def chain of the name compared. Instead
1875 it is in the set of use stmts.
1876 Similar cases happen for conversions that were simplified through
1877 fold_{sign_changed,widened}_comparison. */
1878 if ((comp_code
== NE_EXPR
1879 || comp_code
== EQ_EXPR
)
1880 && TREE_CODE (val
) == INTEGER_CST
)
1882 imm_use_iterator ui
;
1884 FOR_EACH_IMM_USE_STMT (use_stmt
, ui
, name
)
1886 if (!is_gimple_assign (use_stmt
))
1889 /* Cut off to use-stmts that are dominating the predecessor. */
1890 if (!dominated_by_p (CDI_DOMINATORS
, e
->src
, gimple_bb (use_stmt
)))
1893 tree name2
= gimple_assign_lhs (use_stmt
);
1894 if (TREE_CODE (name2
) != SSA_NAME
)
1897 enum tree_code code
= gimple_assign_rhs_code (use_stmt
);
1899 if (code
== PLUS_EXPR
1900 || code
== MINUS_EXPR
)
1902 cst
= gimple_assign_rhs2 (use_stmt
);
1903 if (TREE_CODE (cst
) != INTEGER_CST
)
1905 cst
= int_const_binop (code
, val
, cst
);
1907 else if (CONVERT_EXPR_CODE_P (code
))
1909 /* For truncating conversions we cannot record
1911 if (comp_code
== NE_EXPR
1912 && (TYPE_PRECISION (TREE_TYPE (name2
))
1913 < TYPE_PRECISION (TREE_TYPE (name
))))
1915 cst
= fold_convert (TREE_TYPE (name2
), val
);
1920 if (TREE_OVERFLOW_P (cst
))
1921 cst
= drop_tree_overflow (cst
);
1922 add_assert_info (asserts
, name2
, name2
, comp_code
, cst
);
1926 if (TREE_CODE_CLASS (comp_code
) == tcc_comparison
1927 && TREE_CODE (val
) == INTEGER_CST
)
1929 gimple
*def_stmt
= SSA_NAME_DEF_STMT (name
);
1930 tree name2
= NULL_TREE
, names
[2], cst2
= NULL_TREE
;
1931 tree val2
= NULL_TREE
;
1932 unsigned int prec
= TYPE_PRECISION (TREE_TYPE (val
));
1933 wide_int mask
= wi::zero (prec
);
1934 unsigned int nprec
= prec
;
1935 enum tree_code rhs_code
= ERROR_MARK
;
1937 if (is_gimple_assign (def_stmt
))
1938 rhs_code
= gimple_assign_rhs_code (def_stmt
);
1940 /* In the case of NAME != CST1 where NAME = A +- CST2 we can
1941 assert that A != CST1 -+ CST2. */
1942 if ((comp_code
== EQ_EXPR
|| comp_code
== NE_EXPR
)
1943 && (rhs_code
== PLUS_EXPR
|| rhs_code
== MINUS_EXPR
))
1945 tree op0
= gimple_assign_rhs1 (def_stmt
);
1946 tree op1
= gimple_assign_rhs2 (def_stmt
);
1947 if (TREE_CODE (op0
) == SSA_NAME
1948 && TREE_CODE (op1
) == INTEGER_CST
)
1950 enum tree_code reverse_op
= (rhs_code
== PLUS_EXPR
1951 ? MINUS_EXPR
: PLUS_EXPR
);
1952 op1
= int_const_binop (reverse_op
, val
, op1
);
1953 if (TREE_OVERFLOW (op1
))
1954 op1
= drop_tree_overflow (op1
);
1955 add_assert_info (asserts
, op0
, op0
, comp_code
, op1
);
1959 /* Add asserts for NAME cmp CST and NAME being defined
1960 as NAME = (int) NAME2. */
1961 if (!TYPE_UNSIGNED (TREE_TYPE (val
))
1962 && (comp_code
== LE_EXPR
|| comp_code
== LT_EXPR
1963 || comp_code
== GT_EXPR
|| comp_code
== GE_EXPR
)
1964 && gimple_assign_cast_p (def_stmt
))
1966 name2
= gimple_assign_rhs1 (def_stmt
);
1967 if (CONVERT_EXPR_CODE_P (rhs_code
)
1968 && TREE_CODE (name2
) == SSA_NAME
1969 && INTEGRAL_TYPE_P (TREE_TYPE (name2
))
1970 && TYPE_UNSIGNED (TREE_TYPE (name2
))
1971 && prec
== TYPE_PRECISION (TREE_TYPE (name2
))
1972 && (comp_code
== LE_EXPR
|| comp_code
== GT_EXPR
1973 || !tree_int_cst_equal (val
,
1974 TYPE_MIN_VALUE (TREE_TYPE (val
)))))
1977 enum tree_code new_comp_code
= comp_code
;
1979 cst
= fold_convert (TREE_TYPE (name2
),
1980 TYPE_MIN_VALUE (TREE_TYPE (val
)));
1981 /* Build an expression for the range test. */
1982 tmp
= build2 (PLUS_EXPR
, TREE_TYPE (name2
), name2
, cst
);
1983 cst
= fold_build2 (PLUS_EXPR
, TREE_TYPE (name2
), cst
,
1984 fold_convert (TREE_TYPE (name2
), val
));
1985 if (comp_code
== LT_EXPR
|| comp_code
== GE_EXPR
)
1987 new_comp_code
= comp_code
== LT_EXPR
? LE_EXPR
: GT_EXPR
;
1988 cst
= fold_build2 (MINUS_EXPR
, TREE_TYPE (name2
), cst
,
1989 build_int_cst (TREE_TYPE (name2
), 1));
1991 add_assert_info (asserts
, name2
, tmp
, new_comp_code
, cst
);
1995 /* Add asserts for NAME cmp CST and NAME being defined as
1996 NAME = NAME2 >> CST2.
1998 Extract CST2 from the right shift. */
1999 if (rhs_code
== RSHIFT_EXPR
)
2001 name2
= gimple_assign_rhs1 (def_stmt
);
2002 cst2
= gimple_assign_rhs2 (def_stmt
);
2003 if (TREE_CODE (name2
) == SSA_NAME
2004 && tree_fits_uhwi_p (cst2
)
2005 && INTEGRAL_TYPE_P (TREE_TYPE (name2
))
2006 && IN_RANGE (tree_to_uhwi (cst2
), 1, prec
- 1)
2007 && type_has_mode_precision_p (TREE_TYPE (val
)))
2009 mask
= wi::mask (tree_to_uhwi (cst2
), false, prec
);
2010 val2
= fold_binary (LSHIFT_EXPR
, TREE_TYPE (val
), val
, cst2
);
2013 if (val2
!= NULL_TREE
2014 && TREE_CODE (val2
) == INTEGER_CST
2015 && simple_cst_equal (fold_build2 (RSHIFT_EXPR
,
2019 enum tree_code new_comp_code
= comp_code
;
2023 if (comp_code
== EQ_EXPR
|| comp_code
== NE_EXPR
)
2025 if (!TYPE_UNSIGNED (TREE_TYPE (val
)))
2027 tree type
= build_nonstandard_integer_type (prec
, 1);
2028 tmp
= build1 (NOP_EXPR
, type
, name2
);
2029 val2
= fold_convert (type
, val2
);
2031 tmp
= fold_build2 (MINUS_EXPR
, TREE_TYPE (tmp
), tmp
, val2
);
2032 new_val
= wide_int_to_tree (TREE_TYPE (tmp
), mask
);
2033 new_comp_code
= comp_code
== EQ_EXPR
? LE_EXPR
: GT_EXPR
;
2035 else if (comp_code
== LT_EXPR
|| comp_code
== GE_EXPR
)
2038 = wi::min_value (prec
, TYPE_SIGN (TREE_TYPE (val
)));
2040 if (minval
== wi::to_wide (new_val
))
2041 new_val
= NULL_TREE
;
2046 = wi::max_value (prec
, TYPE_SIGN (TREE_TYPE (val
)));
2047 mask
|= wi::to_wide (val2
);
2048 if (wi::eq_p (mask
, maxval
))
2049 new_val
= NULL_TREE
;
2051 new_val
= wide_int_to_tree (TREE_TYPE (val2
), mask
);
2055 add_assert_info (asserts
, name2
, tmp
, new_comp_code
, new_val
);
2058 /* If we have a conversion that doesn't change the value of the source
2059 simply register the same assert for it. */
2060 if (CONVERT_EXPR_CODE_P (rhs_code
))
2062 wide_int rmin
, rmax
;
2063 tree rhs1
= gimple_assign_rhs1 (def_stmt
);
2064 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1
))
2065 && TREE_CODE (rhs1
) == SSA_NAME
2066 /* Make sure the relation preserves the upper/lower boundary of
2067 the range conservatively. */
2068 && (comp_code
== NE_EXPR
2069 || comp_code
== EQ_EXPR
2070 || (TYPE_SIGN (TREE_TYPE (name
))
2071 == TYPE_SIGN (TREE_TYPE (rhs1
)))
2072 || ((comp_code
== LE_EXPR
2073 || comp_code
== LT_EXPR
)
2074 && !TYPE_UNSIGNED (TREE_TYPE (rhs1
)))
2075 || ((comp_code
== GE_EXPR
2076 || comp_code
== GT_EXPR
)
2077 && TYPE_UNSIGNED (TREE_TYPE (rhs1
))))
2078 /* And the conversion does not alter the value we compare
2079 against and all values in rhs1 can be represented in
2080 the converted to type. */
2081 && int_fits_type_p (val
, TREE_TYPE (rhs1
))
2082 && ((TYPE_PRECISION (TREE_TYPE (name
))
2083 > TYPE_PRECISION (TREE_TYPE (rhs1
)))
2084 || (get_range_info (rhs1
, &rmin
, &rmax
) == VR_RANGE
2085 && wi::fits_to_tree_p (rmin
, TREE_TYPE (name
))
2086 && wi::fits_to_tree_p (rmax
, TREE_TYPE (name
)))))
2087 add_assert_info (asserts
, rhs1
, rhs1
,
2088 comp_code
, fold_convert (TREE_TYPE (rhs1
), val
));
2091 /* Add asserts for NAME cmp CST and NAME being defined as
2092 NAME = NAME2 & CST2.
2094 Extract CST2 from the and.
2097 NAME = (unsigned) NAME2;
2098 casts where NAME's type is unsigned and has smaller precision
2099 than NAME2's type as if it was NAME = NAME2 & MASK. */
2100 names
[0] = NULL_TREE
;
2101 names
[1] = NULL_TREE
;
2103 if (rhs_code
== BIT_AND_EXPR
2104 || (CONVERT_EXPR_CODE_P (rhs_code
)
2105 && INTEGRAL_TYPE_P (TREE_TYPE (val
))
2106 && TYPE_UNSIGNED (TREE_TYPE (val
))
2107 && TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt
)))
2110 name2
= gimple_assign_rhs1 (def_stmt
);
2111 if (rhs_code
== BIT_AND_EXPR
)
2112 cst2
= gimple_assign_rhs2 (def_stmt
);
2115 cst2
= TYPE_MAX_VALUE (TREE_TYPE (val
));
2116 nprec
= TYPE_PRECISION (TREE_TYPE (name2
));
2118 if (TREE_CODE (name2
) == SSA_NAME
2119 && INTEGRAL_TYPE_P (TREE_TYPE (name2
))
2120 && TREE_CODE (cst2
) == INTEGER_CST
2121 && !integer_zerop (cst2
)
2123 || TYPE_UNSIGNED (TREE_TYPE (val
))))
2125 gimple
*def_stmt2
= SSA_NAME_DEF_STMT (name2
);
2126 if (gimple_assign_cast_p (def_stmt2
))
2128 names
[1] = gimple_assign_rhs1 (def_stmt2
);
2129 if (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt2
))
2130 || TREE_CODE (names
[1]) != SSA_NAME
2131 || !INTEGRAL_TYPE_P (TREE_TYPE (names
[1]))
2132 || (TYPE_PRECISION (TREE_TYPE (name2
))
2133 != TYPE_PRECISION (TREE_TYPE (names
[1]))))
2134 names
[1] = NULL_TREE
;
2139 if (names
[0] || names
[1])
2141 wide_int minv
, maxv
, valv
, cst2v
;
2142 wide_int tem
, sgnbit
;
2143 bool valid_p
= false, valn
, cst2n
;
2144 enum tree_code ccode
= comp_code
;
2146 valv
= wide_int::from (wi::to_wide (val
), nprec
, UNSIGNED
);
2147 cst2v
= wide_int::from (wi::to_wide (cst2
), nprec
, UNSIGNED
);
2148 valn
= wi::neg_p (valv
, TYPE_SIGN (TREE_TYPE (val
)));
2149 cst2n
= wi::neg_p (cst2v
, TYPE_SIGN (TREE_TYPE (val
)));
2150 /* If CST2 doesn't have most significant bit set,
2151 but VAL is negative, we have comparison like
2152 if ((x & 0x123) > -4) (always true). Just give up. */
2156 sgnbit
= wi::set_bit_in_zero (nprec
- 1, nprec
);
2158 sgnbit
= wi::zero (nprec
);
2159 minv
= valv
& cst2v
;
2163 /* Minimum unsigned value for equality is VAL & CST2
2164 (should be equal to VAL, otherwise we probably should
2165 have folded the comparison into false) and
2166 maximum unsigned value is VAL | ~CST2. */
2167 maxv
= valv
| ~cst2v
;
2172 tem
= valv
| ~cst2v
;
2173 /* If VAL is 0, handle (X & CST2) != 0 as (X & CST2) > 0U. */
2177 sgnbit
= wi::zero (nprec
);
2180 /* If (VAL | ~CST2) is all ones, handle it as
2181 (X & CST2) < VAL. */
2186 sgnbit
= wi::zero (nprec
);
2189 if (!cst2n
&& wi::neg_p (cst2v
))
2190 sgnbit
= wi::set_bit_in_zero (nprec
- 1, nprec
);
2199 if (tem
== wi::mask (nprec
- 1, false, nprec
))
2205 sgnbit
= wi::zero (nprec
);
2210 /* Minimum unsigned value for >= if (VAL & CST2) == VAL
2211 is VAL and maximum unsigned value is ~0. For signed
2212 comparison, if CST2 doesn't have most significant bit
2213 set, handle it similarly. If CST2 has MSB set,
2214 the minimum is the same, and maximum is ~0U/2. */
2217 /* If (VAL & CST2) != VAL, X & CST2 can't be equal to
2219 minv
= masked_increment (valv
, cst2v
, sgnbit
, nprec
);
2223 maxv
= wi::mask (nprec
- (cst2n
? 1 : 0), false, nprec
);
2229 /* Find out smallest MINV where MINV > VAL
2230 && (MINV & CST2) == MINV, if any. If VAL is signed and
2231 CST2 has MSB set, compute it biased by 1 << (nprec - 1). */
2232 minv
= masked_increment (valv
, cst2v
, sgnbit
, nprec
);
2235 maxv
= wi::mask (nprec
- (cst2n
? 1 : 0), false, nprec
);
2240 /* Minimum unsigned value for <= is 0 and maximum
2241 unsigned value is VAL | ~CST2 if (VAL & CST2) == VAL.
2242 Otherwise, find smallest VAL2 where VAL2 > VAL
2243 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
2245 For signed comparison, if CST2 doesn't have most
2246 significant bit set, handle it similarly. If CST2 has
2247 MSB set, the maximum is the same and minimum is INT_MIN. */
2252 maxv
= masked_increment (valv
, cst2v
, sgnbit
, nprec
);
2264 /* Minimum unsigned value for < is 0 and maximum
2265 unsigned value is (VAL-1) | ~CST2 if (VAL & CST2) == VAL.
2266 Otherwise, find smallest VAL2 where VAL2 > VAL
2267 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
2269 For signed comparison, if CST2 doesn't have most
2270 significant bit set, handle it similarly. If CST2 has
2271 MSB set, the maximum is the same and minimum is INT_MIN. */
2280 maxv
= masked_increment (valv
, cst2v
, sgnbit
, nprec
);
2294 && (maxv
- minv
) != -1)
2296 tree tmp
, new_val
, type
;
2299 for (i
= 0; i
< 2; i
++)
2302 wide_int maxv2
= maxv
;
2304 type
= TREE_TYPE (names
[i
]);
2305 if (!TYPE_UNSIGNED (type
))
2307 type
= build_nonstandard_integer_type (nprec
, 1);
2308 tmp
= build1 (NOP_EXPR
, type
, names
[i
]);
2312 tmp
= build2 (PLUS_EXPR
, type
, tmp
,
2313 wide_int_to_tree (type
, -minv
));
2314 maxv2
= maxv
- minv
;
2316 new_val
= wide_int_to_tree (type
, maxv2
);
2317 add_assert_info (asserts
, names
[i
], tmp
, LE_EXPR
, new_val
);
2324 /* OP is an operand of a truth value expression which is known to have
2325 a particular value. Register any asserts for OP and for any
2326 operands in OP's defining statement.
2328 If CODE is EQ_EXPR, then we want to register OP is zero (false),
2329 if CODE is NE_EXPR, then we want to register OP is nonzero (true). */
2332 register_edge_assert_for_1 (tree op
, enum tree_code code
,
2333 edge e
, vec
<assert_info
> &asserts
)
2337 enum tree_code rhs_code
;
2339 /* We only care about SSA_NAMEs. */
2340 if (TREE_CODE (op
) != SSA_NAME
)
2343 /* We know that OP will have a zero or nonzero value. */
2344 val
= build_int_cst (TREE_TYPE (op
), 0);
2345 add_assert_info (asserts
, op
, op
, code
, val
);
2347 /* Now look at how OP is set. If it's set from a comparison,
2348 a truth operation or some bit operations, then we may be able
2349 to register information about the operands of that assignment. */
2350 op_def
= SSA_NAME_DEF_STMT (op
);
2351 if (gimple_code (op_def
) != GIMPLE_ASSIGN
)
2354 rhs_code
= gimple_assign_rhs_code (op_def
);
2356 if (TREE_CODE_CLASS (rhs_code
) == tcc_comparison
)
2358 bool invert
= (code
== EQ_EXPR
? true : false);
2359 tree op0
= gimple_assign_rhs1 (op_def
);
2360 tree op1
= gimple_assign_rhs2 (op_def
);
2362 if (TREE_CODE (op0
) == SSA_NAME
)
2363 register_edge_assert_for_2 (op0
, e
, rhs_code
, op0
, op1
, invert
, asserts
);
2364 if (TREE_CODE (op1
) == SSA_NAME
)
2365 register_edge_assert_for_2 (op1
, e
, rhs_code
, op0
, op1
, invert
, asserts
);
2367 else if ((code
== NE_EXPR
2368 && gimple_assign_rhs_code (op_def
) == BIT_AND_EXPR
)
2370 && gimple_assign_rhs_code (op_def
) == BIT_IOR_EXPR
))
2372 /* Recurse on each operand. */
2373 tree op0
= gimple_assign_rhs1 (op_def
);
2374 tree op1
= gimple_assign_rhs2 (op_def
);
2375 if (TREE_CODE (op0
) == SSA_NAME
2376 && has_single_use (op0
))
2377 register_edge_assert_for_1 (op0
, code
, e
, asserts
);
2378 if (TREE_CODE (op1
) == SSA_NAME
2379 && has_single_use (op1
))
2380 register_edge_assert_for_1 (op1
, code
, e
, asserts
);
2382 else if (gimple_assign_rhs_code (op_def
) == BIT_NOT_EXPR
2383 && TYPE_PRECISION (TREE_TYPE (gimple_assign_lhs (op_def
))) == 1)
2385 /* Recurse, flipping CODE. */
2386 code
= invert_tree_comparison (code
, false);
2387 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def
), code
, e
, asserts
);
2389 else if (gimple_assign_rhs_code (op_def
) == SSA_NAME
)
2391 /* Recurse through the copy. */
2392 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def
), code
, e
, asserts
);
2394 else if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (op_def
)))
2396 /* Recurse through the type conversion, unless it is a narrowing
2397 conversion or conversion from non-integral type. */
2398 tree rhs
= gimple_assign_rhs1 (op_def
);
2399 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs
))
2400 && (TYPE_PRECISION (TREE_TYPE (rhs
))
2401 <= TYPE_PRECISION (TREE_TYPE (op
))))
2402 register_edge_assert_for_1 (rhs
, code
, e
, asserts
);
2406 /* Check if comparison
2407 NAME COND_OP INTEGER_CST
2409 (X & 11...100..0) COND_OP XX...X00...0
2410 Such comparison can yield assertions like
2413 in case of COND_OP being EQ_EXPR or
2416 in case of NE_EXPR. */
2419 is_masked_range_test (tree name
, tree valt
, enum tree_code cond_code
,
2420 tree
*new_name
, tree
*low
, enum tree_code
*low_code
,
2421 tree
*high
, enum tree_code
*high_code
)
2423 gimple
*def_stmt
= SSA_NAME_DEF_STMT (name
);
2425 if (!is_gimple_assign (def_stmt
)
2426 || gimple_assign_rhs_code (def_stmt
) != BIT_AND_EXPR
)
2429 tree t
= gimple_assign_rhs1 (def_stmt
);
2430 tree maskt
= gimple_assign_rhs2 (def_stmt
);
2431 if (TREE_CODE (t
) != SSA_NAME
|| TREE_CODE (maskt
) != INTEGER_CST
)
2434 wi::tree_to_wide_ref mask
= wi::to_wide (maskt
);
2435 wide_int inv_mask
= ~mask
;
2436 /* Must have been removed by now so don't bother optimizing. */
2437 if (mask
== 0 || inv_mask
== 0)
2440 /* Assume VALT is INTEGER_CST. */
2441 wi::tree_to_wide_ref val
= wi::to_wide (valt
);
2443 if ((inv_mask
& (inv_mask
+ 1)) != 0
2444 || (val
& mask
) != val
)
2447 bool is_range
= cond_code
== EQ_EXPR
;
2449 tree type
= TREE_TYPE (t
);
2450 wide_int min
= wi::min_value (type
),
2451 max
= wi::max_value (type
);
2455 *low_code
= val
== min
? ERROR_MARK
: GE_EXPR
;
2456 *high_code
= val
== max
? ERROR_MARK
: LE_EXPR
;
2460 /* We can still generate assertion if one of alternatives
2461 is known to always be false. */
2464 *low_code
= (enum tree_code
) 0;
2465 *high_code
= GT_EXPR
;
2467 else if ((val
| inv_mask
) == max
)
2469 *low_code
= LT_EXPR
;
2470 *high_code
= (enum tree_code
) 0;
2477 *low
= wide_int_to_tree (type
, val
);
2478 *high
= wide_int_to_tree (type
, val
| inv_mask
);
2483 /* Try to register an edge assertion for SSA name NAME on edge E for
2484 the condition COND contributing to the conditional jump pointed to by
2488 register_edge_assert_for (tree name
, edge e
,
2489 enum tree_code cond_code
, tree cond_op0
,
2490 tree cond_op1
, vec
<assert_info
> &asserts
)
2493 enum tree_code comp_code
;
2494 bool is_else_edge
= (e
->flags
& EDGE_FALSE_VALUE
) != 0;
2496 /* Do not attempt to infer anything in names that flow through
2498 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name
))
2501 if (!extract_code_and_val_from_cond_with_ops (name
, cond_code
,
2507 /* Register ASSERT_EXPRs for name. */
2508 register_edge_assert_for_2 (name
, e
, cond_code
, cond_op0
,
2509 cond_op1
, is_else_edge
, asserts
);
2512 /* If COND is effectively an equality test of an SSA_NAME against
2513 the value zero or one, then we may be able to assert values
2514 for SSA_NAMEs which flow into COND. */
2516 /* In the case of NAME == 1 or NAME != 0, for BIT_AND_EXPR defining
2517 statement of NAME we can assert both operands of the BIT_AND_EXPR
2518 have nonzero value. */
2519 if (((comp_code
== EQ_EXPR
&& integer_onep (val
))
2520 || (comp_code
== NE_EXPR
&& integer_zerop (val
))))
2522 gimple
*def_stmt
= SSA_NAME_DEF_STMT (name
);
2524 if (is_gimple_assign (def_stmt
)
2525 && gimple_assign_rhs_code (def_stmt
) == BIT_AND_EXPR
)
2527 tree op0
= gimple_assign_rhs1 (def_stmt
);
2528 tree op1
= gimple_assign_rhs2 (def_stmt
);
2529 register_edge_assert_for_1 (op0
, NE_EXPR
, e
, asserts
);
2530 register_edge_assert_for_1 (op1
, NE_EXPR
, e
, asserts
);
2534 /* In the case of NAME == 0 or NAME != 1, for BIT_IOR_EXPR defining
2535 statement of NAME we can assert both operands of the BIT_IOR_EXPR
2537 if (((comp_code
== EQ_EXPR
&& integer_zerop (val
))
2538 || (comp_code
== NE_EXPR
&& integer_onep (val
))))
2540 gimple
*def_stmt
= SSA_NAME_DEF_STMT (name
);
2542 /* For BIT_IOR_EXPR only if NAME == 0 both operands have
2543 necessarily zero value, or if type-precision is one. */
2544 if (is_gimple_assign (def_stmt
)
2545 && (gimple_assign_rhs_code (def_stmt
) == BIT_IOR_EXPR
2546 && (TYPE_PRECISION (TREE_TYPE (name
)) == 1
2547 || comp_code
== EQ_EXPR
)))
2549 tree op0
= gimple_assign_rhs1 (def_stmt
);
2550 tree op1
= gimple_assign_rhs2 (def_stmt
);
2551 register_edge_assert_for_1 (op0
, EQ_EXPR
, e
, asserts
);
2552 register_edge_assert_for_1 (op1
, EQ_EXPR
, e
, asserts
);
2556 /* Sometimes we can infer ranges from (NAME & MASK) == VALUE. */
2557 if ((comp_code
== EQ_EXPR
|| comp_code
== NE_EXPR
)
2558 && TREE_CODE (val
) == INTEGER_CST
)
2560 enum tree_code low_code
, high_code
;
2562 if (is_masked_range_test (name
, val
, comp_code
, &name
, &low
,
2563 &low_code
, &high
, &high_code
))
2565 if (low_code
!= ERROR_MARK
)
2566 register_edge_assert_for_2 (name
, e
, low_code
, name
,
2567 low
, /*invert*/false, asserts
);
2568 if (high_code
!= ERROR_MARK
)
2569 register_edge_assert_for_2 (name
, e
, high_code
, name
,
2570 high
, /*invert*/false, asserts
);
2575 /* Finish found ASSERTS for E and register them at GSI. */
2578 vrp_insert::finish_register_edge_assert_for (edge e
, gimple_stmt_iterator gsi
,
2579 vec
<assert_info
> &asserts
)
2581 for (unsigned i
= 0; i
< asserts
.length (); ++i
)
2582 /* Only register an ASSERT_EXPR if NAME was found in the sub-graph
2583 reachable from E. */
2584 if (live
.live_on_edge_p (asserts
[i
].name
, e
))
2585 register_new_assert_for (asserts
[i
].name
, asserts
[i
].expr
,
2586 asserts
[i
].comp_code
, asserts
[i
].val
,
2592 /* Determine whether the outgoing edges of BB should receive an
2593 ASSERT_EXPR for each of the operands of BB's LAST statement.
2594 The last statement of BB must be a COND_EXPR.
2596 If any of the sub-graphs rooted at BB have an interesting use of
2597 the predicate operands, an assert location node is added to the
2598 list of assertions for the corresponding operands. */
2601 vrp_insert::find_conditional_asserts (basic_block bb
, gcond
*last
)
2603 gimple_stmt_iterator bsi
;
2609 bsi
= gsi_for_stmt (last
);
2611 /* Look for uses of the operands in each of the sub-graphs
2612 rooted at BB. We need to check each of the outgoing edges
2613 separately, so that we know what kind of ASSERT_EXPR to
2615 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
2620 /* Register the necessary assertions for each operand in the
2621 conditional predicate. */
2622 auto_vec
<assert_info
, 8> asserts
;
2623 FOR_EACH_SSA_TREE_OPERAND (op
, last
, iter
, SSA_OP_USE
)
2624 register_edge_assert_for (op
, e
,
2625 gimple_cond_code (last
),
2626 gimple_cond_lhs (last
),
2627 gimple_cond_rhs (last
), asserts
);
2628 finish_register_edge_assert_for (e
, bsi
, asserts
);
2638 /* Compare two case labels sorting first by the destination bb index
2639 and then by the case value. */
2642 compare_case_labels (const void *p1
, const void *p2
)
2644 const struct case_info
*ci1
= (const struct case_info
*) p1
;
2645 const struct case_info
*ci2
= (const struct case_info
*) p2
;
2646 int idx1
= ci1
->bb
->index
;
2647 int idx2
= ci2
->bb
->index
;
2651 else if (idx1
== idx2
)
2653 /* Make sure the default label is first in a group. */
2654 if (!CASE_LOW (ci1
->expr
))
2656 else if (!CASE_LOW (ci2
->expr
))
2659 return tree_int_cst_compare (CASE_LOW (ci1
->expr
),
2660 CASE_LOW (ci2
->expr
));
2666 /* Determine whether the outgoing edges of BB should receive an
2667 ASSERT_EXPR for each of the operands of BB's LAST statement.
2668 The last statement of BB must be a SWITCH_EXPR.
2670 If any of the sub-graphs rooted at BB have an interesting use of
2671 the predicate operands, an assert location node is added to the
2672 list of assertions for the corresponding operands. */
2675 vrp_insert::find_switch_asserts (basic_block bb
, gswitch
*last
)
2677 gimple_stmt_iterator bsi
;
2680 struct case_info
*ci
;
2681 size_t n
= gimple_switch_num_labels (last
);
2682 #if GCC_VERSION >= 4000
2685 /* Work around GCC 3.4 bug (PR 37086). */
2686 volatile unsigned int idx
;
2689 bsi
= gsi_for_stmt (last
);
2690 op
= gimple_switch_index (last
);
2691 if (TREE_CODE (op
) != SSA_NAME
)
2694 /* Build a vector of case labels sorted by destination label. */
2695 ci
= XNEWVEC (struct case_info
, n
);
2696 for (idx
= 0; idx
< n
; ++idx
)
2698 ci
[idx
].expr
= gimple_switch_label (last
, idx
);
2699 ci
[idx
].bb
= label_to_block (fun
, CASE_LABEL (ci
[idx
].expr
));
2701 edge default_edge
= find_edge (bb
, ci
[0].bb
);
2702 qsort (ci
, n
, sizeof (struct case_info
), compare_case_labels
);
2704 for (idx
= 0; idx
< n
; ++idx
)
2707 tree cl
= ci
[idx
].expr
;
2708 basic_block cbb
= ci
[idx
].bb
;
2710 min
= CASE_LOW (cl
);
2711 max
= CASE_HIGH (cl
);
2713 /* If there are multiple case labels with the same destination
2714 we need to combine them to a single value range for the edge. */
2715 if (idx
+ 1 < n
&& cbb
== ci
[idx
+ 1].bb
)
2717 /* Skip labels until the last of the group. */
2720 } while (idx
< n
&& cbb
== ci
[idx
].bb
);
2723 /* Pick up the maximum of the case label range. */
2724 if (CASE_HIGH (ci
[idx
].expr
))
2725 max
= CASE_HIGH (ci
[idx
].expr
);
2727 max
= CASE_LOW (ci
[idx
].expr
);
2730 /* Can't extract a useful assertion out of a range that includes the
2732 if (min
== NULL_TREE
)
2735 /* Find the edge to register the assert expr on. */
2736 e
= find_edge (bb
, cbb
);
2738 /* Register the necessary assertions for the operand in the
2740 auto_vec
<assert_info
, 8> asserts
;
2741 register_edge_assert_for (op
, e
,
2742 max
? GE_EXPR
: EQ_EXPR
,
2743 op
, fold_convert (TREE_TYPE (op
), min
),
2746 register_edge_assert_for (op
, e
, LE_EXPR
, op
,
2747 fold_convert (TREE_TYPE (op
), max
),
2749 finish_register_edge_assert_for (e
, bsi
, asserts
);
2754 if (!live
.live_on_edge_p (op
, default_edge
))
2757 /* Now register along the default label assertions that correspond to the
2758 anti-range of each label. */
2759 int insertion_limit
= param_max_vrp_switch_assertions
;
2760 if (insertion_limit
== 0)
2763 /* We can't do this if the default case shares a label with another case. */
2764 tree default_cl
= gimple_switch_default_label (last
);
2765 for (idx
= 1; idx
< n
; idx
++)
2768 tree cl
= gimple_switch_label (last
, idx
);
2769 if (CASE_LABEL (cl
) == CASE_LABEL (default_cl
))
2772 min
= CASE_LOW (cl
);
2773 max
= CASE_HIGH (cl
);
2775 /* Combine contiguous case ranges to reduce the number of assertions
2777 for (idx
= idx
+ 1; idx
< n
; idx
++)
2779 tree next_min
, next_max
;
2780 tree next_cl
= gimple_switch_label (last
, idx
);
2781 if (CASE_LABEL (next_cl
) == CASE_LABEL (default_cl
))
2784 next_min
= CASE_LOW (next_cl
);
2785 next_max
= CASE_HIGH (next_cl
);
2787 wide_int difference
= (wi::to_wide (next_min
)
2788 - wi::to_wide (max
? max
: min
));
2789 if (wi::eq_p (difference
, 1))
2790 max
= next_max
? next_max
: next_min
;
2796 if (max
== NULL_TREE
)
2798 /* Register the assertion OP != MIN. */
2799 auto_vec
<assert_info
, 8> asserts
;
2800 min
= fold_convert (TREE_TYPE (op
), min
);
2801 register_edge_assert_for (op
, default_edge
, NE_EXPR
, op
, min
,
2803 finish_register_edge_assert_for (default_edge
, bsi
, asserts
);
2807 /* Register the assertion (unsigned)OP - MIN > (MAX - MIN),
2808 which will give OP the anti-range ~[MIN,MAX]. */
2809 tree uop
= fold_convert (unsigned_type_for (TREE_TYPE (op
)), op
);
2810 min
= fold_convert (TREE_TYPE (uop
), min
);
2811 max
= fold_convert (TREE_TYPE (uop
), max
);
2813 tree lhs
= fold_build2 (MINUS_EXPR
, TREE_TYPE (uop
), uop
, min
);
2814 tree rhs
= int_const_binop (MINUS_EXPR
, max
, min
);
2815 register_new_assert_for (op
, lhs
, GT_EXPR
, rhs
,
2816 NULL
, default_edge
, bsi
);
2819 if (--insertion_limit
== 0)
2825 /* Traverse all the statements in block BB looking for statements that
2826 may generate useful assertions for the SSA names in their operand.
2827 If a statement produces a useful assertion A for name N_i, then the
2828 list of assertions already generated for N_i is scanned to
2829 determine if A is actually needed.
2831 If N_i already had the assertion A at a location dominating the
2832 current location, then nothing needs to be done. Otherwise, the
2833 new location for A is recorded instead.
2835 1- For every statement S in BB, all the variables used by S are
2836 added to bitmap FOUND_IN_SUBGRAPH.
2838 2- If statement S uses an operand N in a way that exposes a known
2839 value range for N, then if N was not already generated by an
2840 ASSERT_EXPR, create a new assert location for N. For instance,
2841 if N is a pointer and the statement dereferences it, we can
2842 assume that N is not NULL.
2844 3- COND_EXPRs are a special case of #2. We can derive range
2845 information from the predicate but need to insert different
2846 ASSERT_EXPRs for each of the sub-graphs rooted at the
2847 conditional block. If the last statement of BB is a conditional
2848 expression of the form 'X op Y', then
2850 a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
2852 b) If the conditional is the only entry point to the sub-graph
2853 corresponding to the THEN_CLAUSE, recurse into it. On
2854 return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
2855 an ASSERT_EXPR is added for the corresponding variable.
2857 c) Repeat step (b) on the ELSE_CLAUSE.
2859 d) Mark X and Y in FOUND_IN_SUBGRAPH.
2868 In this case, an assertion on the THEN clause is useful to
2869 determine that 'a' is always 9 on that edge. However, an assertion
2870 on the ELSE clause would be unnecessary.
2872 4- If BB does not end in a conditional expression, then we recurse
2873 into BB's dominator children.
2875 At the end of the recursive traversal, every SSA name will have a
2876 list of locations where ASSERT_EXPRs should be added. When a new
2877 location for name N is found, it is registered by calling
2878 register_new_assert_for. That function keeps track of all the
2879 registered assertions to prevent adding unnecessary assertions.
2880 For instance, if a pointer P_4 is dereferenced more than once in a
2881 dominator tree, only the location dominating all the dereference of
2882 P_4 will receive an ASSERT_EXPR. */
2885 vrp_insert::find_assert_locations_in_bb (basic_block bb
)
2889 last
= last_stmt (bb
);
2891 /* If BB's last statement is a conditional statement involving integer
2892 operands, determine if we need to add ASSERT_EXPRs. */
2894 && gimple_code (last
) == GIMPLE_COND
2895 && !fp_predicate (last
)
2896 && !ZERO_SSA_OPERANDS (last
, SSA_OP_USE
))
2897 find_conditional_asserts (bb
, as_a
<gcond
*> (last
));
2899 /* If BB's last statement is a switch statement involving integer
2900 operands, determine if we need to add ASSERT_EXPRs. */
2902 && gimple_code (last
) == GIMPLE_SWITCH
2903 && !ZERO_SSA_OPERANDS (last
, SSA_OP_USE
))
2904 find_switch_asserts (bb
, as_a
<gswitch
*> (last
));
2906 /* Traverse all the statements in BB marking used names and looking
2907 for statements that may infer assertions for their used operands. */
2908 for (gimple_stmt_iterator si
= gsi_last_bb (bb
); !gsi_end_p (si
);
2915 stmt
= gsi_stmt (si
);
2917 if (is_gimple_debug (stmt
))
2920 /* See if we can derive an assertion for any of STMT's operands. */
2921 FOR_EACH_SSA_TREE_OPERAND (op
, stmt
, i
, SSA_OP_USE
)
2924 enum tree_code comp_code
;
2926 /* If op is not live beyond this stmt, do not bother to insert
2928 if (!live
.live_on_block_p (op
, bb
))
2931 /* If OP is used in such a way that we can infer a value
2932 range for it, and we don't find a previous assertion for
2933 it, create a new assertion location node for OP. */
2934 if (infer_value_range (stmt
, op
, &comp_code
, &value
))
2936 /* If we are able to infer a nonzero value range for OP,
2937 then walk backwards through the use-def chain to see if OP
2938 was set via a typecast.
2940 If so, then we can also infer a nonzero value range
2941 for the operand of the NOP_EXPR. */
2942 if (comp_code
== NE_EXPR
&& integer_zerop (value
))
2945 gimple
*def_stmt
= SSA_NAME_DEF_STMT (t
);
2947 while (is_gimple_assign (def_stmt
)
2948 && CONVERT_EXPR_CODE_P
2949 (gimple_assign_rhs_code (def_stmt
))
2951 (gimple_assign_rhs1 (def_stmt
)) == SSA_NAME
2953 (TREE_TYPE (gimple_assign_rhs1 (def_stmt
))))
2955 t
= gimple_assign_rhs1 (def_stmt
);
2956 def_stmt
= SSA_NAME_DEF_STMT (t
);
2958 /* Note we want to register the assert for the
2959 operand of the NOP_EXPR after SI, not after the
2961 if (live
.live_on_block_p (t
, bb
))
2962 register_new_assert_for (t
, t
, comp_code
, value
,
2967 register_new_assert_for (op
, op
, comp_code
, value
, bb
, NULL
, si
);
2972 FOR_EACH_SSA_TREE_OPERAND (op
, stmt
, i
, SSA_OP_USE
)
2974 FOR_EACH_SSA_TREE_OPERAND (op
, stmt
, i
, SSA_OP_DEF
)
2975 live
.clear (op
, bb
);
2978 /* Traverse all PHI nodes in BB, updating live. */
2979 for (gphi_iterator si
= gsi_start_phis (bb
); !gsi_end_p (si
);
2982 use_operand_p arg_p
;
2984 gphi
*phi
= si
.phi ();
2985 tree res
= gimple_phi_result (phi
);
2987 if (virtual_operand_p (res
))
2990 FOR_EACH_PHI_ARG (arg_p
, phi
, i
, SSA_OP_USE
)
2992 tree arg
= USE_FROM_PTR (arg_p
);
2993 if (TREE_CODE (arg
) == SSA_NAME
)
2997 live
.clear (res
, bb
);
3001 /* Do an RPO walk over the function computing SSA name liveness
3002 on-the-fly and deciding on assert expressions to insert. */
3005 vrp_insert::find_assert_locations (void)
3007 int *rpo
= XNEWVEC (int, last_basic_block_for_fn (fun
));
3008 int *bb_rpo
= XNEWVEC (int, last_basic_block_for_fn (fun
));
3009 int *last_rpo
= XCNEWVEC (int, last_basic_block_for_fn (fun
));
3012 rpo_cnt
= pre_and_rev_post_order_compute (NULL
, rpo
, false);
3013 for (i
= 0; i
< rpo_cnt
; ++i
)
3016 /* Pre-seed loop latch liveness from loop header PHI nodes. Due to
3017 the order we compute liveness and insert asserts we otherwise
3018 fail to insert asserts into the loop latch. */
3020 FOR_EACH_LOOP (loop
, 0)
3022 i
= loop
->latch
->index
;
3023 unsigned int j
= single_succ_edge (loop
->latch
)->dest_idx
;
3024 for (gphi_iterator gsi
= gsi_start_phis (loop
->header
);
3025 !gsi_end_p (gsi
); gsi_next (&gsi
))
3027 gphi
*phi
= gsi
.phi ();
3028 if (virtual_operand_p (gimple_phi_result (phi
)))
3030 tree arg
= gimple_phi_arg_def (phi
, j
);
3031 if (TREE_CODE (arg
) == SSA_NAME
)
3032 live
.set (arg
, loop
->latch
);
3036 for (i
= rpo_cnt
- 1; i
>= 0; --i
)
3038 basic_block bb
= BASIC_BLOCK_FOR_FN (fun
, rpo
[i
]);
3042 /* Process BB and update the live information with uses in
3044 find_assert_locations_in_bb (bb
);
3046 /* Merge liveness into the predecessor blocks and free it. */
3047 if (!live
.block_has_live_names_p (bb
))
3050 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
3052 int pred
= e
->src
->index
;
3053 if ((e
->flags
& EDGE_DFS_BACK
) || pred
== ENTRY_BLOCK
)
3056 live
.merge (e
->src
, bb
);
3058 if (bb_rpo
[pred
] < pred_rpo
)
3059 pred_rpo
= bb_rpo
[pred
];
3062 /* Record the RPO number of the last visited block that needs
3063 live information from this block. */
3064 last_rpo
[rpo
[i
]] = pred_rpo
;
3067 live
.clear_block (bb
);
3069 /* We can free all successors live bitmaps if all their
3070 predecessors have been visited already. */
3071 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
3072 if (last_rpo
[e
->dest
->index
] == i
)
3073 live
.clear_block (e
->dest
);
3077 XDELETEVEC (bb_rpo
);
3078 XDELETEVEC (last_rpo
);
3081 /* Create an ASSERT_EXPR for NAME and insert it in the location
3082 indicated by LOC. Return true if we made any edge insertions. */
3085 vrp_insert::process_assert_insertions_for (tree name
, assert_locus
*loc
)
3087 /* Build the comparison expression NAME_i COMP_CODE VAL. */
3090 gimple
*assert_stmt
;
3094 /* If we have X <=> X do not insert an assert expr for that. */
3095 if (loc
->expr
== loc
->val
)
3098 cond
= build2 (loc
->comp_code
, boolean_type_node
, loc
->expr
, loc
->val
);
3099 assert_stmt
= build_assert_expr_for (cond
, name
);
3102 /* We have been asked to insert the assertion on an edge. This
3103 is used only by COND_EXPR and SWITCH_EXPR assertions. */
3104 gcc_checking_assert (gimple_code (gsi_stmt (loc
->si
)) == GIMPLE_COND
3105 || (gimple_code (gsi_stmt (loc
->si
))
3108 gsi_insert_on_edge (loc
->e
, assert_stmt
);
3112 /* If the stmt iterator points at the end then this is an insertion
3113 at the beginning of a block. */
3114 if (gsi_end_p (loc
->si
))
3116 gimple_stmt_iterator si
= gsi_after_labels (loc
->bb
);
3117 gsi_insert_before (&si
, assert_stmt
, GSI_SAME_STMT
);
3121 /* Otherwise, we can insert right after LOC->SI iff the
3122 statement must not be the last statement in the block. */
3123 stmt
= gsi_stmt (loc
->si
);
3124 if (!stmt_ends_bb_p (stmt
))
3126 gsi_insert_after (&loc
->si
, assert_stmt
, GSI_SAME_STMT
);
3130 /* If STMT must be the last statement in BB, we can only insert new
3131 assertions on the non-abnormal edge out of BB. Note that since
3132 STMT is not control flow, there may only be one non-abnormal/eh edge
3134 FOR_EACH_EDGE (e
, ei
, loc
->bb
->succs
)
3135 if (!(e
->flags
& (EDGE_ABNORMAL
|EDGE_EH
)))
3137 gsi_insert_on_edge (e
, assert_stmt
);
3144 /* Qsort helper for sorting assert locations. If stable is true, don't
3145 use iterative_hash_expr because it can be unstable for -fcompare-debug,
3146 on the other side some pointers might be NULL. */
3148 template <bool stable
>
3150 vrp_insert::compare_assert_loc (const void *pa
, const void *pb
)
3152 assert_locus
* const a
= *(assert_locus
* const *)pa
;
3153 assert_locus
* const b
= *(assert_locus
* const *)pb
;
3155 /* If stable, some asserts might be optimized away already, sort
3165 if (a
->e
== NULL
&& b
->e
!= NULL
)
3167 else if (a
->e
!= NULL
&& b
->e
== NULL
)
3170 /* After the above checks, we know that (a->e == NULL) == (b->e == NULL),
3171 no need to test both a->e and b->e. */
3173 /* Sort after destination index. */
3176 else if (a
->e
->dest
->index
> b
->e
->dest
->index
)
3178 else if (a
->e
->dest
->index
< b
->e
->dest
->index
)
3181 /* Sort after comp_code. */
3182 if (a
->comp_code
> b
->comp_code
)
3184 else if (a
->comp_code
< b
->comp_code
)
3189 /* E.g. if a->val is ADDR_EXPR of a VAR_DECL, iterative_hash_expr
3190 uses DECL_UID of the VAR_DECL, so sorting might differ between
3191 -g and -g0. When doing the removal of redundant assert exprs
3192 and commonization to successors, this does not matter, but for
3193 the final sort needs to be stable. */
3201 ha
= iterative_hash_expr (a
->expr
, iterative_hash_expr (a
->val
, 0));
3202 hb
= iterative_hash_expr (b
->expr
, iterative_hash_expr (b
->val
, 0));
3205 /* Break the tie using hashing and source/bb index. */
3207 return (a
->e
!= NULL
3208 ? a
->e
->src
->index
- b
->e
->src
->index
3209 : a
->bb
->index
- b
->bb
->index
);
3210 return ha
> hb
? 1 : -1;
3213 /* Process all the insertions registered for every name N_i registered
3214 in NEED_ASSERT_FOR. The list of assertions to be inserted are
3215 found in ASSERTS_FOR[i]. */
3218 vrp_insert::process_assert_insertions ()
3222 bool update_edges_p
= false;
3223 int num_asserts
= 0;
3225 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3228 EXECUTE_IF_SET_IN_BITMAP (need_assert_for
, 0, i
, bi
)
3230 assert_locus
*loc
= asserts_for
[i
];
3233 auto_vec
<assert_locus
*, 16> asserts
;
3234 for (; loc
; loc
= loc
->next
)
3235 asserts
.safe_push (loc
);
3236 asserts
.qsort (compare_assert_loc
<false>);
3238 /* Push down common asserts to successors and remove redundant ones. */
3240 assert_locus
*common
= NULL
;
3241 unsigned commonj
= 0;
3242 for (unsigned j
= 0; j
< asserts
.length (); ++j
)
3248 || loc
->e
->dest
!= common
->e
->dest
3249 || loc
->comp_code
!= common
->comp_code
3250 || ! operand_equal_p (loc
->val
, common
->val
, 0)
3251 || ! operand_equal_p (loc
->expr
, common
->expr
, 0))
3257 else if (loc
->e
== asserts
[j
-1]->e
)
3259 /* Remove duplicate asserts. */
3260 if (commonj
== j
- 1)
3265 free (asserts
[j
-1]);
3266 asserts
[j
-1] = NULL
;
3271 if (EDGE_COUNT (common
->e
->dest
->preds
) == ecnt
)
3273 /* We have the same assertion on all incoming edges of a BB.
3274 Insert it at the beginning of that block. */
3275 loc
->bb
= loc
->e
->dest
;
3277 loc
->si
= gsi_none ();
3279 /* Clear asserts commoned. */
3280 for (; commonj
!= j
; ++commonj
)
3281 if (asserts
[commonj
])
3283 free (asserts
[commonj
]);
3284 asserts
[commonj
] = NULL
;
3290 /* The asserts vector sorting above might be unstable for
3291 -fcompare-debug, sort again to ensure a stable sort. */
3292 asserts
.qsort (compare_assert_loc
<true>);
3293 for (unsigned j
= 0; j
< asserts
.length (); ++j
)
3298 update_edges_p
|= process_assert_insertions_for (ssa_name (i
), loc
);
3305 gsi_commit_edge_inserts ();
3307 statistics_counter_event (fun
, "Number of ASSERT_EXPR expressions inserted",
3312 /* Traverse the flowgraph looking for conditional jumps to insert range
3313 expressions. These range expressions are meant to provide information
3314 to optimizations that need to reason in terms of value ranges. They
3315 will not be expanded into RTL. For instance, given:
3324 this pass will transform the code into:
3330 x = ASSERT_EXPR <x, x < y>
3335 y = ASSERT_EXPR <y, x >= y>
3339 The idea is that once copy and constant propagation have run, other
3340 optimizations will be able to determine what ranges of values can 'x'
3341 take in different paths of the code, simply by checking the reaching
3342 definition of 'x'. */
3345 vrp_insert::insert_range_assertions (void)
3347 need_assert_for
= BITMAP_ALLOC (NULL
);
3348 asserts_for
= XCNEWVEC (assert_locus
*, num_ssa_names
);
3350 calculate_dominance_info (CDI_DOMINATORS
);
3352 find_assert_locations ();
3353 if (!bitmap_empty_p (need_assert_for
))
3355 process_assert_insertions ();
3356 update_ssa (TODO_update_ssa_no_phi
);
3359 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3361 fprintf (dump_file
, "\nSSA form after inserting ASSERT_EXPRs\n");
3362 dump_function_to_file (current_function_decl
, dump_file
, dump_flags
);
3366 BITMAP_FREE (need_assert_for
);
3369 class vrp_prop
: public ssa_propagation_engine
3372 enum ssa_prop_result
visit_stmt (gimple
*, edge
*, tree
*) FINAL OVERRIDE
;
3373 enum ssa_prop_result
visit_phi (gphi
*) FINAL OVERRIDE
;
3375 struct function
*fun
;
3377 void vrp_initialize (struct function
*);
3378 void vrp_finalize (bool);
3380 class vr_values vr_values
;
3383 /* Temporary delegator to minimize code churn. */
3384 const value_range_equiv
*get_value_range (const_tree op
)
3385 { return vr_values
.get_value_range (op
); }
3386 void set_def_to_varying (const_tree def
)
3387 { vr_values
.set_def_to_varying (def
); }
3388 void set_defs_to_varying (gimple
*stmt
)
3389 { vr_values
.set_defs_to_varying (stmt
); }
3390 void extract_range_from_stmt (gimple
*stmt
, edge
*taken_edge_p
,
3391 tree
*output_p
, value_range_equiv
*vr
)
3392 { vr_values
.extract_range_from_stmt (stmt
, taken_edge_p
, output_p
, vr
); }
3393 bool update_value_range (const_tree op
, value_range_equiv
*vr
)
3394 { return vr_values
.update_value_range (op
, vr
); }
3395 void extract_range_basic (value_range_equiv
*vr
, gimple
*stmt
)
3396 { vr_values
.extract_range_basic (vr
, stmt
); }
3397 void extract_range_from_phi_node (gphi
*phi
, value_range_equiv
*vr
)
3398 { vr_values
.extract_range_from_phi_node (phi
, vr
); }
3401 /* Array bounds checking pass. */
3403 class array_bounds_checker
3405 friend class check_array_bounds_dom_walker
;
3408 array_bounds_checker (struct function
*fun
, class vr_values
*v
)
3409 : fun (fun
), ranges (v
) { }
3413 static tree
check_array_bounds (tree
*tp
, int *walk_subtree
, void *data
);
3414 bool check_array_ref (location_t
, tree
, bool ignore_off_by_one
);
3415 bool check_mem_ref (location_t
, tree
, bool ignore_off_by_one
);
3416 void check_addr_expr (location_t
, tree
);
3417 const value_range_equiv
*get_value_range (const_tree op
)
3418 { return ranges
->get_value_range (op
); }
3419 struct function
*fun
;
3420 class vr_values
*ranges
;
3423 /* Checks one ARRAY_REF in REF, located at LOCUS. Ignores flexible arrays
3424 and "struct" hacks. If VRP can determine that the
3425 array subscript is a constant, check if it is outside valid
3426 range. If the array subscript is a RANGE, warn if it is
3427 non-overlapping with valid range.
3428 IGNORE_OFF_BY_ONE is true if the ARRAY_REF is inside a ADDR_EXPR.
3429 Returns true if a warning has been issued. */
3432 array_bounds_checker::check_array_ref (location_t location
, tree ref
,
3433 bool ignore_off_by_one
)
3435 if (TREE_NO_WARNING (ref
))
3438 tree low_sub
= TREE_OPERAND (ref
, 1);
3439 tree up_sub
= low_sub
;
3440 tree up_bound
= array_ref_up_bound (ref
);
3442 /* Referenced decl if one can be determined. */
3443 tree decl
= NULL_TREE
;
3445 /* Set for accesses to interior zero-length arrays. */
3446 bool interior_zero_len
= false;
3451 || TREE_CODE (up_bound
) != INTEGER_CST
3452 || (warn_array_bounds
< 2
3453 && array_at_struct_end_p (ref
)))
3455 /* Accesses to trailing arrays via pointers may access storage
3456 beyond the types array bounds. For such arrays, or for flexible
3457 array members, as well as for other arrays of an unknown size,
3458 replace the upper bound with a more permissive one that assumes
3459 the size of the largest object is PTRDIFF_MAX. */
3460 tree eltsize
= array_ref_element_size (ref
);
3462 if (TREE_CODE (eltsize
) != INTEGER_CST
3463 || integer_zerop (eltsize
))
3465 up_bound
= NULL_TREE
;
3466 up_bound_p1
= NULL_TREE
;
3470 tree ptrdiff_max
= TYPE_MAX_VALUE (ptrdiff_type_node
);
3471 tree maxbound
= ptrdiff_max
;
3472 tree arg
= TREE_OPERAND (ref
, 0);
3474 const bool compref
= TREE_CODE (arg
) == COMPONENT_REF
;
3477 /* Try to determine the size of the trailing array from
3478 its initializer (if it has one). */
3479 if (tree refsize
= component_ref_size (arg
, &interior_zero_len
))
3480 if (TREE_CODE (refsize
) == INTEGER_CST
)
3484 if (maxbound
== ptrdiff_max
)
3486 /* Try to determine the size of the base object. Avoid
3487 COMPONENT_REF already tried above. Using its DECL_SIZE
3488 size wouldn't necessarily be correct if the reference is
3489 to its flexible array member initialized in a different
3490 translation unit. */
3492 if (tree base
= get_addr_base_and_unit_offset (arg
, &off
))
3494 if (!compref
&& DECL_P (base
))
3495 if (tree basesize
= DECL_SIZE_UNIT (base
))
3496 if (TREE_CODE (basesize
) == INTEGER_CST
)
3498 maxbound
= basesize
;
3502 if (known_gt (off
, 0))
3503 maxbound
= wide_int_to_tree (sizetype
,
3504 wi::sub (wi::to_wide (maxbound
),
3509 maxbound
= fold_convert (sizetype
, maxbound
);
3511 up_bound_p1
= int_const_binop (TRUNC_DIV_EXPR
, maxbound
, eltsize
);
3513 if (up_bound_p1
!= NULL_TREE
)
3514 up_bound
= int_const_binop (MINUS_EXPR
, up_bound_p1
,
3515 build_int_cst (ptrdiff_type_node
, 1));
3517 up_bound
= NULL_TREE
;
3521 up_bound_p1
= int_const_binop (PLUS_EXPR
, up_bound
,
3522 build_int_cst (TREE_TYPE (up_bound
), 1));
3524 tree low_bound
= array_ref_low_bound (ref
);
3526 tree artype
= TREE_TYPE (TREE_OPERAND (ref
, 0));
3528 bool warned
= false;
3531 if (up_bound
&& tree_int_cst_equal (low_bound
, up_bound_p1
))
3532 warned
= warning_at (location
, OPT_Warray_bounds
,
3533 "array subscript %E is outside array bounds of %qT",
3536 const value_range_equiv
*vr
= NULL
;
3537 if (TREE_CODE (low_sub
) == SSA_NAME
)
3539 vr
= get_value_range (low_sub
);
3540 if (!vr
->undefined_p () && !vr
->varying_p ())
3542 low_sub
= vr
->kind () == VR_RANGE
? vr
->max () : vr
->min ();
3543 up_sub
= vr
->kind () == VR_RANGE
? vr
->min () : vr
->max ();
3549 else if (vr
&& vr
->kind () == VR_ANTI_RANGE
)
3552 && TREE_CODE (up_sub
) == INTEGER_CST
3553 && (ignore_off_by_one
3554 ? tree_int_cst_lt (up_bound
, up_sub
)
3555 : tree_int_cst_le (up_bound
, up_sub
))
3556 && TREE_CODE (low_sub
) == INTEGER_CST
3557 && tree_int_cst_le (low_sub
, low_bound
))
3558 warned
= warning_at (location
, OPT_Warray_bounds
,
3559 "array subscript [%E, %E] is outside "
3560 "array bounds of %qT",
3561 low_sub
, up_sub
, artype
);
3564 && TREE_CODE (up_sub
) == INTEGER_CST
3565 && (ignore_off_by_one
3566 ? !tree_int_cst_le (up_sub
, up_bound_p1
)
3567 : !tree_int_cst_le (up_sub
, up_bound
)))
3568 warned
= warning_at (location
, OPT_Warray_bounds
,
3569 "array subscript %E is above array bounds of %qT",
3571 else if (TREE_CODE (low_sub
) == INTEGER_CST
3572 && tree_int_cst_lt (low_sub
, low_bound
))
3573 warned
= warning_at (location
, OPT_Warray_bounds
,
3574 "array subscript %E is below array bounds of %qT",
3577 if (!warned
&& interior_zero_len
)
3578 warned
= warning_at (location
, OPT_Wzero_length_bounds
,
3579 (TREE_CODE (low_sub
) == INTEGER_CST
3580 ? G_("array subscript %E is outside the bounds "
3581 "of an interior zero-length array %qT")
3582 : G_("array subscript %qE is outside the bounds "
3583 "of an interior zero-length array %qT")),
3588 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3590 fprintf (dump_file
, "Array bound warning for ");
3591 dump_generic_expr (MSG_NOTE
, TDF_SLIM
, ref
);
3592 fprintf (dump_file
, "\n");
3595 ref
= decl
? decl
: TREE_OPERAND (ref
, 0);
3597 tree rec
= NULL_TREE
;
3598 if (TREE_CODE (ref
) == COMPONENT_REF
)
3600 /* For a reference to a member of a struct object also mention
3601 the object if it's known. It may be defined in a different
3602 function than the out-of-bounds access. */
3603 rec
= TREE_OPERAND (ref
, 0);
3606 ref
= TREE_OPERAND (ref
, 1);
3610 inform (DECL_SOURCE_LOCATION (ref
), "while referencing %qD", ref
);
3611 if (rec
&& DECL_P (rec
))
3612 inform (DECL_SOURCE_LOCATION (rec
), "defined here %qD", rec
);
3614 TREE_NO_WARNING (ref
) = 1;
3620 /* Checks one MEM_REF in REF, located at LOCATION, for out-of-bounds
3621 references to string constants. If VRP can determine that the array
3622 subscript is a constant, check if it is outside valid range.
3623 If the array subscript is a RANGE, warn if it is non-overlapping
3625 IGNORE_OFF_BY_ONE is true if the MEM_REF is inside an ADDR_EXPR
3626 (used to allow one-past-the-end indices for code that takes
3627 the address of the just-past-the-end element of an array).
3628 Returns true if a warning has been issued. */
3631 array_bounds_checker::check_mem_ref (location_t location
, tree ref
,
3632 bool ignore_off_by_one
)
3634 if (TREE_NO_WARNING (ref
))
3637 tree arg
= TREE_OPERAND (ref
, 0);
3638 /* The constant and variable offset of the reference. */
3639 tree cstoff
= TREE_OPERAND (ref
, 1);
3640 tree varoff
= NULL_TREE
;
3642 const offset_int maxobjsize
= tree_to_shwi (max_object_size ());
3644 /* The array or string constant bounds in bytes. Initially set
3645 to [-MAXOBJSIZE - 1, MAXOBJSIZE] until a tighter bound is
3647 offset_int arrbounds
[2] = { -maxobjsize
- 1, maxobjsize
};
3649 /* The minimum and maximum intermediate offset. For a reference
3650 to be valid, not only does the final offset/subscript must be
3651 in bounds but all intermediate offsets should be as well.
3652 GCC may be able to deal gracefully with such out-of-bounds
3653 offsets so the checking is only enbaled at -Warray-bounds=2
3654 where it may help detect bugs in uses of the intermediate
3655 offsets that could otherwise not be detectable. */
3656 offset_int ioff
= wi::to_offset (fold_convert (ptrdiff_type_node
, cstoff
));
3657 offset_int extrema
[2] = { 0, wi::abs (ioff
) };
3659 /* The range of the byte offset into the reference. */
3660 offset_int offrange
[2] = { 0, 0 };
3662 const value_range_equiv
*vr
= NULL
;
3664 /* Determine the offsets and increment OFFRANGE for the bounds of each.
3665 The loop computes the range of the final offset for expressions such
3666 as (A + i0 + ... + iN)[CSTOFF] where i0 through iN are SSA_NAMEs in
3668 const unsigned limit
= param_ssa_name_def_chain_limit
;
3669 for (unsigned n
= 0; TREE_CODE (arg
) == SSA_NAME
&& n
< limit
; ++n
)
3671 gimple
*def
= SSA_NAME_DEF_STMT (arg
);
3672 if (!is_gimple_assign (def
))
3675 tree_code code
= gimple_assign_rhs_code (def
);
3676 if (code
== POINTER_PLUS_EXPR
)
3678 arg
= gimple_assign_rhs1 (def
);
3679 varoff
= gimple_assign_rhs2 (def
);
3681 else if (code
== ASSERT_EXPR
)
3683 arg
= TREE_OPERAND (gimple_assign_rhs1 (def
), 0);
3689 /* VAROFF should always be a SSA_NAME here (and not even
3690 INTEGER_CST) but there's no point in taking chances. */
3691 if (TREE_CODE (varoff
) != SSA_NAME
)
3694 vr
= get_value_range (varoff
);
3695 if (!vr
|| vr
->undefined_p () || vr
->varying_p ())
3698 if (!vr
->constant_p ())
3701 if (vr
->kind () == VR_RANGE
)
3704 = wi::to_offset (fold_convert (ptrdiff_type_node
, vr
->min ()));
3706 = wi::to_offset (fold_convert (ptrdiff_type_node
, vr
->max ()));
3714 /* When MIN >= MAX, the offset is effectively in a union
3715 of two ranges: [-MAXOBJSIZE -1, MAX] and [MIN, MAXOBJSIZE].
3716 Since there is no way to represent such a range across
3717 additions, conservatively add [-MAXOBJSIZE -1, MAXOBJSIZE]
3719 offrange
[0] += arrbounds
[0];
3720 offrange
[1] += arrbounds
[1];
3725 /* For an anti-range, analogously to the above, conservatively
3726 add [-MAXOBJSIZE -1, MAXOBJSIZE] to OFFRANGE. */
3727 offrange
[0] += arrbounds
[0];
3728 offrange
[1] += arrbounds
[1];
3731 /* Keep track of the minimum and maximum offset. */
3732 if (offrange
[1] < 0 && offrange
[1] < extrema
[0])
3733 extrema
[0] = offrange
[1];
3734 if (offrange
[0] > 0 && offrange
[0] > extrema
[1])
3735 extrema
[1] = offrange
[0];
3737 if (offrange
[0] < arrbounds
[0])
3738 offrange
[0] = arrbounds
[0];
3740 if (offrange
[1] > arrbounds
[1])
3741 offrange
[1] = arrbounds
[1];
3744 if (TREE_CODE (arg
) == ADDR_EXPR
)
3746 arg
= TREE_OPERAND (arg
, 0);
3747 if (TREE_CODE (arg
) != STRING_CST
3748 && TREE_CODE (arg
) != PARM_DECL
3749 && TREE_CODE (arg
) != VAR_DECL
)
3755 /* The type of the object being referred to. It can be an array,
3756 string literal, or a non-array type when the MEM_REF represents
3757 a reference/subscript via a pointer to an object that is not
3758 an element of an array. Incomplete types are excluded as well
3759 because their size is not known. */
3760 tree reftype
= TREE_TYPE (arg
);
3761 if (POINTER_TYPE_P (reftype
)
3762 || !COMPLETE_TYPE_P (reftype
)
3763 || TREE_CODE (TYPE_SIZE_UNIT (reftype
)) != INTEGER_CST
)
3766 /* Except in declared objects, references to trailing array members
3767 of structs and union objects are excluded because MEM_REF doesn't
3768 make it possible to identify the member where the reference
3770 if (RECORD_OR_UNION_TYPE_P (reftype
)
3772 || (DECL_EXTERNAL (arg
) && array_at_struct_end_p (ref
))))
3778 if (TREE_CODE (reftype
) == ARRAY_TYPE
)
3780 eltsize
= wi::to_offset (TYPE_SIZE_UNIT (TREE_TYPE (reftype
)));
3781 if (tree dom
= TYPE_DOMAIN (reftype
))
3783 tree bnds
[] = { TYPE_MIN_VALUE (dom
), TYPE_MAX_VALUE (dom
) };
3784 if (TREE_CODE (arg
) == COMPONENT_REF
)
3786 offset_int size
= maxobjsize
;
3787 if (tree fldsize
= component_ref_size (arg
))
3788 size
= wi::to_offset (fldsize
);
3789 arrbounds
[1] = wi::lrshift (size
, wi::floor_log2 (eltsize
));
3791 else if (array_at_struct_end_p (arg
) || !bnds
[0] || !bnds
[1])
3792 arrbounds
[1] = wi::lrshift (maxobjsize
, wi::floor_log2 (eltsize
));
3794 arrbounds
[1] = (wi::to_offset (bnds
[1]) - wi::to_offset (bnds
[0])
3798 arrbounds
[1] = wi::lrshift (maxobjsize
, wi::floor_log2 (eltsize
));
3800 /* Determine a tighter bound of the non-array element type. */
3801 tree eltype
= TREE_TYPE (reftype
);
3802 while (TREE_CODE (eltype
) == ARRAY_TYPE
)
3803 eltype
= TREE_TYPE (eltype
);
3804 eltsize
= wi::to_offset (TYPE_SIZE_UNIT (eltype
));
3809 tree size
= TYPE_SIZE_UNIT (reftype
);
3811 if (tree initsize
= DECL_SIZE_UNIT (arg
))
3812 if (tree_int_cst_lt (size
, initsize
))
3815 arrbounds
[1] = wi::to_offset (size
);
3818 offrange
[0] += ioff
;
3819 offrange
[1] += ioff
;
3821 /* Compute the more permissive upper bound when IGNORE_OFF_BY_ONE
3822 is set (when taking the address of the one-past-last element
3823 of an array) but always use the stricter bound in diagnostics. */
3824 offset_int ubound
= arrbounds
[1];
3825 if (ignore_off_by_one
)
3828 if (arrbounds
[0] == arrbounds
[1]
3829 || offrange
[0] >= ubound
3830 || offrange
[1] < arrbounds
[0])
3832 /* Treat a reference to a non-array object as one to an array
3833 of a single element. */
3834 if (TREE_CODE (reftype
) != ARRAY_TYPE
)
3835 reftype
= build_array_type_nelts (reftype
, 1);
3837 /* Extract the element type out of MEM_REF and use its size
3838 to compute the index to print in the diagnostic; arrays
3839 in MEM_REF don't mean anything. A type with no size like
3840 void is as good as having a size of 1. */
3841 tree type
= TREE_TYPE (ref
);
3842 while (TREE_CODE (type
) == ARRAY_TYPE
)
3843 type
= TREE_TYPE (type
);
3844 if (tree size
= TYPE_SIZE_UNIT (type
))
3846 offrange
[0] = offrange
[0] / wi::to_offset (size
);
3847 offrange
[1] = offrange
[1] / wi::to_offset (size
);
3851 if (offrange
[0] == offrange
[1])
3852 warned
= warning_at (location
, OPT_Warray_bounds
,
3853 "array subscript %wi is outside array bounds "
3855 offrange
[0].to_shwi (), reftype
);
3857 warned
= warning_at (location
, OPT_Warray_bounds
,
3858 "array subscript [%wi, %wi] is outside "
3859 "array bounds of %qT",
3860 offrange
[0].to_shwi (),
3861 offrange
[1].to_shwi (), reftype
);
3862 if (warned
&& DECL_P (arg
))
3863 inform (DECL_SOURCE_LOCATION (arg
), "while referencing %qD", arg
);
3866 TREE_NO_WARNING (ref
) = 1;
3870 if (warn_array_bounds
< 2)
3873 /* At level 2 check also intermediate offsets. */
3875 if (extrema
[i
] < -arrbounds
[1] || extrema
[i
= 1] > ubound
)
3877 HOST_WIDE_INT tmpidx
= extrema
[i
].to_shwi () / eltsize
.to_shwi ();
3879 if (warning_at (location
, OPT_Warray_bounds
,
3880 "intermediate array offset %wi is outside array bounds "
3881 "of %qT", tmpidx
, reftype
))
3883 TREE_NO_WARNING (ref
) = 1;
3891 /* Searches if the expr T, located at LOCATION computes
3892 address of an ARRAY_REF, and call check_array_ref on it. */
3895 array_bounds_checker::check_addr_expr (location_t location
, tree t
)
3897 /* Check each ARRAY_REF and MEM_REF in the reference chain. */
3900 bool warned
= false;
3901 if (TREE_CODE (t
) == ARRAY_REF
)
3902 warned
= check_array_ref (location
, t
, true /*ignore_off_by_one*/);
3903 else if (TREE_CODE (t
) == MEM_REF
)
3904 warned
= check_mem_ref (location
, t
, true /*ignore_off_by_one*/);
3907 TREE_NO_WARNING (t
) = true;
3909 t
= TREE_OPERAND (t
, 0);
3911 while (handled_component_p (t
) || TREE_CODE (t
) == MEM_REF
);
3913 if (TREE_CODE (t
) != MEM_REF
3914 || TREE_CODE (TREE_OPERAND (t
, 0)) != ADDR_EXPR
3915 || TREE_NO_WARNING (t
))
3918 tree tem
= TREE_OPERAND (TREE_OPERAND (t
, 0), 0);
3919 tree low_bound
, up_bound
, el_sz
;
3920 if (TREE_CODE (TREE_TYPE (tem
)) != ARRAY_TYPE
3921 || TREE_CODE (TREE_TYPE (TREE_TYPE (tem
))) == ARRAY_TYPE
3922 || !TYPE_DOMAIN (TREE_TYPE (tem
)))
3925 low_bound
= TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (tem
)));
3926 up_bound
= TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (tem
)));
3927 el_sz
= TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (tem
)));
3929 || TREE_CODE (low_bound
) != INTEGER_CST
3931 || TREE_CODE (up_bound
) != INTEGER_CST
3933 || TREE_CODE (el_sz
) != INTEGER_CST
)
3937 if (!mem_ref_offset (t
).is_constant (&idx
))
3940 bool warned
= false;
3941 idx
= wi::sdiv_trunc (idx
, wi::to_offset (el_sz
));
3944 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3946 fprintf (dump_file
, "Array bound warning for ");
3947 dump_generic_expr (MSG_NOTE
, TDF_SLIM
, t
);
3948 fprintf (dump_file
, "\n");
3950 warned
= warning_at (location
, OPT_Warray_bounds
,
3951 "array subscript %wi is below "
3952 "array bounds of %qT",
3953 idx
.to_shwi (), TREE_TYPE (tem
));
3955 else if (idx
> (wi::to_offset (up_bound
)
3956 - wi::to_offset (low_bound
) + 1))
3958 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3960 fprintf (dump_file
, "Array bound warning for ");
3961 dump_generic_expr (MSG_NOTE
, TDF_SLIM
, t
);
3962 fprintf (dump_file
, "\n");
3964 warned
= warning_at (location
, OPT_Warray_bounds
,
3965 "array subscript %wu is above "
3966 "array bounds of %qT",
3967 idx
.to_uhwi (), TREE_TYPE (tem
));
3973 inform (DECL_SOURCE_LOCATION (t
), "while referencing %qD", t
);
3975 TREE_NO_WARNING (t
) = 1;
3979 /* Callback for walk_tree to check a tree for out of bounds array
3980 accesses. The array_bounds_checker class is passed in DATA. */
3983 array_bounds_checker::check_array_bounds (tree
*tp
, int *walk_subtree
,
3987 struct walk_stmt_info
*wi
= (struct walk_stmt_info
*) data
;
3988 location_t location
;
3990 if (EXPR_HAS_LOCATION (t
))
3991 location
= EXPR_LOCATION (t
);
3993 location
= gimple_location (wi
->stmt
);
3995 *walk_subtree
= TRUE
;
3997 bool warned
= false;
3998 array_bounds_checker
*checker
= (array_bounds_checker
*) wi
->info
;
3999 if (TREE_CODE (t
) == ARRAY_REF
)
4000 warned
= checker
->check_array_ref (location
, t
,
4001 false/*ignore_off_by_one*/);
4002 else if (TREE_CODE (t
) == MEM_REF
)
4003 warned
= checker
->check_mem_ref (location
, t
,
4004 false /*ignore_off_by_one*/);
4005 else if (TREE_CODE (t
) == ADDR_EXPR
)
4007 checker
->check_addr_expr (location
, t
);
4008 *walk_subtree
= FALSE
;
4010 /* Propagate the no-warning bit to the outer expression. */
4012 TREE_NO_WARNING (t
) = true;
4017 /* A dom_walker subclass for use by check_all_array_refs, to walk over
4018 all statements of all reachable BBs and call check_array_bounds on
4021 class check_array_bounds_dom_walker
: public dom_walker
4024 check_array_bounds_dom_walker (array_bounds_checker
*checker
)
4025 : dom_walker (CDI_DOMINATORS
,
4026 /* Discover non-executable edges, preserving EDGE_EXECUTABLE
4027 flags, so that we can merge in information on
4028 non-executable edges from vrp_folder . */
4029 REACHABLE_BLOCKS_PRESERVING_FLAGS
),
4030 checker (checker
) { }
4031 ~check_array_bounds_dom_walker () {}
4033 edge
before_dom_children (basic_block
) FINAL OVERRIDE
;
4036 array_bounds_checker
*checker
;
4039 /* Implementation of dom_walker::before_dom_children.
4041 Walk over all statements of BB and call check_array_bounds on them,
4042 and determine if there's a unique successor edge. */
4045 check_array_bounds_dom_walker::before_dom_children (basic_block bb
)
4047 gimple_stmt_iterator si
;
4048 for (si
= gsi_start_bb (bb
); !gsi_end_p (si
); gsi_next (&si
))
4050 gimple
*stmt
= gsi_stmt (si
);
4051 struct walk_stmt_info wi
;
4052 if (!gimple_has_location (stmt
)
4053 || is_gimple_debug (stmt
))
4056 memset (&wi
, 0, sizeof (wi
));
4060 walk_gimple_op (stmt
, array_bounds_checker::check_array_bounds
, &wi
);
4063 /* Determine if there's a unique successor edge, and if so, return
4064 that back to dom_walker, ensuring that we don't visit blocks that
4065 became unreachable during the VRP propagation
4066 (PR tree-optimization/83312). */
4067 return find_taken_edge (bb
, NULL_TREE
);
4070 /* Entry point into array bounds checking pass. */
4073 array_bounds_checker::check ()
4075 check_array_bounds_dom_walker
w (this);
4076 w
.walk (ENTRY_BLOCK_PTR_FOR_FN (fun
));
4079 /* Return true if all imm uses of VAR are either in STMT, or
4080 feed (optionally through a chain of single imm uses) GIMPLE_COND
4081 in basic block COND_BB. */
4084 all_imm_uses_in_stmt_or_feed_cond (tree var
, gimple
*stmt
, basic_block cond_bb
)
4086 use_operand_p use_p
, use2_p
;
4087 imm_use_iterator iter
;
4089 FOR_EACH_IMM_USE_FAST (use_p
, iter
, var
)
4090 if (USE_STMT (use_p
) != stmt
)
4092 gimple
*use_stmt
= USE_STMT (use_p
), *use_stmt2
;
4093 if (is_gimple_debug (use_stmt
))
4095 while (is_gimple_assign (use_stmt
)
4096 && TREE_CODE (gimple_assign_lhs (use_stmt
)) == SSA_NAME
4097 && single_imm_use (gimple_assign_lhs (use_stmt
),
4098 &use2_p
, &use_stmt2
))
4099 use_stmt
= use_stmt2
;
4100 if (gimple_code (use_stmt
) != GIMPLE_COND
4101 || gimple_bb (use_stmt
) != cond_bb
)
4114 __builtin_unreachable ();
4116 x_5 = ASSERT_EXPR <x_3, ...>;
4117 If x_3 has no other immediate uses (checked by caller),
4118 var is the x_3 var from ASSERT_EXPR, we can clear low 5 bits
4119 from the non-zero bitmask. */
4122 maybe_set_nonzero_bits (edge e
, tree var
)
4124 basic_block cond_bb
= e
->src
;
4125 gimple
*stmt
= last_stmt (cond_bb
);
4129 || gimple_code (stmt
) != GIMPLE_COND
4130 || gimple_cond_code (stmt
) != ((e
->flags
& EDGE_TRUE_VALUE
)
4131 ? EQ_EXPR
: NE_EXPR
)
4132 || TREE_CODE (gimple_cond_lhs (stmt
)) != SSA_NAME
4133 || !integer_zerop (gimple_cond_rhs (stmt
)))
4136 stmt
= SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt
));
4137 if (!is_gimple_assign (stmt
)
4138 || gimple_assign_rhs_code (stmt
) != BIT_AND_EXPR
4139 || TREE_CODE (gimple_assign_rhs2 (stmt
)) != INTEGER_CST
)
4141 if (gimple_assign_rhs1 (stmt
) != var
)
4145 if (TREE_CODE (gimple_assign_rhs1 (stmt
)) != SSA_NAME
)
4147 stmt2
= SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt
));
4148 if (!gimple_assign_cast_p (stmt2
)
4149 || gimple_assign_rhs1 (stmt2
) != var
4150 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt2
))
4151 || (TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (stmt
)))
4152 != TYPE_PRECISION (TREE_TYPE (var
))))
4155 cst
= gimple_assign_rhs2 (stmt
);
4156 set_nonzero_bits (var
, wi::bit_and_not (get_nonzero_bits (var
),
4157 wi::to_wide (cst
)));
4160 /* Convert range assertion expressions into the implied copies and
4161 copy propagate away the copies. Doing the trivial copy propagation
4162 here avoids the need to run the full copy propagation pass after
4165 FIXME, this will eventually lead to copy propagation removing the
4166 names that had useful range information attached to them. For
4167 instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
4168 then N_i will have the range [3, +INF].
4170 However, by converting the assertion into the implied copy
4171 operation N_i = N_j, we will then copy-propagate N_j into the uses
4172 of N_i and lose the range information. We may want to hold on to
4173 ASSERT_EXPRs a little while longer as the ranges could be used in
4174 things like jump threading.
4176 The problem with keeping ASSERT_EXPRs around is that passes after
4177 VRP need to handle them appropriately.
4179 Another approach would be to make the range information a first
4180 class property of the SSA_NAME so that it can be queried from
4181 any pass. This is made somewhat more complex by the need for
4182 multiple ranges to be associated with one SSA_NAME. */
4185 vrp_insert::remove_range_assertions ()
4188 gimple_stmt_iterator si
;
4189 /* 1 if looking at ASSERT_EXPRs immediately at the beginning of
4190 a basic block preceeded by GIMPLE_COND branching to it and
4191 __builtin_trap, -1 if not yet checked, 0 otherwise. */
4194 /* Note that the BSI iterator bump happens at the bottom of the
4195 loop and no bump is necessary if we're removing the statement
4196 referenced by the current BSI. */
4197 FOR_EACH_BB_FN (bb
, fun
)
4198 for (si
= gsi_after_labels (bb
), is_unreachable
= -1; !gsi_end_p (si
);)
4200 gimple
*stmt
= gsi_stmt (si
);
4202 if (is_gimple_assign (stmt
)
4203 && gimple_assign_rhs_code (stmt
) == ASSERT_EXPR
)
4205 tree lhs
= gimple_assign_lhs (stmt
);
4206 tree rhs
= gimple_assign_rhs1 (stmt
);
4209 var
= ASSERT_EXPR_VAR (rhs
);
4211 if (TREE_CODE (var
) == SSA_NAME
4212 && !POINTER_TYPE_P (TREE_TYPE (lhs
))
4213 && SSA_NAME_RANGE_INFO (lhs
))
4215 if (is_unreachable
== -1)
4218 if (single_pred_p (bb
)
4219 && assert_unreachable_fallthru_edge_p
4220 (single_pred_edge (bb
)))
4224 if (x_7 >= 10 && x_7 < 20)
4225 __builtin_unreachable ();
4226 x_8 = ASSERT_EXPR <x_7, ...>;
4227 if the only uses of x_7 are in the ASSERT_EXPR and
4228 in the condition. In that case, we can copy the
4229 range info from x_8 computed in this pass also
4232 && all_imm_uses_in_stmt_or_feed_cond (var
, stmt
,
4235 set_range_info (var
, SSA_NAME_RANGE_TYPE (lhs
),
4236 SSA_NAME_RANGE_INFO (lhs
)->get_min (),
4237 SSA_NAME_RANGE_INFO (lhs
)->get_max ());
4238 maybe_set_nonzero_bits (single_pred_edge (bb
), var
);
4242 /* Propagate the RHS into every use of the LHS. For SSA names
4243 also propagate abnormals as it merely restores the original
4244 IL in this case (an replace_uses_by would assert). */
4245 if (TREE_CODE (var
) == SSA_NAME
)
4247 imm_use_iterator iter
;
4248 use_operand_p use_p
;
4250 FOR_EACH_IMM_USE_STMT (use_stmt
, iter
, lhs
)
4251 FOR_EACH_IMM_USE_ON_STMT (use_p
, iter
)
4252 SET_USE (use_p
, var
);
4255 replace_uses_by (lhs
, var
);
4257 /* And finally, remove the copy, it is not needed. */
4258 gsi_remove (&si
, true);
4259 release_defs (stmt
);
4263 if (!is_gimple_debug (gsi_stmt (si
)))
4270 /* Return true if STMT is interesting for VRP. */
4273 stmt_interesting_for_vrp (gimple
*stmt
)
4275 if (gimple_code (stmt
) == GIMPLE_PHI
)
4277 tree res
= gimple_phi_result (stmt
);
4278 return (!virtual_operand_p (res
)
4279 && (INTEGRAL_TYPE_P (TREE_TYPE (res
))
4280 || POINTER_TYPE_P (TREE_TYPE (res
))));
4282 else if (is_gimple_assign (stmt
) || is_gimple_call (stmt
))
4284 tree lhs
= gimple_get_lhs (stmt
);
4286 /* In general, assignments with virtual operands are not useful
4287 for deriving ranges, with the obvious exception of calls to
4288 builtin functions. */
4289 if (lhs
&& TREE_CODE (lhs
) == SSA_NAME
4290 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs
))
4291 || POINTER_TYPE_P (TREE_TYPE (lhs
)))
4292 && (is_gimple_call (stmt
)
4293 || !gimple_vuse (stmt
)))
4295 else if (is_gimple_call (stmt
) && gimple_call_internal_p (stmt
))
4296 switch (gimple_call_internal_fn (stmt
))
4298 case IFN_ADD_OVERFLOW
:
4299 case IFN_SUB_OVERFLOW
:
4300 case IFN_MUL_OVERFLOW
:
4301 case IFN_ATOMIC_COMPARE_EXCHANGE
:
4302 /* These internal calls return _Complex integer type,
4303 but are interesting to VRP nevertheless. */
4304 if (lhs
&& TREE_CODE (lhs
) == SSA_NAME
)
4311 else if (gimple_code (stmt
) == GIMPLE_COND
4312 || gimple_code (stmt
) == GIMPLE_SWITCH
)
4318 /* Initialization required by ssa_propagate engine. */
4321 vrp_prop::vrp_initialize (struct function
*fn
)
4326 FOR_EACH_BB_FN (bb
, fun
)
4328 for (gphi_iterator si
= gsi_start_phis (bb
); !gsi_end_p (si
);
4331 gphi
*phi
= si
.phi ();
4332 if (!stmt_interesting_for_vrp (phi
))
4334 tree lhs
= PHI_RESULT (phi
);
4335 set_def_to_varying (lhs
);
4336 prop_set_simulate_again (phi
, false);
4339 prop_set_simulate_again (phi
, true);
4342 for (gimple_stmt_iterator si
= gsi_start_bb (bb
); !gsi_end_p (si
);
4345 gimple
*stmt
= gsi_stmt (si
);
4347 /* If the statement is a control insn, then we do not
4348 want to avoid simulating the statement once. Failure
4349 to do so means that those edges will never get added. */
4350 if (stmt_ends_bb_p (stmt
))
4351 prop_set_simulate_again (stmt
, true);
4352 else if (!stmt_interesting_for_vrp (stmt
))
4354 set_defs_to_varying (stmt
);
4355 prop_set_simulate_again (stmt
, false);
4358 prop_set_simulate_again (stmt
, true);
4363 /* Searches the case label vector VEC for the index *IDX of the CASE_LABEL
4364 that includes the value VAL. The search is restricted to the range
4365 [START_IDX, n - 1] where n is the size of VEC.
4367 If there is a CASE_LABEL for VAL, its index is placed in IDX and true is
4370 If there is no CASE_LABEL for VAL and there is one that is larger than VAL,
4371 it is placed in IDX and false is returned.
4373 If VAL is larger than any CASE_LABEL, n is placed on IDX and false is
4377 find_case_label_index (gswitch
*stmt
, size_t start_idx
, tree val
, size_t *idx
)
4379 size_t n
= gimple_switch_num_labels (stmt
);
4382 /* Find case label for minimum of the value range or the next one.
4383 At each iteration we are searching in [low, high - 1]. */
4385 for (low
= start_idx
, high
= n
; high
!= low
; )
4389 /* Note that i != high, so we never ask for n. */
4390 size_t i
= (high
+ low
) / 2;
4391 t
= gimple_switch_label (stmt
, i
);
4393 /* Cache the result of comparing CASE_LOW and val. */
4394 cmp
= tree_int_cst_compare (CASE_LOW (t
), val
);
4398 /* Ranges cannot be empty. */
4407 if (CASE_HIGH (t
) != NULL
4408 && tree_int_cst_compare (CASE_HIGH (t
), val
) >= 0)
4420 /* Searches the case label vector VEC for the range of CASE_LABELs that is used
4421 for values between MIN and MAX. The first index is placed in MIN_IDX. The
4422 last index is placed in MAX_IDX. If the range of CASE_LABELs is empty
4423 then MAX_IDX < MIN_IDX.
4424 Returns true if the default label is not needed. */
4427 find_case_label_range (gswitch
*stmt
, tree min
, tree max
, size_t *min_idx
,
4431 bool min_take_default
= !find_case_label_index (stmt
, 1, min
, &i
);
4432 bool max_take_default
= !find_case_label_index (stmt
, i
, max
, &j
);
4436 && max_take_default
)
4438 /* Only the default case label reached.
4439 Return an empty range. */
4446 bool take_default
= min_take_default
|| max_take_default
;
4450 if (max_take_default
)
4453 /* If the case label range is continuous, we do not need
4454 the default case label. Verify that. */
4455 high
= CASE_LOW (gimple_switch_label (stmt
, i
));
4456 if (CASE_HIGH (gimple_switch_label (stmt
, i
)))
4457 high
= CASE_HIGH (gimple_switch_label (stmt
, i
));
4458 for (k
= i
+ 1; k
<= j
; ++k
)
4460 low
= CASE_LOW (gimple_switch_label (stmt
, k
));
4461 if (!integer_onep (int_const_binop (MINUS_EXPR
, low
, high
)))
4463 take_default
= true;
4467 if (CASE_HIGH (gimple_switch_label (stmt
, k
)))
4468 high
= CASE_HIGH (gimple_switch_label (stmt
, k
));
4473 return !take_default
;
4477 /* Evaluate statement STMT. If the statement produces a useful range,
4478 return SSA_PROP_INTERESTING and record the SSA name with the
4479 interesting range into *OUTPUT_P.
4481 If STMT is a conditional branch and we can determine its truth
4482 value, the taken edge is recorded in *TAKEN_EDGE_P.
4484 If STMT produces a varying value, return SSA_PROP_VARYING. */
4486 enum ssa_prop_result
4487 vrp_prop::visit_stmt (gimple
*stmt
, edge
*taken_edge_p
, tree
*output_p
)
4489 tree lhs
= gimple_get_lhs (stmt
);
4490 value_range_equiv vr
;
4491 extract_range_from_stmt (stmt
, taken_edge_p
, output_p
, &vr
);
4495 if (update_value_range (*output_p
, &vr
))
4497 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
4499 fprintf (dump_file
, "Found new range for ");
4500 print_generic_expr (dump_file
, *output_p
);
4501 fprintf (dump_file
, ": ");
4502 dump_value_range (dump_file
, &vr
);
4503 fprintf (dump_file
, "\n");
4506 if (vr
.varying_p ())
4507 return SSA_PROP_VARYING
;
4509 return SSA_PROP_INTERESTING
;
4511 return SSA_PROP_NOT_INTERESTING
;
4514 if (is_gimple_call (stmt
) && gimple_call_internal_p (stmt
))
4515 switch (gimple_call_internal_fn (stmt
))
4517 case IFN_ADD_OVERFLOW
:
4518 case IFN_SUB_OVERFLOW
:
4519 case IFN_MUL_OVERFLOW
:
4520 case IFN_ATOMIC_COMPARE_EXCHANGE
:
4521 /* These internal calls return _Complex integer type,
4522 which VRP does not track, but the immediate uses
4523 thereof might be interesting. */
4524 if (lhs
&& TREE_CODE (lhs
) == SSA_NAME
)
4526 imm_use_iterator iter
;
4527 use_operand_p use_p
;
4528 enum ssa_prop_result res
= SSA_PROP_VARYING
;
4530 set_def_to_varying (lhs
);
4532 FOR_EACH_IMM_USE_FAST (use_p
, iter
, lhs
)
4534 gimple
*use_stmt
= USE_STMT (use_p
);
4535 if (!is_gimple_assign (use_stmt
))
4537 enum tree_code rhs_code
= gimple_assign_rhs_code (use_stmt
);
4538 if (rhs_code
!= REALPART_EXPR
&& rhs_code
!= IMAGPART_EXPR
)
4540 tree rhs1
= gimple_assign_rhs1 (use_stmt
);
4541 tree use_lhs
= gimple_assign_lhs (use_stmt
);
4542 if (TREE_CODE (rhs1
) != rhs_code
4543 || TREE_OPERAND (rhs1
, 0) != lhs
4544 || TREE_CODE (use_lhs
) != SSA_NAME
4545 || !stmt_interesting_for_vrp (use_stmt
)
4546 || (!INTEGRAL_TYPE_P (TREE_TYPE (use_lhs
))
4547 || !TYPE_MIN_VALUE (TREE_TYPE (use_lhs
))
4548 || !TYPE_MAX_VALUE (TREE_TYPE (use_lhs
))))
4551 /* If there is a change in the value range for any of the
4552 REALPART_EXPR/IMAGPART_EXPR immediate uses, return
4553 SSA_PROP_INTERESTING. If there are any REALPART_EXPR
4554 or IMAGPART_EXPR immediate uses, but none of them have
4555 a change in their value ranges, return
4556 SSA_PROP_NOT_INTERESTING. If there are no
4557 {REAL,IMAG}PART_EXPR uses at all,
4558 return SSA_PROP_VARYING. */
4559 value_range_equiv new_vr
;
4560 extract_range_basic (&new_vr
, use_stmt
);
4561 const value_range_equiv
*old_vr
= get_value_range (use_lhs
);
4562 if (!old_vr
->equal_p (new_vr
, /*ignore_equivs=*/false))
4563 res
= SSA_PROP_INTERESTING
;
4565 res
= SSA_PROP_NOT_INTERESTING
;
4566 new_vr
.equiv_clear ();
4567 if (res
== SSA_PROP_INTERESTING
)
4581 /* All other statements produce nothing of interest for VRP, so mark
4582 their outputs varying and prevent further simulation. */
4583 set_defs_to_varying (stmt
);
4585 return (*taken_edge_p
) ? SSA_PROP_INTERESTING
: SSA_PROP_VARYING
;
4588 /* Visit all arguments for PHI node PHI that flow through executable
4589 edges. If a valid value range can be derived from all the incoming
4590 value ranges, set a new range for the LHS of PHI. */
4592 enum ssa_prop_result
4593 vrp_prop::visit_phi (gphi
*phi
)
4595 tree lhs
= PHI_RESULT (phi
);
4596 value_range_equiv vr_result
;
4597 extract_range_from_phi_node (phi
, &vr_result
);
4598 if (update_value_range (lhs
, &vr_result
))
4600 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
4602 fprintf (dump_file
, "Found new range for ");
4603 print_generic_expr (dump_file
, lhs
);
4604 fprintf (dump_file
, ": ");
4605 dump_value_range (dump_file
, &vr_result
);
4606 fprintf (dump_file
, "\n");
4609 if (vr_result
.varying_p ())
4610 return SSA_PROP_VARYING
;
4612 return SSA_PROP_INTERESTING
;
4615 /* Nothing changed, don't add outgoing edges. */
4616 return SSA_PROP_NOT_INTERESTING
;
4619 class vrp_folder
: public substitute_and_fold_engine
4622 vrp_folder () : substitute_and_fold_engine (/* Fold all stmts. */ true) { }
4623 tree
get_value (tree
) FINAL OVERRIDE
;
4624 bool fold_stmt (gimple_stmt_iterator
*) FINAL OVERRIDE
;
4626 class vr_values
*vr_values
;
4629 bool fold_predicate_in (gimple_stmt_iterator
*);
4631 tree
vrp_evaluate_conditional (tree_code code
, tree op0
,
4632 tree op1
, gimple
*stmt
)
4633 { return vr_values
->vrp_evaluate_conditional (code
, op0
, op1
, stmt
); }
4634 bool simplify_stmt_using_ranges (gimple_stmt_iterator
*gsi
)
4635 { return vr_values
->simplify_stmt_using_ranges (gsi
); }
4636 tree
op_with_constant_singleton_value_range (tree op
)
4637 { return vr_values
->op_with_constant_singleton_value_range (op
); }
4640 /* If the statement pointed by SI has a predicate whose value can be
4641 computed using the value range information computed by VRP, compute
4642 its value and return true. Otherwise, return false. */
4645 vrp_folder::fold_predicate_in (gimple_stmt_iterator
*si
)
4647 bool assignment_p
= false;
4649 gimple
*stmt
= gsi_stmt (*si
);
4651 if (is_gimple_assign (stmt
)
4652 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt
)) == tcc_comparison
)
4654 assignment_p
= true;
4655 val
= vrp_evaluate_conditional (gimple_assign_rhs_code (stmt
),
4656 gimple_assign_rhs1 (stmt
),
4657 gimple_assign_rhs2 (stmt
),
4660 else if (gcond
*cond_stmt
= dyn_cast
<gcond
*> (stmt
))
4661 val
= vrp_evaluate_conditional (gimple_cond_code (cond_stmt
),
4662 gimple_cond_lhs (cond_stmt
),
4663 gimple_cond_rhs (cond_stmt
),
4671 val
= fold_convert (gimple_expr_type (stmt
), val
);
4675 fprintf (dump_file
, "Folding predicate ");
4676 print_gimple_expr (dump_file
, stmt
, 0);
4677 fprintf (dump_file
, " to ");
4678 print_generic_expr (dump_file
, val
);
4679 fprintf (dump_file
, "\n");
4682 if (is_gimple_assign (stmt
))
4683 gimple_assign_set_rhs_from_tree (si
, val
);
4686 gcc_assert (gimple_code (stmt
) == GIMPLE_COND
);
4687 gcond
*cond_stmt
= as_a
<gcond
*> (stmt
);
4688 if (integer_zerop (val
))
4689 gimple_cond_make_false (cond_stmt
);
4690 else if (integer_onep (val
))
4691 gimple_cond_make_true (cond_stmt
);
4702 /* Callback for substitute_and_fold folding the stmt at *SI. */
4705 vrp_folder::fold_stmt (gimple_stmt_iterator
*si
)
4707 if (fold_predicate_in (si
))
4710 return simplify_stmt_using_ranges (si
);
4713 /* If OP has a value range with a single constant value return that,
4714 otherwise return NULL_TREE. This returns OP itself if OP is a
4717 Implemented as a pure wrapper right now, but this will change. */
4720 vrp_folder::get_value (tree op
)
4722 return op_with_constant_singleton_value_range (op
);
4725 /* Return the LHS of any ASSERT_EXPR where OP appears as the first
4726 argument to the ASSERT_EXPR and in which the ASSERT_EXPR dominates
4727 BB. If no such ASSERT_EXPR is found, return OP. */
4730 lhs_of_dominating_assert (tree op
, basic_block bb
, gimple
*stmt
)
4732 imm_use_iterator imm_iter
;
4734 use_operand_p use_p
;
4736 if (TREE_CODE (op
) == SSA_NAME
)
4738 FOR_EACH_IMM_USE_FAST (use_p
, imm_iter
, op
)
4740 use_stmt
= USE_STMT (use_p
);
4741 if (use_stmt
!= stmt
4742 && gimple_assign_single_p (use_stmt
)
4743 && TREE_CODE (gimple_assign_rhs1 (use_stmt
)) == ASSERT_EXPR
4744 && TREE_OPERAND (gimple_assign_rhs1 (use_stmt
), 0) == op
4745 && dominated_by_p (CDI_DOMINATORS
, bb
, gimple_bb (use_stmt
)))
4746 return gimple_assign_lhs (use_stmt
);
4753 static class vr_values
*x_vr_values
;
4755 /* A trivial wrapper so that we can present the generic jump threading
4756 code with a simple API for simplifying statements. STMT is the
4757 statement we want to simplify, WITHIN_STMT provides the location
4758 for any overflow warnings. */
4761 simplify_stmt_for_jump_threading (gimple
*stmt
, gimple
*within_stmt
,
4762 class avail_exprs_stack
*avail_exprs_stack ATTRIBUTE_UNUSED
,
4765 /* First see if the conditional is in the hash table. */
4766 tree cached_lhs
= avail_exprs_stack
->lookup_avail_expr (stmt
, false, true);
4767 if (cached_lhs
&& is_gimple_min_invariant (cached_lhs
))
4770 vr_values
*vr_values
= x_vr_values
;
4771 if (gcond
*cond_stmt
= dyn_cast
<gcond
*> (stmt
))
4773 tree op0
= gimple_cond_lhs (cond_stmt
);
4774 op0
= lhs_of_dominating_assert (op0
, bb
, stmt
);
4776 tree op1
= gimple_cond_rhs (cond_stmt
);
4777 op1
= lhs_of_dominating_assert (op1
, bb
, stmt
);
4779 return vr_values
->vrp_evaluate_conditional (gimple_cond_code (cond_stmt
),
4780 op0
, op1
, within_stmt
);
4783 /* We simplify a switch statement by trying to determine which case label
4784 will be taken. If we are successful then we return the corresponding
4786 if (gswitch
*switch_stmt
= dyn_cast
<gswitch
*> (stmt
))
4788 tree op
= gimple_switch_index (switch_stmt
);
4789 if (TREE_CODE (op
) != SSA_NAME
)
4792 op
= lhs_of_dominating_assert (op
, bb
, stmt
);
4794 const value_range_equiv
*vr
= vr_values
->get_value_range (op
);
4795 if (vr
->undefined_p ()
4797 || vr
->symbolic_p ())
4800 if (vr
->kind () == VR_RANGE
)
4803 /* Get the range of labels that contain a part of the operand's
4805 find_case_label_range (switch_stmt
, vr
->min (), vr
->max (), &i
, &j
);
4807 /* Is there only one such label? */
4810 tree label
= gimple_switch_label (switch_stmt
, i
);
4812 /* The i'th label will be taken only if the value range of the
4813 operand is entirely within the bounds of this label. */
4814 if (CASE_HIGH (label
) != NULL_TREE
4815 ? (tree_int_cst_compare (CASE_LOW (label
), vr
->min ()) <= 0
4816 && tree_int_cst_compare (CASE_HIGH (label
),
4818 : (tree_int_cst_equal (CASE_LOW (label
), vr
->min ())
4819 && tree_int_cst_equal (vr
->min (), vr
->max ())))
4823 /* If there are no such labels then the default label will be
4826 return gimple_switch_label (switch_stmt
, 0);
4829 if (vr
->kind () == VR_ANTI_RANGE
)
4831 unsigned n
= gimple_switch_num_labels (switch_stmt
);
4832 tree min_label
= gimple_switch_label (switch_stmt
, 1);
4833 tree max_label
= gimple_switch_label (switch_stmt
, n
- 1);
4835 /* The default label will be taken only if the anti-range of the
4836 operand is entirely outside the bounds of all the (non-default)
4838 if (tree_int_cst_compare (vr
->min (), CASE_LOW (min_label
)) <= 0
4839 && (CASE_HIGH (max_label
) != NULL_TREE
4840 ? tree_int_cst_compare (vr
->max (),
4841 CASE_HIGH (max_label
)) >= 0
4842 : tree_int_cst_compare (vr
->max (),
4843 CASE_LOW (max_label
)) >= 0))
4844 return gimple_switch_label (switch_stmt
, 0);
4850 if (gassign
*assign_stmt
= dyn_cast
<gassign
*> (stmt
))
4852 tree lhs
= gimple_assign_lhs (assign_stmt
);
4853 if (TREE_CODE (lhs
) == SSA_NAME
4854 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs
))
4855 || POINTER_TYPE_P (TREE_TYPE (lhs
)))
4856 && stmt_interesting_for_vrp (stmt
))
4860 value_range_equiv new_vr
;
4861 vr_values
->extract_range_from_stmt (stmt
, &dummy_e
,
4862 &dummy_tree
, &new_vr
);
4864 if (new_vr
.singleton_p (&singleton
))
4872 class vrp_dom_walker
: public dom_walker
4875 vrp_dom_walker (cdi_direction direction
,
4876 class const_and_copies
*const_and_copies
,
4877 class avail_exprs_stack
*avail_exprs_stack
)
4878 : dom_walker (direction
, REACHABLE_BLOCKS
),
4879 m_const_and_copies (const_and_copies
),
4880 m_avail_exprs_stack (avail_exprs_stack
),
4881 m_dummy_cond (NULL
) {}
4883 virtual edge
before_dom_children (basic_block
);
4884 virtual void after_dom_children (basic_block
);
4886 class vr_values
*vr_values
;
4889 class const_and_copies
*m_const_and_copies
;
4890 class avail_exprs_stack
*m_avail_exprs_stack
;
4892 gcond
*m_dummy_cond
;
4896 /* Called before processing dominator children of BB. We want to look
4897 at ASSERT_EXPRs and record information from them in the appropriate
4900 We could look at other statements here. It's not seen as likely
4901 to significantly increase the jump threads we discover. */
4904 vrp_dom_walker::before_dom_children (basic_block bb
)
4906 gimple_stmt_iterator gsi
;
4908 m_avail_exprs_stack
->push_marker ();
4909 m_const_and_copies
->push_marker ();
4910 for (gsi
= gsi_start_nondebug_bb (bb
); !gsi_end_p (gsi
); gsi_next (&gsi
))
4912 gimple
*stmt
= gsi_stmt (gsi
);
4913 if (gimple_assign_single_p (stmt
)
4914 && TREE_CODE (gimple_assign_rhs1 (stmt
)) == ASSERT_EXPR
)
4916 tree rhs1
= gimple_assign_rhs1 (stmt
);
4917 tree cond
= TREE_OPERAND (rhs1
, 1);
4918 tree inverted
= invert_truthvalue (cond
);
4919 vec
<cond_equivalence
> p
;
4921 record_conditions (&p
, cond
, inverted
);
4922 for (unsigned int i
= 0; i
< p
.length (); i
++)
4923 m_avail_exprs_stack
->record_cond (&p
[i
]);
4925 tree lhs
= gimple_assign_lhs (stmt
);
4926 m_const_and_copies
->record_const_or_copy (lhs
,
4927 TREE_OPERAND (rhs1
, 0));
4936 /* Called after processing dominator children of BB. This is where we
4937 actually call into the threader. */
4939 vrp_dom_walker::after_dom_children (basic_block bb
)
4942 m_dummy_cond
= gimple_build_cond (NE_EXPR
,
4943 integer_zero_node
, integer_zero_node
,
4946 x_vr_values
= vr_values
;
4947 thread_outgoing_edges (bb
, m_dummy_cond
, m_const_and_copies
,
4948 m_avail_exprs_stack
, NULL
,
4949 simplify_stmt_for_jump_threading
);
4952 m_avail_exprs_stack
->pop_to_marker ();
4953 m_const_and_copies
->pop_to_marker ();
4956 /* Blocks which have more than one predecessor and more than
4957 one successor present jump threading opportunities, i.e.,
4958 when the block is reached from a specific predecessor, we
4959 may be able to determine which of the outgoing edges will
4960 be traversed. When this optimization applies, we are able
4961 to avoid conditionals at runtime and we may expose secondary
4962 optimization opportunities.
4964 This routine is effectively a driver for the generic jump
4965 threading code. It basically just presents the generic code
4966 with edges that may be suitable for jump threading.
4968 Unlike DOM, we do not iterate VRP if jump threading was successful.
4969 While iterating may expose new opportunities for VRP, it is expected
4970 those opportunities would be very limited and the compile time cost
4971 to expose those opportunities would be significant.
4973 As jump threading opportunities are discovered, they are registered
4974 for later realization. */
4977 identify_jump_threads (struct function
*fun
, class vr_values
*vr_values
)
4979 /* Ugh. When substituting values earlier in this pass we can
4980 wipe the dominance information. So rebuild the dominator
4981 information as we need it within the jump threading code. */
4982 calculate_dominance_info (CDI_DOMINATORS
);
4984 /* We do not allow VRP information to be used for jump threading
4985 across a back edge in the CFG. Otherwise it becomes too
4986 difficult to avoid eliminating loop exit tests. Of course
4987 EDGE_DFS_BACK is not accurate at this time so we have to
4989 mark_dfs_back_edges ();
4991 /* Allocate our unwinder stack to unwind any temporary equivalences
4992 that might be recorded. */
4993 const_and_copies
*equiv_stack
= new const_and_copies ();
4995 hash_table
<expr_elt_hasher
> *avail_exprs
4996 = new hash_table
<expr_elt_hasher
> (1024);
4997 avail_exprs_stack
*avail_exprs_stack
4998 = new class avail_exprs_stack (avail_exprs
);
5000 vrp_dom_walker
walker (CDI_DOMINATORS
, equiv_stack
, avail_exprs_stack
);
5001 walker
.vr_values
= vr_values
;
5002 walker
.walk (fun
->cfg
->x_entry_block_ptr
);
5004 /* We do not actually update the CFG or SSA graphs at this point as
5005 ASSERT_EXPRs are still in the IL and cfg cleanup code does not yet
5006 handle ASSERT_EXPRs gracefully. */
5009 delete avail_exprs_stack
;
5012 /* Traverse all the blocks folding conditionals with known ranges. */
5015 vrp_prop::vrp_finalize (bool warn_array_bounds_p
)
5019 /* We have completed propagating through the lattice. */
5020 vr_values
.set_lattice_propagation_complete ();
5024 fprintf (dump_file
, "\nValue ranges after VRP:\n\n");
5025 vr_values
.dump_all_value_ranges (dump_file
);
5026 fprintf (dump_file
, "\n");
5029 /* Set value range to non pointer SSA_NAMEs. */
5030 for (i
= 0; i
< num_ssa_names
; i
++)
5032 tree name
= ssa_name (i
);
5036 const value_range_equiv
*vr
= get_value_range (name
);
5037 if (!name
|| !vr
->constant_p ())
5040 if (POINTER_TYPE_P (TREE_TYPE (name
))
5041 && range_includes_zero_p (vr
) == 0)
5042 set_ptr_nonnull (name
);
5043 else if (!POINTER_TYPE_P (TREE_TYPE (name
)))
5044 set_range_info (name
, *vr
);
5047 /* If we're checking array refs, we want to merge information on
5048 the executability of each edge between vrp_folder and the
5049 check_array_bounds_dom_walker: each can clear the
5050 EDGE_EXECUTABLE flag on edges, in different ways.
5052 Hence, if we're going to call check_all_array_refs, set
5053 the flag on every edge now, rather than in
5054 check_array_bounds_dom_walker's ctor; vrp_folder may clear
5055 it from some edges. */
5056 if (warn_array_bounds
&& warn_array_bounds_p
)
5057 set_all_edges_as_executable (fun
);
5059 class vrp_folder vrp_folder
;
5060 vrp_folder
.vr_values
= &vr_values
;
5061 vrp_folder
.substitute_and_fold ();
5063 if (warn_array_bounds
&& warn_array_bounds_p
)
5065 array_bounds_checker
array_checker (fun
, &vr_values
);
5066 array_checker
.check ();
5070 /* Main entry point to VRP (Value Range Propagation). This pass is
5071 loosely based on J. R. C. Patterson, ``Accurate Static Branch
5072 Prediction by Value Range Propagation,'' in SIGPLAN Conference on
5073 Programming Language Design and Implementation, pp. 67-78, 1995.
5074 Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
5076 This is essentially an SSA-CCP pass modified to deal with ranges
5077 instead of constants.
5079 While propagating ranges, we may find that two or more SSA name
5080 have equivalent, though distinct ranges. For instance,
5083 2 p_4 = ASSERT_EXPR <p_3, p_3 != 0>
5085 4 p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
5089 In the code above, pointer p_5 has range [q_2, q_2], but from the
5090 code we can also determine that p_5 cannot be NULL and, if q_2 had
5091 a non-varying range, p_5's range should also be compatible with it.
5093 These equivalences are created by two expressions: ASSERT_EXPR and
5094 copy operations. Since p_5 is an assertion on p_4, and p_4 was the
5095 result of another assertion, then we can use the fact that p_5 and
5096 p_4 are equivalent when evaluating p_5's range.
5098 Together with value ranges, we also propagate these equivalences
5099 between names so that we can take advantage of information from
5100 multiple ranges when doing final replacement. Note that this
5101 equivalency relation is transitive but not symmetric.
5103 In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
5104 cannot assert that q_2 is equivalent to p_5 because q_2 may be used
5105 in contexts where that assertion does not hold (e.g., in line 6).
5107 TODO, the main difference between this pass and Patterson's is that
5108 we do not propagate edge probabilities. We only compute whether
5109 edges can be taken or not. That is, instead of having a spectrum
5110 of jump probabilities between 0 and 1, we only deal with 0, 1 and
5111 DON'T KNOW. In the future, it may be worthwhile to propagate
5112 probabilities to aid branch prediction. */
5115 execute_vrp (struct function
*fun
, bool warn_array_bounds_p
)
5118 loop_optimizer_init (LOOPS_NORMAL
| LOOPS_HAVE_RECORDED_EXITS
);
5119 rewrite_into_loop_closed_ssa (NULL
, TODO_update_ssa
);
5122 /* ??? This ends up using stale EDGE_DFS_BACK for liveness computation.
5123 Inserting assertions may split edges which will invalidate
5125 vrp_insert
assert_engine (fun
);
5126 assert_engine
.insert_range_assertions ();
5128 threadedge_initialize_values ();
5130 /* For visiting PHI nodes we need EDGE_DFS_BACK computed. */
5131 mark_dfs_back_edges ();
5133 class vrp_prop vrp_prop
;
5134 vrp_prop
.vrp_initialize (fun
);
5135 vrp_prop
.ssa_propagate ();
5136 vrp_prop
.vrp_finalize (warn_array_bounds_p
);
5138 /* We must identify jump threading opportunities before we release
5139 the datastructures built by VRP. */
5140 identify_jump_threads (fun
, &vrp_prop
.vr_values
);
5142 /* A comparison of an SSA_NAME against a constant where the SSA_NAME
5143 was set by a type conversion can often be rewritten to use the
5144 RHS of the type conversion.
5146 However, doing so inhibits jump threading through the comparison.
5147 So that transformation is not performed until after jump threading
5150 FOR_EACH_BB_FN (bb
, fun
)
5152 gimple
*last
= last_stmt (bb
);
5153 if (last
&& gimple_code (last
) == GIMPLE_COND
)
5154 vrp_prop
.vr_values
.simplify_cond_using_ranges_2 (as_a
<gcond
*> (last
));
5157 free_numbers_of_iterations_estimates (fun
);
5159 /* ASSERT_EXPRs must be removed before finalizing jump threads
5160 as finalizing jump threads calls the CFG cleanup code which
5161 does not properly handle ASSERT_EXPRs. */
5162 assert_engine
.remove_range_assertions ();
5164 /* If we exposed any new variables, go ahead and put them into
5165 SSA form now, before we handle jump threading. This simplifies
5166 interactions between rewriting of _DECL nodes into SSA form
5167 and rewriting SSA_NAME nodes into SSA form after block
5168 duplication and CFG manipulation. */
5169 update_ssa (TODO_update_ssa
);
5171 /* We identified all the jump threading opportunities earlier, but could
5172 not transform the CFG at that time. This routine transforms the
5173 CFG and arranges for the dominator tree to be rebuilt if necessary.
5175 Note the SSA graph update will occur during the normal TODO
5176 processing by the pass manager. */
5177 thread_through_all_blocks (false);
5179 vrp_prop
.vr_values
.cleanup_edges_and_switches ();
5180 threadedge_finalize_values ();
5183 loop_optimizer_finalize ();
5189 const pass_data pass_data_vrp
=
5191 GIMPLE_PASS
, /* type */
5193 OPTGROUP_NONE
, /* optinfo_flags */
5194 TV_TREE_VRP
, /* tv_id */
5195 PROP_ssa
, /* properties_required */
5196 0, /* properties_provided */
5197 0, /* properties_destroyed */
5198 0, /* todo_flags_start */
5199 ( TODO_cleanup_cfg
| TODO_update_ssa
), /* todo_flags_finish */
5202 class pass_vrp
: public gimple_opt_pass
5205 pass_vrp (gcc::context
*ctxt
)
5206 : gimple_opt_pass (pass_data_vrp
, ctxt
), warn_array_bounds_p (false)
5209 /* opt_pass methods: */
5210 opt_pass
* clone () { return new pass_vrp (m_ctxt
); }
5211 void set_pass_param (unsigned int n
, bool param
)
5213 gcc_assert (n
== 0);
5214 warn_array_bounds_p
= param
;
5216 virtual bool gate (function
*) { return flag_tree_vrp
!= 0; }
5217 virtual unsigned int execute (function
*fun
)
5218 { return execute_vrp (fun
, warn_array_bounds_p
); }
5221 bool warn_array_bounds_p
;
5222 }; // class pass_vrp
5227 make_pass_vrp (gcc::context
*ctxt
)
5229 return new pass_vrp (ctxt
);
5233 /* Worker for determine_value_range. */
5236 determine_value_range_1 (value_range
*vr
, tree expr
)
5238 if (BINARY_CLASS_P (expr
))
5240 value_range vr0
, vr1
;
5241 determine_value_range_1 (&vr0
, TREE_OPERAND (expr
, 0));
5242 determine_value_range_1 (&vr1
, TREE_OPERAND (expr
, 1));
5243 range_fold_binary_expr (vr
, TREE_CODE (expr
), TREE_TYPE (expr
),
5246 else if (UNARY_CLASS_P (expr
))
5249 determine_value_range_1 (&vr0
, TREE_OPERAND (expr
, 0));
5250 range_fold_unary_expr (vr
, TREE_CODE (expr
), TREE_TYPE (expr
),
5251 &vr0
, TREE_TYPE (TREE_OPERAND (expr
, 0)));
5253 else if (TREE_CODE (expr
) == INTEGER_CST
)
5257 value_range_kind kind
;
5259 /* For SSA names try to extract range info computed by VRP. Otherwise
5260 fall back to varying. */
5261 if (TREE_CODE (expr
) == SSA_NAME
5262 && INTEGRAL_TYPE_P (TREE_TYPE (expr
))
5263 && (kind
= get_range_info (expr
, &min
, &max
)) != VR_VARYING
)
5264 vr
->set (wide_int_to_tree (TREE_TYPE (expr
), min
),
5265 wide_int_to_tree (TREE_TYPE (expr
), max
),
5268 vr
->set_varying (TREE_TYPE (expr
));
5272 /* Compute a value-range for EXPR and set it in *MIN and *MAX. Return
5273 the determined range type. */
5276 determine_value_range (tree expr
, wide_int
*min
, wide_int
*max
)
5279 determine_value_range_1 (&vr
, expr
);
5280 if (vr
.constant_p ())
5282 *min
= wi::to_wide (vr
.min ());
5283 *max
= wi::to_wide (vr
.max ());