]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/tree-vrp.c
[Ada] Update headers
[thirdparty/gcc.git] / gcc / tree-vrp.c
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>.
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
11
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "backend.h"
25 #include "insn-codes.h"
26 #include "rtl.h"
27 #include "tree.h"
28 #include "gimple.h"
29 #include "cfghooks.h"
30 #include "tree-pass.h"
31 #include "ssa.h"
32 #include "optabs-tree.h"
33 #include "gimple-pretty-print.h"
34 #include "flags.h"
35 #include "fold-const.h"
36 #include "stor-layout.h"
37 #include "calls.h"
38 #include "cfganal.h"
39 #include "gimple-fold.h"
40 #include "tree-eh.h"
41 #include "gimple-iterator.h"
42 #include "gimple-walk.h"
43 #include "tree-cfg.h"
44 #include "tree-ssa-loop-manip.h"
45 #include "tree-ssa-loop-niter.h"
46 #include "tree-ssa-loop.h"
47 #include "tree-into-ssa.h"
48 #include "tree-ssa.h"
49 #include "cfgloop.h"
50 #include "tree-scalar-evolution.h"
51 #include "tree-ssa-propagate.h"
52 #include "tree-chrec.h"
53 #include "tree-ssa-threadupdate.h"
54 #include "tree-ssa-scopedtables.h"
55 #include "tree-ssa-threadedge.h"
56 #include "omp-general.h"
57 #include "target.h"
58 #include "case-cfn-macros.h"
59 #include "alloc-pool.h"
60 #include "domwalk.h"
61 #include "tree-cfgcleanup.h"
62 #include "stringpool.h"
63 #include "attribs.h"
64 #include "vr-values.h"
65 #include "builtins.h"
66 #include "range-op.h"
67 #include "value-range-equiv.h"
68 #include "gimple-array-bounds.h"
69
70 /* Set of SSA names found live during the RPO traversal of the function
71 for still active basic-blocks. */
72 class live_names
73 {
74 public:
75 live_names ();
76 ~live_names ();
77 void set (tree, basic_block);
78 void clear (tree, basic_block);
79 void merge (basic_block dest, basic_block src);
80 bool live_on_block_p (tree, basic_block);
81 bool live_on_edge_p (tree, edge);
82 bool block_has_live_names_p (basic_block);
83 void clear_block (basic_block);
84
85 private:
86 sbitmap *live;
87 unsigned num_blocks;
88 void init_bitmap_if_needed (basic_block);
89 };
90
91 void
92 live_names::init_bitmap_if_needed (basic_block bb)
93 {
94 unsigned i = bb->index;
95 if (!live[i])
96 {
97 live[i] = sbitmap_alloc (num_ssa_names);
98 bitmap_clear (live[i]);
99 }
100 }
101
102 bool
103 live_names::block_has_live_names_p (basic_block bb)
104 {
105 unsigned i = bb->index;
106 return live[i] && bitmap_empty_p (live[i]);
107 }
108
109 void
110 live_names::clear_block (basic_block bb)
111 {
112 unsigned i = bb->index;
113 if (live[i])
114 {
115 sbitmap_free (live[i]);
116 live[i] = NULL;
117 }
118 }
119
120 void
121 live_names::merge (basic_block dest, basic_block src)
122 {
123 init_bitmap_if_needed (dest);
124 init_bitmap_if_needed (src);
125 bitmap_ior (live[dest->index], live[dest->index], live[src->index]);
126 }
127
128 void
129 live_names::set (tree name, basic_block bb)
130 {
131 init_bitmap_if_needed (bb);
132 bitmap_set_bit (live[bb->index], SSA_NAME_VERSION (name));
133 }
134
135 void
136 live_names::clear (tree name, basic_block bb)
137 {
138 unsigned i = bb->index;
139 if (live[i])
140 bitmap_clear_bit (live[i], SSA_NAME_VERSION (name));
141 }
142
143 live_names::live_names ()
144 {
145 num_blocks = last_basic_block_for_fn (cfun);
146 live = XCNEWVEC (sbitmap, num_blocks);
147 }
148
149 live_names::~live_names ()
150 {
151 for (unsigned i = 0; i < num_blocks; ++i)
152 if (live[i])
153 sbitmap_free (live[i]);
154 XDELETEVEC (live);
155 }
156
157 bool
158 live_names::live_on_block_p (tree name, basic_block bb)
159 {
160 return (live[bb->index]
161 && bitmap_bit_p (live[bb->index], SSA_NAME_VERSION (name)));
162 }
163
164
165 /* Location information for ASSERT_EXPRs. Each instance of this
166 structure describes an ASSERT_EXPR for an SSA name. Since a single
167 SSA name may have more than one assertion associated with it, these
168 locations are kept in a linked list attached to the corresponding
169 SSA name. */
170 struct assert_locus
171 {
172 /* Basic block where the assertion would be inserted. */
173 basic_block bb;
174
175 /* Some assertions need to be inserted on an edge (e.g., assertions
176 generated by COND_EXPRs). In those cases, BB will be NULL. */
177 edge e;
178
179 /* Pointer to the statement that generated this assertion. */
180 gimple_stmt_iterator si;
181
182 /* Predicate code for the ASSERT_EXPR. Must be COMPARISON_CLASS_P. */
183 enum tree_code comp_code;
184
185 /* Value being compared against. */
186 tree val;
187
188 /* Expression to compare. */
189 tree expr;
190
191 /* Next node in the linked list. */
192 assert_locus *next;
193 };
194
195 class vrp_insert
196 {
197 public:
198 vrp_insert (struct function *fn) : fun (fn) { }
199
200 /* Traverse the flowgraph looking for conditional jumps to insert range
201 expressions. These range expressions are meant to provide information
202 to optimizations that need to reason in terms of value ranges. They
203 will not be expanded into RTL. See method implementation comment
204 for example. */
205 void insert_range_assertions ();
206
207 /* Convert range assertion expressions into the implied copies and
208 copy propagate away the copies. */
209 void remove_range_assertions ();
210
211 /* Dump all the registered assertions for all the names to FILE. */
212 void dump (FILE *);
213
214 /* Dump all the registered assertions for NAME to FILE. */
215 void dump (FILE *file, tree name);
216
217 /* Dump all the registered assertions for NAME to stderr. */
218 void debug (tree name)
219 {
220 dump (stderr, name);
221 }
222
223 /* Dump all the registered assertions for all the names to stderr. */
224 void debug ()
225 {
226 dump (stderr);
227 }
228
229 private:
230 /* Set of SSA names found live during the RPO traversal of the function
231 for still active basic-blocks. */
232 live_names live;
233
234 /* Function to work on. */
235 struct function *fun;
236
237 /* If bit I is present, it means that SSA name N_i has a list of
238 assertions that should be inserted in the IL. */
239 bitmap need_assert_for;
240
241 /* Array of locations lists where to insert assertions. ASSERTS_FOR[I]
242 holds a list of ASSERT_LOCUS_T nodes that describe where
243 ASSERT_EXPRs for SSA name N_I should be inserted. */
244 assert_locus **asserts_for;
245
246 /* Finish found ASSERTS for E and register them at GSI. */
247 void finish_register_edge_assert_for (edge e, gimple_stmt_iterator gsi,
248 vec<assert_info> &asserts);
249
250 /* Determine whether the outgoing edges of BB should receive an
251 ASSERT_EXPR for each of the operands of BB's LAST statement. The
252 last statement of BB must be a SWITCH_EXPR.
253
254 If any of the sub-graphs rooted at BB have an interesting use of
255 the predicate operands, an assert location node is added to the
256 list of assertions for the corresponding operands. */
257 void find_switch_asserts (basic_block bb, gswitch *last);
258
259 /* Do an RPO walk over the function computing SSA name liveness
260 on-the-fly and deciding on assert expressions to insert. */
261 void find_assert_locations ();
262
263 /* Traverse all the statements in block BB looking for statements that
264 may generate useful assertions for the SSA names in their operand.
265 See method implementation comentary for more information. */
266 void find_assert_locations_in_bb (basic_block bb);
267
268 /* Determine whether the outgoing edges of BB should receive an
269 ASSERT_EXPR for each of the operands of BB's LAST statement.
270 The last statement of BB must be a COND_EXPR.
271
272 If any of the sub-graphs rooted at BB have an interesting use of
273 the predicate operands, an assert location node is added to the
274 list of assertions for the corresponding operands. */
275 void find_conditional_asserts (basic_block bb, gcond *last);
276
277 /* Process all the insertions registered for every name N_i registered
278 in NEED_ASSERT_FOR. The list of assertions to be inserted are
279 found in ASSERTS_FOR[i]. */
280 void process_assert_insertions ();
281
282 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
283 'EXPR COMP_CODE VAL' at a location that dominates block BB or
284 E->DEST, then register this location as a possible insertion point
285 for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
286
287 BB, E and SI provide the exact insertion point for the new
288 ASSERT_EXPR. If BB is NULL, then the ASSERT_EXPR is to be inserted
289 on edge E. Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
290 BB. If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
291 must not be NULL. */
292 void register_new_assert_for (tree name, tree expr,
293 enum tree_code comp_code,
294 tree val, basic_block bb,
295 edge e, gimple_stmt_iterator si);
296
297 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
298 create a new SSA name N and return the assertion assignment
299 'N = ASSERT_EXPR <V, V OP W>'. */
300 gimple *build_assert_expr_for (tree cond, tree v);
301
302 /* Create an ASSERT_EXPR for NAME and insert it in the location
303 indicated by LOC. Return true if we made any edge insertions. */
304 bool process_assert_insertions_for (tree name, assert_locus *loc);
305
306 /* Qsort callback for sorting assert locations. */
307 template <bool stable> static int compare_assert_loc (const void *,
308 const void *);
309 };
310
311 /* Return true if the SSA name NAME is live on the edge E. */
312
313 bool
314 live_names::live_on_edge_p (tree name, edge e)
315 {
316 return live_on_block_p (name, e->dest);
317 }
318
319
320 /* VR_TYPE describes a range with mininum value *MIN and maximum
321 value *MAX. Restrict the range to the set of values that have
322 no bits set outside NONZERO_BITS. Update *MIN and *MAX and
323 return the new range type.
324
325 SGN gives the sign of the values described by the range. */
326
327 enum value_range_kind
328 intersect_range_with_nonzero_bits (enum value_range_kind vr_type,
329 wide_int *min, wide_int *max,
330 const wide_int &nonzero_bits,
331 signop sgn)
332 {
333 if (vr_type == VR_ANTI_RANGE)
334 {
335 /* The VR_ANTI_RANGE is equivalent to the union of the ranges
336 A: [-INF, *MIN) and B: (*MAX, +INF]. First use NONZERO_BITS
337 to create an inclusive upper bound for A and an inclusive lower
338 bound for B. */
339 wide_int a_max = wi::round_down_for_mask (*min - 1, nonzero_bits);
340 wide_int b_min = wi::round_up_for_mask (*max + 1, nonzero_bits);
341
342 /* If the calculation of A_MAX wrapped, A is effectively empty
343 and A_MAX is the highest value that satisfies NONZERO_BITS.
344 Likewise if the calculation of B_MIN wrapped, B is effectively
345 empty and B_MIN is the lowest value that satisfies NONZERO_BITS. */
346 bool a_empty = wi::ge_p (a_max, *min, sgn);
347 bool b_empty = wi::le_p (b_min, *max, sgn);
348
349 /* If both A and B are empty, there are no valid values. */
350 if (a_empty && b_empty)
351 return VR_UNDEFINED;
352
353 /* If exactly one of A or B is empty, return a VR_RANGE for the
354 other one. */
355 if (a_empty || b_empty)
356 {
357 *min = b_min;
358 *max = a_max;
359 gcc_checking_assert (wi::le_p (*min, *max, sgn));
360 return VR_RANGE;
361 }
362
363 /* Update the VR_ANTI_RANGE bounds. */
364 *min = a_max + 1;
365 *max = b_min - 1;
366 gcc_checking_assert (wi::le_p (*min, *max, sgn));
367
368 /* Now check whether the excluded range includes any values that
369 satisfy NONZERO_BITS. If not, switch to a full VR_RANGE. */
370 if (wi::round_up_for_mask (*min, nonzero_bits) == b_min)
371 {
372 unsigned int precision = min->get_precision ();
373 *min = wi::min_value (precision, sgn);
374 *max = wi::max_value (precision, sgn);
375 vr_type = VR_RANGE;
376 }
377 }
378 if (vr_type == VR_RANGE)
379 {
380 *max = wi::round_down_for_mask (*max, nonzero_bits);
381
382 /* Check that the range contains at least one valid value. */
383 if (wi::gt_p (*min, *max, sgn))
384 return VR_UNDEFINED;
385
386 *min = wi::round_up_for_mask (*min, nonzero_bits);
387 gcc_checking_assert (wi::le_p (*min, *max, sgn));
388 }
389 return vr_type;
390 }
391
392 /* Return true if max and min of VR are INTEGER_CST. It's not necessary
393 a singleton. */
394
395 bool
396 range_int_cst_p (const value_range *vr)
397 {
398 return (vr->kind () == VR_RANGE && range_has_numeric_bounds_p (vr));
399 }
400
401 /* Return the single symbol (an SSA_NAME) contained in T if any, or NULL_TREE
402 otherwise. We only handle additive operations and set NEG to true if the
403 symbol is negated and INV to the invariant part, if any. */
404
405 tree
406 get_single_symbol (tree t, bool *neg, tree *inv)
407 {
408 bool neg_;
409 tree inv_;
410
411 *inv = NULL_TREE;
412 *neg = false;
413
414 if (TREE_CODE (t) == PLUS_EXPR
415 || TREE_CODE (t) == POINTER_PLUS_EXPR
416 || TREE_CODE (t) == MINUS_EXPR)
417 {
418 if (is_gimple_min_invariant (TREE_OPERAND (t, 0)))
419 {
420 neg_ = (TREE_CODE (t) == MINUS_EXPR);
421 inv_ = TREE_OPERAND (t, 0);
422 t = TREE_OPERAND (t, 1);
423 }
424 else if (is_gimple_min_invariant (TREE_OPERAND (t, 1)))
425 {
426 neg_ = false;
427 inv_ = TREE_OPERAND (t, 1);
428 t = TREE_OPERAND (t, 0);
429 }
430 else
431 return NULL_TREE;
432 }
433 else
434 {
435 neg_ = false;
436 inv_ = NULL_TREE;
437 }
438
439 if (TREE_CODE (t) == NEGATE_EXPR)
440 {
441 t = TREE_OPERAND (t, 0);
442 neg_ = !neg_;
443 }
444
445 if (TREE_CODE (t) != SSA_NAME)
446 return NULL_TREE;
447
448 if (inv_ && TREE_OVERFLOW_P (inv_))
449 inv_ = drop_tree_overflow (inv_);
450
451 *neg = neg_;
452 *inv = inv_;
453 return t;
454 }
455
456 /* The reverse operation: build a symbolic expression with TYPE
457 from symbol SYM, negated according to NEG, and invariant INV. */
458
459 static tree
460 build_symbolic_expr (tree type, tree sym, bool neg, tree inv)
461 {
462 const bool pointer_p = POINTER_TYPE_P (type);
463 tree t = sym;
464
465 if (neg)
466 t = build1 (NEGATE_EXPR, type, t);
467
468 if (integer_zerop (inv))
469 return t;
470
471 return build2 (pointer_p ? POINTER_PLUS_EXPR : PLUS_EXPR, type, t, inv);
472 }
473
474 /* Return
475 1 if VAL < VAL2
476 0 if !(VAL < VAL2)
477 -2 if those are incomparable. */
478 int
479 operand_less_p (tree val, tree val2)
480 {
481 /* LT is folded faster than GE and others. Inline the common case. */
482 if (TREE_CODE (val) == INTEGER_CST && TREE_CODE (val2) == INTEGER_CST)
483 return tree_int_cst_lt (val, val2);
484 else if (TREE_CODE (val) == SSA_NAME && TREE_CODE (val2) == SSA_NAME)
485 return val == val2 ? 0 : -2;
486 else
487 {
488 int cmp = compare_values (val, val2);
489 if (cmp == -1)
490 return 1;
491 else if (cmp == 0 || cmp == 1)
492 return 0;
493 else
494 return -2;
495 }
496
497 return 0;
498 }
499
500 /* Compare two values VAL1 and VAL2. Return
501
502 -2 if VAL1 and VAL2 cannot be compared at compile-time,
503 -1 if VAL1 < VAL2,
504 0 if VAL1 == VAL2,
505 +1 if VAL1 > VAL2, and
506 +2 if VAL1 != VAL2
507
508 This is similar to tree_int_cst_compare but supports pointer values
509 and values that cannot be compared at compile time.
510
511 If STRICT_OVERFLOW_P is not NULL, then set *STRICT_OVERFLOW_P to
512 true if the return value is only valid if we assume that signed
513 overflow is undefined. */
514
515 int
516 compare_values_warnv (tree val1, tree val2, bool *strict_overflow_p)
517 {
518 if (val1 == val2)
519 return 0;
520
521 /* Below we rely on the fact that VAL1 and VAL2 are both pointers or
522 both integers. */
523 gcc_assert (POINTER_TYPE_P (TREE_TYPE (val1))
524 == POINTER_TYPE_P (TREE_TYPE (val2)));
525
526 /* Convert the two values into the same type. This is needed because
527 sizetype causes sign extension even for unsigned types. */
528 if (!useless_type_conversion_p (TREE_TYPE (val1), TREE_TYPE (val2)))
529 val2 = fold_convert (TREE_TYPE (val1), val2);
530
531 const bool overflow_undefined
532 = INTEGRAL_TYPE_P (TREE_TYPE (val1))
533 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (val1));
534 tree inv1, inv2;
535 bool neg1, neg2;
536 tree sym1 = get_single_symbol (val1, &neg1, &inv1);
537 tree sym2 = get_single_symbol (val2, &neg2, &inv2);
538
539 /* If VAL1 and VAL2 are of the form '[-]NAME [+ CST]', return -1 or +1
540 accordingly. If VAL1 and VAL2 don't use the same name, return -2. */
541 if (sym1 && sym2)
542 {
543 /* Both values must use the same name with the same sign. */
544 if (sym1 != sym2 || neg1 != neg2)
545 return -2;
546
547 /* [-]NAME + CST == [-]NAME + CST. */
548 if (inv1 == inv2)
549 return 0;
550
551 /* If overflow is defined we cannot simplify more. */
552 if (!overflow_undefined)
553 return -2;
554
555 if (strict_overflow_p != NULL
556 /* Symbolic range building sets TREE_NO_WARNING to declare
557 that overflow doesn't happen. */
558 && (!inv1 || !TREE_NO_WARNING (val1))
559 && (!inv2 || !TREE_NO_WARNING (val2)))
560 *strict_overflow_p = true;
561
562 if (!inv1)
563 inv1 = build_int_cst (TREE_TYPE (val1), 0);
564 if (!inv2)
565 inv2 = build_int_cst (TREE_TYPE (val2), 0);
566
567 return wi::cmp (wi::to_wide (inv1), wi::to_wide (inv2),
568 TYPE_SIGN (TREE_TYPE (val1)));
569 }
570
571 const bool cst1 = is_gimple_min_invariant (val1);
572 const bool cst2 = is_gimple_min_invariant (val2);
573
574 /* If one is of the form '[-]NAME + CST' and the other is constant, then
575 it might be possible to say something depending on the constants. */
576 if ((sym1 && inv1 && cst2) || (sym2 && inv2 && cst1))
577 {
578 if (!overflow_undefined)
579 return -2;
580
581 if (strict_overflow_p != NULL
582 /* Symbolic range building sets TREE_NO_WARNING to declare
583 that overflow doesn't happen. */
584 && (!sym1 || !TREE_NO_WARNING (val1))
585 && (!sym2 || !TREE_NO_WARNING (val2)))
586 *strict_overflow_p = true;
587
588 const signop sgn = TYPE_SIGN (TREE_TYPE (val1));
589 tree cst = cst1 ? val1 : val2;
590 tree inv = cst1 ? inv2 : inv1;
591
592 /* Compute the difference between the constants. If it overflows or
593 underflows, this means that we can trivially compare the NAME with
594 it and, consequently, the two values with each other. */
595 wide_int diff = wi::to_wide (cst) - wi::to_wide (inv);
596 if (wi::cmp (0, wi::to_wide (inv), sgn)
597 != wi::cmp (diff, wi::to_wide (cst), sgn))
598 {
599 const int res = wi::cmp (wi::to_wide (cst), wi::to_wide (inv), sgn);
600 return cst1 ? res : -res;
601 }
602
603 return -2;
604 }
605
606 /* We cannot say anything more for non-constants. */
607 if (!cst1 || !cst2)
608 return -2;
609
610 if (!POINTER_TYPE_P (TREE_TYPE (val1)))
611 {
612 /* We cannot compare overflowed values. */
613 if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
614 return -2;
615
616 if (TREE_CODE (val1) == INTEGER_CST
617 && TREE_CODE (val2) == INTEGER_CST)
618 return tree_int_cst_compare (val1, val2);
619
620 if (poly_int_tree_p (val1) && poly_int_tree_p (val2))
621 {
622 if (known_eq (wi::to_poly_widest (val1),
623 wi::to_poly_widest (val2)))
624 return 0;
625 if (known_lt (wi::to_poly_widest (val1),
626 wi::to_poly_widest (val2)))
627 return -1;
628 if (known_gt (wi::to_poly_widest (val1),
629 wi::to_poly_widest (val2)))
630 return 1;
631 }
632
633 return -2;
634 }
635 else
636 {
637 if (TREE_CODE (val1) == INTEGER_CST && TREE_CODE (val2) == INTEGER_CST)
638 {
639 /* We cannot compare overflowed values. */
640 if (TREE_OVERFLOW (val1) || TREE_OVERFLOW (val2))
641 return -2;
642
643 return tree_int_cst_compare (val1, val2);
644 }
645
646 /* First see if VAL1 and VAL2 are not the same. */
647 if (operand_equal_p (val1, val2, 0))
648 return 0;
649
650 fold_defer_overflow_warnings ();
651
652 /* If VAL1 is a lower address than VAL2, return -1. */
653 tree t = fold_binary_to_constant (LT_EXPR, boolean_type_node, val1, val2);
654 if (t && integer_onep (t))
655 {
656 fold_undefer_and_ignore_overflow_warnings ();
657 return -1;
658 }
659
660 /* If VAL1 is a higher address than VAL2, return +1. */
661 t = fold_binary_to_constant (LT_EXPR, boolean_type_node, val2, val1);
662 if (t && integer_onep (t))
663 {
664 fold_undefer_and_ignore_overflow_warnings ();
665 return 1;
666 }
667
668 /* If VAL1 is different than VAL2, return +2. */
669 t = fold_binary_to_constant (NE_EXPR, boolean_type_node, val1, val2);
670 fold_undefer_and_ignore_overflow_warnings ();
671 if (t && integer_onep (t))
672 return 2;
673
674 return -2;
675 }
676 }
677
678 /* Compare values like compare_values_warnv. */
679
680 int
681 compare_values (tree val1, tree val2)
682 {
683 bool sop;
684 return compare_values_warnv (val1, val2, &sop);
685 }
686
687 /* If BOUND will include a symbolic bound, adjust it accordingly,
688 otherwise leave it as is.
689
690 CODE is the original operation that combined the bounds (PLUS_EXPR
691 or MINUS_EXPR).
692
693 TYPE is the type of the original operation.
694
695 SYM_OPn is the symbolic for OPn if it has a symbolic.
696
697 NEG_OPn is TRUE if the OPn was negated. */
698
699 static void
700 adjust_symbolic_bound (tree &bound, enum tree_code code, tree type,
701 tree sym_op0, tree sym_op1,
702 bool neg_op0, bool neg_op1)
703 {
704 bool minus_p = (code == MINUS_EXPR);
705 /* If the result bound is constant, we're done; otherwise, build the
706 symbolic lower bound. */
707 if (sym_op0 == sym_op1)
708 ;
709 else if (sym_op0)
710 bound = build_symbolic_expr (type, sym_op0,
711 neg_op0, bound);
712 else if (sym_op1)
713 {
714 /* We may not negate if that might introduce
715 undefined overflow. */
716 if (!minus_p
717 || neg_op1
718 || TYPE_OVERFLOW_WRAPS (type))
719 bound = build_symbolic_expr (type, sym_op1,
720 neg_op1 ^ minus_p, bound);
721 else
722 bound = NULL_TREE;
723 }
724 }
725
726 /* Combine OP1 and OP1, which are two parts of a bound, into one wide
727 int bound according to CODE. CODE is the operation combining the
728 bound (either a PLUS_EXPR or a MINUS_EXPR).
729
730 TYPE is the type of the combine operation.
731
732 WI is the wide int to store the result.
733
734 OVF is -1 if an underflow occurred, +1 if an overflow occurred or 0
735 if over/underflow occurred. */
736
737 static void
738 combine_bound (enum tree_code code, wide_int &wi, wi::overflow_type &ovf,
739 tree type, tree op0, tree op1)
740 {
741 bool minus_p = (code == MINUS_EXPR);
742 const signop sgn = TYPE_SIGN (type);
743 const unsigned int prec = TYPE_PRECISION (type);
744
745 /* Combine the bounds, if any. */
746 if (op0 && op1)
747 {
748 if (minus_p)
749 wi = wi::sub (wi::to_wide (op0), wi::to_wide (op1), sgn, &ovf);
750 else
751 wi = wi::add (wi::to_wide (op0), wi::to_wide (op1), sgn, &ovf);
752 }
753 else if (op0)
754 wi = wi::to_wide (op0);
755 else if (op1)
756 {
757 if (minus_p)
758 wi = wi::neg (wi::to_wide (op1), &ovf);
759 else
760 wi = wi::to_wide (op1);
761 }
762 else
763 wi = wi::shwi (0, prec);
764 }
765
766 /* Given a range in [WMIN, WMAX], adjust it for possible overflow and
767 put the result in VR.
768
769 TYPE is the type of the range.
770
771 MIN_OVF and MAX_OVF indicate what type of overflow, if any,
772 occurred while originally calculating WMIN or WMAX. -1 indicates
773 underflow. +1 indicates overflow. 0 indicates neither. */
774
775 static void
776 set_value_range_with_overflow (value_range_kind &kind, tree &min, tree &max,
777 tree type,
778 const wide_int &wmin, const wide_int &wmax,
779 wi::overflow_type min_ovf,
780 wi::overflow_type max_ovf)
781 {
782 const signop sgn = TYPE_SIGN (type);
783 const unsigned int prec = TYPE_PRECISION (type);
784
785 /* For one bit precision if max < min, then the swapped
786 range covers all values. */
787 if (prec == 1 && wi::lt_p (wmax, wmin, sgn))
788 {
789 kind = VR_VARYING;
790 return;
791 }
792
793 if (TYPE_OVERFLOW_WRAPS (type))
794 {
795 /* If overflow wraps, truncate the values and adjust the
796 range kind and bounds appropriately. */
797 wide_int tmin = wide_int::from (wmin, prec, sgn);
798 wide_int tmax = wide_int::from (wmax, prec, sgn);
799 if ((min_ovf != wi::OVF_NONE) == (max_ovf != wi::OVF_NONE))
800 {
801 /* If the limits are swapped, we wrapped around and cover
802 the entire range. */
803 if (wi::gt_p (tmin, tmax, sgn))
804 kind = VR_VARYING;
805 else
806 {
807 kind = VR_RANGE;
808 /* No overflow or both overflow or underflow. The
809 range kind stays VR_RANGE. */
810 min = wide_int_to_tree (type, tmin);
811 max = wide_int_to_tree (type, tmax);
812 }
813 return;
814 }
815 else if ((min_ovf == wi::OVF_UNDERFLOW && max_ovf == wi::OVF_NONE)
816 || (max_ovf == wi::OVF_OVERFLOW && min_ovf == wi::OVF_NONE))
817 {
818 /* Min underflow or max overflow. The range kind
819 changes to VR_ANTI_RANGE. */
820 bool covers = false;
821 wide_int tem = tmin;
822 tmin = tmax + 1;
823 if (wi::cmp (tmin, tmax, sgn) < 0)
824 covers = true;
825 tmax = tem - 1;
826 if (wi::cmp (tmax, tem, sgn) > 0)
827 covers = true;
828 /* If the anti-range would cover nothing, drop to varying.
829 Likewise if the anti-range bounds are outside of the
830 types values. */
831 if (covers || wi::cmp (tmin, tmax, sgn) > 0)
832 {
833 kind = VR_VARYING;
834 return;
835 }
836 kind = VR_ANTI_RANGE;
837 min = wide_int_to_tree (type, tmin);
838 max = wide_int_to_tree (type, tmax);
839 return;
840 }
841 else
842 {
843 /* Other underflow and/or overflow, drop to VR_VARYING. */
844 kind = VR_VARYING;
845 return;
846 }
847 }
848 else
849 {
850 /* If overflow does not wrap, saturate to the types min/max
851 value. */
852 wide_int type_min = wi::min_value (prec, sgn);
853 wide_int type_max = wi::max_value (prec, sgn);
854 kind = VR_RANGE;
855 if (min_ovf == wi::OVF_UNDERFLOW)
856 min = wide_int_to_tree (type, type_min);
857 else if (min_ovf == wi::OVF_OVERFLOW)
858 min = wide_int_to_tree (type, type_max);
859 else
860 min = wide_int_to_tree (type, wmin);
861
862 if (max_ovf == wi::OVF_UNDERFLOW)
863 max = wide_int_to_tree (type, type_min);
864 else if (max_ovf == wi::OVF_OVERFLOW)
865 max = wide_int_to_tree (type, type_max);
866 else
867 max = wide_int_to_tree (type, wmax);
868 }
869 }
870
871 /* Fold two value range's of a POINTER_PLUS_EXPR into VR. */
872
873 static void
874 extract_range_from_pointer_plus_expr (value_range *vr,
875 enum tree_code code,
876 tree expr_type,
877 const value_range *vr0,
878 const value_range *vr1)
879 {
880 gcc_checking_assert (POINTER_TYPE_P (expr_type)
881 && code == POINTER_PLUS_EXPR);
882 /* For pointer types, we are really only interested in asserting
883 whether the expression evaluates to non-NULL.
884 With -fno-delete-null-pointer-checks we need to be more
885 conservative. As some object might reside at address 0,
886 then some offset could be added to it and the same offset
887 subtracted again and the result would be NULL.
888 E.g.
889 static int a[12]; where &a[0] is NULL and
890 ptr = &a[6];
891 ptr -= 6;
892 ptr will be NULL here, even when there is POINTER_PLUS_EXPR
893 where the first range doesn't include zero and the second one
894 doesn't either. As the second operand is sizetype (unsigned),
895 consider all ranges where the MSB could be set as possible
896 subtractions where the result might be NULL. */
897 if ((!range_includes_zero_p (vr0)
898 || !range_includes_zero_p (vr1))
899 && !TYPE_OVERFLOW_WRAPS (expr_type)
900 && (flag_delete_null_pointer_checks
901 || (range_int_cst_p (vr1)
902 && !tree_int_cst_sign_bit (vr1->max ()))))
903 vr->set_nonzero (expr_type);
904 else if (vr0->zero_p () && vr1->zero_p ())
905 vr->set_zero (expr_type);
906 else
907 vr->set_varying (expr_type);
908 }
909
910 /* Extract range information from a PLUS/MINUS_EXPR and store the
911 result in *VR. */
912
913 static void
914 extract_range_from_plus_minus_expr (value_range *vr,
915 enum tree_code code,
916 tree expr_type,
917 const value_range *vr0_,
918 const value_range *vr1_)
919 {
920 gcc_checking_assert (code == PLUS_EXPR || code == MINUS_EXPR);
921
922 value_range vr0 = *vr0_, vr1 = *vr1_;
923 value_range vrtem0, vrtem1;
924
925 /* Now canonicalize anti-ranges to ranges when they are not symbolic
926 and express ~[] op X as ([]' op X) U ([]'' op X). */
927 if (vr0.kind () == VR_ANTI_RANGE
928 && ranges_from_anti_range (&vr0, &vrtem0, &vrtem1))
929 {
930 extract_range_from_plus_minus_expr (vr, code, expr_type, &vrtem0, vr1_);
931 if (!vrtem1.undefined_p ())
932 {
933 value_range vrres;
934 extract_range_from_plus_minus_expr (&vrres, code, expr_type,
935 &vrtem1, vr1_);
936 vr->union_ (&vrres);
937 }
938 return;
939 }
940 /* Likewise for X op ~[]. */
941 if (vr1.kind () == VR_ANTI_RANGE
942 && ranges_from_anti_range (&vr1, &vrtem0, &vrtem1))
943 {
944 extract_range_from_plus_minus_expr (vr, code, expr_type, vr0_, &vrtem0);
945 if (!vrtem1.undefined_p ())
946 {
947 value_range vrres;
948 extract_range_from_plus_minus_expr (&vrres, code, expr_type,
949 vr0_, &vrtem1);
950 vr->union_ (&vrres);
951 }
952 return;
953 }
954
955 value_range_kind kind;
956 value_range_kind vr0_kind = vr0.kind (), vr1_kind = vr1.kind ();
957 tree vr0_min = vr0.min (), vr0_max = vr0.max ();
958 tree vr1_min = vr1.min (), vr1_max = vr1.max ();
959 tree min = NULL_TREE, max = NULL_TREE;
960
961 /* This will normalize things such that calculating
962 [0,0] - VR_VARYING is not dropped to varying, but is
963 calculated as [MIN+1, MAX]. */
964 if (vr0.varying_p ())
965 {
966 vr0_kind = VR_RANGE;
967 vr0_min = vrp_val_min (expr_type);
968 vr0_max = vrp_val_max (expr_type);
969 }
970 if (vr1.varying_p ())
971 {
972 vr1_kind = VR_RANGE;
973 vr1_min = vrp_val_min (expr_type);
974 vr1_max = vrp_val_max (expr_type);
975 }
976
977 const bool minus_p = (code == MINUS_EXPR);
978 tree min_op0 = vr0_min;
979 tree min_op1 = minus_p ? vr1_max : vr1_min;
980 tree max_op0 = vr0_max;
981 tree max_op1 = minus_p ? vr1_min : vr1_max;
982 tree sym_min_op0 = NULL_TREE;
983 tree sym_min_op1 = NULL_TREE;
984 tree sym_max_op0 = NULL_TREE;
985 tree sym_max_op1 = NULL_TREE;
986 bool neg_min_op0, neg_min_op1, neg_max_op0, neg_max_op1;
987
988 neg_min_op0 = neg_min_op1 = neg_max_op0 = neg_max_op1 = false;
989
990 /* If we have a PLUS or MINUS with two VR_RANGEs, either constant or
991 single-symbolic ranges, try to compute the precise resulting range,
992 but only if we know that this resulting range will also be constant
993 or single-symbolic. */
994 if (vr0_kind == VR_RANGE && vr1_kind == VR_RANGE
995 && (TREE_CODE (min_op0) == INTEGER_CST
996 || (sym_min_op0
997 = get_single_symbol (min_op0, &neg_min_op0, &min_op0)))
998 && (TREE_CODE (min_op1) == INTEGER_CST
999 || (sym_min_op1
1000 = get_single_symbol (min_op1, &neg_min_op1, &min_op1)))
1001 && (!(sym_min_op0 && sym_min_op1)
1002 || (sym_min_op0 == sym_min_op1
1003 && neg_min_op0 == (minus_p ? neg_min_op1 : !neg_min_op1)))
1004 && (TREE_CODE (max_op0) == INTEGER_CST
1005 || (sym_max_op0
1006 = get_single_symbol (max_op0, &neg_max_op0, &max_op0)))
1007 && (TREE_CODE (max_op1) == INTEGER_CST
1008 || (sym_max_op1
1009 = get_single_symbol (max_op1, &neg_max_op1, &max_op1)))
1010 && (!(sym_max_op0 && sym_max_op1)
1011 || (sym_max_op0 == sym_max_op1
1012 && neg_max_op0 == (minus_p ? neg_max_op1 : !neg_max_op1))))
1013 {
1014 wide_int wmin, wmax;
1015 wi::overflow_type min_ovf = wi::OVF_NONE;
1016 wi::overflow_type max_ovf = wi::OVF_NONE;
1017
1018 /* Build the bounds. */
1019 combine_bound (code, wmin, min_ovf, expr_type, min_op0, min_op1);
1020 combine_bound (code, wmax, max_ovf, expr_type, max_op0, max_op1);
1021
1022 /* If the resulting range will be symbolic, we need to eliminate any
1023 explicit or implicit overflow introduced in the above computation
1024 because compare_values could make an incorrect use of it. That's
1025 why we require one of the ranges to be a singleton. */
1026 if ((sym_min_op0 != sym_min_op1 || sym_max_op0 != sym_max_op1)
1027 && ((bool)min_ovf || (bool)max_ovf
1028 || (min_op0 != max_op0 && min_op1 != max_op1)))
1029 {
1030 vr->set_varying (expr_type);
1031 return;
1032 }
1033
1034 /* Adjust the range for possible overflow. */
1035 set_value_range_with_overflow (kind, min, max, expr_type,
1036 wmin, wmax, min_ovf, max_ovf);
1037 if (kind == VR_VARYING)
1038 {
1039 vr->set_varying (expr_type);
1040 return;
1041 }
1042
1043 /* Build the symbolic bounds if needed. */
1044 adjust_symbolic_bound (min, code, expr_type,
1045 sym_min_op0, sym_min_op1,
1046 neg_min_op0, neg_min_op1);
1047 adjust_symbolic_bound (max, code, expr_type,
1048 sym_max_op0, sym_max_op1,
1049 neg_max_op0, neg_max_op1);
1050 }
1051 else
1052 {
1053 /* For other cases, for example if we have a PLUS_EXPR with two
1054 VR_ANTI_RANGEs, drop to VR_VARYING. It would take more effort
1055 to compute a precise range for such a case.
1056 ??? General even mixed range kind operations can be expressed
1057 by for example transforming ~[3, 5] + [1, 2] to range-only
1058 operations and a union primitive:
1059 [-INF, 2] + [1, 2] U [5, +INF] + [1, 2]
1060 [-INF+1, 4] U [6, +INF(OVF)]
1061 though usually the union is not exactly representable with
1062 a single range or anti-range as the above is
1063 [-INF+1, +INF(OVF)] intersected with ~[5, 5]
1064 but one could use a scheme similar to equivalences for this. */
1065 vr->set_varying (expr_type);
1066 return;
1067 }
1068
1069 /* If either MIN or MAX overflowed, then set the resulting range to
1070 VARYING. */
1071 if (min == NULL_TREE
1072 || TREE_OVERFLOW_P (min)
1073 || max == NULL_TREE
1074 || TREE_OVERFLOW_P (max))
1075 {
1076 vr->set_varying (expr_type);
1077 return;
1078 }
1079
1080 int cmp = compare_values (min, max);
1081 if (cmp == -2 || cmp == 1)
1082 {
1083 /* If the new range has its limits swapped around (MIN > MAX),
1084 then the operation caused one of them to wrap around, mark
1085 the new range VARYING. */
1086 vr->set_varying (expr_type);
1087 }
1088 else
1089 vr->set (min, max, kind);
1090 }
1091
1092 /* Return the range-ops handler for CODE and EXPR_TYPE. If no
1093 suitable operator is found, return NULL and set VR to VARYING. */
1094
1095 static const range_operator *
1096 get_range_op_handler (value_range *vr,
1097 enum tree_code code,
1098 tree expr_type)
1099 {
1100 const range_operator *op = range_op_handler (code, expr_type);
1101 if (!op)
1102 vr->set_varying (expr_type);
1103 return op;
1104 }
1105
1106 /* If the types passed are supported, return TRUE, otherwise set VR to
1107 VARYING and return FALSE. */
1108
1109 static bool
1110 supported_types_p (value_range *vr,
1111 tree type0,
1112 tree type1 = NULL)
1113 {
1114 if (!value_range::supports_type_p (type0)
1115 || (type1 && !value_range::supports_type_p (type1)))
1116 {
1117 vr->set_varying (type0);
1118 return false;
1119 }
1120 return true;
1121 }
1122
1123 /* If any of the ranges passed are defined, return TRUE, otherwise set
1124 VR to UNDEFINED and return FALSE. */
1125
1126 static bool
1127 defined_ranges_p (value_range *vr,
1128 const value_range *vr0, const value_range *vr1 = NULL)
1129 {
1130 if (vr0->undefined_p () && (!vr1 || vr1->undefined_p ()))
1131 {
1132 vr->set_undefined ();
1133 return false;
1134 }
1135 return true;
1136 }
1137
1138 static value_range
1139 drop_undefines_to_varying (const value_range *vr, tree expr_type)
1140 {
1141 if (vr->undefined_p ())
1142 return value_range (expr_type);
1143 else
1144 return *vr;
1145 }
1146
1147 /* If any operand is symbolic, perform a binary operation on them and
1148 return TRUE, otherwise return FALSE. */
1149
1150 static bool
1151 range_fold_binary_symbolics_p (value_range *vr,
1152 tree_code code,
1153 tree expr_type,
1154 const value_range *vr0, const value_range *vr1)
1155 {
1156 if (vr0->symbolic_p () || vr1->symbolic_p ())
1157 {
1158 if ((code == PLUS_EXPR || code == MINUS_EXPR))
1159 {
1160 extract_range_from_plus_minus_expr (vr, code, expr_type, vr0, vr1);
1161 return true;
1162 }
1163 if (POINTER_TYPE_P (expr_type) && code == POINTER_PLUS_EXPR)
1164 {
1165 extract_range_from_pointer_plus_expr (vr, code, expr_type, vr0, vr1);
1166 return true;
1167 }
1168 const range_operator *op = get_range_op_handler (vr, code, expr_type);
1169 value_range vr0_cst (*vr0), vr1_cst (*vr1);
1170 vr0_cst.normalize_symbolics ();
1171 vr1_cst.normalize_symbolics ();
1172 return op->fold_range (*vr, expr_type, vr0_cst, vr1_cst);
1173 }
1174 return false;
1175 }
1176
1177 /* If operand is symbolic, perform a unary operation on it and return
1178 TRUE, otherwise return FALSE. */
1179
1180 static bool
1181 range_fold_unary_symbolics_p (value_range *vr,
1182 tree_code code,
1183 tree expr_type,
1184 const value_range *vr0)
1185 {
1186 if (vr0->symbolic_p ())
1187 {
1188 if (code == NEGATE_EXPR)
1189 {
1190 /* -X is simply 0 - X. */
1191 value_range zero;
1192 zero.set_zero (vr0->type ());
1193 range_fold_binary_expr (vr, MINUS_EXPR, expr_type, &zero, vr0);
1194 return true;
1195 }
1196 if (code == BIT_NOT_EXPR)
1197 {
1198 /* ~X is simply -1 - X. */
1199 value_range minusone;
1200 minusone.set (build_int_cst (vr0->type (), -1));
1201 range_fold_binary_expr (vr, MINUS_EXPR, expr_type, &minusone, vr0);
1202 return true;
1203 }
1204 const range_operator *op = get_range_op_handler (vr, code, expr_type);
1205 value_range vr0_cst (*vr0);
1206 vr0_cst.normalize_symbolics ();
1207 return op->fold_range (*vr, expr_type, vr0_cst, value_range (expr_type));
1208 }
1209 return false;
1210 }
1211
1212 /* Perform a binary operation on a pair of ranges. */
1213
1214 void
1215 range_fold_binary_expr (value_range *vr,
1216 enum tree_code code,
1217 tree expr_type,
1218 const value_range *vr0_,
1219 const value_range *vr1_)
1220 {
1221 if (!supported_types_p (vr, expr_type)
1222 || !defined_ranges_p (vr, vr0_, vr1_))
1223 return;
1224 const range_operator *op = get_range_op_handler (vr, code, expr_type);
1225 if (!op)
1226 return;
1227
1228 value_range vr0 = drop_undefines_to_varying (vr0_, expr_type);
1229 value_range vr1 = drop_undefines_to_varying (vr1_, expr_type);
1230 if (range_fold_binary_symbolics_p (vr, code, expr_type, &vr0, &vr1))
1231 return;
1232
1233 vr0.normalize_addresses ();
1234 vr1.normalize_addresses ();
1235 op->fold_range (*vr, expr_type, vr0, vr1);
1236 }
1237
1238 /* Perform a unary operation on a range. */
1239
1240 void
1241 range_fold_unary_expr (value_range *vr,
1242 enum tree_code code, tree expr_type,
1243 const value_range *vr0,
1244 tree vr0_type)
1245 {
1246 if (!supported_types_p (vr, expr_type, vr0_type)
1247 || !defined_ranges_p (vr, vr0))
1248 return;
1249 const range_operator *op = get_range_op_handler (vr, code, expr_type);
1250 if (!op)
1251 return;
1252
1253 if (range_fold_unary_symbolics_p (vr, code, expr_type, vr0))
1254 return;
1255
1256 value_range vr0_cst (*vr0);
1257 vr0_cst.normalize_addresses ();
1258 op->fold_range (*vr, expr_type, vr0_cst, value_range (expr_type));
1259 }
1260
1261 /* Given a COND_EXPR COND of the form 'V OP W', and an SSA name V,
1262 create a new SSA name N and return the assertion assignment
1263 'N = ASSERT_EXPR <V, V OP W>'. */
1264
1265 gimple *
1266 vrp_insert::build_assert_expr_for (tree cond, tree v)
1267 {
1268 tree a;
1269 gassign *assertion;
1270
1271 gcc_assert (TREE_CODE (v) == SSA_NAME
1272 && COMPARISON_CLASS_P (cond));
1273
1274 a = build2 (ASSERT_EXPR, TREE_TYPE (v), v, cond);
1275 assertion = gimple_build_assign (NULL_TREE, a);
1276
1277 /* The new ASSERT_EXPR, creates a new SSA name that replaces the
1278 operand of the ASSERT_EXPR. Create it so the new name and the old one
1279 are registered in the replacement table so that we can fix the SSA web
1280 after adding all the ASSERT_EXPRs. */
1281 tree new_def = create_new_def_for (v, assertion, NULL);
1282 /* Make sure we preserve abnormalness throughout an ASSERT_EXPR chain
1283 given we have to be able to fully propagate those out to re-create
1284 valid SSA when removing the asserts. */
1285 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (v))
1286 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_def) = 1;
1287
1288 return assertion;
1289 }
1290
1291
1292 /* Return false if EXPR is a predicate expression involving floating
1293 point values. */
1294
1295 static inline bool
1296 fp_predicate (gimple *stmt)
1297 {
1298 GIMPLE_CHECK (stmt, GIMPLE_COND);
1299
1300 return FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (stmt)));
1301 }
1302
1303 /* If the range of values taken by OP can be inferred after STMT executes,
1304 return the comparison code (COMP_CODE_P) and value (VAL_P) that
1305 describes the inferred range. Return true if a range could be
1306 inferred. */
1307
1308 bool
1309 infer_value_range (gimple *stmt, tree op, tree_code *comp_code_p, tree *val_p)
1310 {
1311 *val_p = NULL_TREE;
1312 *comp_code_p = ERROR_MARK;
1313
1314 /* Do not attempt to infer anything in names that flow through
1315 abnormal edges. */
1316 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
1317 return false;
1318
1319 /* If STMT is the last statement of a basic block with no normal
1320 successors, there is no point inferring anything about any of its
1321 operands. We would not be able to find a proper insertion point
1322 for the assertion, anyway. */
1323 if (stmt_ends_bb_p (stmt))
1324 {
1325 edge_iterator ei;
1326 edge e;
1327
1328 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
1329 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
1330 break;
1331 if (e == NULL)
1332 return false;
1333 }
1334
1335 if (infer_nonnull_range (stmt, op))
1336 {
1337 *val_p = build_int_cst (TREE_TYPE (op), 0);
1338 *comp_code_p = NE_EXPR;
1339 return true;
1340 }
1341
1342 return false;
1343 }
1344
1345 /* Dump all the registered assertions for NAME to FILE. */
1346
1347 void
1348 vrp_insert::dump (FILE *file, tree name)
1349 {
1350 assert_locus *loc;
1351
1352 fprintf (file, "Assertions to be inserted for ");
1353 print_generic_expr (file, name);
1354 fprintf (file, "\n");
1355
1356 loc = asserts_for[SSA_NAME_VERSION (name)];
1357 while (loc)
1358 {
1359 fprintf (file, "\t");
1360 print_gimple_stmt (file, gsi_stmt (loc->si), 0);
1361 fprintf (file, "\n\tBB #%d", loc->bb->index);
1362 if (loc->e)
1363 {
1364 fprintf (file, "\n\tEDGE %d->%d", loc->e->src->index,
1365 loc->e->dest->index);
1366 dump_edge_info (file, loc->e, dump_flags, 0);
1367 }
1368 fprintf (file, "\n\tPREDICATE: ");
1369 print_generic_expr (file, loc->expr);
1370 fprintf (file, " %s ", get_tree_code_name (loc->comp_code));
1371 print_generic_expr (file, loc->val);
1372 fprintf (file, "\n\n");
1373 loc = loc->next;
1374 }
1375
1376 fprintf (file, "\n");
1377 }
1378
1379 /* Dump all the registered assertions for all the names to FILE. */
1380
1381 void
1382 vrp_insert::dump (FILE *file)
1383 {
1384 unsigned i;
1385 bitmap_iterator bi;
1386
1387 fprintf (file, "\nASSERT_EXPRs to be inserted\n\n");
1388 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
1389 dump (file, ssa_name (i));
1390 fprintf (file, "\n");
1391 }
1392
1393 /* Dump assert_info structure. */
1394
1395 void
1396 dump_assert_info (FILE *file, const assert_info &assert)
1397 {
1398 fprintf (file, "Assert for: ");
1399 print_generic_expr (file, assert.name);
1400 fprintf (file, "\n\tPREDICATE: expr=[");
1401 print_generic_expr (file, assert.expr);
1402 fprintf (file, "] %s ", get_tree_code_name (assert.comp_code));
1403 fprintf (file, "val=[");
1404 print_generic_expr (file, assert.val);
1405 fprintf (file, "]\n\n");
1406 }
1407
1408 DEBUG_FUNCTION void
1409 debug (const assert_info &assert)
1410 {
1411 dump_assert_info (stderr, assert);
1412 }
1413
1414 /* Dump a vector of assert_info's. */
1415
1416 void
1417 dump_asserts_info (FILE *file, const vec<assert_info> &asserts)
1418 {
1419 for (unsigned i = 0; i < asserts.length (); ++i)
1420 {
1421 dump_assert_info (file, asserts[i]);
1422 fprintf (file, "\n");
1423 }
1424 }
1425
1426 DEBUG_FUNCTION void
1427 debug (const vec<assert_info> &asserts)
1428 {
1429 dump_asserts_info (stderr, asserts);
1430 }
1431
1432 /* Push the assert info for NAME, EXPR, COMP_CODE and VAL to ASSERTS. */
1433
1434 static void
1435 add_assert_info (vec<assert_info> &asserts,
1436 tree name, tree expr, enum tree_code comp_code, tree val)
1437 {
1438 assert_info info;
1439 info.comp_code = comp_code;
1440 info.name = name;
1441 if (TREE_OVERFLOW_P (val))
1442 val = drop_tree_overflow (val);
1443 info.val = val;
1444 info.expr = expr;
1445 asserts.safe_push (info);
1446 if (dump_enabled_p ())
1447 dump_printf (MSG_NOTE | MSG_PRIORITY_INTERNALS,
1448 "Adding assert for %T from %T %s %T\n",
1449 name, expr, op_symbol_code (comp_code), val);
1450 }
1451
1452 /* If NAME doesn't have an ASSERT_EXPR registered for asserting
1453 'EXPR COMP_CODE VAL' at a location that dominates block BB or
1454 E->DEST, then register this location as a possible insertion point
1455 for ASSERT_EXPR <NAME, EXPR COMP_CODE VAL>.
1456
1457 BB, E and SI provide the exact insertion point for the new
1458 ASSERT_EXPR. If BB is NULL, then the ASSERT_EXPR is to be inserted
1459 on edge E. Otherwise, if E is NULL, the ASSERT_EXPR is inserted on
1460 BB. If SI points to a COND_EXPR or a SWITCH_EXPR statement, then E
1461 must not be NULL. */
1462
1463 void
1464 vrp_insert::register_new_assert_for (tree name, tree expr,
1465 enum tree_code comp_code,
1466 tree val,
1467 basic_block bb,
1468 edge e,
1469 gimple_stmt_iterator si)
1470 {
1471 assert_locus *n, *loc, *last_loc;
1472 basic_block dest_bb;
1473
1474 gcc_checking_assert (bb == NULL || e == NULL);
1475
1476 if (e == NULL)
1477 gcc_checking_assert (gimple_code (gsi_stmt (si)) != GIMPLE_COND
1478 && gimple_code (gsi_stmt (si)) != GIMPLE_SWITCH);
1479
1480 /* Never build an assert comparing against an integer constant with
1481 TREE_OVERFLOW set. This confuses our undefined overflow warning
1482 machinery. */
1483 if (TREE_OVERFLOW_P (val))
1484 val = drop_tree_overflow (val);
1485
1486 /* The new assertion A will be inserted at BB or E. We need to
1487 determine if the new location is dominated by a previously
1488 registered location for A. If we are doing an edge insertion,
1489 assume that A will be inserted at E->DEST. Note that this is not
1490 necessarily true.
1491
1492 If E is a critical edge, it will be split. But even if E is
1493 split, the new block will dominate the same set of blocks that
1494 E->DEST dominates.
1495
1496 The reverse, however, is not true, blocks dominated by E->DEST
1497 will not be dominated by the new block created to split E. So,
1498 if the insertion location is on a critical edge, we will not use
1499 the new location to move another assertion previously registered
1500 at a block dominated by E->DEST. */
1501 dest_bb = (bb) ? bb : e->dest;
1502
1503 /* If NAME already has an ASSERT_EXPR registered for COMP_CODE and
1504 VAL at a block dominating DEST_BB, then we don't need to insert a new
1505 one. Similarly, if the same assertion already exists at a block
1506 dominated by DEST_BB and the new location is not on a critical
1507 edge, then update the existing location for the assertion (i.e.,
1508 move the assertion up in the dominance tree).
1509
1510 Note, this is implemented as a simple linked list because there
1511 should not be more than a handful of assertions registered per
1512 name. If this becomes a performance problem, a table hashed by
1513 COMP_CODE and VAL could be implemented. */
1514 loc = asserts_for[SSA_NAME_VERSION (name)];
1515 last_loc = loc;
1516 while (loc)
1517 {
1518 if (loc->comp_code == comp_code
1519 && (loc->val == val
1520 || operand_equal_p (loc->val, val, 0))
1521 && (loc->expr == expr
1522 || operand_equal_p (loc->expr, expr, 0)))
1523 {
1524 /* If E is not a critical edge and DEST_BB
1525 dominates the existing location for the assertion, move
1526 the assertion up in the dominance tree by updating its
1527 location information. */
1528 if ((e == NULL || !EDGE_CRITICAL_P (e))
1529 && dominated_by_p (CDI_DOMINATORS, loc->bb, dest_bb))
1530 {
1531 loc->bb = dest_bb;
1532 loc->e = e;
1533 loc->si = si;
1534 return;
1535 }
1536 }
1537
1538 /* Update the last node of the list and move to the next one. */
1539 last_loc = loc;
1540 loc = loc->next;
1541 }
1542
1543 /* If we didn't find an assertion already registered for
1544 NAME COMP_CODE VAL, add a new one at the end of the list of
1545 assertions associated with NAME. */
1546 n = XNEW (struct assert_locus);
1547 n->bb = dest_bb;
1548 n->e = e;
1549 n->si = si;
1550 n->comp_code = comp_code;
1551 n->val = val;
1552 n->expr = expr;
1553 n->next = NULL;
1554
1555 if (last_loc)
1556 last_loc->next = n;
1557 else
1558 asserts_for[SSA_NAME_VERSION (name)] = n;
1559
1560 bitmap_set_bit (need_assert_for, SSA_NAME_VERSION (name));
1561 }
1562
1563 /* (COND_OP0 COND_CODE COND_OP1) is a predicate which uses NAME.
1564 Extract a suitable test code and value and store them into *CODE_P and
1565 *VAL_P so the predicate is normalized to NAME *CODE_P *VAL_P.
1566
1567 If no extraction was possible, return FALSE, otherwise return TRUE.
1568
1569 If INVERT is true, then we invert the result stored into *CODE_P. */
1570
1571 static bool
1572 extract_code_and_val_from_cond_with_ops (tree name, enum tree_code cond_code,
1573 tree cond_op0, tree cond_op1,
1574 bool invert, enum tree_code *code_p,
1575 tree *val_p)
1576 {
1577 enum tree_code comp_code;
1578 tree val;
1579
1580 /* Otherwise, we have a comparison of the form NAME COMP VAL
1581 or VAL COMP NAME. */
1582 if (name == cond_op1)
1583 {
1584 /* If the predicate is of the form VAL COMP NAME, flip
1585 COMP around because we need to register NAME as the
1586 first operand in the predicate. */
1587 comp_code = swap_tree_comparison (cond_code);
1588 val = cond_op0;
1589 }
1590 else if (name == cond_op0)
1591 {
1592 /* The comparison is of the form NAME COMP VAL, so the
1593 comparison code remains unchanged. */
1594 comp_code = cond_code;
1595 val = cond_op1;
1596 }
1597 else
1598 gcc_unreachable ();
1599
1600 /* Invert the comparison code as necessary. */
1601 if (invert)
1602 comp_code = invert_tree_comparison (comp_code, 0);
1603
1604 /* VRP only handles integral and pointer types. */
1605 if (! INTEGRAL_TYPE_P (TREE_TYPE (val))
1606 && ! POINTER_TYPE_P (TREE_TYPE (val)))
1607 return false;
1608
1609 /* Do not register always-false predicates.
1610 FIXME: this works around a limitation in fold() when dealing with
1611 enumerations. Given 'enum { N1, N2 } x;', fold will not
1612 fold 'if (x > N2)' to 'if (0)'. */
1613 if ((comp_code == GT_EXPR || comp_code == LT_EXPR)
1614 && INTEGRAL_TYPE_P (TREE_TYPE (val)))
1615 {
1616 tree min = TYPE_MIN_VALUE (TREE_TYPE (val));
1617 tree max = TYPE_MAX_VALUE (TREE_TYPE (val));
1618
1619 if (comp_code == GT_EXPR
1620 && (!max
1621 || compare_values (val, max) == 0))
1622 return false;
1623
1624 if (comp_code == LT_EXPR
1625 && (!min
1626 || compare_values (val, min) == 0))
1627 return false;
1628 }
1629 *code_p = comp_code;
1630 *val_p = val;
1631 return true;
1632 }
1633
1634 /* Find out smallest RES where RES > VAL && (RES & MASK) == RES, if any
1635 (otherwise return VAL). VAL and MASK must be zero-extended for
1636 precision PREC. If SGNBIT is non-zero, first xor VAL with SGNBIT
1637 (to transform signed values into unsigned) and at the end xor
1638 SGNBIT back. */
1639
1640 static wide_int
1641 masked_increment (const wide_int &val_in, const wide_int &mask,
1642 const wide_int &sgnbit, unsigned int prec)
1643 {
1644 wide_int bit = wi::one (prec), res;
1645 unsigned int i;
1646
1647 wide_int val = val_in ^ sgnbit;
1648 for (i = 0; i < prec; i++, bit += bit)
1649 {
1650 res = mask;
1651 if ((res & bit) == 0)
1652 continue;
1653 res = bit - 1;
1654 res = wi::bit_and_not (val + bit, res);
1655 res &= mask;
1656 if (wi::gtu_p (res, val))
1657 return res ^ sgnbit;
1658 }
1659 return val ^ sgnbit;
1660 }
1661
1662 /* Helper for overflow_comparison_p
1663
1664 OP0 CODE OP1 is a comparison. Examine the comparison and potentially
1665 OP1's defining statement to see if it ultimately has the form
1666 OP0 CODE (OP0 PLUS INTEGER_CST)
1667
1668 If so, return TRUE indicating this is an overflow test and store into
1669 *NEW_CST an updated constant that can be used in a narrowed range test.
1670
1671 REVERSED indicates if the comparison was originally:
1672
1673 OP1 CODE' OP0.
1674
1675 This affects how we build the updated constant. */
1676
1677 static bool
1678 overflow_comparison_p_1 (enum tree_code code, tree op0, tree op1,
1679 bool follow_assert_exprs, bool reversed, tree *new_cst)
1680 {
1681 /* See if this is a relational operation between two SSA_NAMES with
1682 unsigned, overflow wrapping values. If so, check it more deeply. */
1683 if ((code == LT_EXPR || code == LE_EXPR
1684 || code == GE_EXPR || code == GT_EXPR)
1685 && TREE_CODE (op0) == SSA_NAME
1686 && TREE_CODE (op1) == SSA_NAME
1687 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
1688 && TYPE_UNSIGNED (TREE_TYPE (op0))
1689 && TYPE_OVERFLOW_WRAPS (TREE_TYPE (op0)))
1690 {
1691 gimple *op1_def = SSA_NAME_DEF_STMT (op1);
1692
1693 /* If requested, follow any ASSERT_EXPRs backwards for OP1. */
1694 if (follow_assert_exprs)
1695 {
1696 while (gimple_assign_single_p (op1_def)
1697 && TREE_CODE (gimple_assign_rhs1 (op1_def)) == ASSERT_EXPR)
1698 {
1699 op1 = TREE_OPERAND (gimple_assign_rhs1 (op1_def), 0);
1700 if (TREE_CODE (op1) != SSA_NAME)
1701 break;
1702 op1_def = SSA_NAME_DEF_STMT (op1);
1703 }
1704 }
1705
1706 /* Now look at the defining statement of OP1 to see if it adds
1707 or subtracts a nonzero constant from another operand. */
1708 if (op1_def
1709 && is_gimple_assign (op1_def)
1710 && gimple_assign_rhs_code (op1_def) == PLUS_EXPR
1711 && TREE_CODE (gimple_assign_rhs2 (op1_def)) == INTEGER_CST
1712 && !integer_zerop (gimple_assign_rhs2 (op1_def)))
1713 {
1714 tree target = gimple_assign_rhs1 (op1_def);
1715
1716 /* If requested, follow ASSERT_EXPRs backwards for op0 looking
1717 for one where TARGET appears on the RHS. */
1718 if (follow_assert_exprs)
1719 {
1720 /* Now see if that "other operand" is op0, following the chain
1721 of ASSERT_EXPRs if necessary. */
1722 gimple *op0_def = SSA_NAME_DEF_STMT (op0);
1723 while (op0 != target
1724 && gimple_assign_single_p (op0_def)
1725 && TREE_CODE (gimple_assign_rhs1 (op0_def)) == ASSERT_EXPR)
1726 {
1727 op0 = TREE_OPERAND (gimple_assign_rhs1 (op0_def), 0);
1728 if (TREE_CODE (op0) != SSA_NAME)
1729 break;
1730 op0_def = SSA_NAME_DEF_STMT (op0);
1731 }
1732 }
1733
1734 /* If we did not find our target SSA_NAME, then this is not
1735 an overflow test. */
1736 if (op0 != target)
1737 return false;
1738
1739 tree type = TREE_TYPE (op0);
1740 wide_int max = wi::max_value (TYPE_PRECISION (type), UNSIGNED);
1741 tree inc = gimple_assign_rhs2 (op1_def);
1742 if (reversed)
1743 *new_cst = wide_int_to_tree (type, max + wi::to_wide (inc));
1744 else
1745 *new_cst = wide_int_to_tree (type, max - wi::to_wide (inc));
1746 return true;
1747 }
1748 }
1749 return false;
1750 }
1751
1752 /* OP0 CODE OP1 is a comparison. Examine the comparison and potentially
1753 OP1's defining statement to see if it ultimately has the form
1754 OP0 CODE (OP0 PLUS INTEGER_CST)
1755
1756 If so, return TRUE indicating this is an overflow test and store into
1757 *NEW_CST an updated constant that can be used in a narrowed range test.
1758
1759 These statements are left as-is in the IL to facilitate discovery of
1760 {ADD,SUB}_OVERFLOW sequences later in the optimizer pipeline. But
1761 the alternate range representation is often useful within VRP. */
1762
1763 bool
1764 overflow_comparison_p (tree_code code, tree name, tree val,
1765 bool use_equiv_p, tree *new_cst)
1766 {
1767 if (overflow_comparison_p_1 (code, name, val, use_equiv_p, false, new_cst))
1768 return true;
1769 return overflow_comparison_p_1 (swap_tree_comparison (code), val, name,
1770 use_equiv_p, true, new_cst);
1771 }
1772
1773
1774 /* Try to register an edge assertion for SSA name NAME on edge E for
1775 the condition COND contributing to the conditional jump pointed to by BSI.
1776 Invert the condition COND if INVERT is true. */
1777
1778 static void
1779 register_edge_assert_for_2 (tree name, edge e,
1780 enum tree_code cond_code,
1781 tree cond_op0, tree cond_op1, bool invert,
1782 vec<assert_info> &asserts)
1783 {
1784 tree val;
1785 enum tree_code comp_code;
1786
1787 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
1788 cond_op0,
1789 cond_op1,
1790 invert, &comp_code, &val))
1791 return;
1792
1793 /* Queue the assert. */
1794 tree x;
1795 if (overflow_comparison_p (comp_code, name, val, false, &x))
1796 {
1797 enum tree_code new_code = ((comp_code == GT_EXPR || comp_code == GE_EXPR)
1798 ? GT_EXPR : LE_EXPR);
1799 add_assert_info (asserts, name, name, new_code, x);
1800 }
1801 add_assert_info (asserts, name, name, comp_code, val);
1802
1803 /* In the case of NAME <= CST and NAME being defined as
1804 NAME = (unsigned) NAME2 + CST2 we can assert NAME2 >= -CST2
1805 and NAME2 <= CST - CST2. We can do the same for NAME > CST.
1806 This catches range and anti-range tests. */
1807 if ((comp_code == LE_EXPR
1808 || comp_code == GT_EXPR)
1809 && TREE_CODE (val) == INTEGER_CST
1810 && TYPE_UNSIGNED (TREE_TYPE (val)))
1811 {
1812 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
1813 tree cst2 = NULL_TREE, name2 = NULL_TREE, name3 = NULL_TREE;
1814
1815 /* Extract CST2 from the (optional) addition. */
1816 if (is_gimple_assign (def_stmt)
1817 && gimple_assign_rhs_code (def_stmt) == PLUS_EXPR)
1818 {
1819 name2 = gimple_assign_rhs1 (def_stmt);
1820 cst2 = gimple_assign_rhs2 (def_stmt);
1821 if (TREE_CODE (name2) == SSA_NAME
1822 && TREE_CODE (cst2) == INTEGER_CST)
1823 def_stmt = SSA_NAME_DEF_STMT (name2);
1824 }
1825
1826 /* Extract NAME2 from the (optional) sign-changing cast. */
1827 if (gimple_assign_cast_p (def_stmt))
1828 {
1829 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt))
1830 && ! TYPE_UNSIGNED (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
1831 && (TYPE_PRECISION (gimple_expr_type (def_stmt))
1832 == TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))))
1833 name3 = gimple_assign_rhs1 (def_stmt);
1834 }
1835
1836 /* If name3 is used later, create an ASSERT_EXPR for it. */
1837 if (name3 != NULL_TREE
1838 && TREE_CODE (name3) == SSA_NAME
1839 && (cst2 == NULL_TREE
1840 || TREE_CODE (cst2) == INTEGER_CST)
1841 && INTEGRAL_TYPE_P (TREE_TYPE (name3)))
1842 {
1843 tree tmp;
1844
1845 /* Build an expression for the range test. */
1846 tmp = build1 (NOP_EXPR, TREE_TYPE (name), name3);
1847 if (cst2 != NULL_TREE)
1848 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
1849 add_assert_info (asserts, name3, tmp, comp_code, val);
1850 }
1851
1852 /* If name2 is used later, create an ASSERT_EXPR for it. */
1853 if (name2 != NULL_TREE
1854 && TREE_CODE (name2) == SSA_NAME
1855 && TREE_CODE (cst2) == INTEGER_CST
1856 && INTEGRAL_TYPE_P (TREE_TYPE (name2)))
1857 {
1858 tree tmp;
1859
1860 /* Build an expression for the range test. */
1861 tmp = name2;
1862 if (TREE_TYPE (name) != TREE_TYPE (name2))
1863 tmp = build1 (NOP_EXPR, TREE_TYPE (name), tmp);
1864 if (cst2 != NULL_TREE)
1865 tmp = build2 (PLUS_EXPR, TREE_TYPE (name), tmp, cst2);
1866 add_assert_info (asserts, name2, tmp, comp_code, val);
1867 }
1868 }
1869
1870 /* In the case of post-in/decrement tests like if (i++) ... and uses
1871 of the in/decremented value on the edge the extra name we want to
1872 assert for is not on the def chain of the name compared. Instead
1873 it is in the set of use stmts.
1874 Similar cases happen for conversions that were simplified through
1875 fold_{sign_changed,widened}_comparison. */
1876 if ((comp_code == NE_EXPR
1877 || comp_code == EQ_EXPR)
1878 && TREE_CODE (val) == INTEGER_CST)
1879 {
1880 imm_use_iterator ui;
1881 gimple *use_stmt;
1882 FOR_EACH_IMM_USE_STMT (use_stmt, ui, name)
1883 {
1884 if (!is_gimple_assign (use_stmt))
1885 continue;
1886
1887 /* Cut off to use-stmts that are dominating the predecessor. */
1888 if (!dominated_by_p (CDI_DOMINATORS, e->src, gimple_bb (use_stmt)))
1889 continue;
1890
1891 tree name2 = gimple_assign_lhs (use_stmt);
1892 if (TREE_CODE (name2) != SSA_NAME)
1893 continue;
1894
1895 enum tree_code code = gimple_assign_rhs_code (use_stmt);
1896 tree cst;
1897 if (code == PLUS_EXPR
1898 || code == MINUS_EXPR)
1899 {
1900 cst = gimple_assign_rhs2 (use_stmt);
1901 if (TREE_CODE (cst) != INTEGER_CST)
1902 continue;
1903 cst = int_const_binop (code, val, cst);
1904 }
1905 else if (CONVERT_EXPR_CODE_P (code))
1906 {
1907 /* For truncating conversions we cannot record
1908 an inequality. */
1909 if (comp_code == NE_EXPR
1910 && (TYPE_PRECISION (TREE_TYPE (name2))
1911 < TYPE_PRECISION (TREE_TYPE (name))))
1912 continue;
1913 cst = fold_convert (TREE_TYPE (name2), val);
1914 }
1915 else
1916 continue;
1917
1918 if (TREE_OVERFLOW_P (cst))
1919 cst = drop_tree_overflow (cst);
1920 add_assert_info (asserts, name2, name2, comp_code, cst);
1921 }
1922 }
1923
1924 if (TREE_CODE_CLASS (comp_code) == tcc_comparison
1925 && TREE_CODE (val) == INTEGER_CST)
1926 {
1927 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
1928 tree name2 = NULL_TREE, names[2], cst2 = NULL_TREE;
1929 tree val2 = NULL_TREE;
1930 unsigned int prec = TYPE_PRECISION (TREE_TYPE (val));
1931 wide_int mask = wi::zero (prec);
1932 unsigned int nprec = prec;
1933 enum tree_code rhs_code = ERROR_MARK;
1934
1935 if (is_gimple_assign (def_stmt))
1936 rhs_code = gimple_assign_rhs_code (def_stmt);
1937
1938 /* In the case of NAME != CST1 where NAME = A +- CST2 we can
1939 assert that A != CST1 -+ CST2. */
1940 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
1941 && (rhs_code == PLUS_EXPR || rhs_code == MINUS_EXPR))
1942 {
1943 tree op0 = gimple_assign_rhs1 (def_stmt);
1944 tree op1 = gimple_assign_rhs2 (def_stmt);
1945 if (TREE_CODE (op0) == SSA_NAME
1946 && TREE_CODE (op1) == INTEGER_CST)
1947 {
1948 enum tree_code reverse_op = (rhs_code == PLUS_EXPR
1949 ? MINUS_EXPR : PLUS_EXPR);
1950 op1 = int_const_binop (reverse_op, val, op1);
1951 if (TREE_OVERFLOW (op1))
1952 op1 = drop_tree_overflow (op1);
1953 add_assert_info (asserts, op0, op0, comp_code, op1);
1954 }
1955 }
1956
1957 /* Add asserts for NAME cmp CST and NAME being defined
1958 as NAME = (int) NAME2. */
1959 if (!TYPE_UNSIGNED (TREE_TYPE (val))
1960 && (comp_code == LE_EXPR || comp_code == LT_EXPR
1961 || comp_code == GT_EXPR || comp_code == GE_EXPR)
1962 && gimple_assign_cast_p (def_stmt))
1963 {
1964 name2 = gimple_assign_rhs1 (def_stmt);
1965 if (CONVERT_EXPR_CODE_P (rhs_code)
1966 && TREE_CODE (name2) == SSA_NAME
1967 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
1968 && TYPE_UNSIGNED (TREE_TYPE (name2))
1969 && prec == TYPE_PRECISION (TREE_TYPE (name2))
1970 && (comp_code == LE_EXPR || comp_code == GT_EXPR
1971 || !tree_int_cst_equal (val,
1972 TYPE_MIN_VALUE (TREE_TYPE (val)))))
1973 {
1974 tree tmp, cst;
1975 enum tree_code new_comp_code = comp_code;
1976
1977 cst = fold_convert (TREE_TYPE (name2),
1978 TYPE_MIN_VALUE (TREE_TYPE (val)));
1979 /* Build an expression for the range test. */
1980 tmp = build2 (PLUS_EXPR, TREE_TYPE (name2), name2, cst);
1981 cst = fold_build2 (PLUS_EXPR, TREE_TYPE (name2), cst,
1982 fold_convert (TREE_TYPE (name2), val));
1983 if (comp_code == LT_EXPR || comp_code == GE_EXPR)
1984 {
1985 new_comp_code = comp_code == LT_EXPR ? LE_EXPR : GT_EXPR;
1986 cst = fold_build2 (MINUS_EXPR, TREE_TYPE (name2), cst,
1987 build_int_cst (TREE_TYPE (name2), 1));
1988 }
1989 add_assert_info (asserts, name2, tmp, new_comp_code, cst);
1990 }
1991 }
1992
1993 /* Add asserts for NAME cmp CST and NAME being defined as
1994 NAME = NAME2 >> CST2.
1995
1996 Extract CST2 from the right shift. */
1997 if (rhs_code == RSHIFT_EXPR)
1998 {
1999 name2 = gimple_assign_rhs1 (def_stmt);
2000 cst2 = gimple_assign_rhs2 (def_stmt);
2001 if (TREE_CODE (name2) == SSA_NAME
2002 && tree_fits_uhwi_p (cst2)
2003 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
2004 && IN_RANGE (tree_to_uhwi (cst2), 1, prec - 1)
2005 && type_has_mode_precision_p (TREE_TYPE (val)))
2006 {
2007 mask = wi::mask (tree_to_uhwi (cst2), false, prec);
2008 val2 = fold_binary (LSHIFT_EXPR, TREE_TYPE (val), val, cst2);
2009 }
2010 }
2011 if (val2 != NULL_TREE
2012 && TREE_CODE (val2) == INTEGER_CST
2013 && simple_cst_equal (fold_build2 (RSHIFT_EXPR,
2014 TREE_TYPE (val),
2015 val2, cst2), val))
2016 {
2017 enum tree_code new_comp_code = comp_code;
2018 tree tmp, new_val;
2019
2020 tmp = name2;
2021 if (comp_code == EQ_EXPR || comp_code == NE_EXPR)
2022 {
2023 if (!TYPE_UNSIGNED (TREE_TYPE (val)))
2024 {
2025 tree type = build_nonstandard_integer_type (prec, 1);
2026 tmp = build1 (NOP_EXPR, type, name2);
2027 val2 = fold_convert (type, val2);
2028 }
2029 tmp = fold_build2 (MINUS_EXPR, TREE_TYPE (tmp), tmp, val2);
2030 new_val = wide_int_to_tree (TREE_TYPE (tmp), mask);
2031 new_comp_code = comp_code == EQ_EXPR ? LE_EXPR : GT_EXPR;
2032 }
2033 else if (comp_code == LT_EXPR || comp_code == GE_EXPR)
2034 {
2035 wide_int minval
2036 = wi::min_value (prec, TYPE_SIGN (TREE_TYPE (val)));
2037 new_val = val2;
2038 if (minval == wi::to_wide (new_val))
2039 new_val = NULL_TREE;
2040 }
2041 else
2042 {
2043 wide_int maxval
2044 = wi::max_value (prec, TYPE_SIGN (TREE_TYPE (val)));
2045 mask |= wi::to_wide (val2);
2046 if (wi::eq_p (mask, maxval))
2047 new_val = NULL_TREE;
2048 else
2049 new_val = wide_int_to_tree (TREE_TYPE (val2), mask);
2050 }
2051
2052 if (new_val)
2053 add_assert_info (asserts, name2, tmp, new_comp_code, new_val);
2054 }
2055
2056 /* If we have a conversion that doesn't change the value of the source
2057 simply register the same assert for it. */
2058 if (CONVERT_EXPR_CODE_P (rhs_code))
2059 {
2060 wide_int rmin, rmax;
2061 tree rhs1 = gimple_assign_rhs1 (def_stmt);
2062 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1))
2063 && TREE_CODE (rhs1) == SSA_NAME
2064 /* Make sure the relation preserves the upper/lower boundary of
2065 the range conservatively. */
2066 && (comp_code == NE_EXPR
2067 || comp_code == EQ_EXPR
2068 || (TYPE_SIGN (TREE_TYPE (name))
2069 == TYPE_SIGN (TREE_TYPE (rhs1)))
2070 || ((comp_code == LE_EXPR
2071 || comp_code == LT_EXPR)
2072 && !TYPE_UNSIGNED (TREE_TYPE (rhs1)))
2073 || ((comp_code == GE_EXPR
2074 || comp_code == GT_EXPR)
2075 && TYPE_UNSIGNED (TREE_TYPE (rhs1))))
2076 /* And the conversion does not alter the value we compare
2077 against and all values in rhs1 can be represented in
2078 the converted to type. */
2079 && int_fits_type_p (val, TREE_TYPE (rhs1))
2080 && ((TYPE_PRECISION (TREE_TYPE (name))
2081 > TYPE_PRECISION (TREE_TYPE (rhs1)))
2082 || (get_range_info (rhs1, &rmin, &rmax) == VR_RANGE
2083 && wi::fits_to_tree_p (rmin, TREE_TYPE (name))
2084 && wi::fits_to_tree_p (rmax, TREE_TYPE (name)))))
2085 add_assert_info (asserts, rhs1, rhs1,
2086 comp_code, fold_convert (TREE_TYPE (rhs1), val));
2087 }
2088
2089 /* Add asserts for NAME cmp CST and NAME being defined as
2090 NAME = NAME2 & CST2.
2091
2092 Extract CST2 from the and.
2093
2094 Also handle
2095 NAME = (unsigned) NAME2;
2096 casts where NAME's type is unsigned and has smaller precision
2097 than NAME2's type as if it was NAME = NAME2 & MASK. */
2098 names[0] = NULL_TREE;
2099 names[1] = NULL_TREE;
2100 cst2 = NULL_TREE;
2101 if (rhs_code == BIT_AND_EXPR
2102 || (CONVERT_EXPR_CODE_P (rhs_code)
2103 && INTEGRAL_TYPE_P (TREE_TYPE (val))
2104 && TYPE_UNSIGNED (TREE_TYPE (val))
2105 && TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (def_stmt)))
2106 > prec))
2107 {
2108 name2 = gimple_assign_rhs1 (def_stmt);
2109 if (rhs_code == BIT_AND_EXPR)
2110 cst2 = gimple_assign_rhs2 (def_stmt);
2111 else
2112 {
2113 cst2 = TYPE_MAX_VALUE (TREE_TYPE (val));
2114 nprec = TYPE_PRECISION (TREE_TYPE (name2));
2115 }
2116 if (TREE_CODE (name2) == SSA_NAME
2117 && INTEGRAL_TYPE_P (TREE_TYPE (name2))
2118 && TREE_CODE (cst2) == INTEGER_CST
2119 && !integer_zerop (cst2)
2120 && (nprec > 1
2121 || TYPE_UNSIGNED (TREE_TYPE (val))))
2122 {
2123 gimple *def_stmt2 = SSA_NAME_DEF_STMT (name2);
2124 if (gimple_assign_cast_p (def_stmt2))
2125 {
2126 names[1] = gimple_assign_rhs1 (def_stmt2);
2127 if (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt2))
2128 || TREE_CODE (names[1]) != SSA_NAME
2129 || !INTEGRAL_TYPE_P (TREE_TYPE (names[1]))
2130 || (TYPE_PRECISION (TREE_TYPE (name2))
2131 != TYPE_PRECISION (TREE_TYPE (names[1]))))
2132 names[1] = NULL_TREE;
2133 }
2134 names[0] = name2;
2135 }
2136 }
2137 if (names[0] || names[1])
2138 {
2139 wide_int minv, maxv, valv, cst2v;
2140 wide_int tem, sgnbit;
2141 bool valid_p = false, valn, cst2n;
2142 enum tree_code ccode = comp_code;
2143
2144 valv = wide_int::from (wi::to_wide (val), nprec, UNSIGNED);
2145 cst2v = wide_int::from (wi::to_wide (cst2), nprec, UNSIGNED);
2146 valn = wi::neg_p (valv, TYPE_SIGN (TREE_TYPE (val)));
2147 cst2n = wi::neg_p (cst2v, TYPE_SIGN (TREE_TYPE (val)));
2148 /* If CST2 doesn't have most significant bit set,
2149 but VAL is negative, we have comparison like
2150 if ((x & 0x123) > -4) (always true). Just give up. */
2151 if (!cst2n && valn)
2152 ccode = ERROR_MARK;
2153 if (cst2n)
2154 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
2155 else
2156 sgnbit = wi::zero (nprec);
2157 minv = valv & cst2v;
2158 switch (ccode)
2159 {
2160 case EQ_EXPR:
2161 /* Minimum unsigned value for equality is VAL & CST2
2162 (should be equal to VAL, otherwise we probably should
2163 have folded the comparison into false) and
2164 maximum unsigned value is VAL | ~CST2. */
2165 maxv = valv | ~cst2v;
2166 valid_p = true;
2167 break;
2168
2169 case NE_EXPR:
2170 tem = valv | ~cst2v;
2171 /* If VAL is 0, handle (X & CST2) != 0 as (X & CST2) > 0U. */
2172 if (valv == 0)
2173 {
2174 cst2n = false;
2175 sgnbit = wi::zero (nprec);
2176 goto gt_expr;
2177 }
2178 /* If (VAL | ~CST2) is all ones, handle it as
2179 (X & CST2) < VAL. */
2180 if (tem == -1)
2181 {
2182 cst2n = false;
2183 valn = false;
2184 sgnbit = wi::zero (nprec);
2185 goto lt_expr;
2186 }
2187 if (!cst2n && wi::neg_p (cst2v))
2188 sgnbit = wi::set_bit_in_zero (nprec - 1, nprec);
2189 if (sgnbit != 0)
2190 {
2191 if (valv == sgnbit)
2192 {
2193 cst2n = true;
2194 valn = true;
2195 goto gt_expr;
2196 }
2197 if (tem == wi::mask (nprec - 1, false, nprec))
2198 {
2199 cst2n = true;
2200 goto lt_expr;
2201 }
2202 if (!cst2n)
2203 sgnbit = wi::zero (nprec);
2204 }
2205 break;
2206
2207 case GE_EXPR:
2208 /* Minimum unsigned value for >= if (VAL & CST2) == VAL
2209 is VAL and maximum unsigned value is ~0. For signed
2210 comparison, if CST2 doesn't have most significant bit
2211 set, handle it similarly. If CST2 has MSB set,
2212 the minimum is the same, and maximum is ~0U/2. */
2213 if (minv != valv)
2214 {
2215 /* If (VAL & CST2) != VAL, X & CST2 can't be equal to
2216 VAL. */
2217 minv = masked_increment (valv, cst2v, sgnbit, nprec);
2218 if (minv == valv)
2219 break;
2220 }
2221 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
2222 valid_p = true;
2223 break;
2224
2225 case GT_EXPR:
2226 gt_expr:
2227 /* Find out smallest MINV where MINV > VAL
2228 && (MINV & CST2) == MINV, if any. If VAL is signed and
2229 CST2 has MSB set, compute it biased by 1 << (nprec - 1). */
2230 minv = masked_increment (valv, cst2v, sgnbit, nprec);
2231 if (minv == valv)
2232 break;
2233 maxv = wi::mask (nprec - (cst2n ? 1 : 0), false, nprec);
2234 valid_p = true;
2235 break;
2236
2237 case LE_EXPR:
2238 /* Minimum unsigned value for <= is 0 and maximum
2239 unsigned value is VAL | ~CST2 if (VAL & CST2) == VAL.
2240 Otherwise, find smallest VAL2 where VAL2 > VAL
2241 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
2242 as maximum.
2243 For signed comparison, if CST2 doesn't have most
2244 significant bit set, handle it similarly. If CST2 has
2245 MSB set, the maximum is the same and minimum is INT_MIN. */
2246 if (minv == valv)
2247 maxv = valv;
2248 else
2249 {
2250 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
2251 if (maxv == valv)
2252 break;
2253 maxv -= 1;
2254 }
2255 maxv |= ~cst2v;
2256 minv = sgnbit;
2257 valid_p = true;
2258 break;
2259
2260 case LT_EXPR:
2261 lt_expr:
2262 /* Minimum unsigned value for < is 0 and maximum
2263 unsigned value is (VAL-1) | ~CST2 if (VAL & CST2) == VAL.
2264 Otherwise, find smallest VAL2 where VAL2 > VAL
2265 && (VAL2 & CST2) == VAL2 and use (VAL2 - 1) | ~CST2
2266 as maximum.
2267 For signed comparison, if CST2 doesn't have most
2268 significant bit set, handle it similarly. If CST2 has
2269 MSB set, the maximum is the same and minimum is INT_MIN. */
2270 if (minv == valv)
2271 {
2272 if (valv == sgnbit)
2273 break;
2274 maxv = valv;
2275 }
2276 else
2277 {
2278 maxv = masked_increment (valv, cst2v, sgnbit, nprec);
2279 if (maxv == valv)
2280 break;
2281 }
2282 maxv -= 1;
2283 maxv |= ~cst2v;
2284 minv = sgnbit;
2285 valid_p = true;
2286 break;
2287
2288 default:
2289 break;
2290 }
2291 if (valid_p
2292 && (maxv - minv) != -1)
2293 {
2294 tree tmp, new_val, type;
2295 int i;
2296
2297 for (i = 0; i < 2; i++)
2298 if (names[i])
2299 {
2300 wide_int maxv2 = maxv;
2301 tmp = names[i];
2302 type = TREE_TYPE (names[i]);
2303 if (!TYPE_UNSIGNED (type))
2304 {
2305 type = build_nonstandard_integer_type (nprec, 1);
2306 tmp = build1 (NOP_EXPR, type, names[i]);
2307 }
2308 if (minv != 0)
2309 {
2310 tmp = build2 (PLUS_EXPR, type, tmp,
2311 wide_int_to_tree (type, -minv));
2312 maxv2 = maxv - minv;
2313 }
2314 new_val = wide_int_to_tree (type, maxv2);
2315 add_assert_info (asserts, names[i], tmp, LE_EXPR, new_val);
2316 }
2317 }
2318 }
2319 }
2320 }
2321
2322 /* OP is an operand of a truth value expression which is known to have
2323 a particular value. Register any asserts for OP and for any
2324 operands in OP's defining statement.
2325
2326 If CODE is EQ_EXPR, then we want to register OP is zero (false),
2327 if CODE is NE_EXPR, then we want to register OP is nonzero (true). */
2328
2329 static void
2330 register_edge_assert_for_1 (tree op, enum tree_code code,
2331 edge e, vec<assert_info> &asserts)
2332 {
2333 gimple *op_def;
2334 tree val;
2335 enum tree_code rhs_code;
2336
2337 /* We only care about SSA_NAMEs. */
2338 if (TREE_CODE (op) != SSA_NAME)
2339 return;
2340
2341 /* We know that OP will have a zero or nonzero value. */
2342 val = build_int_cst (TREE_TYPE (op), 0);
2343 add_assert_info (asserts, op, op, code, val);
2344
2345 /* Now look at how OP is set. If it's set from a comparison,
2346 a truth operation or some bit operations, then we may be able
2347 to register information about the operands of that assignment. */
2348 op_def = SSA_NAME_DEF_STMT (op);
2349 if (gimple_code (op_def) != GIMPLE_ASSIGN)
2350 return;
2351
2352 rhs_code = gimple_assign_rhs_code (op_def);
2353
2354 if (TREE_CODE_CLASS (rhs_code) == tcc_comparison)
2355 {
2356 bool invert = (code == EQ_EXPR ? true : false);
2357 tree op0 = gimple_assign_rhs1 (op_def);
2358 tree op1 = gimple_assign_rhs2 (op_def);
2359
2360 if (TREE_CODE (op0) == SSA_NAME)
2361 register_edge_assert_for_2 (op0, e, rhs_code, op0, op1, invert, asserts);
2362 if (TREE_CODE (op1) == SSA_NAME)
2363 register_edge_assert_for_2 (op1, e, rhs_code, op0, op1, invert, asserts);
2364 }
2365 else if ((code == NE_EXPR
2366 && gimple_assign_rhs_code (op_def) == BIT_AND_EXPR)
2367 || (code == EQ_EXPR
2368 && gimple_assign_rhs_code (op_def) == BIT_IOR_EXPR))
2369 {
2370 /* Recurse on each operand. */
2371 tree op0 = gimple_assign_rhs1 (op_def);
2372 tree op1 = gimple_assign_rhs2 (op_def);
2373 if (TREE_CODE (op0) == SSA_NAME
2374 && has_single_use (op0))
2375 register_edge_assert_for_1 (op0, code, e, asserts);
2376 if (TREE_CODE (op1) == SSA_NAME
2377 && has_single_use (op1))
2378 register_edge_assert_for_1 (op1, code, e, asserts);
2379 }
2380 else if (gimple_assign_rhs_code (op_def) == BIT_NOT_EXPR
2381 && TYPE_PRECISION (TREE_TYPE (gimple_assign_lhs (op_def))) == 1)
2382 {
2383 /* Recurse, flipping CODE. */
2384 code = invert_tree_comparison (code, false);
2385 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
2386 }
2387 else if (gimple_assign_rhs_code (op_def) == SSA_NAME)
2388 {
2389 /* Recurse through the copy. */
2390 register_edge_assert_for_1 (gimple_assign_rhs1 (op_def), code, e, asserts);
2391 }
2392 else if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (op_def)))
2393 {
2394 /* Recurse through the type conversion, unless it is a narrowing
2395 conversion or conversion from non-integral type. */
2396 tree rhs = gimple_assign_rhs1 (op_def);
2397 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs))
2398 && (TYPE_PRECISION (TREE_TYPE (rhs))
2399 <= TYPE_PRECISION (TREE_TYPE (op))))
2400 register_edge_assert_for_1 (rhs, code, e, asserts);
2401 }
2402 }
2403
2404 /* Check if comparison
2405 NAME COND_OP INTEGER_CST
2406 has a form of
2407 (X & 11...100..0) COND_OP XX...X00...0
2408 Such comparison can yield assertions like
2409 X >= XX...X00...0
2410 X <= XX...X11...1
2411 in case of COND_OP being EQ_EXPR or
2412 X < XX...X00...0
2413 X > XX...X11...1
2414 in case of NE_EXPR. */
2415
2416 static bool
2417 is_masked_range_test (tree name, tree valt, enum tree_code cond_code,
2418 tree *new_name, tree *low, enum tree_code *low_code,
2419 tree *high, enum tree_code *high_code)
2420 {
2421 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
2422
2423 if (!is_gimple_assign (def_stmt)
2424 || gimple_assign_rhs_code (def_stmt) != BIT_AND_EXPR)
2425 return false;
2426
2427 tree t = gimple_assign_rhs1 (def_stmt);
2428 tree maskt = gimple_assign_rhs2 (def_stmt);
2429 if (TREE_CODE (t) != SSA_NAME || TREE_CODE (maskt) != INTEGER_CST)
2430 return false;
2431
2432 wi::tree_to_wide_ref mask = wi::to_wide (maskt);
2433 wide_int inv_mask = ~mask;
2434 /* Must have been removed by now so don't bother optimizing. */
2435 if (mask == 0 || inv_mask == 0)
2436 return false;
2437
2438 /* Assume VALT is INTEGER_CST. */
2439 wi::tree_to_wide_ref val = wi::to_wide (valt);
2440
2441 if ((inv_mask & (inv_mask + 1)) != 0
2442 || (val & mask) != val)
2443 return false;
2444
2445 bool is_range = cond_code == EQ_EXPR;
2446
2447 tree type = TREE_TYPE (t);
2448 wide_int min = wi::min_value (type),
2449 max = wi::max_value (type);
2450
2451 if (is_range)
2452 {
2453 *low_code = val == min ? ERROR_MARK : GE_EXPR;
2454 *high_code = val == max ? ERROR_MARK : LE_EXPR;
2455 }
2456 else
2457 {
2458 /* We can still generate assertion if one of alternatives
2459 is known to always be false. */
2460 if (val == min)
2461 {
2462 *low_code = (enum tree_code) 0;
2463 *high_code = GT_EXPR;
2464 }
2465 else if ((val | inv_mask) == max)
2466 {
2467 *low_code = LT_EXPR;
2468 *high_code = (enum tree_code) 0;
2469 }
2470 else
2471 return false;
2472 }
2473
2474 *new_name = t;
2475 *low = wide_int_to_tree (type, val);
2476 *high = wide_int_to_tree (type, val | inv_mask);
2477
2478 return true;
2479 }
2480
2481 /* Try to register an edge assertion for SSA name NAME on edge E for
2482 the condition COND contributing to the conditional jump pointed to by
2483 SI. */
2484
2485 void
2486 register_edge_assert_for (tree name, edge e,
2487 enum tree_code cond_code, tree cond_op0,
2488 tree cond_op1, vec<assert_info> &asserts)
2489 {
2490 tree val;
2491 enum tree_code comp_code;
2492 bool is_else_edge = (e->flags & EDGE_FALSE_VALUE) != 0;
2493
2494 /* Do not attempt to infer anything in names that flow through
2495 abnormal edges. */
2496 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
2497 return;
2498
2499 if (!extract_code_and_val_from_cond_with_ops (name, cond_code,
2500 cond_op0, cond_op1,
2501 is_else_edge,
2502 &comp_code, &val))
2503 return;
2504
2505 /* Register ASSERT_EXPRs for name. */
2506 register_edge_assert_for_2 (name, e, cond_code, cond_op0,
2507 cond_op1, is_else_edge, asserts);
2508
2509
2510 /* If COND is effectively an equality test of an SSA_NAME against
2511 the value zero or one, then we may be able to assert values
2512 for SSA_NAMEs which flow into COND. */
2513
2514 /* In the case of NAME == 1 or NAME != 0, for BIT_AND_EXPR defining
2515 statement of NAME we can assert both operands of the BIT_AND_EXPR
2516 have nonzero value. */
2517 if (((comp_code == EQ_EXPR && integer_onep (val))
2518 || (comp_code == NE_EXPR && integer_zerop (val))))
2519 {
2520 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
2521
2522 if (is_gimple_assign (def_stmt)
2523 && gimple_assign_rhs_code (def_stmt) == BIT_AND_EXPR)
2524 {
2525 tree op0 = gimple_assign_rhs1 (def_stmt);
2526 tree op1 = gimple_assign_rhs2 (def_stmt);
2527 register_edge_assert_for_1 (op0, NE_EXPR, e, asserts);
2528 register_edge_assert_for_1 (op1, NE_EXPR, e, asserts);
2529 }
2530 }
2531
2532 /* In the case of NAME == 0 or NAME != 1, for BIT_IOR_EXPR defining
2533 statement of NAME we can assert both operands of the BIT_IOR_EXPR
2534 have zero value. */
2535 if (((comp_code == EQ_EXPR && integer_zerop (val))
2536 || (comp_code == NE_EXPR && integer_onep (val))))
2537 {
2538 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
2539
2540 /* For BIT_IOR_EXPR only if NAME == 0 both operands have
2541 necessarily zero value, or if type-precision is one. */
2542 if (is_gimple_assign (def_stmt)
2543 && (gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR
2544 && (TYPE_PRECISION (TREE_TYPE (name)) == 1
2545 || comp_code == EQ_EXPR)))
2546 {
2547 tree op0 = gimple_assign_rhs1 (def_stmt);
2548 tree op1 = gimple_assign_rhs2 (def_stmt);
2549 register_edge_assert_for_1 (op0, EQ_EXPR, e, asserts);
2550 register_edge_assert_for_1 (op1, EQ_EXPR, e, asserts);
2551 }
2552 }
2553
2554 /* Sometimes we can infer ranges from (NAME & MASK) == VALUE. */
2555 if ((comp_code == EQ_EXPR || comp_code == NE_EXPR)
2556 && TREE_CODE (val) == INTEGER_CST)
2557 {
2558 enum tree_code low_code, high_code;
2559 tree low, high;
2560 if (is_masked_range_test (name, val, comp_code, &name, &low,
2561 &low_code, &high, &high_code))
2562 {
2563 if (low_code != ERROR_MARK)
2564 register_edge_assert_for_2 (name, e, low_code, name,
2565 low, /*invert*/false, asserts);
2566 if (high_code != ERROR_MARK)
2567 register_edge_assert_for_2 (name, e, high_code, name,
2568 high, /*invert*/false, asserts);
2569 }
2570 }
2571 }
2572
2573 /* Finish found ASSERTS for E and register them at GSI. */
2574
2575 void
2576 vrp_insert::finish_register_edge_assert_for (edge e, gimple_stmt_iterator gsi,
2577 vec<assert_info> &asserts)
2578 {
2579 for (unsigned i = 0; i < asserts.length (); ++i)
2580 /* Only register an ASSERT_EXPR if NAME was found in the sub-graph
2581 reachable from E. */
2582 if (live.live_on_edge_p (asserts[i].name, e))
2583 register_new_assert_for (asserts[i].name, asserts[i].expr,
2584 asserts[i].comp_code, asserts[i].val,
2585 NULL, e, gsi);
2586 }
2587
2588
2589
2590 /* Determine whether the outgoing edges of BB should receive an
2591 ASSERT_EXPR for each of the operands of BB's LAST statement.
2592 The last statement of BB must be a COND_EXPR.
2593
2594 If any of the sub-graphs rooted at BB have an interesting use of
2595 the predicate operands, an assert location node is added to the
2596 list of assertions for the corresponding operands. */
2597
2598 void
2599 vrp_insert::find_conditional_asserts (basic_block bb, gcond *last)
2600 {
2601 gimple_stmt_iterator bsi;
2602 tree op;
2603 edge_iterator ei;
2604 edge e;
2605 ssa_op_iter iter;
2606
2607 bsi = gsi_for_stmt (last);
2608
2609 /* Look for uses of the operands in each of the sub-graphs
2610 rooted at BB. We need to check each of the outgoing edges
2611 separately, so that we know what kind of ASSERT_EXPR to
2612 insert. */
2613 FOR_EACH_EDGE (e, ei, bb->succs)
2614 {
2615 if (e->dest == bb)
2616 continue;
2617
2618 /* Register the necessary assertions for each operand in the
2619 conditional predicate. */
2620 auto_vec<assert_info, 8> asserts;
2621 FOR_EACH_SSA_TREE_OPERAND (op, last, iter, SSA_OP_USE)
2622 register_edge_assert_for (op, e,
2623 gimple_cond_code (last),
2624 gimple_cond_lhs (last),
2625 gimple_cond_rhs (last), asserts);
2626 finish_register_edge_assert_for (e, bsi, asserts);
2627 }
2628 }
2629
2630 struct case_info
2631 {
2632 tree expr;
2633 basic_block bb;
2634 };
2635
2636 /* Compare two case labels sorting first by the destination bb index
2637 and then by the case value. */
2638
2639 static int
2640 compare_case_labels (const void *p1, const void *p2)
2641 {
2642 const struct case_info *ci1 = (const struct case_info *) p1;
2643 const struct case_info *ci2 = (const struct case_info *) p2;
2644 int idx1 = ci1->bb->index;
2645 int idx2 = ci2->bb->index;
2646
2647 if (idx1 < idx2)
2648 return -1;
2649 else if (idx1 == idx2)
2650 {
2651 /* Make sure the default label is first in a group. */
2652 if (!CASE_LOW (ci1->expr))
2653 return -1;
2654 else if (!CASE_LOW (ci2->expr))
2655 return 1;
2656 else
2657 return tree_int_cst_compare (CASE_LOW (ci1->expr),
2658 CASE_LOW (ci2->expr));
2659 }
2660 else
2661 return 1;
2662 }
2663
2664 /* Determine whether the outgoing edges of BB should receive an
2665 ASSERT_EXPR for each of the operands of BB's LAST statement.
2666 The last statement of BB must be a SWITCH_EXPR.
2667
2668 If any of the sub-graphs rooted at BB have an interesting use of
2669 the predicate operands, an assert location node is added to the
2670 list of assertions for the corresponding operands. */
2671
2672 void
2673 vrp_insert::find_switch_asserts (basic_block bb, gswitch *last)
2674 {
2675 gimple_stmt_iterator bsi;
2676 tree op;
2677 edge e;
2678 struct case_info *ci;
2679 size_t n = gimple_switch_num_labels (last);
2680 #if GCC_VERSION >= 4000
2681 unsigned int idx;
2682 #else
2683 /* Work around GCC 3.4 bug (PR 37086). */
2684 volatile unsigned int idx;
2685 #endif
2686
2687 bsi = gsi_for_stmt (last);
2688 op = gimple_switch_index (last);
2689 if (TREE_CODE (op) != SSA_NAME)
2690 return;
2691
2692 /* Build a vector of case labels sorted by destination label. */
2693 ci = XNEWVEC (struct case_info, n);
2694 for (idx = 0; idx < n; ++idx)
2695 {
2696 ci[idx].expr = gimple_switch_label (last, idx);
2697 ci[idx].bb = label_to_block (fun, CASE_LABEL (ci[idx].expr));
2698 }
2699 edge default_edge = find_edge (bb, ci[0].bb);
2700 qsort (ci, n, sizeof (struct case_info), compare_case_labels);
2701
2702 for (idx = 0; idx < n; ++idx)
2703 {
2704 tree min, max;
2705 tree cl = ci[idx].expr;
2706 basic_block cbb = ci[idx].bb;
2707
2708 min = CASE_LOW (cl);
2709 max = CASE_HIGH (cl);
2710
2711 /* If there are multiple case labels with the same destination
2712 we need to combine them to a single value range for the edge. */
2713 if (idx + 1 < n && cbb == ci[idx + 1].bb)
2714 {
2715 /* Skip labels until the last of the group. */
2716 do {
2717 ++idx;
2718 } while (idx < n && cbb == ci[idx].bb);
2719 --idx;
2720
2721 /* Pick up the maximum of the case label range. */
2722 if (CASE_HIGH (ci[idx].expr))
2723 max = CASE_HIGH (ci[idx].expr);
2724 else
2725 max = CASE_LOW (ci[idx].expr);
2726 }
2727
2728 /* Can't extract a useful assertion out of a range that includes the
2729 default label. */
2730 if (min == NULL_TREE)
2731 continue;
2732
2733 /* Find the edge to register the assert expr on. */
2734 e = find_edge (bb, cbb);
2735
2736 /* Register the necessary assertions for the operand in the
2737 SWITCH_EXPR. */
2738 auto_vec<assert_info, 8> asserts;
2739 register_edge_assert_for (op, e,
2740 max ? GE_EXPR : EQ_EXPR,
2741 op, fold_convert (TREE_TYPE (op), min),
2742 asserts);
2743 if (max)
2744 register_edge_assert_for (op, e, LE_EXPR, op,
2745 fold_convert (TREE_TYPE (op), max),
2746 asserts);
2747 finish_register_edge_assert_for (e, bsi, asserts);
2748 }
2749
2750 XDELETEVEC (ci);
2751
2752 if (!live.live_on_edge_p (op, default_edge))
2753 return;
2754
2755 /* Now register along the default label assertions that correspond to the
2756 anti-range of each label. */
2757 int insertion_limit = param_max_vrp_switch_assertions;
2758 if (insertion_limit == 0)
2759 return;
2760
2761 /* We can't do this if the default case shares a label with another case. */
2762 tree default_cl = gimple_switch_default_label (last);
2763 for (idx = 1; idx < n; idx++)
2764 {
2765 tree min, max;
2766 tree cl = gimple_switch_label (last, idx);
2767 if (CASE_LABEL (cl) == CASE_LABEL (default_cl))
2768 continue;
2769
2770 min = CASE_LOW (cl);
2771 max = CASE_HIGH (cl);
2772
2773 /* Combine contiguous case ranges to reduce the number of assertions
2774 to insert. */
2775 for (idx = idx + 1; idx < n; idx++)
2776 {
2777 tree next_min, next_max;
2778 tree next_cl = gimple_switch_label (last, idx);
2779 if (CASE_LABEL (next_cl) == CASE_LABEL (default_cl))
2780 break;
2781
2782 next_min = CASE_LOW (next_cl);
2783 next_max = CASE_HIGH (next_cl);
2784
2785 wide_int difference = (wi::to_wide (next_min)
2786 - wi::to_wide (max ? max : min));
2787 if (wi::eq_p (difference, 1))
2788 max = next_max ? next_max : next_min;
2789 else
2790 break;
2791 }
2792 idx--;
2793
2794 if (max == NULL_TREE)
2795 {
2796 /* Register the assertion OP != MIN. */
2797 auto_vec<assert_info, 8> asserts;
2798 min = fold_convert (TREE_TYPE (op), min);
2799 register_edge_assert_for (op, default_edge, NE_EXPR, op, min,
2800 asserts);
2801 finish_register_edge_assert_for (default_edge, bsi, asserts);
2802 }
2803 else
2804 {
2805 /* Register the assertion (unsigned)OP - MIN > (MAX - MIN),
2806 which will give OP the anti-range ~[MIN,MAX]. */
2807 tree uop = fold_convert (unsigned_type_for (TREE_TYPE (op)), op);
2808 min = fold_convert (TREE_TYPE (uop), min);
2809 max = fold_convert (TREE_TYPE (uop), max);
2810
2811 tree lhs = fold_build2 (MINUS_EXPR, TREE_TYPE (uop), uop, min);
2812 tree rhs = int_const_binop (MINUS_EXPR, max, min);
2813 register_new_assert_for (op, lhs, GT_EXPR, rhs,
2814 NULL, default_edge, bsi);
2815 }
2816
2817 if (--insertion_limit == 0)
2818 break;
2819 }
2820 }
2821
2822
2823 /* Traverse all the statements in block BB looking for statements that
2824 may generate useful assertions for the SSA names in their operand.
2825 If a statement produces a useful assertion A for name N_i, then the
2826 list of assertions already generated for N_i is scanned to
2827 determine if A is actually needed.
2828
2829 If N_i already had the assertion A at a location dominating the
2830 current location, then nothing needs to be done. Otherwise, the
2831 new location for A is recorded instead.
2832
2833 1- For every statement S in BB, all the variables used by S are
2834 added to bitmap FOUND_IN_SUBGRAPH.
2835
2836 2- If statement S uses an operand N in a way that exposes a known
2837 value range for N, then if N was not already generated by an
2838 ASSERT_EXPR, create a new assert location for N. For instance,
2839 if N is a pointer and the statement dereferences it, we can
2840 assume that N is not NULL.
2841
2842 3- COND_EXPRs are a special case of #2. We can derive range
2843 information from the predicate but need to insert different
2844 ASSERT_EXPRs for each of the sub-graphs rooted at the
2845 conditional block. If the last statement of BB is a conditional
2846 expression of the form 'X op Y', then
2847
2848 a) Remove X and Y from the set FOUND_IN_SUBGRAPH.
2849
2850 b) If the conditional is the only entry point to the sub-graph
2851 corresponding to the THEN_CLAUSE, recurse into it. On
2852 return, if X and/or Y are marked in FOUND_IN_SUBGRAPH, then
2853 an ASSERT_EXPR is added for the corresponding variable.
2854
2855 c) Repeat step (b) on the ELSE_CLAUSE.
2856
2857 d) Mark X and Y in FOUND_IN_SUBGRAPH.
2858
2859 For instance,
2860
2861 if (a == 9)
2862 b = a;
2863 else
2864 b = c + 1;
2865
2866 In this case, an assertion on the THEN clause is useful to
2867 determine that 'a' is always 9 on that edge. However, an assertion
2868 on the ELSE clause would be unnecessary.
2869
2870 4- If BB does not end in a conditional expression, then we recurse
2871 into BB's dominator children.
2872
2873 At the end of the recursive traversal, every SSA name will have a
2874 list of locations where ASSERT_EXPRs should be added. When a new
2875 location for name N is found, it is registered by calling
2876 register_new_assert_for. That function keeps track of all the
2877 registered assertions to prevent adding unnecessary assertions.
2878 For instance, if a pointer P_4 is dereferenced more than once in a
2879 dominator tree, only the location dominating all the dereference of
2880 P_4 will receive an ASSERT_EXPR. */
2881
2882 void
2883 vrp_insert::find_assert_locations_in_bb (basic_block bb)
2884 {
2885 gimple *last;
2886
2887 last = last_stmt (bb);
2888
2889 /* If BB's last statement is a conditional statement involving integer
2890 operands, determine if we need to add ASSERT_EXPRs. */
2891 if (last
2892 && gimple_code (last) == GIMPLE_COND
2893 && !fp_predicate (last)
2894 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
2895 find_conditional_asserts (bb, as_a <gcond *> (last));
2896
2897 /* If BB's last statement is a switch statement involving integer
2898 operands, determine if we need to add ASSERT_EXPRs. */
2899 if (last
2900 && gimple_code (last) == GIMPLE_SWITCH
2901 && !ZERO_SSA_OPERANDS (last, SSA_OP_USE))
2902 find_switch_asserts (bb, as_a <gswitch *> (last));
2903
2904 /* Traverse all the statements in BB marking used names and looking
2905 for statements that may infer assertions for their used operands. */
2906 for (gimple_stmt_iterator si = gsi_last_bb (bb); !gsi_end_p (si);
2907 gsi_prev (&si))
2908 {
2909 gimple *stmt;
2910 tree op;
2911 ssa_op_iter i;
2912
2913 stmt = gsi_stmt (si);
2914
2915 if (is_gimple_debug (stmt))
2916 continue;
2917
2918 /* See if we can derive an assertion for any of STMT's operands. */
2919 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
2920 {
2921 tree value;
2922 enum tree_code comp_code;
2923
2924 /* If op is not live beyond this stmt, do not bother to insert
2925 asserts for it. */
2926 if (!live.live_on_block_p (op, bb))
2927 continue;
2928
2929 /* If OP is used in such a way that we can infer a value
2930 range for it, and we don't find a previous assertion for
2931 it, create a new assertion location node for OP. */
2932 if (infer_value_range (stmt, op, &comp_code, &value))
2933 {
2934 /* If we are able to infer a nonzero value range for OP,
2935 then walk backwards through the use-def chain to see if OP
2936 was set via a typecast.
2937
2938 If so, then we can also infer a nonzero value range
2939 for the operand of the NOP_EXPR. */
2940 if (comp_code == NE_EXPR && integer_zerop (value))
2941 {
2942 tree t = op;
2943 gimple *def_stmt = SSA_NAME_DEF_STMT (t);
2944
2945 while (is_gimple_assign (def_stmt)
2946 && CONVERT_EXPR_CODE_P
2947 (gimple_assign_rhs_code (def_stmt))
2948 && TREE_CODE
2949 (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
2950 && POINTER_TYPE_P
2951 (TREE_TYPE (gimple_assign_rhs1 (def_stmt))))
2952 {
2953 t = gimple_assign_rhs1 (def_stmt);
2954 def_stmt = SSA_NAME_DEF_STMT (t);
2955
2956 /* Note we want to register the assert for the
2957 operand of the NOP_EXPR after SI, not after the
2958 conversion. */
2959 if (live.live_on_block_p (t, bb))
2960 register_new_assert_for (t, t, comp_code, value,
2961 bb, NULL, si);
2962 }
2963 }
2964
2965 register_new_assert_for (op, op, comp_code, value, bb, NULL, si);
2966 }
2967 }
2968
2969 /* Update live. */
2970 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_USE)
2971 live.set (op, bb);
2972 FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_DEF)
2973 live.clear (op, bb);
2974 }
2975
2976 /* Traverse all PHI nodes in BB, updating live. */
2977 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
2978 gsi_next (&si))
2979 {
2980 use_operand_p arg_p;
2981 ssa_op_iter i;
2982 gphi *phi = si.phi ();
2983 tree res = gimple_phi_result (phi);
2984
2985 if (virtual_operand_p (res))
2986 continue;
2987
2988 FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_USE)
2989 {
2990 tree arg = USE_FROM_PTR (arg_p);
2991 if (TREE_CODE (arg) == SSA_NAME)
2992 live.set (arg, bb);
2993 }
2994
2995 live.clear (res, bb);
2996 }
2997 }
2998
2999 /* Do an RPO walk over the function computing SSA name liveness
3000 on-the-fly and deciding on assert expressions to insert. */
3001
3002 void
3003 vrp_insert::find_assert_locations (void)
3004 {
3005 int *rpo = XNEWVEC (int, last_basic_block_for_fn (fun));
3006 int *bb_rpo = XNEWVEC (int, last_basic_block_for_fn (fun));
3007 int *last_rpo = XCNEWVEC (int, last_basic_block_for_fn (fun));
3008 int rpo_cnt, i;
3009
3010 rpo_cnt = pre_and_rev_post_order_compute (NULL, rpo, false);
3011 for (i = 0; i < rpo_cnt; ++i)
3012 bb_rpo[rpo[i]] = i;
3013
3014 /* Pre-seed loop latch liveness from loop header PHI nodes. Due to
3015 the order we compute liveness and insert asserts we otherwise
3016 fail to insert asserts into the loop latch. */
3017 loop_p loop;
3018 FOR_EACH_LOOP (loop, 0)
3019 {
3020 i = loop->latch->index;
3021 unsigned int j = single_succ_edge (loop->latch)->dest_idx;
3022 for (gphi_iterator gsi = gsi_start_phis (loop->header);
3023 !gsi_end_p (gsi); gsi_next (&gsi))
3024 {
3025 gphi *phi = gsi.phi ();
3026 if (virtual_operand_p (gimple_phi_result (phi)))
3027 continue;
3028 tree arg = gimple_phi_arg_def (phi, j);
3029 if (TREE_CODE (arg) == SSA_NAME)
3030 live.set (arg, loop->latch);
3031 }
3032 }
3033
3034 for (i = rpo_cnt - 1; i >= 0; --i)
3035 {
3036 basic_block bb = BASIC_BLOCK_FOR_FN (fun, rpo[i]);
3037 edge e;
3038 edge_iterator ei;
3039
3040 /* Process BB and update the live information with uses in
3041 this block. */
3042 find_assert_locations_in_bb (bb);
3043
3044 /* Merge liveness into the predecessor blocks and free it. */
3045 if (!live.block_has_live_names_p (bb))
3046 {
3047 int pred_rpo = i;
3048 FOR_EACH_EDGE (e, ei, bb->preds)
3049 {
3050 int pred = e->src->index;
3051 if ((e->flags & EDGE_DFS_BACK) || pred == ENTRY_BLOCK)
3052 continue;
3053
3054 live.merge (e->src, bb);
3055
3056 if (bb_rpo[pred] < pred_rpo)
3057 pred_rpo = bb_rpo[pred];
3058 }
3059
3060 /* Record the RPO number of the last visited block that needs
3061 live information from this block. */
3062 last_rpo[rpo[i]] = pred_rpo;
3063 }
3064 else
3065 live.clear_block (bb);
3066
3067 /* We can free all successors live bitmaps if all their
3068 predecessors have been visited already. */
3069 FOR_EACH_EDGE (e, ei, bb->succs)
3070 if (last_rpo[e->dest->index] == i)
3071 live.clear_block (e->dest);
3072 }
3073
3074 XDELETEVEC (rpo);
3075 XDELETEVEC (bb_rpo);
3076 XDELETEVEC (last_rpo);
3077 }
3078
3079 /* Create an ASSERT_EXPR for NAME and insert it in the location
3080 indicated by LOC. Return true if we made any edge insertions. */
3081
3082 bool
3083 vrp_insert::process_assert_insertions_for (tree name, assert_locus *loc)
3084 {
3085 /* Build the comparison expression NAME_i COMP_CODE VAL. */
3086 gimple *stmt;
3087 tree cond;
3088 gimple *assert_stmt;
3089 edge_iterator ei;
3090 edge e;
3091
3092 /* If we have X <=> X do not insert an assert expr for that. */
3093 if (loc->expr == loc->val)
3094 return false;
3095
3096 cond = build2 (loc->comp_code, boolean_type_node, loc->expr, loc->val);
3097 assert_stmt = build_assert_expr_for (cond, name);
3098 if (loc->e)
3099 {
3100 /* We have been asked to insert the assertion on an edge. This
3101 is used only by COND_EXPR and SWITCH_EXPR assertions. */
3102 gcc_checking_assert (gimple_code (gsi_stmt (loc->si)) == GIMPLE_COND
3103 || (gimple_code (gsi_stmt (loc->si))
3104 == GIMPLE_SWITCH));
3105
3106 gsi_insert_on_edge (loc->e, assert_stmt);
3107 return true;
3108 }
3109
3110 /* If the stmt iterator points at the end then this is an insertion
3111 at the beginning of a block. */
3112 if (gsi_end_p (loc->si))
3113 {
3114 gimple_stmt_iterator si = gsi_after_labels (loc->bb);
3115 gsi_insert_before (&si, assert_stmt, GSI_SAME_STMT);
3116 return false;
3117
3118 }
3119 /* Otherwise, we can insert right after LOC->SI iff the
3120 statement must not be the last statement in the block. */
3121 stmt = gsi_stmt (loc->si);
3122 if (!stmt_ends_bb_p (stmt))
3123 {
3124 gsi_insert_after (&loc->si, assert_stmt, GSI_SAME_STMT);
3125 return false;
3126 }
3127
3128 /* If STMT must be the last statement in BB, we can only insert new
3129 assertions on the non-abnormal edge out of BB. Note that since
3130 STMT is not control flow, there may only be one non-abnormal/eh edge
3131 out of BB. */
3132 FOR_EACH_EDGE (e, ei, loc->bb->succs)
3133 if (!(e->flags & (EDGE_ABNORMAL|EDGE_EH)))
3134 {
3135 gsi_insert_on_edge (e, assert_stmt);
3136 return true;
3137 }
3138
3139 gcc_unreachable ();
3140 }
3141
3142 /* Qsort helper for sorting assert locations. If stable is true, don't
3143 use iterative_hash_expr because it can be unstable for -fcompare-debug,
3144 on the other side some pointers might be NULL. */
3145
3146 template <bool stable>
3147 int
3148 vrp_insert::compare_assert_loc (const void *pa, const void *pb)
3149 {
3150 assert_locus * const a = *(assert_locus * const *)pa;
3151 assert_locus * const b = *(assert_locus * const *)pb;
3152
3153 /* If stable, some asserts might be optimized away already, sort
3154 them last. */
3155 if (stable)
3156 {
3157 if (a == NULL)
3158 return b != NULL;
3159 else if (b == NULL)
3160 return -1;
3161 }
3162
3163 if (a->e == NULL && b->e != NULL)
3164 return 1;
3165 else if (a->e != NULL && b->e == NULL)
3166 return -1;
3167
3168 /* After the above checks, we know that (a->e == NULL) == (b->e == NULL),
3169 no need to test both a->e and b->e. */
3170
3171 /* Sort after destination index. */
3172 if (a->e == NULL)
3173 ;
3174 else if (a->e->dest->index > b->e->dest->index)
3175 return 1;
3176 else if (a->e->dest->index < b->e->dest->index)
3177 return -1;
3178
3179 /* Sort after comp_code. */
3180 if (a->comp_code > b->comp_code)
3181 return 1;
3182 else if (a->comp_code < b->comp_code)
3183 return -1;
3184
3185 hashval_t ha, hb;
3186
3187 /* E.g. if a->val is ADDR_EXPR of a VAR_DECL, iterative_hash_expr
3188 uses DECL_UID of the VAR_DECL, so sorting might differ between
3189 -g and -g0. When doing the removal of redundant assert exprs
3190 and commonization to successors, this does not matter, but for
3191 the final sort needs to be stable. */
3192 if (stable)
3193 {
3194 ha = 0;
3195 hb = 0;
3196 }
3197 else
3198 {
3199 ha = iterative_hash_expr (a->expr, iterative_hash_expr (a->val, 0));
3200 hb = iterative_hash_expr (b->expr, iterative_hash_expr (b->val, 0));
3201 }
3202
3203 /* Break the tie using hashing and source/bb index. */
3204 if (ha == hb)
3205 return (a->e != NULL
3206 ? a->e->src->index - b->e->src->index
3207 : a->bb->index - b->bb->index);
3208 return ha > hb ? 1 : -1;
3209 }
3210
3211 /* Process all the insertions registered for every name N_i registered
3212 in NEED_ASSERT_FOR. The list of assertions to be inserted are
3213 found in ASSERTS_FOR[i]. */
3214
3215 void
3216 vrp_insert::process_assert_insertions ()
3217 {
3218 unsigned i;
3219 bitmap_iterator bi;
3220 bool update_edges_p = false;
3221 int num_asserts = 0;
3222
3223 if (dump_file && (dump_flags & TDF_DETAILS))
3224 dump (dump_file);
3225
3226 EXECUTE_IF_SET_IN_BITMAP (need_assert_for, 0, i, bi)
3227 {
3228 assert_locus *loc = asserts_for[i];
3229 gcc_assert (loc);
3230
3231 auto_vec<assert_locus *, 16> asserts;
3232 for (; loc; loc = loc->next)
3233 asserts.safe_push (loc);
3234 asserts.qsort (compare_assert_loc<false>);
3235
3236 /* Push down common asserts to successors and remove redundant ones. */
3237 unsigned ecnt = 0;
3238 assert_locus *common = NULL;
3239 unsigned commonj = 0;
3240 for (unsigned j = 0; j < asserts.length (); ++j)
3241 {
3242 loc = asserts[j];
3243 if (! loc->e)
3244 common = NULL;
3245 else if (! common
3246 || loc->e->dest != common->e->dest
3247 || loc->comp_code != common->comp_code
3248 || ! operand_equal_p (loc->val, common->val, 0)
3249 || ! operand_equal_p (loc->expr, common->expr, 0))
3250 {
3251 commonj = j;
3252 common = loc;
3253 ecnt = 1;
3254 }
3255 else if (loc->e == asserts[j-1]->e)
3256 {
3257 /* Remove duplicate asserts. */
3258 if (commonj == j - 1)
3259 {
3260 commonj = j;
3261 common = loc;
3262 }
3263 free (asserts[j-1]);
3264 asserts[j-1] = NULL;
3265 }
3266 else
3267 {
3268 ecnt++;
3269 if (EDGE_COUNT (common->e->dest->preds) == ecnt)
3270 {
3271 /* We have the same assertion on all incoming edges of a BB.
3272 Insert it at the beginning of that block. */
3273 loc->bb = loc->e->dest;
3274 loc->e = NULL;
3275 loc->si = gsi_none ();
3276 common = NULL;
3277 /* Clear asserts commoned. */
3278 for (; commonj != j; ++commonj)
3279 if (asserts[commonj])
3280 {
3281 free (asserts[commonj]);
3282 asserts[commonj] = NULL;
3283 }
3284 }
3285 }
3286 }
3287
3288 /* The asserts vector sorting above might be unstable for
3289 -fcompare-debug, sort again to ensure a stable sort. */
3290 asserts.qsort (compare_assert_loc<true>);
3291 for (unsigned j = 0; j < asserts.length (); ++j)
3292 {
3293 loc = asserts[j];
3294 if (! loc)
3295 break;
3296 update_edges_p |= process_assert_insertions_for (ssa_name (i), loc);
3297 num_asserts++;
3298 free (loc);
3299 }
3300 }
3301
3302 if (update_edges_p)
3303 gsi_commit_edge_inserts ();
3304
3305 statistics_counter_event (fun, "Number of ASSERT_EXPR expressions inserted",
3306 num_asserts);
3307 }
3308
3309
3310 /* Traverse the flowgraph looking for conditional jumps to insert range
3311 expressions. These range expressions are meant to provide information
3312 to optimizations that need to reason in terms of value ranges. They
3313 will not be expanded into RTL. For instance, given:
3314
3315 x = ...
3316 y = ...
3317 if (x < y)
3318 y = x - 2;
3319 else
3320 x = y + 3;
3321
3322 this pass will transform the code into:
3323
3324 x = ...
3325 y = ...
3326 if (x < y)
3327 {
3328 x = ASSERT_EXPR <x, x < y>
3329 y = x - 2
3330 }
3331 else
3332 {
3333 y = ASSERT_EXPR <y, x >= y>
3334 x = y + 3
3335 }
3336
3337 The idea is that once copy and constant propagation have run, other
3338 optimizations will be able to determine what ranges of values can 'x'
3339 take in different paths of the code, simply by checking the reaching
3340 definition of 'x'. */
3341
3342 void
3343 vrp_insert::insert_range_assertions (void)
3344 {
3345 need_assert_for = BITMAP_ALLOC (NULL);
3346 asserts_for = XCNEWVEC (assert_locus *, num_ssa_names);
3347
3348 calculate_dominance_info (CDI_DOMINATORS);
3349
3350 find_assert_locations ();
3351 if (!bitmap_empty_p (need_assert_for))
3352 {
3353 process_assert_insertions ();
3354 update_ssa (TODO_update_ssa_no_phi);
3355 }
3356
3357 if (dump_file && (dump_flags & TDF_DETAILS))
3358 {
3359 fprintf (dump_file, "\nSSA form after inserting ASSERT_EXPRs\n");
3360 dump_function_to_file (current_function_decl, dump_file, dump_flags);
3361 }
3362
3363 free (asserts_for);
3364 BITMAP_FREE (need_assert_for);
3365 }
3366
3367 class vrp_prop : public ssa_propagation_engine
3368 {
3369 public:
3370 enum ssa_prop_result visit_stmt (gimple *, edge *, tree *) FINAL OVERRIDE;
3371 enum ssa_prop_result visit_phi (gphi *) FINAL OVERRIDE;
3372
3373 struct function *fun;
3374
3375 void vrp_initialize (struct function *);
3376 void vrp_finalize (bool);
3377
3378 class vr_values vr_values;
3379
3380 private:
3381 /* Temporary delegator to minimize code churn. */
3382 const value_range_equiv *get_value_range (const_tree op)
3383 { return vr_values.get_value_range (op); }
3384 void set_def_to_varying (const_tree def)
3385 { vr_values.set_def_to_varying (def); }
3386 void set_defs_to_varying (gimple *stmt)
3387 { vr_values.set_defs_to_varying (stmt); }
3388 void extract_range_from_stmt (gimple *stmt, edge *taken_edge_p,
3389 tree *output_p, value_range_equiv *vr)
3390 { vr_values.extract_range_from_stmt (stmt, taken_edge_p, output_p, vr); }
3391 bool update_value_range (const_tree op, value_range_equiv *vr)
3392 { return vr_values.update_value_range (op, vr); }
3393 void extract_range_basic (value_range_equiv *vr, gimple *stmt)
3394 { vr_values.extract_range_basic (vr, stmt); }
3395 void extract_range_from_phi_node (gphi *phi, value_range_equiv *vr)
3396 { vr_values.extract_range_from_phi_node (phi, vr); }
3397 };
3398
3399 /* Return true if all imm uses of VAR are either in STMT, or
3400 feed (optionally through a chain of single imm uses) GIMPLE_COND
3401 in basic block COND_BB. */
3402
3403 static bool
3404 all_imm_uses_in_stmt_or_feed_cond (tree var, gimple *stmt, basic_block cond_bb)
3405 {
3406 use_operand_p use_p, use2_p;
3407 imm_use_iterator iter;
3408
3409 FOR_EACH_IMM_USE_FAST (use_p, iter, var)
3410 if (USE_STMT (use_p) != stmt)
3411 {
3412 gimple *use_stmt = USE_STMT (use_p), *use_stmt2;
3413 if (is_gimple_debug (use_stmt))
3414 continue;
3415 while (is_gimple_assign (use_stmt)
3416 && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
3417 && single_imm_use (gimple_assign_lhs (use_stmt),
3418 &use2_p, &use_stmt2))
3419 use_stmt = use_stmt2;
3420 if (gimple_code (use_stmt) != GIMPLE_COND
3421 || gimple_bb (use_stmt) != cond_bb)
3422 return false;
3423 }
3424 return true;
3425 }
3426
3427 /* Handle
3428 _4 = x_3 & 31;
3429 if (_4 != 0)
3430 goto <bb 6>;
3431 else
3432 goto <bb 7>;
3433 <bb 6>:
3434 __builtin_unreachable ();
3435 <bb 7>:
3436 x_5 = ASSERT_EXPR <x_3, ...>;
3437 If x_3 has no other immediate uses (checked by caller),
3438 var is the x_3 var from ASSERT_EXPR, we can clear low 5 bits
3439 from the non-zero bitmask. */
3440
3441 void
3442 maybe_set_nonzero_bits (edge e, tree var)
3443 {
3444 basic_block cond_bb = e->src;
3445 gimple *stmt = last_stmt (cond_bb);
3446 tree cst;
3447
3448 if (stmt == NULL
3449 || gimple_code (stmt) != GIMPLE_COND
3450 || gimple_cond_code (stmt) != ((e->flags & EDGE_TRUE_VALUE)
3451 ? EQ_EXPR : NE_EXPR)
3452 || TREE_CODE (gimple_cond_lhs (stmt)) != SSA_NAME
3453 || !integer_zerop (gimple_cond_rhs (stmt)))
3454 return;
3455
3456 stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt));
3457 if (!is_gimple_assign (stmt)
3458 || gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
3459 || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
3460 return;
3461 if (gimple_assign_rhs1 (stmt) != var)
3462 {
3463 gimple *stmt2;
3464
3465 if (TREE_CODE (gimple_assign_rhs1 (stmt)) != SSA_NAME)
3466 return;
3467 stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
3468 if (!gimple_assign_cast_p (stmt2)
3469 || gimple_assign_rhs1 (stmt2) != var
3470 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt2))
3471 || (TYPE_PRECISION (TREE_TYPE (gimple_assign_rhs1 (stmt)))
3472 != TYPE_PRECISION (TREE_TYPE (var))))
3473 return;
3474 }
3475 cst = gimple_assign_rhs2 (stmt);
3476 set_nonzero_bits (var, wi::bit_and_not (get_nonzero_bits (var),
3477 wi::to_wide (cst)));
3478 }
3479
3480 /* Convert range assertion expressions into the implied copies and
3481 copy propagate away the copies. Doing the trivial copy propagation
3482 here avoids the need to run the full copy propagation pass after
3483 VRP.
3484
3485 FIXME, this will eventually lead to copy propagation removing the
3486 names that had useful range information attached to them. For
3487 instance, if we had the assertion N_i = ASSERT_EXPR <N_j, N_j > 3>,
3488 then N_i will have the range [3, +INF].
3489
3490 However, by converting the assertion into the implied copy
3491 operation N_i = N_j, we will then copy-propagate N_j into the uses
3492 of N_i and lose the range information. We may want to hold on to
3493 ASSERT_EXPRs a little while longer as the ranges could be used in
3494 things like jump threading.
3495
3496 The problem with keeping ASSERT_EXPRs around is that passes after
3497 VRP need to handle them appropriately.
3498
3499 Another approach would be to make the range information a first
3500 class property of the SSA_NAME so that it can be queried from
3501 any pass. This is made somewhat more complex by the need for
3502 multiple ranges to be associated with one SSA_NAME. */
3503
3504 void
3505 vrp_insert::remove_range_assertions ()
3506 {
3507 basic_block bb;
3508 gimple_stmt_iterator si;
3509 /* 1 if looking at ASSERT_EXPRs immediately at the beginning of
3510 a basic block preceeded by GIMPLE_COND branching to it and
3511 __builtin_trap, -1 if not yet checked, 0 otherwise. */
3512 int is_unreachable;
3513
3514 /* Note that the BSI iterator bump happens at the bottom of the
3515 loop and no bump is necessary if we're removing the statement
3516 referenced by the current BSI. */
3517 FOR_EACH_BB_FN (bb, fun)
3518 for (si = gsi_after_labels (bb), is_unreachable = -1; !gsi_end_p (si);)
3519 {
3520 gimple *stmt = gsi_stmt (si);
3521
3522 if (is_gimple_assign (stmt)
3523 && gimple_assign_rhs_code (stmt) == ASSERT_EXPR)
3524 {
3525 tree lhs = gimple_assign_lhs (stmt);
3526 tree rhs = gimple_assign_rhs1 (stmt);
3527 tree var;
3528
3529 var = ASSERT_EXPR_VAR (rhs);
3530
3531 if (TREE_CODE (var) == SSA_NAME
3532 && !POINTER_TYPE_P (TREE_TYPE (lhs))
3533 && SSA_NAME_RANGE_INFO (lhs))
3534 {
3535 if (is_unreachable == -1)
3536 {
3537 is_unreachable = 0;
3538 if (single_pred_p (bb)
3539 && assert_unreachable_fallthru_edge_p
3540 (single_pred_edge (bb)))
3541 is_unreachable = 1;
3542 }
3543 /* Handle
3544 if (x_7 >= 10 && x_7 < 20)
3545 __builtin_unreachable ();
3546 x_8 = ASSERT_EXPR <x_7, ...>;
3547 if the only uses of x_7 are in the ASSERT_EXPR and
3548 in the condition. In that case, we can copy the
3549 range info from x_8 computed in this pass also
3550 for x_7. */
3551 if (is_unreachable
3552 && all_imm_uses_in_stmt_or_feed_cond (var, stmt,
3553 single_pred (bb)))
3554 {
3555 set_range_info (var, SSA_NAME_RANGE_TYPE (lhs),
3556 SSA_NAME_RANGE_INFO (lhs)->get_min (),
3557 SSA_NAME_RANGE_INFO (lhs)->get_max ());
3558 maybe_set_nonzero_bits (single_pred_edge (bb), var);
3559 }
3560 }
3561
3562 /* Propagate the RHS into every use of the LHS. For SSA names
3563 also propagate abnormals as it merely restores the original
3564 IL in this case (an replace_uses_by would assert). */
3565 if (TREE_CODE (var) == SSA_NAME)
3566 {
3567 imm_use_iterator iter;
3568 use_operand_p use_p;
3569 gimple *use_stmt;
3570 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
3571 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
3572 SET_USE (use_p, var);
3573 }
3574 else
3575 replace_uses_by (lhs, var);
3576
3577 /* And finally, remove the copy, it is not needed. */
3578 gsi_remove (&si, true);
3579 release_defs (stmt);
3580 }
3581 else
3582 {
3583 if (!is_gimple_debug (gsi_stmt (si)))
3584 is_unreachable = 0;
3585 gsi_next (&si);
3586 }
3587 }
3588 }
3589
3590 /* Return true if STMT is interesting for VRP. */
3591
3592 bool
3593 stmt_interesting_for_vrp (gimple *stmt)
3594 {
3595 if (gimple_code (stmt) == GIMPLE_PHI)
3596 {
3597 tree res = gimple_phi_result (stmt);
3598 return (!virtual_operand_p (res)
3599 && (INTEGRAL_TYPE_P (TREE_TYPE (res))
3600 || POINTER_TYPE_P (TREE_TYPE (res))));
3601 }
3602 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
3603 {
3604 tree lhs = gimple_get_lhs (stmt);
3605
3606 /* In general, assignments with virtual operands are not useful
3607 for deriving ranges, with the obvious exception of calls to
3608 builtin functions. */
3609 if (lhs && TREE_CODE (lhs) == SSA_NAME
3610 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
3611 || POINTER_TYPE_P (TREE_TYPE (lhs)))
3612 && (is_gimple_call (stmt)
3613 || !gimple_vuse (stmt)))
3614 return true;
3615 else if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
3616 switch (gimple_call_internal_fn (stmt))
3617 {
3618 case IFN_ADD_OVERFLOW:
3619 case IFN_SUB_OVERFLOW:
3620 case IFN_MUL_OVERFLOW:
3621 case IFN_ATOMIC_COMPARE_EXCHANGE:
3622 /* These internal calls return _Complex integer type,
3623 but are interesting to VRP nevertheless. */
3624 if (lhs && TREE_CODE (lhs) == SSA_NAME)
3625 return true;
3626 break;
3627 default:
3628 break;
3629 }
3630 }
3631 else if (gimple_code (stmt) == GIMPLE_COND
3632 || gimple_code (stmt) == GIMPLE_SWITCH)
3633 return true;
3634
3635 return false;
3636 }
3637
3638 /* Initialization required by ssa_propagate engine. */
3639
3640 void
3641 vrp_prop::vrp_initialize (struct function *fn)
3642 {
3643 basic_block bb;
3644 fun = fn;
3645
3646 FOR_EACH_BB_FN (bb, fun)
3647 {
3648 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
3649 gsi_next (&si))
3650 {
3651 gphi *phi = si.phi ();
3652 if (!stmt_interesting_for_vrp (phi))
3653 {
3654 tree lhs = PHI_RESULT (phi);
3655 set_def_to_varying (lhs);
3656 prop_set_simulate_again (phi, false);
3657 }
3658 else
3659 prop_set_simulate_again (phi, true);
3660 }
3661
3662 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
3663 gsi_next (&si))
3664 {
3665 gimple *stmt = gsi_stmt (si);
3666
3667 /* If the statement is a control insn, then we do not
3668 want to avoid simulating the statement once. Failure
3669 to do so means that those edges will never get added. */
3670 if (stmt_ends_bb_p (stmt))
3671 prop_set_simulate_again (stmt, true);
3672 else if (!stmt_interesting_for_vrp (stmt))
3673 {
3674 set_defs_to_varying (stmt);
3675 prop_set_simulate_again (stmt, false);
3676 }
3677 else
3678 prop_set_simulate_again (stmt, true);
3679 }
3680 }
3681 }
3682
3683 /* Searches the case label vector VEC for the index *IDX of the CASE_LABEL
3684 that includes the value VAL. The search is restricted to the range
3685 [START_IDX, n - 1] where n is the size of VEC.
3686
3687 If there is a CASE_LABEL for VAL, its index is placed in IDX and true is
3688 returned.
3689
3690 If there is no CASE_LABEL for VAL and there is one that is larger than VAL,
3691 it is placed in IDX and false is returned.
3692
3693 If VAL is larger than any CASE_LABEL, n is placed on IDX and false is
3694 returned. */
3695
3696 bool
3697 find_case_label_index (gswitch *stmt, size_t start_idx, tree val, size_t *idx)
3698 {
3699 size_t n = gimple_switch_num_labels (stmt);
3700 size_t low, high;
3701
3702 /* Find case label for minimum of the value range or the next one.
3703 At each iteration we are searching in [low, high - 1]. */
3704
3705 for (low = start_idx, high = n; high != low; )
3706 {
3707 tree t;
3708 int cmp;
3709 /* Note that i != high, so we never ask for n. */
3710 size_t i = (high + low) / 2;
3711 t = gimple_switch_label (stmt, i);
3712
3713 /* Cache the result of comparing CASE_LOW and val. */
3714 cmp = tree_int_cst_compare (CASE_LOW (t), val);
3715
3716 if (cmp == 0)
3717 {
3718 /* Ranges cannot be empty. */
3719 *idx = i;
3720 return true;
3721 }
3722 else if (cmp > 0)
3723 high = i;
3724 else
3725 {
3726 low = i + 1;
3727 if (CASE_HIGH (t) != NULL
3728 && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
3729 {
3730 *idx = i;
3731 return true;
3732 }
3733 }
3734 }
3735
3736 *idx = high;
3737 return false;
3738 }
3739
3740 /* Searches the case label vector VEC for the range of CASE_LABELs that is used
3741 for values between MIN and MAX. The first index is placed in MIN_IDX. The
3742 last index is placed in MAX_IDX. If the range of CASE_LABELs is empty
3743 then MAX_IDX < MIN_IDX.
3744 Returns true if the default label is not needed. */
3745
3746 bool
3747 find_case_label_range (gswitch *stmt, tree min, tree max, size_t *min_idx,
3748 size_t *max_idx)
3749 {
3750 size_t i, j;
3751 bool min_take_default = !find_case_label_index (stmt, 1, min, &i);
3752 bool max_take_default = !find_case_label_index (stmt, i, max, &j);
3753
3754 if (i == j
3755 && min_take_default
3756 && max_take_default)
3757 {
3758 /* Only the default case label reached.
3759 Return an empty range. */
3760 *min_idx = 1;
3761 *max_idx = 0;
3762 return false;
3763 }
3764 else
3765 {
3766 bool take_default = min_take_default || max_take_default;
3767 tree low, high;
3768 size_t k;
3769
3770 if (max_take_default)
3771 j--;
3772
3773 /* If the case label range is continuous, we do not need
3774 the default case label. Verify that. */
3775 high = CASE_LOW (gimple_switch_label (stmt, i));
3776 if (CASE_HIGH (gimple_switch_label (stmt, i)))
3777 high = CASE_HIGH (gimple_switch_label (stmt, i));
3778 for (k = i + 1; k <= j; ++k)
3779 {
3780 low = CASE_LOW (gimple_switch_label (stmt, k));
3781 if (!integer_onep (int_const_binop (MINUS_EXPR, low, high)))
3782 {
3783 take_default = true;
3784 break;
3785 }
3786 high = low;
3787 if (CASE_HIGH (gimple_switch_label (stmt, k)))
3788 high = CASE_HIGH (gimple_switch_label (stmt, k));
3789 }
3790
3791 *min_idx = i;
3792 *max_idx = j;
3793 return !take_default;
3794 }
3795 }
3796
3797 /* Evaluate statement STMT. If the statement produces a useful range,
3798 return SSA_PROP_INTERESTING and record the SSA name with the
3799 interesting range into *OUTPUT_P.
3800
3801 If STMT is a conditional branch and we can determine its truth
3802 value, the taken edge is recorded in *TAKEN_EDGE_P.
3803
3804 If STMT produces a varying value, return SSA_PROP_VARYING. */
3805
3806 enum ssa_prop_result
3807 vrp_prop::visit_stmt (gimple *stmt, edge *taken_edge_p, tree *output_p)
3808 {
3809 tree lhs = gimple_get_lhs (stmt);
3810 value_range_equiv vr;
3811 extract_range_from_stmt (stmt, taken_edge_p, output_p, &vr);
3812
3813 if (*output_p)
3814 {
3815 if (update_value_range (*output_p, &vr))
3816 {
3817 if (dump_file && (dump_flags & TDF_DETAILS))
3818 {
3819 fprintf (dump_file, "Found new range for ");
3820 print_generic_expr (dump_file, *output_p);
3821 fprintf (dump_file, ": ");
3822 dump_value_range (dump_file, &vr);
3823 fprintf (dump_file, "\n");
3824 }
3825
3826 if (vr.varying_p ())
3827 return SSA_PROP_VARYING;
3828
3829 return SSA_PROP_INTERESTING;
3830 }
3831 return SSA_PROP_NOT_INTERESTING;
3832 }
3833
3834 if (is_gimple_call (stmt) && gimple_call_internal_p (stmt))
3835 switch (gimple_call_internal_fn (stmt))
3836 {
3837 case IFN_ADD_OVERFLOW:
3838 case IFN_SUB_OVERFLOW:
3839 case IFN_MUL_OVERFLOW:
3840 case IFN_ATOMIC_COMPARE_EXCHANGE:
3841 /* These internal calls return _Complex integer type,
3842 which VRP does not track, but the immediate uses
3843 thereof might be interesting. */
3844 if (lhs && TREE_CODE (lhs) == SSA_NAME)
3845 {
3846 imm_use_iterator iter;
3847 use_operand_p use_p;
3848 enum ssa_prop_result res = SSA_PROP_VARYING;
3849
3850 set_def_to_varying (lhs);
3851
3852 FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
3853 {
3854 gimple *use_stmt = USE_STMT (use_p);
3855 if (!is_gimple_assign (use_stmt))
3856 continue;
3857 enum tree_code rhs_code = gimple_assign_rhs_code (use_stmt);
3858 if (rhs_code != REALPART_EXPR && rhs_code != IMAGPART_EXPR)
3859 continue;
3860 tree rhs1 = gimple_assign_rhs1 (use_stmt);
3861 tree use_lhs = gimple_assign_lhs (use_stmt);
3862 if (TREE_CODE (rhs1) != rhs_code
3863 || TREE_OPERAND (rhs1, 0) != lhs
3864 || TREE_CODE (use_lhs) != SSA_NAME
3865 || !stmt_interesting_for_vrp (use_stmt)
3866 || (!INTEGRAL_TYPE_P (TREE_TYPE (use_lhs))
3867 || !TYPE_MIN_VALUE (TREE_TYPE (use_lhs))
3868 || !TYPE_MAX_VALUE (TREE_TYPE (use_lhs))))
3869 continue;
3870
3871 /* If there is a change in the value range for any of the
3872 REALPART_EXPR/IMAGPART_EXPR immediate uses, return
3873 SSA_PROP_INTERESTING. If there are any REALPART_EXPR
3874 or IMAGPART_EXPR immediate uses, but none of them have
3875 a change in their value ranges, return
3876 SSA_PROP_NOT_INTERESTING. If there are no
3877 {REAL,IMAG}PART_EXPR uses at all,
3878 return SSA_PROP_VARYING. */
3879 value_range_equiv new_vr;
3880 extract_range_basic (&new_vr, use_stmt);
3881 const value_range_equiv *old_vr = get_value_range (use_lhs);
3882 if (!old_vr->equal_p (new_vr, /*ignore_equivs=*/false))
3883 res = SSA_PROP_INTERESTING;
3884 else
3885 res = SSA_PROP_NOT_INTERESTING;
3886 new_vr.equiv_clear ();
3887 if (res == SSA_PROP_INTERESTING)
3888 {
3889 *output_p = lhs;
3890 return res;
3891 }
3892 }
3893
3894 return res;
3895 }
3896 break;
3897 default:
3898 break;
3899 }
3900
3901 /* All other statements produce nothing of interest for VRP, so mark
3902 their outputs varying and prevent further simulation. */
3903 set_defs_to_varying (stmt);
3904
3905 return (*taken_edge_p) ? SSA_PROP_INTERESTING : SSA_PROP_VARYING;
3906 }
3907
3908 /* Visit all arguments for PHI node PHI that flow through executable
3909 edges. If a valid value range can be derived from all the incoming
3910 value ranges, set a new range for the LHS of PHI. */
3911
3912 enum ssa_prop_result
3913 vrp_prop::visit_phi (gphi *phi)
3914 {
3915 tree lhs = PHI_RESULT (phi);
3916 value_range_equiv vr_result;
3917 extract_range_from_phi_node (phi, &vr_result);
3918 if (update_value_range (lhs, &vr_result))
3919 {
3920 if (dump_file && (dump_flags & TDF_DETAILS))
3921 {
3922 fprintf (dump_file, "Found new range for ");
3923 print_generic_expr (dump_file, lhs);
3924 fprintf (dump_file, ": ");
3925 dump_value_range (dump_file, &vr_result);
3926 fprintf (dump_file, "\n");
3927 }
3928
3929 if (vr_result.varying_p ())
3930 return SSA_PROP_VARYING;
3931
3932 return SSA_PROP_INTERESTING;
3933 }
3934
3935 /* Nothing changed, don't add outgoing edges. */
3936 return SSA_PROP_NOT_INTERESTING;
3937 }
3938
3939 class vrp_folder : public substitute_and_fold_engine
3940 {
3941 public:
3942 vrp_folder () : substitute_and_fold_engine (/* Fold all stmts. */ true) { }
3943 tree get_value (tree, gimple *stmt) FINAL OVERRIDE;
3944 bool fold_stmt (gimple_stmt_iterator *) FINAL OVERRIDE;
3945
3946 class vr_values *vr_values;
3947
3948 private:
3949 bool fold_predicate_in (gimple_stmt_iterator *);
3950 /* Delegators. */
3951 tree vrp_evaluate_conditional (tree_code code, tree op0,
3952 tree op1, gimple *stmt)
3953 { return vr_values->vrp_evaluate_conditional (code, op0, op1, stmt); }
3954 bool simplify_stmt_using_ranges (gimple_stmt_iterator *gsi)
3955 { return vr_values->simplify_stmt_using_ranges (gsi); }
3956 tree op_with_constant_singleton_value_range (tree op)
3957 { return vr_values->op_with_constant_singleton_value_range (op); }
3958 };
3959
3960 /* If the statement pointed by SI has a predicate whose value can be
3961 computed using the value range information computed by VRP, compute
3962 its value and return true. Otherwise, return false. */
3963
3964 bool
3965 vrp_folder::fold_predicate_in (gimple_stmt_iterator *si)
3966 {
3967 bool assignment_p = false;
3968 tree val;
3969 gimple *stmt = gsi_stmt (*si);
3970
3971 if (is_gimple_assign (stmt)
3972 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
3973 {
3974 assignment_p = true;
3975 val = vrp_evaluate_conditional (gimple_assign_rhs_code (stmt),
3976 gimple_assign_rhs1 (stmt),
3977 gimple_assign_rhs2 (stmt),
3978 stmt);
3979 }
3980 else if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
3981 val = vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
3982 gimple_cond_lhs (cond_stmt),
3983 gimple_cond_rhs (cond_stmt),
3984 stmt);
3985 else
3986 return false;
3987
3988 if (val)
3989 {
3990 if (assignment_p)
3991 val = fold_convert (gimple_expr_type (stmt), val);
3992
3993 if (dump_file)
3994 {
3995 fprintf (dump_file, "Folding predicate ");
3996 print_gimple_expr (dump_file, stmt, 0);
3997 fprintf (dump_file, " to ");
3998 print_generic_expr (dump_file, val);
3999 fprintf (dump_file, "\n");
4000 }
4001
4002 if (is_gimple_assign (stmt))
4003 gimple_assign_set_rhs_from_tree (si, val);
4004 else
4005 {
4006 gcc_assert (gimple_code (stmt) == GIMPLE_COND);
4007 gcond *cond_stmt = as_a <gcond *> (stmt);
4008 if (integer_zerop (val))
4009 gimple_cond_make_false (cond_stmt);
4010 else if (integer_onep (val))
4011 gimple_cond_make_true (cond_stmt);
4012 else
4013 gcc_unreachable ();
4014 }
4015
4016 return true;
4017 }
4018
4019 return false;
4020 }
4021
4022 /* Callback for substitute_and_fold folding the stmt at *SI. */
4023
4024 bool
4025 vrp_folder::fold_stmt (gimple_stmt_iterator *si)
4026 {
4027 if (fold_predicate_in (si))
4028 return true;
4029
4030 return simplify_stmt_using_ranges (si);
4031 }
4032
4033 /* If OP has a value range with a single constant value return that,
4034 otherwise return NULL_TREE. This returns OP itself if OP is a
4035 constant.
4036
4037 Implemented as a pure wrapper right now, but this will change. */
4038
4039 tree
4040 vrp_folder::get_value (tree op, gimple *stmt ATTRIBUTE_UNUSED)
4041 {
4042 return op_with_constant_singleton_value_range (op);
4043 }
4044
4045 /* Return the LHS of any ASSERT_EXPR where OP appears as the first
4046 argument to the ASSERT_EXPR and in which the ASSERT_EXPR dominates
4047 BB. If no such ASSERT_EXPR is found, return OP. */
4048
4049 static tree
4050 lhs_of_dominating_assert (tree op, basic_block bb, gimple *stmt)
4051 {
4052 imm_use_iterator imm_iter;
4053 gimple *use_stmt;
4054 use_operand_p use_p;
4055
4056 if (TREE_CODE (op) == SSA_NAME)
4057 {
4058 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, op)
4059 {
4060 use_stmt = USE_STMT (use_p);
4061 if (use_stmt != stmt
4062 && gimple_assign_single_p (use_stmt)
4063 && TREE_CODE (gimple_assign_rhs1 (use_stmt)) == ASSERT_EXPR
4064 && TREE_OPERAND (gimple_assign_rhs1 (use_stmt), 0) == op
4065 && dominated_by_p (CDI_DOMINATORS, bb, gimple_bb (use_stmt)))
4066 return gimple_assign_lhs (use_stmt);
4067 }
4068 }
4069 return op;
4070 }
4071
4072 /* A hack. */
4073 static class vr_values *x_vr_values;
4074
4075 /* A trivial wrapper so that we can present the generic jump threading
4076 code with a simple API for simplifying statements. STMT is the
4077 statement we want to simplify, WITHIN_STMT provides the location
4078 for any overflow warnings. */
4079
4080 static tree
4081 simplify_stmt_for_jump_threading (gimple *stmt, gimple *within_stmt,
4082 class avail_exprs_stack *avail_exprs_stack ATTRIBUTE_UNUSED,
4083 basic_block bb)
4084 {
4085 /* First see if the conditional is in the hash table. */
4086 tree cached_lhs = avail_exprs_stack->lookup_avail_expr (stmt, false, true);
4087 if (cached_lhs && is_gimple_min_invariant (cached_lhs))
4088 return cached_lhs;
4089
4090 vr_values *vr_values = x_vr_values;
4091 if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
4092 {
4093 tree op0 = gimple_cond_lhs (cond_stmt);
4094 op0 = lhs_of_dominating_assert (op0, bb, stmt);
4095
4096 tree op1 = gimple_cond_rhs (cond_stmt);
4097 op1 = lhs_of_dominating_assert (op1, bb, stmt);
4098
4099 return vr_values->vrp_evaluate_conditional (gimple_cond_code (cond_stmt),
4100 op0, op1, within_stmt);
4101 }
4102
4103 /* We simplify a switch statement by trying to determine which case label
4104 will be taken. If we are successful then we return the corresponding
4105 CASE_LABEL_EXPR. */
4106 if (gswitch *switch_stmt = dyn_cast <gswitch *> (stmt))
4107 {
4108 tree op = gimple_switch_index (switch_stmt);
4109 if (TREE_CODE (op) != SSA_NAME)
4110 return NULL_TREE;
4111
4112 op = lhs_of_dominating_assert (op, bb, stmt);
4113
4114 const value_range_equiv *vr = vr_values->get_value_range (op);
4115 if (vr->undefined_p ()
4116 || vr->varying_p ()
4117 || vr->symbolic_p ())
4118 return NULL_TREE;
4119
4120 if (vr->kind () == VR_RANGE)
4121 {
4122 size_t i, j;
4123 /* Get the range of labels that contain a part of the operand's
4124 value range. */
4125 find_case_label_range (switch_stmt, vr->min (), vr->max (), &i, &j);
4126
4127 /* Is there only one such label? */
4128 if (i == j)
4129 {
4130 tree label = gimple_switch_label (switch_stmt, i);
4131
4132 /* The i'th label will be taken only if the value range of the
4133 operand is entirely within the bounds of this label. */
4134 if (CASE_HIGH (label) != NULL_TREE
4135 ? (tree_int_cst_compare (CASE_LOW (label), vr->min ()) <= 0
4136 && tree_int_cst_compare (CASE_HIGH (label),
4137 vr->max ()) >= 0)
4138 : (tree_int_cst_equal (CASE_LOW (label), vr->min ())
4139 && tree_int_cst_equal (vr->min (), vr->max ())))
4140 return label;
4141 }
4142
4143 /* If there are no such labels then the default label will be
4144 taken. */
4145 if (i > j)
4146 return gimple_switch_label (switch_stmt, 0);
4147 }
4148
4149 if (vr->kind () == VR_ANTI_RANGE)
4150 {
4151 unsigned n = gimple_switch_num_labels (switch_stmt);
4152 tree min_label = gimple_switch_label (switch_stmt, 1);
4153 tree max_label = gimple_switch_label (switch_stmt, n - 1);
4154
4155 /* The default label will be taken only if the anti-range of the
4156 operand is entirely outside the bounds of all the (non-default)
4157 case labels. */
4158 if (tree_int_cst_compare (vr->min (), CASE_LOW (min_label)) <= 0
4159 && (CASE_HIGH (max_label) != NULL_TREE
4160 ? tree_int_cst_compare (vr->max (),
4161 CASE_HIGH (max_label)) >= 0
4162 : tree_int_cst_compare (vr->max (),
4163 CASE_LOW (max_label)) >= 0))
4164 return gimple_switch_label (switch_stmt, 0);
4165 }
4166
4167 return NULL_TREE;
4168 }
4169
4170 if (gassign *assign_stmt = dyn_cast <gassign *> (stmt))
4171 {
4172 tree lhs = gimple_assign_lhs (assign_stmt);
4173 if (TREE_CODE (lhs) == SSA_NAME
4174 && (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
4175 || POINTER_TYPE_P (TREE_TYPE (lhs)))
4176 && stmt_interesting_for_vrp (stmt))
4177 {
4178 edge dummy_e;
4179 tree dummy_tree;
4180 value_range_equiv new_vr;
4181 vr_values->extract_range_from_stmt (stmt, &dummy_e,
4182 &dummy_tree, &new_vr);
4183 tree singleton;
4184 if (new_vr.singleton_p (&singleton))
4185 return singleton;
4186 }
4187 }
4188
4189 return NULL_TREE;
4190 }
4191
4192 class vrp_dom_walker : public dom_walker
4193 {
4194 public:
4195 vrp_dom_walker (cdi_direction direction,
4196 class const_and_copies *const_and_copies,
4197 class avail_exprs_stack *avail_exprs_stack)
4198 : dom_walker (direction, REACHABLE_BLOCKS),
4199 m_const_and_copies (const_and_copies),
4200 m_avail_exprs_stack (avail_exprs_stack),
4201 m_dummy_cond (NULL) {}
4202
4203 virtual edge before_dom_children (basic_block);
4204 virtual void after_dom_children (basic_block);
4205
4206 class vr_values *vr_values;
4207
4208 private:
4209 class const_and_copies *m_const_and_copies;
4210 class avail_exprs_stack *m_avail_exprs_stack;
4211
4212 gcond *m_dummy_cond;
4213
4214 };
4215
4216 /* Called before processing dominator children of BB. We want to look
4217 at ASSERT_EXPRs and record information from them in the appropriate
4218 tables.
4219
4220 We could look at other statements here. It's not seen as likely
4221 to significantly increase the jump threads we discover. */
4222
4223 edge
4224 vrp_dom_walker::before_dom_children (basic_block bb)
4225 {
4226 gimple_stmt_iterator gsi;
4227
4228 m_avail_exprs_stack->push_marker ();
4229 m_const_and_copies->push_marker ();
4230 for (gsi = gsi_start_nondebug_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4231 {
4232 gimple *stmt = gsi_stmt (gsi);
4233 if (gimple_assign_single_p (stmt)
4234 && TREE_CODE (gimple_assign_rhs1 (stmt)) == ASSERT_EXPR)
4235 {
4236 tree rhs1 = gimple_assign_rhs1 (stmt);
4237 tree cond = TREE_OPERAND (rhs1, 1);
4238 tree inverted = invert_truthvalue (cond);
4239 vec<cond_equivalence> p;
4240 p.create (3);
4241 record_conditions (&p, cond, inverted);
4242 for (unsigned int i = 0; i < p.length (); i++)
4243 m_avail_exprs_stack->record_cond (&p[i]);
4244
4245 tree lhs = gimple_assign_lhs (stmt);
4246 m_const_and_copies->record_const_or_copy (lhs,
4247 TREE_OPERAND (rhs1, 0));
4248 p.release ();
4249 continue;
4250 }
4251 break;
4252 }
4253 return NULL;
4254 }
4255
4256 /* Called after processing dominator children of BB. This is where we
4257 actually call into the threader. */
4258 void
4259 vrp_dom_walker::after_dom_children (basic_block bb)
4260 {
4261 if (!m_dummy_cond)
4262 m_dummy_cond = gimple_build_cond (NE_EXPR,
4263 integer_zero_node, integer_zero_node,
4264 NULL, NULL);
4265
4266 x_vr_values = vr_values;
4267 thread_outgoing_edges (bb, m_dummy_cond, m_const_and_copies,
4268 m_avail_exprs_stack, NULL,
4269 simplify_stmt_for_jump_threading);
4270 x_vr_values = NULL;
4271
4272 m_avail_exprs_stack->pop_to_marker ();
4273 m_const_and_copies->pop_to_marker ();
4274 }
4275
4276 /* Blocks which have more than one predecessor and more than
4277 one successor present jump threading opportunities, i.e.,
4278 when the block is reached from a specific predecessor, we
4279 may be able to determine which of the outgoing edges will
4280 be traversed. When this optimization applies, we are able
4281 to avoid conditionals at runtime and we may expose secondary
4282 optimization opportunities.
4283
4284 This routine is effectively a driver for the generic jump
4285 threading code. It basically just presents the generic code
4286 with edges that may be suitable for jump threading.
4287
4288 Unlike DOM, we do not iterate VRP if jump threading was successful.
4289 While iterating may expose new opportunities for VRP, it is expected
4290 those opportunities would be very limited and the compile time cost
4291 to expose those opportunities would be significant.
4292
4293 As jump threading opportunities are discovered, they are registered
4294 for later realization. */
4295
4296 static void
4297 identify_jump_threads (struct function *fun, class vr_values *vr_values)
4298 {
4299 /* Ugh. When substituting values earlier in this pass we can
4300 wipe the dominance information. So rebuild the dominator
4301 information as we need it within the jump threading code. */
4302 calculate_dominance_info (CDI_DOMINATORS);
4303
4304 /* We do not allow VRP information to be used for jump threading
4305 across a back edge in the CFG. Otherwise it becomes too
4306 difficult to avoid eliminating loop exit tests. Of course
4307 EDGE_DFS_BACK is not accurate at this time so we have to
4308 recompute it. */
4309 mark_dfs_back_edges ();
4310
4311 /* Allocate our unwinder stack to unwind any temporary equivalences
4312 that might be recorded. */
4313 const_and_copies *equiv_stack = new const_and_copies ();
4314
4315 hash_table<expr_elt_hasher> *avail_exprs
4316 = new hash_table<expr_elt_hasher> (1024);
4317 avail_exprs_stack *avail_exprs_stack
4318 = new class avail_exprs_stack (avail_exprs);
4319
4320 vrp_dom_walker walker (CDI_DOMINATORS, equiv_stack, avail_exprs_stack);
4321 walker.vr_values = vr_values;
4322 walker.walk (fun->cfg->x_entry_block_ptr);
4323
4324 /* We do not actually update the CFG or SSA graphs at this point as
4325 ASSERT_EXPRs are still in the IL and cfg cleanup code does not yet
4326 handle ASSERT_EXPRs gracefully. */
4327 delete equiv_stack;
4328 delete avail_exprs;
4329 delete avail_exprs_stack;
4330 }
4331
4332 /* Traverse all the blocks folding conditionals with known ranges. */
4333
4334 void
4335 vrp_prop::vrp_finalize (bool warn_array_bounds_p)
4336 {
4337 size_t i;
4338
4339 /* We have completed propagating through the lattice. */
4340 vr_values.set_lattice_propagation_complete ();
4341
4342 if (dump_file)
4343 {
4344 fprintf (dump_file, "\nValue ranges after VRP:\n\n");
4345 vr_values.dump_all_value_ranges (dump_file);
4346 fprintf (dump_file, "\n");
4347 }
4348
4349 /* Set value range to non pointer SSA_NAMEs. */
4350 for (i = 0; i < num_ssa_names; i++)
4351 {
4352 tree name = ssa_name (i);
4353 if (!name)
4354 continue;
4355
4356 const value_range_equiv *vr = get_value_range (name);
4357 if (!name || !vr->constant_p ())
4358 continue;
4359
4360 if (POINTER_TYPE_P (TREE_TYPE (name))
4361 && range_includes_zero_p (vr) == 0)
4362 set_ptr_nonnull (name);
4363 else if (!POINTER_TYPE_P (TREE_TYPE (name)))
4364 set_range_info (name, *vr);
4365 }
4366
4367 /* If we're checking array refs, we want to merge information on
4368 the executability of each edge between vrp_folder and the
4369 check_array_bounds_dom_walker: each can clear the
4370 EDGE_EXECUTABLE flag on edges, in different ways.
4371
4372 Hence, if we're going to call check_all_array_refs, set
4373 the flag on every edge now, rather than in
4374 check_array_bounds_dom_walker's ctor; vrp_folder may clear
4375 it from some edges. */
4376 if (warn_array_bounds && warn_array_bounds_p)
4377 set_all_edges_as_executable (fun);
4378
4379 class vrp_folder vrp_folder;
4380 vrp_folder.vr_values = &vr_values;
4381 vrp_folder.substitute_and_fold ();
4382
4383 if (warn_array_bounds && warn_array_bounds_p)
4384 {
4385 array_bounds_checker array_checker (fun, &vr_values);
4386 array_checker.check ();
4387 }
4388 }
4389
4390 /* Main entry point to VRP (Value Range Propagation). This pass is
4391 loosely based on J. R. C. Patterson, ``Accurate Static Branch
4392 Prediction by Value Range Propagation,'' in SIGPLAN Conference on
4393 Programming Language Design and Implementation, pp. 67-78, 1995.
4394 Also available at http://citeseer.ist.psu.edu/patterson95accurate.html
4395
4396 This is essentially an SSA-CCP pass modified to deal with ranges
4397 instead of constants.
4398
4399 While propagating ranges, we may find that two or more SSA name
4400 have equivalent, though distinct ranges. For instance,
4401
4402 1 x_9 = p_3->a;
4403 2 p_4 = ASSERT_EXPR <p_3, p_3 != 0>
4404 3 if (p_4 == q_2)
4405 4 p_5 = ASSERT_EXPR <p_4, p_4 == q_2>;
4406 5 endif
4407 6 if (q_2)
4408
4409 In the code above, pointer p_5 has range [q_2, q_2], but from the
4410 code we can also determine that p_5 cannot be NULL and, if q_2 had
4411 a non-varying range, p_5's range should also be compatible with it.
4412
4413 These equivalences are created by two expressions: ASSERT_EXPR and
4414 copy operations. Since p_5 is an assertion on p_4, and p_4 was the
4415 result of another assertion, then we can use the fact that p_5 and
4416 p_4 are equivalent when evaluating p_5's range.
4417
4418 Together with value ranges, we also propagate these equivalences
4419 between names so that we can take advantage of information from
4420 multiple ranges when doing final replacement. Note that this
4421 equivalency relation is transitive but not symmetric.
4422
4423 In the example above, p_5 is equivalent to p_4, q_2 and p_3, but we
4424 cannot assert that q_2 is equivalent to p_5 because q_2 may be used
4425 in contexts where that assertion does not hold (e.g., in line 6).
4426
4427 TODO, the main difference between this pass and Patterson's is that
4428 we do not propagate edge probabilities. We only compute whether
4429 edges can be taken or not. That is, instead of having a spectrum
4430 of jump probabilities between 0 and 1, we only deal with 0, 1 and
4431 DON'T KNOW. In the future, it may be worthwhile to propagate
4432 probabilities to aid branch prediction. */
4433
4434 static unsigned int
4435 execute_vrp (struct function *fun, bool warn_array_bounds_p)
4436 {
4437
4438 loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
4439 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
4440 scev_initialize ();
4441
4442 /* ??? This ends up using stale EDGE_DFS_BACK for liveness computation.
4443 Inserting assertions may split edges which will invalidate
4444 EDGE_DFS_BACK. */
4445 vrp_insert assert_engine (fun);
4446 assert_engine.insert_range_assertions ();
4447
4448 threadedge_initialize_values ();
4449
4450 /* For visiting PHI nodes we need EDGE_DFS_BACK computed. */
4451 mark_dfs_back_edges ();
4452
4453 class vrp_prop vrp_prop;
4454 vrp_prop.vrp_initialize (fun);
4455 vrp_prop.ssa_propagate ();
4456 vrp_prop.vrp_finalize (warn_array_bounds_p);
4457
4458 /* We must identify jump threading opportunities before we release
4459 the datastructures built by VRP. */
4460 identify_jump_threads (fun, &vrp_prop.vr_values);
4461
4462 /* A comparison of an SSA_NAME against a constant where the SSA_NAME
4463 was set by a type conversion can often be rewritten to use the
4464 RHS of the type conversion.
4465
4466 However, doing so inhibits jump threading through the comparison.
4467 So that transformation is not performed until after jump threading
4468 is complete. */
4469 basic_block bb;
4470 FOR_EACH_BB_FN (bb, fun)
4471 {
4472 gimple *last = last_stmt (bb);
4473 if (last && gimple_code (last) == GIMPLE_COND)
4474 vrp_prop.vr_values.simplify_cond_using_ranges_2 (as_a <gcond *> (last));
4475 }
4476
4477 free_numbers_of_iterations_estimates (fun);
4478
4479 /* ASSERT_EXPRs must be removed before finalizing jump threads
4480 as finalizing jump threads calls the CFG cleanup code which
4481 does not properly handle ASSERT_EXPRs. */
4482 assert_engine.remove_range_assertions ();
4483
4484 /* If we exposed any new variables, go ahead and put them into
4485 SSA form now, before we handle jump threading. This simplifies
4486 interactions between rewriting of _DECL nodes into SSA form
4487 and rewriting SSA_NAME nodes into SSA form after block
4488 duplication and CFG manipulation. */
4489 update_ssa (TODO_update_ssa);
4490
4491 /* We identified all the jump threading opportunities earlier, but could
4492 not transform the CFG at that time. This routine transforms the
4493 CFG and arranges for the dominator tree to be rebuilt if necessary.
4494
4495 Note the SSA graph update will occur during the normal TODO
4496 processing by the pass manager. */
4497 thread_through_all_blocks (false);
4498
4499 vrp_prop.vr_values.cleanup_edges_and_switches ();
4500 threadedge_finalize_values ();
4501
4502 scev_finalize ();
4503 loop_optimizer_finalize ();
4504 return 0;
4505 }
4506
4507 namespace {
4508
4509 const pass_data pass_data_vrp =
4510 {
4511 GIMPLE_PASS, /* type */
4512 "vrp", /* name */
4513 OPTGROUP_NONE, /* optinfo_flags */
4514 TV_TREE_VRP, /* tv_id */
4515 PROP_ssa, /* properties_required */
4516 0, /* properties_provided */
4517 0, /* properties_destroyed */
4518 0, /* todo_flags_start */
4519 ( TODO_cleanup_cfg | TODO_update_ssa ), /* todo_flags_finish */
4520 };
4521
4522 class pass_vrp : public gimple_opt_pass
4523 {
4524 public:
4525 pass_vrp (gcc::context *ctxt)
4526 : gimple_opt_pass (pass_data_vrp, ctxt), warn_array_bounds_p (false)
4527 {}
4528
4529 /* opt_pass methods: */
4530 opt_pass * clone () { return new pass_vrp (m_ctxt); }
4531 void set_pass_param (unsigned int n, bool param)
4532 {
4533 gcc_assert (n == 0);
4534 warn_array_bounds_p = param;
4535 }
4536 virtual bool gate (function *) { return flag_tree_vrp != 0; }
4537 virtual unsigned int execute (function *fun)
4538 { return execute_vrp (fun, warn_array_bounds_p); }
4539
4540 private:
4541 bool warn_array_bounds_p;
4542 }; // class pass_vrp
4543
4544 } // anon namespace
4545
4546 gimple_opt_pass *
4547 make_pass_vrp (gcc::context *ctxt)
4548 {
4549 return new pass_vrp (ctxt);
4550 }
4551
4552
4553 /* Worker for determine_value_range. */
4554
4555 static void
4556 determine_value_range_1 (value_range *vr, tree expr)
4557 {
4558 if (BINARY_CLASS_P (expr))
4559 {
4560 value_range vr0, vr1;
4561 determine_value_range_1 (&vr0, TREE_OPERAND (expr, 0));
4562 determine_value_range_1 (&vr1, TREE_OPERAND (expr, 1));
4563 range_fold_binary_expr (vr, TREE_CODE (expr), TREE_TYPE (expr),
4564 &vr0, &vr1);
4565 }
4566 else if (UNARY_CLASS_P (expr))
4567 {
4568 value_range vr0;
4569 determine_value_range_1 (&vr0, TREE_OPERAND (expr, 0));
4570 range_fold_unary_expr (vr, TREE_CODE (expr), TREE_TYPE (expr),
4571 &vr0, TREE_TYPE (TREE_OPERAND (expr, 0)));
4572 }
4573 else if (TREE_CODE (expr) == INTEGER_CST)
4574 vr->set (expr);
4575 else
4576 {
4577 value_range_kind kind;
4578 wide_int min, max;
4579 /* For SSA names try to extract range info computed by VRP. Otherwise
4580 fall back to varying. */
4581 if (TREE_CODE (expr) == SSA_NAME
4582 && INTEGRAL_TYPE_P (TREE_TYPE (expr))
4583 && (kind = get_range_info (expr, &min, &max)) != VR_VARYING)
4584 vr->set (wide_int_to_tree (TREE_TYPE (expr), min),
4585 wide_int_to_tree (TREE_TYPE (expr), max),
4586 kind);
4587 else
4588 vr->set_varying (TREE_TYPE (expr));
4589 }
4590 }
4591
4592 /* Compute a value-range for EXPR and set it in *MIN and *MAX. Return
4593 the determined range type. */
4594
4595 value_range_kind
4596 determine_value_range (tree expr, wide_int *min, wide_int *max)
4597 {
4598 value_range vr;
4599 determine_value_range_1 (&vr, expr);
4600 if (vr.constant_p ())
4601 {
4602 *min = wi::to_wide (vr.min ());
4603 *max = wi::to_wide (vr.max ());
4604 return vr.kind ();
4605 }
4606
4607 return VR_VARYING;
4608 }