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