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