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