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