Fix issue for pointers to anonymous types with -fdump-ada-spec
[official-gcc.git] / gcc / vr-values.cc
blobf94da3130e3fce9d19f84d33afd2c9ad281fbadc
1 /* Support routines for Value Range Propagation (VRP).
2 Copyright (C) 2005-2022 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3, or (at your option)
9 any later version.
11 GCC is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "backend.h"
24 #include "insn-codes.h"
25 #include "tree.h"
26 #include "gimple.h"
27 #include "ssa.h"
28 #include "optabs-tree.h"
29 #include "gimple-pretty-print.h"
30 #include "diagnostic-core.h"
31 #include "flags.h"
32 #include "fold-const.h"
33 #include "calls.h"
34 #include "cfganal.h"
35 #include "gimple-fold.h"
36 #include "gimple-iterator.h"
37 #include "tree-cfg.h"
38 #include "tree-ssa-loop-niter.h"
39 #include "tree-ssa-loop.h"
40 #include "intl.h"
41 #include "cfgloop.h"
42 #include "tree-scalar-evolution.h"
43 #include "tree-ssa-propagate.h"
44 #include "tree-chrec.h"
45 #include "omp-general.h"
46 #include "case-cfn-macros.h"
47 #include "alloc-pool.h"
48 #include "attribs.h"
49 #include "range.h"
50 #include "vr-values.h"
51 #include "cfghooks.h"
52 #include "range-op.h"
53 #include "gimple-range.h"
55 /* Set value range VR to a non-negative range of type TYPE. */
57 static inline void
58 set_value_range_to_nonnegative (value_range_equiv *vr, tree type)
60 tree zero = build_int_cst (type, 0);
61 vr->update (zero, vrp_val_max (type));
64 /* Set value range VR to a range of a truthvalue of type TYPE. */
66 static inline void
67 set_value_range_to_truthvalue (value_range_equiv *vr, tree type)
69 if (TYPE_PRECISION (type) == 1)
70 vr->set_varying (type);
71 else
72 vr->update (build_int_cst (type, 0), build_int_cst (type, 1));
75 /* Return the lattice entry for VAR or NULL if it doesn't exist or cannot
76 be initialized. */
78 value_range_equiv *
79 vr_values::get_lattice_entry (const_tree var)
81 value_range_equiv *vr;
82 tree sym;
83 unsigned ver = SSA_NAME_VERSION (var);
85 /* If we query the entry for a new SSA name avoid reallocating the lattice
86 since we should get here at most from the substitute-and-fold stage which
87 will never try to change values. */
88 if (ver >= num_vr_values)
89 return NULL;
91 vr = vr_value[ver];
92 if (vr)
93 return vr;
95 /* Create a default value range. */
96 vr = allocate_value_range_equiv ();
97 vr_value[ver] = vr;
99 /* After propagation finished return varying. */
100 if (values_propagated)
102 vr->set_varying (TREE_TYPE (var));
103 return vr;
106 vr->set_undefined ();
108 /* If VAR is a default definition of a parameter, the variable can
109 take any value in VAR's type. */
110 if (SSA_NAME_IS_DEFAULT_DEF (var))
112 sym = SSA_NAME_VAR (var);
113 if (TREE_CODE (sym) == PARM_DECL)
115 /* Try to use the "nonnull" attribute to create ~[0, 0]
116 anti-ranges for pointers. Note that this is only valid with
117 default definitions of PARM_DECLs. */
118 if (POINTER_TYPE_P (TREE_TYPE (sym))
119 && (nonnull_arg_p (sym)
120 || (get_global_range_query ()->range_of_expr (*vr,
121 const_cast <tree> (var))
122 && vr->nonzero_p ())))
124 vr->set_nonzero (TREE_TYPE (sym));
125 vr->equiv_clear ();
127 else if (INTEGRAL_TYPE_P (TREE_TYPE (sym)))
129 get_global_range_query ()->range_of_expr (*vr, const_cast <tree> (var));
130 if (vr->undefined_p ())
131 vr->set_varying (TREE_TYPE (sym));
133 else
134 vr->set_varying (TREE_TYPE (sym));
136 else if (TREE_CODE (sym) == RESULT_DECL
137 && DECL_BY_REFERENCE (sym))
139 vr->set_nonzero (TREE_TYPE (sym));
140 vr->equiv_clear ();
144 return vr;
147 /* Return value range information for VAR.
149 If we have no values ranges recorded (ie, VRP is not running), then
150 return NULL. Otherwise create an empty range if none existed for VAR. */
152 const value_range_equiv *
153 vr_values::get_value_range (const_tree var,
154 gimple *stmt ATTRIBUTE_UNUSED)
156 /* If we have no recorded ranges, then return NULL. */
157 if (!vr_value)
158 return NULL;
160 value_range_equiv *vr = get_lattice_entry (var);
162 /* Reallocate the lattice if needed. */
163 if (!vr)
165 unsigned int old_sz = num_vr_values;
166 num_vr_values = num_ssa_names + num_ssa_names / 10;
167 vr_value = XRESIZEVEC (value_range_equiv *, vr_value, num_vr_values);
168 for ( ; old_sz < num_vr_values; old_sz++)
169 vr_value [old_sz] = NULL;
171 /* Now that the lattice has been resized, we should never fail. */
172 vr = get_lattice_entry (var);
173 gcc_assert (vr);
176 return vr;
179 bool
180 vr_values::range_of_expr (irange &r, tree expr, gimple *stmt)
182 if (!gimple_range_ssa_p (expr))
183 return get_tree_range (r, expr, stmt);
185 if (const value_range *vr = get_value_range (expr, stmt))
187 if (vr->undefined_p () || vr->constant_p ())
188 r = *vr;
189 else
191 value_range tmp = *vr;
192 tmp.normalize_symbolics ();
193 r = tmp;
195 return true;
197 return false;
200 tree
201 vr_values::value_of_expr (tree op, gimple *)
203 return op_with_constant_singleton_value_range (op);
206 tree
207 vr_values::value_on_edge (edge, tree op)
209 return op_with_constant_singleton_value_range (op);
212 tree
213 vr_values::value_of_stmt (gimple *stmt, tree op)
215 if (!op)
216 op = gimple_get_lhs (stmt);
218 gcc_checking_assert (!op|| op == gimple_get_lhs (stmt));
220 if (op)
221 return op_with_constant_singleton_value_range (op);
222 return NULL_TREE;
225 /* Set the lattice entry for DEF to VARYING. */
227 void
228 vr_values::set_def_to_varying (const_tree def)
230 value_range_equiv *vr = get_lattice_entry (def);
231 if (vr)
232 vr->set_varying (TREE_TYPE (def));
235 /* Set value-ranges of all SSA names defined by STMT to varying. */
237 void
238 vr_values::set_defs_to_varying (gimple *stmt)
240 ssa_op_iter i;
241 tree def;
242 FOR_EACH_SSA_TREE_OPERAND (def, stmt, i, SSA_OP_DEF)
243 set_def_to_varying (def);
246 /* Update the value range and equivalence set for variable VAR to
247 NEW_VR. Return true if NEW_VR is different from VAR's previous
248 value.
250 NOTE: This function assumes that NEW_VR is a temporary value range
251 object created for the sole purpose of updating VAR's range. The
252 storage used by the equivalence set from NEW_VR will be freed by
253 this function. Do not call update_value_range when NEW_VR
254 is the range object associated with another SSA name. */
256 bool
257 vr_values::update_value_range (const_tree var, value_range_equiv *new_vr)
259 value_range_equiv *old_vr;
260 bool is_new;
262 /* If there is a value-range on the SSA name from earlier analysis
263 factor that in. */
264 if (INTEGRAL_TYPE_P (TREE_TYPE (var)))
266 value_range_equiv nr;
267 get_global_range_query ()->range_of_expr (nr, const_cast <tree> (var));
268 if (!nr.undefined_p ())
269 new_vr->intersect (&nr);
272 /* Update the value range, if necessary. If we cannot allocate a lattice
273 entry for VAR keep it at VARYING. This happens when DOM feeds us stmts
274 with SSA names allocated after setting up the lattice. */
275 old_vr = get_lattice_entry (var);
276 if (!old_vr)
277 return false;
278 is_new = !old_vr->equal_p (*new_vr, /*ignore_equivs=*/false);
280 if (is_new)
282 /* Do not allow transitions up the lattice. The following
283 is slightly more awkward than just new_vr->type < old_vr->type
284 because VR_RANGE and VR_ANTI_RANGE need to be considered
285 the same. We may not have is_new when transitioning to
286 UNDEFINED. If old_vr->type is VARYING, we shouldn't be
287 called, if we are anyway, keep it VARYING. */
288 if (old_vr->varying_p ())
290 new_vr->set_varying (TREE_TYPE (var));
291 is_new = false;
293 else if (new_vr->undefined_p ())
295 old_vr->set_varying (TREE_TYPE (var));
296 new_vr->set_varying (TREE_TYPE (var));
297 return true;
299 else
300 old_vr->set (new_vr->min (), new_vr->max (), new_vr->equiv (),
301 new_vr->kind ());
304 new_vr->equiv_clear ();
306 return is_new;
309 /* Return true if value range VR involves exactly one symbol SYM. */
311 static bool
312 symbolic_range_based_on_p (value_range *vr, const_tree sym)
314 bool neg, min_has_symbol, max_has_symbol;
315 tree inv;
317 if (is_gimple_min_invariant (vr->min ()))
318 min_has_symbol = false;
319 else if (get_single_symbol (vr->min (), &neg, &inv) == sym)
320 min_has_symbol = true;
321 else
322 return false;
324 if (is_gimple_min_invariant (vr->max ()))
325 max_has_symbol = false;
326 else if (get_single_symbol (vr->max (), &neg, &inv) == sym)
327 max_has_symbol = true;
328 else
329 return false;
331 return (min_has_symbol || max_has_symbol);
334 /* Return true if the result of assignment STMT is know to be non-zero. */
336 static bool
337 gimple_assign_nonzero_p (gimple *stmt)
339 enum tree_code code = gimple_assign_rhs_code (stmt);
340 bool strict_overflow_p;
341 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
342 switch (get_gimple_rhs_class (code))
344 case GIMPLE_UNARY_RHS:
345 return tree_unary_nonzero_warnv_p (gimple_assign_rhs_code (stmt),
346 type,
347 gimple_assign_rhs1 (stmt),
348 &strict_overflow_p);
349 case GIMPLE_BINARY_RHS:
350 return tree_binary_nonzero_warnv_p (gimple_assign_rhs_code (stmt),
351 type,
352 gimple_assign_rhs1 (stmt),
353 gimple_assign_rhs2 (stmt),
354 &strict_overflow_p);
355 case GIMPLE_TERNARY_RHS:
356 return false;
357 case GIMPLE_SINGLE_RHS:
358 return tree_single_nonzero_warnv_p (gimple_assign_rhs1 (stmt),
359 &strict_overflow_p);
360 case GIMPLE_INVALID_RHS:
361 gcc_unreachable ();
362 default:
363 gcc_unreachable ();
367 /* Return true if STMT is known to compute a non-zero value. */
369 static bool
370 gimple_stmt_nonzero_p (gimple *stmt)
372 switch (gimple_code (stmt))
374 case GIMPLE_ASSIGN:
375 return gimple_assign_nonzero_p (stmt);
376 case GIMPLE_CALL:
378 gcall *call_stmt = as_a<gcall *> (stmt);
379 return (gimple_call_nonnull_result_p (call_stmt)
380 || gimple_call_nonnull_arg (call_stmt));
382 default:
383 gcc_unreachable ();
386 /* Like tree_expr_nonzero_p, but this function uses value ranges
387 obtained so far. */
389 bool
390 vr_values::vrp_stmt_computes_nonzero (gimple *stmt)
392 if (gimple_stmt_nonzero_p (stmt))
393 return true;
395 /* If we have an expression of the form &X->a, then the expression
396 is nonnull if X is nonnull. */
397 if (is_gimple_assign (stmt)
398 && gimple_assign_rhs_code (stmt) == ADDR_EXPR)
400 tree expr = gimple_assign_rhs1 (stmt);
401 poly_int64 bitsize, bitpos;
402 tree offset;
403 machine_mode mode;
404 int unsignedp, reversep, volatilep;
405 tree base = get_inner_reference (TREE_OPERAND (expr, 0), &bitsize,
406 &bitpos, &offset, &mode, &unsignedp,
407 &reversep, &volatilep);
409 if (base != NULL_TREE
410 && TREE_CODE (base) == MEM_REF
411 && TREE_CODE (TREE_OPERAND (base, 0)) == SSA_NAME)
413 poly_offset_int off = 0;
414 bool off_cst = false;
415 if (offset == NULL_TREE || TREE_CODE (offset) == INTEGER_CST)
417 off = mem_ref_offset (base);
418 if (offset)
419 off += poly_offset_int::from (wi::to_poly_wide (offset),
420 SIGNED);
421 off <<= LOG2_BITS_PER_UNIT;
422 off += bitpos;
423 off_cst = true;
425 /* If &X->a is equal to X and X is ~[0, 0], the result is too.
426 For -fdelete-null-pointer-checks -fno-wrapv-pointer we don't
427 allow going from non-NULL pointer to NULL. */
428 if ((off_cst && known_eq (off, 0))
429 || (flag_delete_null_pointer_checks
430 && !TYPE_OVERFLOW_WRAPS (TREE_TYPE (expr))))
432 const value_range_equiv *vr
433 = get_value_range (TREE_OPERAND (base, 0), stmt);
434 if (!range_includes_zero_p (vr))
435 return true;
437 /* If MEM_REF has a "positive" offset, consider it non-NULL
438 always, for -fdelete-null-pointer-checks also "negative"
439 ones. Punt for unknown offsets (e.g. variable ones). */
440 if (!TYPE_OVERFLOW_WRAPS (TREE_TYPE (expr))
441 && off_cst
442 && known_ne (off, 0)
443 && (flag_delete_null_pointer_checks || known_gt (off, 0)))
444 return true;
448 return false;
451 /* Returns true if EXPR is a valid value (as expected by compare_values) --
452 a gimple invariant, or SSA_NAME +- CST. */
454 static bool
455 valid_value_p (tree expr)
457 if (TREE_CODE (expr) == SSA_NAME)
458 return true;
460 if (TREE_CODE (expr) == PLUS_EXPR
461 || TREE_CODE (expr) == MINUS_EXPR)
462 return (TREE_CODE (TREE_OPERAND (expr, 0)) == SSA_NAME
463 && TREE_CODE (TREE_OPERAND (expr, 1)) == INTEGER_CST);
465 return is_gimple_min_invariant (expr);
468 /* If OP has a value range with a single constant value return that,
469 otherwise return NULL_TREE. This returns OP itself if OP is a
470 constant. */
472 tree
473 vr_values::op_with_constant_singleton_value_range (tree op)
475 if (is_gimple_min_invariant (op))
476 return op;
478 if (TREE_CODE (op) != SSA_NAME)
479 return NULL_TREE;
481 tree t;
482 if (get_value_range (op)->singleton_p (&t))
483 return t;
484 return NULL;
487 /* Return true if op is in a boolean [0, 1] value-range. */
489 bool
490 simplify_using_ranges::op_with_boolean_value_range_p (tree op, gimple *s)
492 if (TYPE_PRECISION (TREE_TYPE (op)) == 1)
493 return true;
495 if (integer_zerop (op)
496 || integer_onep (op))
497 return true;
499 if (TREE_CODE (op) != SSA_NAME)
500 return false;
502 /* ?? Errr, this should probably check for [0,0] and [1,1] as well
503 as [0,1]. */
504 const value_range *vr = query->get_value_range (op, s);
505 return *vr == value_range (build_zero_cst (TREE_TYPE (op)),
506 build_one_cst (TREE_TYPE (op)));
509 /* Extract value range information for VAR when (OP COND_CODE LIMIT) is
510 true and store it in *VR_P. */
512 void
513 vr_values::extract_range_for_var_from_comparison_expr (tree var,
514 enum tree_code cond_code,
515 tree op, tree limit,
516 value_range_equiv *vr_p)
518 tree min, max, type;
519 const value_range_equiv *limit_vr;
520 type = TREE_TYPE (var);
522 /* For pointer arithmetic, we only keep track of pointer equality
523 and inequality. If we arrive here with unfolded conditions like
524 _1 > _1 do not derive anything. */
525 if ((POINTER_TYPE_P (type) && cond_code != NE_EXPR && cond_code != EQ_EXPR)
526 || limit == var)
528 vr_p->set_varying (type);
529 return;
532 /* If LIMIT is another SSA name and LIMIT has a range of its own,
533 try to use LIMIT's range to avoid creating symbolic ranges
534 unnecessarily. */
535 limit_vr = (TREE_CODE (limit) == SSA_NAME) ? get_value_range (limit) : NULL;
537 /* LIMIT's range is only interesting if it has any useful information. */
538 if (! limit_vr
539 || limit_vr->undefined_p ()
540 || limit_vr->varying_p ()
541 || (limit_vr->symbolic_p ()
542 && ! (limit_vr->kind () == VR_RANGE
543 && (limit_vr->min () == limit_vr->max ()
544 || operand_equal_p (limit_vr->min (),
545 limit_vr->max (), 0)))))
546 limit_vr = NULL;
548 /* Initially, the new range has the same set of equivalences of
549 VAR's range. This will be revised before returning the final
550 value. Since assertions may be chained via mutually exclusive
551 predicates, we will need to trim the set of equivalences before
552 we are done. */
553 gcc_assert (vr_p->equiv () == NULL);
554 vr_p->equiv_add (var, get_value_range (var), &vrp_equiv_obstack);
556 /* Extract a new range based on the asserted comparison for VAR and
557 LIMIT's value range. Notice that if LIMIT has an anti-range, we
558 will only use it for equality comparisons (EQ_EXPR). For any
559 other kind of assertion, we cannot derive a range from LIMIT's
560 anti-range that can be used to describe the new range. For
561 instance, ASSERT_EXPR <x_2, x_2 <= b_4>. If b_4 is ~[2, 10],
562 then b_4 takes on the ranges [-INF, 1] and [11, +INF]. There is
563 no single range for x_2 that could describe LE_EXPR, so we might
564 as well build the range [b_4, +INF] for it.
565 One special case we handle is extracting a range from a
566 range test encoded as (unsigned)var + CST <= limit. */
567 if (TREE_CODE (op) == NOP_EXPR
568 || TREE_CODE (op) == PLUS_EXPR)
570 if (TREE_CODE (op) == PLUS_EXPR)
572 min = fold_build1 (NEGATE_EXPR, TREE_TYPE (TREE_OPERAND (op, 1)),
573 TREE_OPERAND (op, 1));
574 max = int_const_binop (PLUS_EXPR, limit, min);
575 op = TREE_OPERAND (op, 0);
577 else
579 min = build_int_cst (TREE_TYPE (var), 0);
580 max = limit;
583 /* Make sure to not set TREE_OVERFLOW on the final type
584 conversion. We are willingly interpreting large positive
585 unsigned values as negative signed values here. */
586 min = force_fit_type (TREE_TYPE (var), wi::to_widest (min), 0, false);
587 max = force_fit_type (TREE_TYPE (var), wi::to_widest (max), 0, false);
589 /* We can transform a max, min range to an anti-range or
590 vice-versa. Use set_and_canonicalize which does this for
591 us. */
592 if (cond_code == LE_EXPR)
593 vr_p->set (min, max, vr_p->equiv ());
594 else if (cond_code == GT_EXPR)
595 vr_p->set (min, max, vr_p->equiv (), VR_ANTI_RANGE);
596 else
597 gcc_unreachable ();
599 else if (cond_code == EQ_EXPR)
601 enum value_range_kind range_kind;
603 if (limit_vr)
605 range_kind = limit_vr->kind ();
606 min = limit_vr->min ();
607 max = limit_vr->max ();
609 else
611 range_kind = VR_RANGE;
612 min = limit;
613 max = limit;
616 vr_p->update (min, max, range_kind);
618 /* When asserting the equality VAR == LIMIT and LIMIT is another
619 SSA name, the new range will also inherit the equivalence set
620 from LIMIT. */
621 if (TREE_CODE (limit) == SSA_NAME)
622 vr_p->equiv_add (limit, get_value_range (limit), &vrp_equiv_obstack);
624 else if (cond_code == NE_EXPR)
626 /* As described above, when LIMIT's range is an anti-range and
627 this assertion is an inequality (NE_EXPR), then we cannot
628 derive anything from the anti-range. For instance, if
629 LIMIT's range was ~[0, 0], the assertion 'VAR != LIMIT' does
630 not imply that VAR's range is [0, 0]. So, in the case of
631 anti-ranges, we just assert the inequality using LIMIT and
632 not its anti-range.
634 If LIMIT_VR is a range, we can only use it to build a new
635 anti-range if LIMIT_VR is a single-valued range. For
636 instance, if LIMIT_VR is [0, 1], the predicate
637 VAR != [0, 1] does not mean that VAR's range is ~[0, 1].
638 Rather, it means that for value 0 VAR should be ~[0, 0]
639 and for value 1, VAR should be ~[1, 1]. We cannot
640 represent these ranges.
642 The only situation in which we can build a valid
643 anti-range is when LIMIT_VR is a single-valued range
644 (i.e., LIMIT_VR->MIN == LIMIT_VR->MAX). In that case,
645 build the anti-range ~[LIMIT_VR->MIN, LIMIT_VR->MAX]. */
646 if (limit_vr
647 && limit_vr->kind () == VR_RANGE
648 && compare_values (limit_vr->min (), limit_vr->max ()) == 0)
650 min = limit_vr->min ();
651 max = limit_vr->max ();
653 else
655 /* In any other case, we cannot use LIMIT's range to build a
656 valid anti-range. */
657 min = max = limit;
660 /* If MIN and MAX cover the whole range for their type, then
661 just use the original LIMIT. */
662 if (INTEGRAL_TYPE_P (type)
663 && vrp_val_is_min (min)
664 && vrp_val_is_max (max))
665 min = max = limit;
667 vr_p->set (min, max, vr_p->equiv (), VR_ANTI_RANGE);
669 else if (cond_code == LE_EXPR || cond_code == LT_EXPR)
671 min = TYPE_MIN_VALUE (type);
673 if (limit_vr == NULL || limit_vr->kind () == VR_ANTI_RANGE)
674 max = limit;
675 else
677 /* If LIMIT_VR is of the form [N1, N2], we need to build the
678 range [MIN, N2] for LE_EXPR and [MIN, N2 - 1] for
679 LT_EXPR. */
680 max = limit_vr->max ();
683 /* If the maximum value forces us to be out of bounds, simply punt.
684 It would be pointless to try and do anything more since this
685 all should be optimized away above us. */
686 if (cond_code == LT_EXPR
687 && compare_values (max, min) == 0)
688 vr_p->set_varying (TREE_TYPE (min));
689 else
691 /* For LT_EXPR, we create the range [MIN, MAX - 1]. */
692 if (cond_code == LT_EXPR)
694 if (TYPE_PRECISION (TREE_TYPE (max)) == 1
695 && !TYPE_UNSIGNED (TREE_TYPE (max)))
696 max = fold_build2 (PLUS_EXPR, TREE_TYPE (max), max,
697 build_int_cst (TREE_TYPE (max), -1));
698 else
699 max = fold_build2 (MINUS_EXPR, TREE_TYPE (max), max,
700 build_int_cst (TREE_TYPE (max), 1));
701 /* Signal to compare_values_warnv this expr doesn't overflow. */
702 if (EXPR_P (max))
703 suppress_warning (max, OPT_Woverflow);
706 vr_p->update (min, max);
709 else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
711 max = TYPE_MAX_VALUE (type);
713 if (limit_vr == NULL || limit_vr->kind () == VR_ANTI_RANGE)
714 min = limit;
715 else
717 /* If LIMIT_VR is of the form [N1, N2], we need to build the
718 range [N1, MAX] for GE_EXPR and [N1 + 1, MAX] for
719 GT_EXPR. */
720 min = limit_vr->min ();
723 /* If the minimum value forces us to be out of bounds, simply punt.
724 It would be pointless to try and do anything more since this
725 all should be optimized away above us. */
726 if (cond_code == GT_EXPR
727 && compare_values (min, max) == 0)
728 vr_p->set_varying (TREE_TYPE (min));
729 else
731 /* For GT_EXPR, we create the range [MIN + 1, MAX]. */
732 if (cond_code == GT_EXPR)
734 if (TYPE_PRECISION (TREE_TYPE (min)) == 1
735 && !TYPE_UNSIGNED (TREE_TYPE (min)))
736 min = fold_build2 (MINUS_EXPR, TREE_TYPE (min), min,
737 build_int_cst (TREE_TYPE (min), -1));
738 else
739 min = fold_build2 (PLUS_EXPR, TREE_TYPE (min), min,
740 build_int_cst (TREE_TYPE (min), 1));
741 /* Signal to compare_values_warnv this expr doesn't overflow. */
742 if (EXPR_P (min))
743 suppress_warning (min, OPT_Woverflow);
746 vr_p->update (min, max);
749 else
750 gcc_unreachable ();
752 /* Finally intersect the new range with what we already know about var. */
753 vr_p->intersect (get_value_range (var));
756 /* Extract value range information from an ASSERT_EXPR EXPR and store
757 it in *VR_P. */
759 void
760 vr_values::extract_range_from_assert (value_range_equiv *vr_p, tree expr)
762 tree var = ASSERT_EXPR_VAR (expr);
763 tree cond = ASSERT_EXPR_COND (expr);
764 tree limit, op;
765 enum tree_code cond_code;
766 gcc_assert (COMPARISON_CLASS_P (cond));
768 /* Find VAR in the ASSERT_EXPR conditional. */
769 if (var == TREE_OPERAND (cond, 0)
770 || TREE_CODE (TREE_OPERAND (cond, 0)) == PLUS_EXPR
771 || TREE_CODE (TREE_OPERAND (cond, 0)) == NOP_EXPR)
773 /* If the predicate is of the form VAR COMP LIMIT, then we just
774 take LIMIT from the RHS and use the same comparison code. */
775 cond_code = TREE_CODE (cond);
776 limit = TREE_OPERAND (cond, 1);
777 op = TREE_OPERAND (cond, 0);
779 else
781 /* If the predicate is of the form LIMIT COMP VAR, then we need
782 to flip around the comparison code to create the proper range
783 for VAR. */
784 cond_code = swap_tree_comparison (TREE_CODE (cond));
785 limit = TREE_OPERAND (cond, 0);
786 op = TREE_OPERAND (cond, 1);
788 extract_range_for_var_from_comparison_expr (var, cond_code, op,
789 limit, vr_p);
792 /* Extract range information from SSA name VAR and store it in VR. If
793 VAR has an interesting range, use it. Otherwise, create the
794 range [VAR, VAR] and return it. This is useful in situations where
795 we may have conditionals testing values of VARYING names. For
796 instance,
798 x_3 = y_5;
799 if (x_3 > y_5)
802 Even if y_5 is deemed VARYING, we can determine that x_3 > y_5 is
803 always false. */
805 void
806 vr_values::extract_range_from_ssa_name (value_range_equiv *vr, tree var)
808 const value_range_equiv *var_vr = get_value_range (var);
810 if (!var_vr->varying_p ())
811 vr->deep_copy (var_vr);
812 else
813 vr->set (var);
815 if (!vr->undefined_p ())
816 vr->equiv_add (var, get_value_range (var), &vrp_equiv_obstack);
819 /* Extract range information from a binary expression OP0 CODE OP1 based on
820 the ranges of each of its operands with resulting type EXPR_TYPE.
821 The resulting range is stored in *VR. */
823 void
824 vr_values::extract_range_from_binary_expr (value_range_equiv *vr,
825 enum tree_code code,
826 tree expr_type, tree op0, tree op1)
828 /* Get value ranges for each operand. For constant operands, create
829 a new value range with the operand to simplify processing. */
830 value_range vr0, vr1;
831 if (TREE_CODE (op0) == SSA_NAME)
832 vr0 = *(get_value_range (op0));
833 else if (is_gimple_min_invariant (op0))
834 vr0.set (op0);
835 else
836 vr0.set_varying (TREE_TYPE (op0));
838 if (TREE_CODE (op1) == SSA_NAME)
839 vr1 = *(get_value_range (op1));
840 else if (is_gimple_min_invariant (op1))
841 vr1.set (op1);
842 else
843 vr1.set_varying (TREE_TYPE (op1));
845 /* If one argument is varying, we can sometimes still deduce a
846 range for the output: any + [3, +INF] is in [MIN+3, +INF]. */
847 if (INTEGRAL_TYPE_P (TREE_TYPE (op0))
848 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (op0)))
850 if (vr0.varying_p () && !vr1.varying_p ())
851 vr0 = value_range (vrp_val_min (expr_type), vrp_val_max (expr_type));
852 else if (vr1.varying_p () && !vr0.varying_p ())
853 vr1 = value_range (vrp_val_min (expr_type), vrp_val_max (expr_type));
856 range_fold_binary_expr (vr, code, expr_type, &vr0, &vr1);
858 /* Set value_range for n in following sequence:
859 def = __builtin_memchr (arg, 0, sz)
860 n = def - arg
861 Here the range for n can be set to [0, PTRDIFF_MAX - 1]. */
863 if (vr->varying_p ()
864 && code == POINTER_DIFF_EXPR
865 && TREE_CODE (op0) == SSA_NAME
866 && TREE_CODE (op1) == SSA_NAME)
868 tree op0_ptype = TREE_TYPE (TREE_TYPE (op0));
869 tree op1_ptype = TREE_TYPE (TREE_TYPE (op1));
870 gcall *call_stmt = NULL;
872 if (TYPE_MODE (op0_ptype) == TYPE_MODE (char_type_node)
873 && TYPE_PRECISION (op0_ptype) == TYPE_PRECISION (char_type_node)
874 && TYPE_MODE (op1_ptype) == TYPE_MODE (char_type_node)
875 && TYPE_PRECISION (op1_ptype) == TYPE_PRECISION (char_type_node)
876 && (call_stmt = dyn_cast<gcall *>(SSA_NAME_DEF_STMT (op0)))
877 && gimple_call_builtin_p (call_stmt, BUILT_IN_MEMCHR)
878 && operand_equal_p (op0, gimple_call_lhs (call_stmt), 0)
879 && operand_equal_p (op1, gimple_call_arg (call_stmt, 0), 0)
880 && integer_zerop (gimple_call_arg (call_stmt, 1)))
882 tree max = vrp_val_max (ptrdiff_type_node);
883 wide_int wmax = wi::to_wide (max, TYPE_PRECISION (TREE_TYPE (max)));
884 tree range_min = build_zero_cst (expr_type);
885 tree range_max = wide_int_to_tree (expr_type, wmax - 1);
886 vr->set (range_min, range_max);
887 return;
891 /* Try harder for PLUS and MINUS if the range of one operand is symbolic
892 and based on the other operand, for example if it was deduced from a
893 symbolic comparison. When a bound of the range of the first operand
894 is invariant, we set the corresponding bound of the new range to INF
895 in order to avoid recursing on the range of the second operand. */
896 if (vr->varying_p ()
897 && (code == PLUS_EXPR || code == MINUS_EXPR)
898 && TREE_CODE (op1) == SSA_NAME
899 && vr0.kind () == VR_RANGE
900 && symbolic_range_based_on_p (&vr0, op1))
902 const bool minus_p = (code == MINUS_EXPR);
903 value_range n_vr1;
905 /* Try with VR0 and [-INF, OP1]. */
906 if (is_gimple_min_invariant (minus_p ? vr0.max () : vr0.min ()))
907 n_vr1.set (vrp_val_min (expr_type), op1);
909 /* Try with VR0 and [OP1, +INF]. */
910 else if (is_gimple_min_invariant (minus_p ? vr0.min () : vr0.max ()))
911 n_vr1.set (op1, vrp_val_max (expr_type));
913 /* Try with VR0 and [OP1, OP1]. */
914 else
915 n_vr1.set (op1, op1);
917 range_fold_binary_expr (vr, code, expr_type, &vr0, &n_vr1);
920 if (vr->varying_p ()
921 && (code == PLUS_EXPR || code == MINUS_EXPR)
922 && TREE_CODE (op0) == SSA_NAME
923 && vr1.kind () == VR_RANGE
924 && symbolic_range_based_on_p (&vr1, op0))
926 const bool minus_p = (code == MINUS_EXPR);
927 value_range n_vr0;
929 /* Try with [-INF, OP0] and VR1. */
930 if (is_gimple_min_invariant (minus_p ? vr1.max () : vr1.min ()))
931 n_vr0.set (vrp_val_min (expr_type), op0);
933 /* Try with [OP0, +INF] and VR1. */
934 else if (is_gimple_min_invariant (minus_p ? vr1.min (): vr1.max ()))
935 n_vr0.set (op0, vrp_val_max (expr_type));
937 /* Try with [OP0, OP0] and VR1. */
938 else
939 n_vr0.set (op0);
941 range_fold_binary_expr (vr, code, expr_type, &n_vr0, &vr1);
944 /* If we didn't derive a range for MINUS_EXPR, and
945 op1's range is ~[op0,op0] or vice-versa, then we
946 can derive a non-null range. This happens often for
947 pointer subtraction. */
948 if (vr->varying_p ()
949 && (code == MINUS_EXPR || code == POINTER_DIFF_EXPR)
950 && TREE_CODE (op0) == SSA_NAME
951 && ((vr0.kind () == VR_ANTI_RANGE
952 && vr0.min () == op1
953 && vr0.min () == vr0.max ())
954 || (vr1.kind () == VR_ANTI_RANGE
955 && vr1.min () == op0
956 && vr1.min () == vr1.max ())))
958 vr->set_nonzero (expr_type);
959 vr->equiv_clear ();
963 /* Extract range information from a unary expression CODE OP0 based on
964 the range of its operand with resulting type TYPE.
965 The resulting range is stored in *VR. */
967 void
968 vr_values::extract_range_from_unary_expr (value_range_equiv *vr,
969 enum tree_code code,
970 tree type, tree op0)
972 value_range vr0;
974 /* Get value ranges for the operand. For constant operands, create
975 a new value range with the operand to simplify processing. */
976 if (TREE_CODE (op0) == SSA_NAME)
977 vr0 = *(get_value_range (op0));
978 else if (is_gimple_min_invariant (op0))
979 vr0.set (op0);
980 else
981 vr0.set_varying (type);
983 range_fold_unary_expr (vr, code, type, &vr0, TREE_TYPE (op0));
987 /* Extract range information from a conditional expression STMT based on
988 the ranges of each of its operands and the expression code. */
990 void
991 vr_values::extract_range_from_cond_expr (value_range_equiv *vr, gassign *stmt)
993 /* Get value ranges for each operand. For constant operands, create
994 a new value range with the operand to simplify processing. */
995 tree op0 = gimple_assign_rhs2 (stmt);
996 value_range_equiv tem0;
997 const value_range_equiv *vr0 = &tem0;
998 if (TREE_CODE (op0) == SSA_NAME)
999 vr0 = get_value_range (op0);
1000 else if (is_gimple_min_invariant (op0))
1001 tem0.set (op0);
1002 else
1003 tem0.set_varying (TREE_TYPE (op0));
1005 tree op1 = gimple_assign_rhs3 (stmt);
1006 value_range_equiv tem1;
1007 const value_range_equiv *vr1 = &tem1;
1008 if (TREE_CODE (op1) == SSA_NAME)
1009 vr1 = get_value_range (op1);
1010 else if (is_gimple_min_invariant (op1))
1011 tem1.set (op1);
1012 else
1013 tem1.set_varying (TREE_TYPE (op1));
1015 /* The resulting value range is the union of the operand ranges */
1016 vr->deep_copy (vr0);
1017 vr->union_ (vr1);
1021 /* Extract range information from a comparison expression EXPR based
1022 on the range of its operand and the expression code. */
1024 void
1025 vr_values::extract_range_from_comparison (value_range_equiv *vr,
1026 gimple *stmt)
1028 enum tree_code code = gimple_assign_rhs_code (stmt);
1029 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
1030 tree op0 = gimple_assign_rhs1 (stmt);
1031 tree op1 = gimple_assign_rhs2 (stmt);
1032 bool sop;
1033 tree val
1034 = simplifier.vrp_evaluate_conditional_warnv_with_ops (stmt, code, op0, op1,
1035 false, &sop, NULL);
1036 if (val)
1038 /* Since this expression was found on the RHS of an assignment,
1039 its type may be different from _Bool. Convert VAL to EXPR's
1040 type. */
1041 val = fold_convert (type, val);
1042 if (is_gimple_min_invariant (val))
1043 vr->set (val);
1044 else
1045 vr->update (val, val);
1047 else
1048 /* The result of a comparison is always true or false. */
1049 set_value_range_to_truthvalue (vr, type);
1052 /* Helper function for simplify_internal_call_using_ranges and
1053 extract_range_basic. Return true if OP0 SUBCODE OP1 for
1054 SUBCODE {PLUS,MINUS,MULT}_EXPR is known to never overflow or
1055 always overflow. Set *OVF to true if it is known to always
1056 overflow. */
1058 static bool
1059 check_for_binary_op_overflow (range_query *query,
1060 enum tree_code subcode, tree type,
1061 tree op0, tree op1, bool *ovf, gimple *s = NULL)
1063 value_range vr0, vr1;
1064 if (TREE_CODE (op0) == SSA_NAME)
1065 vr0 = *query->get_value_range (op0, s);
1066 else if (TREE_CODE (op0) == INTEGER_CST)
1067 vr0.set (op0);
1068 else
1069 vr0.set_varying (TREE_TYPE (op0));
1071 if (TREE_CODE (op1) == SSA_NAME)
1072 vr1 = *query->get_value_range (op1, s);
1073 else if (TREE_CODE (op1) == INTEGER_CST)
1074 vr1.set (op1);
1075 else
1076 vr1.set_varying (TREE_TYPE (op1));
1078 tree vr0min = vr0.min (), vr0max = vr0.max ();
1079 tree vr1min = vr1.min (), vr1max = vr1.max ();
1080 if (!range_int_cst_p (&vr0)
1081 || TREE_OVERFLOW (vr0min)
1082 || TREE_OVERFLOW (vr0max))
1084 vr0min = vrp_val_min (TREE_TYPE (op0));
1085 vr0max = vrp_val_max (TREE_TYPE (op0));
1087 if (!range_int_cst_p (&vr1)
1088 || TREE_OVERFLOW (vr1min)
1089 || TREE_OVERFLOW (vr1max))
1091 vr1min = vrp_val_min (TREE_TYPE (op1));
1092 vr1max = vrp_val_max (TREE_TYPE (op1));
1094 *ovf = arith_overflowed_p (subcode, type, vr0min,
1095 subcode == MINUS_EXPR ? vr1max : vr1min);
1096 if (arith_overflowed_p (subcode, type, vr0max,
1097 subcode == MINUS_EXPR ? vr1min : vr1max) != *ovf)
1098 return false;
1099 if (subcode == MULT_EXPR)
1101 if (arith_overflowed_p (subcode, type, vr0min, vr1max) != *ovf
1102 || arith_overflowed_p (subcode, type, vr0max, vr1min) != *ovf)
1103 return false;
1105 if (*ovf)
1107 /* So far we found that there is an overflow on the boundaries.
1108 That doesn't prove that there is an overflow even for all values
1109 in between the boundaries. For that compute widest_int range
1110 of the result and see if it doesn't overlap the range of
1111 type. */
1112 widest_int wmin, wmax;
1113 widest_int w[4];
1114 int i;
1115 w[0] = wi::to_widest (vr0min);
1116 w[1] = wi::to_widest (vr0max);
1117 w[2] = wi::to_widest (vr1min);
1118 w[3] = wi::to_widest (vr1max);
1119 for (i = 0; i < 4; i++)
1121 widest_int wt;
1122 switch (subcode)
1124 case PLUS_EXPR:
1125 wt = wi::add (w[i & 1], w[2 + (i & 2) / 2]);
1126 break;
1127 case MINUS_EXPR:
1128 wt = wi::sub (w[i & 1], w[2 + (i & 2) / 2]);
1129 break;
1130 case MULT_EXPR:
1131 wt = wi::mul (w[i & 1], w[2 + (i & 2) / 2]);
1132 break;
1133 default:
1134 gcc_unreachable ();
1136 if (i == 0)
1138 wmin = wt;
1139 wmax = wt;
1141 else
1143 wmin = wi::smin (wmin, wt);
1144 wmax = wi::smax (wmax, wt);
1147 /* The result of op0 CODE op1 is known to be in range
1148 [wmin, wmax]. */
1149 widest_int wtmin = wi::to_widest (vrp_val_min (type));
1150 widest_int wtmax = wi::to_widest (vrp_val_max (type));
1151 /* If all values in [wmin, wmax] are smaller than
1152 [wtmin, wtmax] or all are larger than [wtmin, wtmax],
1153 the arithmetic operation will always overflow. */
1154 if (wmax < wtmin || wmin > wtmax)
1155 return true;
1156 return false;
1158 return true;
1161 /* Derive a range from a builtin. Set range in VR and return TRUE if
1162 successful. */
1164 bool
1165 vr_values::extract_range_from_ubsan_builtin (value_range_equiv *vr, gimple *stmt)
1167 gcc_assert (is_gimple_call (stmt));
1168 enum tree_code subcode = ERROR_MARK;
1169 combined_fn cfn = gimple_call_combined_fn (stmt);
1170 scalar_int_mode mode;
1172 switch (cfn)
1174 case CFN_UBSAN_CHECK_ADD:
1175 subcode = PLUS_EXPR;
1176 break;
1177 case CFN_UBSAN_CHECK_SUB:
1178 subcode = MINUS_EXPR;
1179 break;
1180 case CFN_UBSAN_CHECK_MUL:
1181 subcode = MULT_EXPR;
1182 break;
1183 default:
1184 break;
1186 if (subcode != ERROR_MARK)
1188 bool saved_flag_wrapv = flag_wrapv;
1189 /* Pretend the arithmetics is wrapping. If there is
1190 any overflow, we'll complain, but will actually do
1191 wrapping operation. */
1192 flag_wrapv = 1;
1193 extract_range_from_binary_expr (vr, subcode,
1194 TREE_TYPE (gimple_call_arg (stmt, 0)),
1195 gimple_call_arg (stmt, 0),
1196 gimple_call_arg (stmt, 1));
1197 flag_wrapv = saved_flag_wrapv;
1199 /* If for both arguments vrp_valueize returned non-NULL,
1200 this should have been already folded and if not, it
1201 wasn't folded because of overflow. Avoid removing the
1202 UBSAN_CHECK_* calls in that case. */
1203 if (vr->kind () == VR_RANGE
1204 && (vr->min () == vr->max ()
1205 || operand_equal_p (vr->min (), vr->max (), 0)))
1206 vr->set_varying (vr->type ());
1208 return !vr->varying_p ();
1210 return false;
1213 /* Try to derive a nonnegative or nonzero range out of STMT relying
1214 primarily on generic routines in fold in conjunction with range data.
1215 Store the result in *VR */
1217 void
1218 vr_values::extract_range_basic (value_range_equiv *vr, gimple *stmt)
1220 bool sop;
1222 if (is_gimple_call (stmt))
1224 combined_fn cfn = gimple_call_combined_fn (stmt);
1225 switch (cfn)
1227 case CFN_UBSAN_CHECK_ADD:
1228 case CFN_UBSAN_CHECK_SUB:
1229 case CFN_UBSAN_CHECK_MUL:
1230 if (extract_range_from_ubsan_builtin (vr, stmt))
1231 return;
1232 break;
1233 default:
1234 if (fold_range (*vr, stmt, this))
1236 /* The original code nuked equivalences every time a
1237 range was found, so do the same here. */
1238 vr->equiv_clear ();
1239 return;
1241 break;
1244 /* Handle extraction of the two results (result of arithmetics and
1245 a flag whether arithmetics overflowed) from {ADD,SUB,MUL}_OVERFLOW
1246 internal function. Similarly from ATOMIC_COMPARE_EXCHANGE. */
1247 if (is_gimple_assign (stmt)
1248 && (gimple_assign_rhs_code (stmt) == REALPART_EXPR
1249 || gimple_assign_rhs_code (stmt) == IMAGPART_EXPR)
1250 && INTEGRAL_TYPE_P (TREE_TYPE (gimple_assign_lhs (stmt))))
1252 enum tree_code code = gimple_assign_rhs_code (stmt);
1253 tree op = gimple_assign_rhs1 (stmt);
1254 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
1255 if (TREE_CODE (op) == code && TREE_CODE (TREE_OPERAND (op, 0)) == SSA_NAME)
1257 gimple *g = SSA_NAME_DEF_STMT (TREE_OPERAND (op, 0));
1258 if (is_gimple_call (g) && gimple_call_internal_p (g))
1260 enum tree_code subcode = ERROR_MARK;
1261 switch (gimple_call_internal_fn (g))
1263 case IFN_ADD_OVERFLOW:
1264 subcode = PLUS_EXPR;
1265 break;
1266 case IFN_SUB_OVERFLOW:
1267 subcode = MINUS_EXPR;
1268 break;
1269 case IFN_MUL_OVERFLOW:
1270 subcode = MULT_EXPR;
1271 break;
1272 case IFN_ATOMIC_COMPARE_EXCHANGE:
1273 if (code == IMAGPART_EXPR)
1275 /* This is the boolean return value whether compare and
1276 exchange changed anything or not. */
1277 vr->set (build_int_cst (type, 0),
1278 build_int_cst (type, 1));
1279 return;
1281 break;
1282 default:
1283 break;
1285 if (subcode != ERROR_MARK)
1287 tree op0 = gimple_call_arg (g, 0);
1288 tree op1 = gimple_call_arg (g, 1);
1289 if (code == IMAGPART_EXPR)
1291 bool ovf = false;
1292 if (check_for_binary_op_overflow (this, subcode, type,
1293 op0, op1, &ovf))
1294 vr->set (build_int_cst (type, ovf));
1295 else if (TYPE_PRECISION (type) == 1
1296 && !TYPE_UNSIGNED (type))
1297 vr->set_varying (type);
1298 else
1299 vr->set (build_int_cst (type, 0),
1300 build_int_cst (type, 1));
1302 else if (types_compatible_p (type, TREE_TYPE (op0))
1303 && types_compatible_p (type, TREE_TYPE (op1)))
1305 bool saved_flag_wrapv = flag_wrapv;
1306 /* Pretend the arithmetics is wrapping. If there is
1307 any overflow, IMAGPART_EXPR will be set. */
1308 flag_wrapv = 1;
1309 extract_range_from_binary_expr (vr, subcode, type,
1310 op0, op1);
1311 flag_wrapv = saved_flag_wrapv;
1313 else
1315 value_range_equiv vr0, vr1;
1316 bool saved_flag_wrapv = flag_wrapv;
1317 /* Pretend the arithmetics is wrapping. If there is
1318 any overflow, IMAGPART_EXPR will be set. */
1319 flag_wrapv = 1;
1320 extract_range_from_unary_expr (&vr0, NOP_EXPR,
1321 type, op0);
1322 extract_range_from_unary_expr (&vr1, NOP_EXPR,
1323 type, op1);
1324 range_fold_binary_expr (vr, subcode, type, &vr0, &vr1);
1325 flag_wrapv = saved_flag_wrapv;
1327 return;
1332 /* None of the below should need a 'type', but we are only called
1333 for assignments and calls with a LHS. */
1334 tree type = TREE_TYPE (gimple_get_lhs (stmt));
1335 if (INTEGRAL_TYPE_P (type)
1336 && gimple_stmt_nonnegative_warnv_p (stmt, &sop))
1337 set_value_range_to_nonnegative (vr, type);
1338 else if (vrp_stmt_computes_nonzero (stmt))
1340 vr->set_nonzero (type);
1341 vr->equiv_clear ();
1343 else
1344 vr->set_varying (type);
1348 /* Try to compute a useful range out of assignment STMT and store it
1349 in *VR. */
1351 void
1352 vr_values::extract_range_from_assignment (value_range_equiv *vr, gassign *stmt)
1354 enum tree_code code = gimple_assign_rhs_code (stmt);
1356 if (code == ASSERT_EXPR)
1357 extract_range_from_assert (vr, gimple_assign_rhs1 (stmt));
1358 else if (code == SSA_NAME)
1359 extract_range_from_ssa_name (vr, gimple_assign_rhs1 (stmt));
1360 else if (TREE_CODE_CLASS (code) == tcc_binary)
1361 extract_range_from_binary_expr (vr, gimple_assign_rhs_code (stmt),
1362 TREE_TYPE (gimple_assign_lhs (stmt)),
1363 gimple_assign_rhs1 (stmt),
1364 gimple_assign_rhs2 (stmt));
1365 else if (TREE_CODE_CLASS (code) == tcc_unary)
1366 extract_range_from_unary_expr (vr, gimple_assign_rhs_code (stmt),
1367 TREE_TYPE (gimple_assign_lhs (stmt)),
1368 gimple_assign_rhs1 (stmt));
1369 else if (code == COND_EXPR)
1370 extract_range_from_cond_expr (vr, stmt);
1371 else if (TREE_CODE_CLASS (code) == tcc_comparison)
1372 extract_range_from_comparison (vr, stmt);
1373 else if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS
1374 && is_gimple_min_invariant (gimple_assign_rhs1 (stmt)))
1375 vr->set (gimple_assign_rhs1 (stmt));
1376 else
1377 vr->set_varying (TREE_TYPE (gimple_assign_lhs (stmt)));
1379 if (vr->varying_p ())
1380 extract_range_basic (vr, stmt);
1383 /* Given two numeric value ranges VR0, VR1 and a comparison code COMP:
1385 - Return BOOLEAN_TRUE_NODE if VR0 COMP VR1 always returns true for
1386 all the values in the ranges.
1388 - Return BOOLEAN_FALSE_NODE if the comparison always returns false.
1390 - Return NULL_TREE if it is not always possible to determine the
1391 value of the comparison.
1393 Also set *STRICT_OVERFLOW_P to indicate whether comparision evaluation
1394 assumed signed overflow is undefined. */
1397 static tree
1398 compare_ranges (enum tree_code comp, const value_range_equiv *vr0,
1399 const value_range_equiv *vr1, bool *strict_overflow_p)
1401 /* VARYING or UNDEFINED ranges cannot be compared. */
1402 if (vr0->varying_p ()
1403 || vr0->undefined_p ()
1404 || vr1->varying_p ()
1405 || vr1->undefined_p ())
1406 return NULL_TREE;
1408 /* Anti-ranges need to be handled separately. */
1409 if (vr0->kind () == VR_ANTI_RANGE || vr1->kind () == VR_ANTI_RANGE)
1411 /* If both are anti-ranges, then we cannot compute any
1412 comparison. */
1413 if (vr0->kind () == VR_ANTI_RANGE && vr1->kind () == VR_ANTI_RANGE)
1414 return NULL_TREE;
1416 /* These comparisons are never statically computable. */
1417 if (comp == GT_EXPR
1418 || comp == GE_EXPR
1419 || comp == LT_EXPR
1420 || comp == LE_EXPR)
1421 return NULL_TREE;
1423 /* Equality can be computed only between a range and an
1424 anti-range. ~[VAL1, VAL2] == [VAL1, VAL2] is always false. */
1425 if (vr0->kind () == VR_RANGE)
1426 /* To simplify processing, make VR0 the anti-range. */
1427 std::swap (vr0, vr1);
1429 gcc_assert (comp == NE_EXPR || comp == EQ_EXPR);
1431 if (compare_values_warnv (vr0->min (), vr1->min (), strict_overflow_p) == 0
1432 && compare_values_warnv (vr0->max (), vr1->max (), strict_overflow_p) == 0)
1433 return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
1435 return NULL_TREE;
1438 /* Simplify processing. If COMP is GT_EXPR or GE_EXPR, switch the
1439 operands around and change the comparison code. */
1440 if (comp == GT_EXPR || comp == GE_EXPR)
1442 comp = (comp == GT_EXPR) ? LT_EXPR : LE_EXPR;
1443 std::swap (vr0, vr1);
1446 if (comp == EQ_EXPR)
1448 /* Equality may only be computed if both ranges represent
1449 exactly one value. */
1450 if (compare_values_warnv (vr0->min (), vr0->max (), strict_overflow_p) == 0
1451 && compare_values_warnv (vr1->min (), vr1->max (), strict_overflow_p) == 0)
1453 int cmp_min = compare_values_warnv (vr0->min (), vr1->min (),
1454 strict_overflow_p);
1455 int cmp_max = compare_values_warnv (vr0->max (), vr1->max (),
1456 strict_overflow_p);
1457 if (cmp_min == 0 && cmp_max == 0)
1458 return boolean_true_node;
1459 else if (cmp_min != -2 && cmp_max != -2)
1460 return boolean_false_node;
1462 /* If [V0_MIN, V1_MAX] < [V1_MIN, V1_MAX] then V0 != V1. */
1463 else if (compare_values_warnv (vr0->min (), vr1->max (),
1464 strict_overflow_p) == 1
1465 || compare_values_warnv (vr1->min (), vr0->max (),
1466 strict_overflow_p) == 1)
1467 return boolean_false_node;
1469 return NULL_TREE;
1471 else if (comp == NE_EXPR)
1473 int cmp1, cmp2;
1475 /* If VR0 is completely to the left or completely to the right
1476 of VR1, they are always different. Notice that we need to
1477 make sure that both comparisons yield similar results to
1478 avoid comparing values that cannot be compared at
1479 compile-time. */
1480 cmp1 = compare_values_warnv (vr0->max (), vr1->min (), strict_overflow_p);
1481 cmp2 = compare_values_warnv (vr0->min (), vr1->max (), strict_overflow_p);
1482 if ((cmp1 == -1 && cmp2 == -1) || (cmp1 == 1 && cmp2 == 1))
1483 return boolean_true_node;
1485 /* If VR0 and VR1 represent a single value and are identical,
1486 return false. */
1487 else if (compare_values_warnv (vr0->min (), vr0->max (),
1488 strict_overflow_p) == 0
1489 && compare_values_warnv (vr1->min (), vr1->max (),
1490 strict_overflow_p) == 0
1491 && compare_values_warnv (vr0->min (), vr1->min (),
1492 strict_overflow_p) == 0
1493 && compare_values_warnv (vr0->max (), vr1->max (),
1494 strict_overflow_p) == 0)
1495 return boolean_false_node;
1497 /* Otherwise, they may or may not be different. */
1498 else
1499 return NULL_TREE;
1501 else if (comp == LT_EXPR || comp == LE_EXPR)
1503 int tst;
1505 /* If VR0 is to the left of VR1, return true. */
1506 tst = compare_values_warnv (vr0->max (), vr1->min (), strict_overflow_p);
1507 if ((comp == LT_EXPR && tst == -1)
1508 || (comp == LE_EXPR && (tst == -1 || tst == 0)))
1509 return boolean_true_node;
1511 /* If VR0 is to the right of VR1, return false. */
1512 tst = compare_values_warnv (vr0->min (), vr1->max (), strict_overflow_p);
1513 if ((comp == LT_EXPR && (tst == 0 || tst == 1))
1514 || (comp == LE_EXPR && tst == 1))
1515 return boolean_false_node;
1517 /* Otherwise, we don't know. */
1518 return NULL_TREE;
1521 gcc_unreachable ();
1524 /* Given a value range VR, a value VAL and a comparison code COMP, return
1525 BOOLEAN_TRUE_NODE if VR COMP VAL always returns true for all the
1526 values in VR. Return BOOLEAN_FALSE_NODE if the comparison
1527 always returns false. Return NULL_TREE if it is not always
1528 possible to determine the value of the comparison. Also set
1529 *STRICT_OVERFLOW_P to indicate whether comparision evaluation
1530 assumed signed overflow is undefined. */
1532 static tree
1533 compare_range_with_value (enum tree_code comp, const value_range *vr,
1534 tree val, bool *strict_overflow_p)
1536 if (vr->varying_p () || vr->undefined_p ())
1537 return NULL_TREE;
1539 /* Anti-ranges need to be handled separately. */
1540 if (vr->kind () == VR_ANTI_RANGE)
1542 /* For anti-ranges, the only predicates that we can compute at
1543 compile time are equality and inequality. */
1544 if (comp == GT_EXPR
1545 || comp == GE_EXPR
1546 || comp == LT_EXPR
1547 || comp == LE_EXPR)
1548 return NULL_TREE;
1550 /* ~[VAL_1, VAL_2] OP VAL is known if VAL_1 <= VAL <= VAL_2. */
1551 if (!vr->may_contain_p (val))
1552 return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
1554 return NULL_TREE;
1557 if (comp == EQ_EXPR)
1559 /* EQ_EXPR may only be computed if VR represents exactly
1560 one value. */
1561 if (compare_values_warnv (vr->min (), vr->max (), strict_overflow_p) == 0)
1563 int cmp = compare_values_warnv (vr->min (), val, strict_overflow_p);
1564 if (cmp == 0)
1565 return boolean_true_node;
1566 else if (cmp == -1 || cmp == 1 || cmp == 2)
1567 return boolean_false_node;
1569 else if (compare_values_warnv (val, vr->min (), strict_overflow_p) == -1
1570 || compare_values_warnv (vr->max (), val, strict_overflow_p) == -1)
1571 return boolean_false_node;
1573 return NULL_TREE;
1575 else if (comp == NE_EXPR)
1577 /* If VAL is not inside VR, then they are always different. */
1578 if (compare_values_warnv (vr->max (), val, strict_overflow_p) == -1
1579 || compare_values_warnv (vr->min (), val, strict_overflow_p) == 1)
1580 return boolean_true_node;
1582 /* If VR represents exactly one value equal to VAL, then return
1583 false. */
1584 if (compare_values_warnv (vr->min (), vr->max (), strict_overflow_p) == 0
1585 && compare_values_warnv (vr->min (), val, strict_overflow_p) == 0)
1586 return boolean_false_node;
1588 /* Otherwise, they may or may not be different. */
1589 return NULL_TREE;
1591 else if (comp == LT_EXPR || comp == LE_EXPR)
1593 int tst;
1595 /* If VR is to the left of VAL, return true. */
1596 tst = compare_values_warnv (vr->max (), val, strict_overflow_p);
1597 if ((comp == LT_EXPR && tst == -1)
1598 || (comp == LE_EXPR && (tst == -1 || tst == 0)))
1599 return boolean_true_node;
1601 /* If VR is to the right of VAL, return false. */
1602 tst = compare_values_warnv (vr->min (), val, strict_overflow_p);
1603 if ((comp == LT_EXPR && (tst == 0 || tst == 1))
1604 || (comp == LE_EXPR && tst == 1))
1605 return boolean_false_node;
1607 /* Otherwise, we don't know. */
1608 return NULL_TREE;
1610 else if (comp == GT_EXPR || comp == GE_EXPR)
1612 int tst;
1614 /* If VR is to the right of VAL, return true. */
1615 tst = compare_values_warnv (vr->min (), val, strict_overflow_p);
1616 if ((comp == GT_EXPR && tst == 1)
1617 || (comp == GE_EXPR && (tst == 0 || tst == 1)))
1618 return boolean_true_node;
1620 /* If VR is to the left of VAL, return false. */
1621 tst = compare_values_warnv (vr->max (), val, strict_overflow_p);
1622 if ((comp == GT_EXPR && (tst == -1 || tst == 0))
1623 || (comp == GE_EXPR && tst == -1))
1624 return boolean_false_node;
1626 /* Otherwise, we don't know. */
1627 return NULL_TREE;
1630 gcc_unreachable ();
1633 /* Given a VAR in STMT within LOOP, determine the bounds of the
1634 variable and store it in MIN/MAX and return TRUE. If no bounds
1635 could be determined, return FALSE. */
1637 bool
1638 bounds_of_var_in_loop (tree *min, tree *max, range_query *query,
1639 class loop *loop, gimple *stmt, tree var)
1641 tree init, step, chrec, tmin, tmax, type = TREE_TYPE (var);
1642 enum ev_direction dir;
1644 chrec = instantiate_parameters (loop, analyze_scalar_evolution (loop, var));
1646 /* Like in PR19590, scev can return a constant function. */
1647 if (is_gimple_min_invariant (chrec))
1649 *min = *max = chrec;
1650 goto fix_overflow;
1653 if (TREE_CODE (chrec) != POLYNOMIAL_CHREC)
1654 return false;
1656 init = initial_condition_in_loop_num (chrec, loop->num);
1657 step = evolution_part_in_loop_num (chrec, loop->num);
1659 if (!init || !step)
1660 return false;
1662 /* If INIT is an SSA with a singleton range, set INIT to said
1663 singleton, otherwise leave INIT alone. */
1664 if (TREE_CODE (init) == SSA_NAME)
1665 query->get_value_range (init, stmt)->singleton_p (&init);
1666 /* Likewise for step. */
1667 if (TREE_CODE (step) == SSA_NAME)
1668 query->get_value_range (step, stmt)->singleton_p (&step);
1670 /* If STEP is symbolic, we can't know whether INIT will be the
1671 minimum or maximum value in the range. Also, unless INIT is
1672 a simple expression, compare_values and possibly other functions
1673 in tree-vrp won't be able to handle it. */
1674 if (step == NULL_TREE
1675 || !is_gimple_min_invariant (step)
1676 || !valid_value_p (init))
1677 return false;
1679 dir = scev_direction (chrec);
1680 if (/* Do not adjust ranges if we do not know whether the iv increases
1681 or decreases, ... */
1682 dir == EV_DIR_UNKNOWN
1683 /* ... or if it may wrap. */
1684 || scev_probably_wraps_p (NULL_TREE, init, step, stmt,
1685 get_chrec_loop (chrec), true))
1686 return false;
1688 if (POINTER_TYPE_P (type) || !TYPE_MIN_VALUE (type))
1689 tmin = lower_bound_in_type (type, type);
1690 else
1691 tmin = TYPE_MIN_VALUE (type);
1692 if (POINTER_TYPE_P (type) || !TYPE_MAX_VALUE (type))
1693 tmax = upper_bound_in_type (type, type);
1694 else
1695 tmax = TYPE_MAX_VALUE (type);
1697 /* Try to use estimated number of iterations for the loop to constrain the
1698 final value in the evolution. */
1699 if (TREE_CODE (step) == INTEGER_CST
1700 && is_gimple_val (init)
1701 && (TREE_CODE (init) != SSA_NAME
1702 || query->get_value_range (init, stmt)->kind () == VR_RANGE))
1704 widest_int nit;
1706 /* We are only entering here for loop header PHI nodes, so using
1707 the number of latch executions is the correct thing to use. */
1708 if (max_loop_iterations (loop, &nit))
1710 signop sgn = TYPE_SIGN (TREE_TYPE (step));
1711 wi::overflow_type overflow;
1713 widest_int wtmp = wi::mul (wi::to_widest (step), nit, sgn,
1714 &overflow);
1715 /* If the multiplication overflowed we can't do a meaningful
1716 adjustment. Likewise if the result doesn't fit in the type
1717 of the induction variable. For a signed type we have to
1718 check whether the result has the expected signedness which
1719 is that of the step as number of iterations is unsigned. */
1720 if (!overflow
1721 && wi::fits_to_tree_p (wtmp, TREE_TYPE (init))
1722 && (sgn == UNSIGNED
1723 || wi::gts_p (wtmp, 0) == wi::gts_p (wi::to_wide (step), 0)))
1725 value_range maxvr, vr0, vr1;
1726 if (TREE_CODE (init) == SSA_NAME)
1727 vr0 = *(query->get_value_range (init, stmt));
1728 else if (is_gimple_min_invariant (init))
1729 vr0.set (init);
1730 else
1731 vr0.set_varying (TREE_TYPE (init));
1732 tree tem = wide_int_to_tree (TREE_TYPE (init), wtmp);
1733 vr1.set (tem, tem);
1734 range_fold_binary_expr (&maxvr, PLUS_EXPR,
1735 TREE_TYPE (init), &vr0, &vr1);
1737 /* Likewise if the addition did. */
1738 if (maxvr.kind () == VR_RANGE)
1740 value_range initvr;
1742 if (TREE_CODE (init) == SSA_NAME)
1743 initvr = *(query->get_value_range (init, stmt));
1744 else if (is_gimple_min_invariant (init))
1745 initvr.set (init);
1746 else
1747 return false;
1749 /* Check if init + nit * step overflows. Though we checked
1750 scev {init, step}_loop doesn't wrap, it is not enough
1751 because the loop may exit immediately. Overflow could
1752 happen in the plus expression in this case. */
1753 if ((dir == EV_DIR_DECREASES
1754 && compare_values (maxvr.min (), initvr.min ()) != -1)
1755 || (dir == EV_DIR_GROWS
1756 && compare_values (maxvr.max (), initvr.max ()) != 1))
1757 return false;
1759 tmin = maxvr.min ();
1760 tmax = maxvr.max ();
1766 *min = tmin;
1767 *max = tmax;
1768 if (dir == EV_DIR_DECREASES)
1769 *max = init;
1770 else
1771 *min = init;
1773 fix_overflow:
1774 /* Even for valid range info, sometimes overflow flag will leak in.
1775 As GIMPLE IL should have no constants with TREE_OVERFLOW set, we
1776 drop them. */
1777 if (TREE_OVERFLOW_P (*min))
1778 *min = drop_tree_overflow (*min);
1779 if (TREE_OVERFLOW_P (*max))
1780 *max = drop_tree_overflow (*max);
1782 gcc_checking_assert (compare_values (*min, *max) != 1);
1783 return true;
1786 /* Given a range VR, a LOOP and a variable VAR, determine whether it
1787 would be profitable to adjust VR using scalar evolution information
1788 for VAR. If so, update VR with the new limits. */
1790 void
1791 vr_values::adjust_range_with_scev (value_range_equiv *vr, class loop *loop,
1792 gimple *stmt, tree var)
1794 tree min, max;
1795 if (bounds_of_var_in_loop (&min, &max, this, loop, stmt, var))
1797 if (vr->undefined_p () || vr->varying_p ())
1799 /* For VARYING or UNDEFINED ranges, just about anything we get
1800 from scalar evolutions should be better. */
1801 vr->update (min, max);
1803 else if (vr->kind () == VR_RANGE)
1805 /* Start with the input range... */
1806 tree vrmin = vr->min ();
1807 tree vrmax = vr->max ();
1809 /* ...and narrow it down with what we got from SCEV. */
1810 if (compare_values (min, vrmin) == 1)
1811 vrmin = min;
1812 if (compare_values (max, vrmax) == -1)
1813 vrmax = max;
1815 vr->update (vrmin, vrmax);
1817 else if (vr->kind () == VR_ANTI_RANGE)
1819 /* ?? As an enhancement, if VR, MIN, and MAX are constants, one
1820 could just intersect VR with a range of [MIN,MAX]. */
1825 /* Dump value ranges of all SSA_NAMEs to FILE. */
1827 void
1828 vr_values::dump (FILE *file)
1830 size_t i;
1832 for (i = 0; i < num_vr_values; i++)
1834 if (vr_value[i] && ssa_name (i))
1836 print_generic_expr (file, ssa_name (i));
1837 fprintf (file, ": ");
1838 dump_value_range (file, vr_value[i]);
1839 fprintf (file, "\n");
1843 fprintf (file, "\n");
1846 /* Initialize VRP lattice. */
1848 vr_values::vr_values () : simplifier (this)
1850 values_propagated = false;
1851 num_vr_values = num_ssa_names * 2;
1852 vr_value = XCNEWVEC (value_range_equiv *, num_vr_values);
1853 vr_phi_edge_counts = XCNEWVEC (int, num_ssa_names);
1854 bitmap_obstack_initialize (&vrp_equiv_obstack);
1857 /* Free VRP lattice. */
1859 vr_values::~vr_values ()
1861 /* Free allocated memory. */
1862 free (vr_value);
1863 free (vr_phi_edge_counts);
1864 bitmap_obstack_release (&vrp_equiv_obstack);
1866 /* So that we can distinguish between VRP data being available
1867 and not available. */
1868 vr_value = NULL;
1869 vr_phi_edge_counts = NULL;
1873 /* A hack. */
1874 static class vr_values *x_vr_values;
1876 /* Return the singleton value-range for NAME or NAME. */
1878 static inline tree
1879 vrp_valueize (tree name)
1881 if (TREE_CODE (name) == SSA_NAME)
1883 const value_range_equiv *vr = x_vr_values->get_value_range (name);
1884 if (vr->kind () == VR_RANGE
1885 && (TREE_CODE (vr->min ()) == SSA_NAME
1886 || is_gimple_min_invariant (vr->min ()))
1887 && vrp_operand_equal_p (vr->min (), vr->max ()))
1888 return vr->min ();
1890 return name;
1893 /* Return the singleton value-range for NAME if that is a constant
1894 but signal to not follow SSA edges. */
1896 static inline tree
1897 vrp_valueize_1 (tree name)
1899 if (TREE_CODE (name) == SSA_NAME)
1901 /* If the definition may be simulated again we cannot follow
1902 this SSA edge as the SSA propagator does not necessarily
1903 re-visit the use. */
1904 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
1905 if (!gimple_nop_p (def_stmt)
1906 && prop_simulate_again_p (def_stmt))
1907 return NULL_TREE;
1908 const value_range_equiv *vr = x_vr_values->get_value_range (name);
1909 tree singleton;
1910 if (vr->singleton_p (&singleton))
1911 return singleton;
1913 return name;
1916 /* Given STMT, an assignment or call, return its LHS if the type
1917 of the LHS is suitable for VRP analysis, else return NULL_TREE. */
1919 tree
1920 get_output_for_vrp (gimple *stmt)
1922 if (!is_gimple_assign (stmt) && !is_gimple_call (stmt))
1923 return NULL_TREE;
1925 /* We only keep track of ranges in integral and pointer types. */
1926 tree lhs = gimple_get_lhs (stmt);
1927 if (TREE_CODE (lhs) == SSA_NAME
1928 && ((INTEGRAL_TYPE_P (TREE_TYPE (lhs))
1929 /* It is valid to have NULL MIN/MAX values on a type. See
1930 build_range_type. */
1931 && TYPE_MIN_VALUE (TREE_TYPE (lhs))
1932 && TYPE_MAX_VALUE (TREE_TYPE (lhs)))
1933 || POINTER_TYPE_P (TREE_TYPE (lhs))))
1934 return lhs;
1936 return NULL_TREE;
1939 /* Visit assignment STMT. If it produces an interesting range, record
1940 the range in VR and set LHS to OUTPUT_P. */
1942 void
1943 vr_values::vrp_visit_assignment_or_call (gimple *stmt, tree *output_p,
1944 value_range_equiv *vr)
1946 tree lhs = get_output_for_vrp (stmt);
1947 *output_p = lhs;
1949 /* We only keep track of ranges in integral and pointer types. */
1950 if (lhs)
1952 enum gimple_code code = gimple_code (stmt);
1954 /* Try folding the statement to a constant first. */
1955 x_vr_values = this;
1956 tree tem = gimple_fold_stmt_to_constant_1 (stmt, vrp_valueize,
1957 vrp_valueize_1);
1958 x_vr_values = NULL;
1959 if (tem)
1961 if (TREE_CODE (tem) == SSA_NAME
1962 && (SSA_NAME_IS_DEFAULT_DEF (tem)
1963 || ! prop_simulate_again_p (SSA_NAME_DEF_STMT (tem))))
1965 extract_range_from_ssa_name (vr, tem);
1966 return;
1968 else if (is_gimple_min_invariant (tem))
1970 vr->set (tem);
1971 return;
1974 /* Then dispatch to value-range extracting functions. */
1975 if (code == GIMPLE_CALL)
1976 extract_range_basic (vr, stmt);
1977 else
1978 extract_range_from_assignment (vr, as_a <gassign *> (stmt));
1982 /* Helper that gets the value range of the SSA_NAME with version I
1983 or a symbolic range containing the SSA_NAME only if the value range
1984 is varying or undefined. Uses TEM as storage for the alternate range. */
1986 const value_range_equiv *
1987 simplify_using_ranges::get_vr_for_comparison (int i, value_range_equiv *tem,
1988 gimple *s)
1990 /* Shallow-copy equiv bitmap. */
1991 const value_range_equiv *vr = query->get_value_range (ssa_name (i), s);
1993 /* If name N_i does not have a valid range, use N_i as its own
1994 range. This allows us to compare against names that may
1995 have N_i in their ranges. */
1996 if (vr->varying_p () || vr->undefined_p ())
1998 tem->set (ssa_name (i));
1999 return tem;
2002 return vr;
2005 /* Compare all the value ranges for names equivalent to VAR with VAL
2006 using comparison code COMP. Return the same value returned by
2007 compare_range_with_value, including the setting of
2008 *STRICT_OVERFLOW_P. */
2010 tree
2011 simplify_using_ranges::compare_name_with_value
2012 (enum tree_code comp, tree var, tree val,
2013 bool *strict_overflow_p, bool use_equiv_p,
2014 gimple *s)
2016 /* Get the set of equivalences for VAR. */
2017 bitmap e = query->get_value_range (var, s)->equiv ();
2019 /* Start at -1. Set it to 0 if we do a comparison without relying
2020 on overflow, or 1 if all comparisons rely on overflow. */
2021 int used_strict_overflow = -1;
2023 /* Compare vars' value range with val. */
2024 value_range_equiv tem_vr;
2025 const value_range_equiv *equiv_vr
2026 = get_vr_for_comparison (SSA_NAME_VERSION (var), &tem_vr, s);
2027 bool sop = false;
2028 tree retval = compare_range_with_value (comp, equiv_vr, val, &sop);
2029 if (retval)
2030 used_strict_overflow = sop ? 1 : 0;
2032 /* If the equiv set is empty we have done all work we need to do. */
2033 if (e == NULL)
2035 if (retval && used_strict_overflow > 0)
2036 *strict_overflow_p = true;
2037 return retval;
2040 unsigned i;
2041 bitmap_iterator bi;
2042 EXECUTE_IF_SET_IN_BITMAP (e, 0, i, bi)
2044 tree name = ssa_name (i);
2045 if (!name)
2046 continue;
2048 if (!use_equiv_p
2049 && !SSA_NAME_IS_DEFAULT_DEF (name)
2050 && prop_simulate_again_p (SSA_NAME_DEF_STMT (name)))
2051 continue;
2053 equiv_vr = get_vr_for_comparison (i, &tem_vr, s);
2054 sop = false;
2055 tree t = compare_range_with_value (comp, equiv_vr, val, &sop);
2056 if (t)
2058 /* If we get different answers from different members
2059 of the equivalence set this check must be in a dead
2060 code region. Folding it to a trap representation
2061 would be correct here. For now just return don't-know. */
2062 if (retval != NULL
2063 && t != retval)
2065 retval = NULL_TREE;
2066 break;
2068 retval = t;
2070 if (!sop)
2071 used_strict_overflow = 0;
2072 else if (used_strict_overflow < 0)
2073 used_strict_overflow = 1;
2077 if (retval && used_strict_overflow > 0)
2078 *strict_overflow_p = true;
2080 return retval;
2084 /* Given a comparison code COMP and names N1 and N2, compare all the
2085 ranges equivalent to N1 against all the ranges equivalent to N2
2086 to determine the value of N1 COMP N2. Return the same value
2087 returned by compare_ranges. Set *STRICT_OVERFLOW_P to indicate
2088 whether we relied on undefined signed overflow in the comparison. */
2091 tree
2092 simplify_using_ranges::compare_names (enum tree_code comp, tree n1, tree n2,
2093 bool *strict_overflow_p, gimple *s)
2095 /* Compare the ranges of every name equivalent to N1 against the
2096 ranges of every name equivalent to N2. */
2097 bitmap e1 = query->get_value_range (n1, s)->equiv ();
2098 bitmap e2 = query->get_value_range (n2, s)->equiv ();
2100 /* Use the fake bitmaps if e1 or e2 are not available. */
2101 static bitmap s_e1 = NULL, s_e2 = NULL;
2102 static bitmap_obstack *s_obstack = NULL;
2103 if (s_obstack == NULL)
2105 s_obstack = XNEW (bitmap_obstack);
2106 bitmap_obstack_initialize (s_obstack);
2107 s_e1 = BITMAP_ALLOC (s_obstack);
2108 s_e2 = BITMAP_ALLOC (s_obstack);
2110 if (e1 == NULL)
2111 e1 = s_e1;
2112 if (e2 == NULL)
2113 e2 = s_e2;
2115 /* Add N1 and N2 to their own set of equivalences to avoid
2116 duplicating the body of the loop just to check N1 and N2
2117 ranges. */
2118 bitmap_set_bit (e1, SSA_NAME_VERSION (n1));
2119 bitmap_set_bit (e2, SSA_NAME_VERSION (n2));
2121 /* If the equivalence sets have a common intersection, then the two
2122 names can be compared without checking their ranges. */
2123 if (bitmap_intersect_p (e1, e2))
2125 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
2126 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
2128 return (comp == EQ_EXPR || comp == GE_EXPR || comp == LE_EXPR)
2129 ? boolean_true_node
2130 : boolean_false_node;
2133 /* Start at -1. Set it to 0 if we do a comparison without relying
2134 on overflow, or 1 if all comparisons rely on overflow. */
2135 int used_strict_overflow = -1;
2137 /* Otherwise, compare all the equivalent ranges. First, add N1 and
2138 N2 to their own set of equivalences to avoid duplicating the body
2139 of the loop just to check N1 and N2 ranges. */
2140 bitmap_iterator bi1;
2141 unsigned i1;
2142 EXECUTE_IF_SET_IN_BITMAP (e1, 0, i1, bi1)
2144 if (!ssa_name (i1))
2145 continue;
2147 value_range_equiv tem_vr1;
2148 const value_range_equiv *vr1 = get_vr_for_comparison (i1, &tem_vr1, s);
2150 tree t = NULL_TREE, retval = NULL_TREE;
2151 bitmap_iterator bi2;
2152 unsigned i2;
2153 EXECUTE_IF_SET_IN_BITMAP (e2, 0, i2, bi2)
2155 if (!ssa_name (i2))
2156 continue;
2158 bool sop = false;
2160 value_range_equiv tem_vr2;
2161 const value_range_equiv *vr2 = get_vr_for_comparison (i2, &tem_vr2,
2164 t = compare_ranges (comp, vr1, vr2, &sop);
2165 if (t)
2167 /* If we get different answers from different members
2168 of the equivalence set this check must be in a dead
2169 code region. Folding it to a trap representation
2170 would be correct here. For now just return don't-know. */
2171 if (retval != NULL && t != retval)
2173 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
2174 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
2175 return NULL_TREE;
2177 retval = t;
2179 if (!sop)
2180 used_strict_overflow = 0;
2181 else if (used_strict_overflow < 0)
2182 used_strict_overflow = 1;
2186 if (retval)
2188 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
2189 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
2190 if (used_strict_overflow > 0)
2191 *strict_overflow_p = true;
2192 return retval;
2196 /* None of the equivalent ranges are useful in computing this
2197 comparison. */
2198 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
2199 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
2200 return NULL_TREE;
2203 /* Helper function for vrp_evaluate_conditional_warnv & other
2204 optimizers. */
2206 tree
2207 simplify_using_ranges::vrp_evaluate_conditional_warnv_with_ops_using_ranges
2208 (enum tree_code code, tree op0, tree op1, bool * strict_overflow_p,
2209 gimple *s)
2211 const value_range_equiv *vr0, *vr1;
2212 vr0 = (TREE_CODE (op0) == SSA_NAME) ? query->get_value_range (op0, s) : NULL;
2213 vr1 = (TREE_CODE (op1) == SSA_NAME) ? query->get_value_range (op1, s) : NULL;
2215 tree res = NULL_TREE;
2216 if (vr0 && vr1)
2217 res = compare_ranges (code, vr0, vr1, strict_overflow_p);
2218 if (!res && vr0)
2219 res = compare_range_with_value (code, vr0, op1, strict_overflow_p);
2220 if (!res && vr1)
2221 res = (compare_range_with_value
2222 (swap_tree_comparison (code), vr1, op0, strict_overflow_p));
2223 return res;
2226 /* Helper function for vrp_evaluate_conditional_warnv. */
2228 tree
2229 simplify_using_ranges::vrp_evaluate_conditional_warnv_with_ops
2230 (gimple *stmt,
2231 enum tree_code code,
2232 tree op0, tree op1,
2233 bool use_equiv_p,
2234 bool *strict_overflow_p,
2235 bool *only_ranges)
2237 tree ret;
2238 if (only_ranges)
2239 *only_ranges = true;
2241 /* We only deal with integral and pointer types. */
2242 if (!INTEGRAL_TYPE_P (TREE_TYPE (op0))
2243 && !POINTER_TYPE_P (TREE_TYPE (op0)))
2244 return NULL_TREE;
2246 /* If OP0 CODE OP1 is an overflow comparison, if it can be expressed
2247 as a simple equality test, then prefer that over its current form
2248 for evaluation.
2250 An overflow test which collapses to an equality test can always be
2251 expressed as a comparison of one argument against zero. Overflow
2252 occurs when the chosen argument is zero and does not occur if the
2253 chosen argument is not zero. */
2254 tree x;
2255 if (overflow_comparison_p (code, op0, op1, use_equiv_p, &x))
2257 wide_int max = wi::max_value (TYPE_PRECISION (TREE_TYPE (op0)), UNSIGNED);
2258 /* B = A - 1; if (A < B) -> B = A - 1; if (A == 0)
2259 B = A - 1; if (A > B) -> B = A - 1; if (A != 0)
2260 B = A + 1; if (B < A) -> B = A + 1; if (B == 0)
2261 B = A + 1; if (B > A) -> B = A + 1; if (B != 0) */
2262 if (integer_zerop (x))
2264 op1 = x;
2265 code = (code == LT_EXPR || code == LE_EXPR) ? EQ_EXPR : NE_EXPR;
2267 /* B = A + 1; if (A > B) -> B = A + 1; if (B == 0)
2268 B = A + 1; if (A < B) -> B = A + 1; if (B != 0)
2269 B = A - 1; if (B > A) -> B = A - 1; if (A == 0)
2270 B = A - 1; if (B < A) -> B = A - 1; if (A != 0) */
2271 else if (wi::to_wide (x) == max - 1)
2273 op0 = op1;
2274 op1 = wide_int_to_tree (TREE_TYPE (op0), 0);
2275 code = (code == GT_EXPR || code == GE_EXPR) ? EQ_EXPR : NE_EXPR;
2277 else
2279 value_range vro, vri;
2280 if (code == GT_EXPR || code == GE_EXPR)
2282 vro.set (TYPE_MIN_VALUE (TREE_TYPE (op0)), x, VR_ANTI_RANGE);
2283 vri.set (TYPE_MIN_VALUE (TREE_TYPE (op0)), x);
2285 else if (code == LT_EXPR || code == LE_EXPR)
2287 vro.set (TYPE_MIN_VALUE (TREE_TYPE (op0)), x);
2288 vri.set (TYPE_MIN_VALUE (TREE_TYPE (op0)), x, VR_ANTI_RANGE);
2290 else
2291 gcc_unreachable ();
2292 const value_range_equiv *vr0 = query->get_value_range (op0, stmt);
2293 /* If vro, the range for OP0 to pass the overflow test, has
2294 no intersection with *vr0, OP0's known range, then the
2295 overflow test can't pass, so return the node for false.
2296 If it is the inverted range, vri, that has no
2297 intersection, then the overflow test must pass, so return
2298 the node for true. In other cases, we could proceed with
2299 a simplified condition comparing OP0 and X, with LE_EXPR
2300 for previously LE_ or LT_EXPR and GT_EXPR otherwise, but
2301 the comments next to the enclosing if suggest it's not
2302 generally profitable to do so. */
2303 vro.intersect (vr0);
2304 if (vro.undefined_p ())
2305 return boolean_false_node;
2306 vri.intersect (vr0);
2307 if (vri.undefined_p ())
2308 return boolean_true_node;
2312 if ((ret = vrp_evaluate_conditional_warnv_with_ops_using_ranges
2313 (code, op0, op1, strict_overflow_p, stmt)))
2314 return ret;
2315 if (only_ranges)
2316 *only_ranges = false;
2317 /* Do not use compare_names during propagation, it's quadratic. */
2318 if (TREE_CODE (op0) == SSA_NAME && TREE_CODE (op1) == SSA_NAME
2319 && use_equiv_p)
2320 return compare_names (code, op0, op1, strict_overflow_p, stmt);
2321 else if (TREE_CODE (op0) == SSA_NAME)
2322 return compare_name_with_value (code, op0, op1,
2323 strict_overflow_p, use_equiv_p, stmt);
2324 else if (TREE_CODE (op1) == SSA_NAME)
2325 return compare_name_with_value (swap_tree_comparison (code), op1, op0,
2326 strict_overflow_p, use_equiv_p, stmt);
2327 return NULL_TREE;
2330 /* Given (CODE OP0 OP1) within STMT, try to simplify it based on value range
2331 information. Return NULL if the conditional cannot be evaluated.
2332 The ranges of all the names equivalent with the operands in COND
2333 will be used when trying to compute the value. If the result is
2334 based on undefined signed overflow, issue a warning if
2335 appropriate. */
2337 tree
2338 simplify_using_ranges::vrp_evaluate_conditional (tree_code code, tree op0,
2339 tree op1, gimple *stmt)
2341 bool sop;
2342 tree ret;
2343 bool only_ranges;
2345 /* Some passes and foldings leak constants with overflow flag set
2346 into the IL. Avoid doing wrong things with these and bail out. */
2347 if ((TREE_CODE (op0) == INTEGER_CST
2348 && TREE_OVERFLOW (op0))
2349 || (TREE_CODE (op1) == INTEGER_CST
2350 && TREE_OVERFLOW (op1)))
2351 return NULL_TREE;
2353 sop = false;
2354 ret = vrp_evaluate_conditional_warnv_with_ops (stmt, code, op0, op1, true,
2355 &sop, &only_ranges);
2357 if (ret && sop)
2359 enum warn_strict_overflow_code wc;
2360 const char* warnmsg;
2362 if (is_gimple_min_invariant (ret))
2364 wc = WARN_STRICT_OVERFLOW_CONDITIONAL;
2365 warnmsg = G_("assuming signed overflow does not occur when "
2366 "simplifying conditional to constant");
2368 else
2370 wc = WARN_STRICT_OVERFLOW_COMPARISON;
2371 warnmsg = G_("assuming signed overflow does not occur when "
2372 "simplifying conditional");
2375 if (issue_strict_overflow_warning (wc))
2377 location_t location;
2379 if (!gimple_has_location (stmt))
2380 location = input_location;
2381 else
2382 location = gimple_location (stmt);
2383 warning_at (location, OPT_Wstrict_overflow, "%s", warnmsg);
2387 if (warn_type_limits
2388 && ret && only_ranges
2389 && TREE_CODE_CLASS (code) == tcc_comparison
2390 && TREE_CODE (op0) == SSA_NAME)
2392 /* If the comparison is being folded and the operand on the LHS
2393 is being compared against a constant value that is outside of
2394 the natural range of OP0's type, then the predicate will
2395 always fold regardless of the value of OP0. If -Wtype-limits
2396 was specified, emit a warning. */
2397 tree type = TREE_TYPE (op0);
2398 const value_range_equiv *vr0 = query->get_value_range (op0, stmt);
2400 if (vr0->varying_p ()
2401 && INTEGRAL_TYPE_P (type)
2402 && is_gimple_min_invariant (op1))
2404 location_t location;
2406 if (!gimple_has_location (stmt))
2407 location = input_location;
2408 else
2409 location = gimple_location (stmt);
2411 warning_at (location, OPT_Wtype_limits,
2412 integer_zerop (ret)
2413 ? G_("comparison always false "
2414 "due to limited range of data type")
2415 : G_("comparison always true "
2416 "due to limited range of data type"));
2420 return ret;
2424 /* Visit conditional statement STMT. If we can determine which edge
2425 will be taken out of STMT's basic block, record it in
2426 *TAKEN_EDGE_P. Otherwise, set *TAKEN_EDGE_P to NULL. */
2428 void
2429 simplify_using_ranges::vrp_visit_cond_stmt (gcond *stmt, edge *taken_edge_p)
2431 tree val;
2433 *taken_edge_p = NULL;
2435 if (dump_file && (dump_flags & TDF_DETAILS))
2437 tree use;
2438 ssa_op_iter i;
2440 fprintf (dump_file, "\nVisiting conditional with predicate: ");
2441 print_gimple_stmt (dump_file, stmt, 0);
2442 fprintf (dump_file, "\nWith known ranges\n");
2444 FOR_EACH_SSA_TREE_OPERAND (use, stmt, i, SSA_OP_USE)
2446 fprintf (dump_file, "\t");
2447 print_generic_expr (dump_file, use);
2448 fprintf (dump_file, ": ");
2449 dump_value_range (dump_file, query->get_value_range (use, stmt));
2452 fprintf (dump_file, "\n");
2455 /* Compute the value of the predicate COND by checking the known
2456 ranges of each of its operands.
2458 Note that we cannot evaluate all the equivalent ranges here
2459 because those ranges may not yet be final and with the current
2460 propagation strategy, we cannot determine when the value ranges
2461 of the names in the equivalence set have changed.
2463 For instance, given the following code fragment
2465 i_5 = PHI <8, i_13>
2467 i_14 = ASSERT_EXPR <i_5, i_5 != 0>
2468 if (i_14 == 1)
2471 Assume that on the first visit to i_14, i_5 has the temporary
2472 range [8, 8] because the second argument to the PHI function is
2473 not yet executable. We derive the range ~[0, 0] for i_14 and the
2474 equivalence set { i_5 }. So, when we visit 'if (i_14 == 1)' for
2475 the first time, since i_14 is equivalent to the range [8, 8], we
2476 determine that the predicate is always false.
2478 On the next round of propagation, i_13 is determined to be
2479 VARYING, which causes i_5 to drop down to VARYING. So, another
2480 visit to i_14 is scheduled. In this second visit, we compute the
2481 exact same range and equivalence set for i_14, namely ~[0, 0] and
2482 { i_5 }. But we did not have the previous range for i_5
2483 registered, so vrp_visit_assignment thinks that the range for
2484 i_14 has not changed. Therefore, the predicate 'if (i_14 == 1)'
2485 is not visited again, which stops propagation from visiting
2486 statements in the THEN clause of that if().
2488 To properly fix this we would need to keep the previous range
2489 value for the names in the equivalence set. This way we would've
2490 discovered that from one visit to the other i_5 changed from
2491 range [8, 8] to VR_VARYING.
2493 However, fixing this apparent limitation may not be worth the
2494 additional checking. Testing on several code bases (GCC, DLV,
2495 MICO, TRAMP3D and SPEC2000) showed that doing this results in
2496 4 more predicates folded in SPEC. */
2498 bool sop;
2499 val = vrp_evaluate_conditional_warnv_with_ops (stmt,
2500 gimple_cond_code (stmt),
2501 gimple_cond_lhs (stmt),
2502 gimple_cond_rhs (stmt),
2503 false, &sop, NULL);
2504 if (val)
2505 *taken_edge_p = find_taken_edge (gimple_bb (stmt), val);
2507 if (dump_file && (dump_flags & TDF_DETAILS))
2509 fprintf (dump_file, "\nPredicate evaluates to: ");
2510 if (val == NULL_TREE)
2511 fprintf (dump_file, "DON'T KNOW\n");
2512 else
2513 print_generic_stmt (dump_file, val);
2517 /* Searches the case label vector VEC for the ranges of CASE_LABELs that are
2518 used in range VR. The indices are placed in MIN_IDX1, MAX_IDX, MIN_IDX2 and
2519 MAX_IDX2. If the ranges of CASE_LABELs are empty then MAX_IDX1 < MIN_IDX1.
2520 Returns true if the default label is not needed. */
2522 static bool
2523 find_case_label_ranges (gswitch *stmt, const value_range *vr,
2524 size_t *min_idx1, size_t *max_idx1,
2525 size_t *min_idx2, size_t *max_idx2)
2527 size_t i, j, k, l;
2528 unsigned int n = gimple_switch_num_labels (stmt);
2529 bool take_default;
2530 tree case_low, case_high;
2531 tree min = vr->min (), max = vr->max ();
2533 gcc_checking_assert (!vr->varying_p () && !vr->undefined_p ());
2535 take_default = !find_case_label_range (stmt, min, max, &i, &j);
2537 /* Set second range to empty. */
2538 *min_idx2 = 1;
2539 *max_idx2 = 0;
2541 if (vr->kind () == VR_RANGE)
2543 *min_idx1 = i;
2544 *max_idx1 = j;
2545 return !take_default;
2548 /* Set first range to all case labels. */
2549 *min_idx1 = 1;
2550 *max_idx1 = n - 1;
2552 if (i > j)
2553 return false;
2555 /* Make sure all the values of case labels [i , j] are contained in
2556 range [MIN, MAX]. */
2557 case_low = CASE_LOW (gimple_switch_label (stmt, i));
2558 case_high = CASE_HIGH (gimple_switch_label (stmt, j));
2559 if (tree_int_cst_compare (case_low, min) < 0)
2560 i += 1;
2561 if (case_high != NULL_TREE
2562 && tree_int_cst_compare (max, case_high) < 0)
2563 j -= 1;
2565 if (i > j)
2566 return false;
2568 /* If the range spans case labels [i, j], the corresponding anti-range spans
2569 the labels [1, i - 1] and [j + 1, n - 1]. */
2570 k = j + 1;
2571 l = n - 1;
2572 if (k > l)
2574 k = 1;
2575 l = 0;
2578 j = i - 1;
2579 i = 1;
2580 if (i > j)
2582 i = k;
2583 j = l;
2584 k = 1;
2585 l = 0;
2588 *min_idx1 = i;
2589 *max_idx1 = j;
2590 *min_idx2 = k;
2591 *max_idx2 = l;
2592 return false;
2595 /* Visit switch statement STMT. If we can determine which edge
2596 will be taken out of STMT's basic block, record it in
2597 *TAKEN_EDGE_P. Otherwise, *TAKEN_EDGE_P set to NULL. */
2599 void
2600 vr_values::vrp_visit_switch_stmt (gswitch *stmt, edge *taken_edge_p)
2602 tree op, val;
2603 const value_range_equiv *vr;
2604 size_t i = 0, j = 0, k, l;
2605 bool take_default;
2607 *taken_edge_p = NULL;
2608 op = gimple_switch_index (stmt);
2609 if (TREE_CODE (op) != SSA_NAME)
2610 return;
2612 vr = get_value_range (op);
2613 if (dump_file && (dump_flags & TDF_DETAILS))
2615 fprintf (dump_file, "\nVisiting switch expression with operand ");
2616 print_generic_expr (dump_file, op);
2617 fprintf (dump_file, " with known range ");
2618 dump_value_range (dump_file, vr);
2619 fprintf (dump_file, "\n");
2622 if (vr->undefined_p ()
2623 || vr->varying_p ()
2624 || vr->symbolic_p ())
2625 return;
2627 /* Find the single edge that is taken from the switch expression. */
2628 take_default = !find_case_label_ranges (stmt, vr, &i, &j, &k, &l);
2630 /* Check if the range spans no CASE_LABEL. If so, we only reach the default
2631 label */
2632 if (j < i)
2634 gcc_assert (take_default);
2635 val = gimple_switch_default_label (stmt);
2637 else
2639 /* Check if labels with index i to j and maybe the default label
2640 are all reaching the same label. */
2642 val = gimple_switch_label (stmt, i);
2643 if (take_default
2644 && CASE_LABEL (gimple_switch_default_label (stmt))
2645 != CASE_LABEL (val))
2647 if (dump_file && (dump_flags & TDF_DETAILS))
2648 fprintf (dump_file, " not a single destination for this "
2649 "range\n");
2650 return;
2652 for (++i; i <= j; ++i)
2654 if (CASE_LABEL (gimple_switch_label (stmt, i)) != CASE_LABEL (val))
2656 if (dump_file && (dump_flags & TDF_DETAILS))
2657 fprintf (dump_file, " not a single destination for this "
2658 "range\n");
2659 return;
2662 for (; k <= l; ++k)
2664 if (CASE_LABEL (gimple_switch_label (stmt, k)) != CASE_LABEL (val))
2666 if (dump_file && (dump_flags & TDF_DETAILS))
2667 fprintf (dump_file, " not a single destination for this "
2668 "range\n");
2669 return;
2674 *taken_edge_p = find_edge (gimple_bb (stmt),
2675 label_to_block (cfun, CASE_LABEL (val)));
2677 if (dump_file && (dump_flags & TDF_DETAILS))
2679 fprintf (dump_file, " will take edge to ");
2680 print_generic_stmt (dump_file, CASE_LABEL (val));
2685 /* Evaluate statement STMT. If the statement produces a useful range,
2686 set VR and corepsponding OUTPUT_P.
2688 If STMT is a conditional branch and we can determine its truth
2689 value, the taken edge is recorded in *TAKEN_EDGE_P. */
2691 void
2692 vr_values::extract_range_from_stmt (gimple *stmt, edge *taken_edge_p,
2693 tree *output_p, value_range_equiv *vr)
2696 if (dump_file && (dump_flags & TDF_DETAILS))
2698 fprintf (dump_file, "\nextract_range_from_stmt visiting:\n");
2699 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
2702 if (!stmt_interesting_for_vrp (stmt))
2703 gcc_assert (stmt_ends_bb_p (stmt));
2704 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
2705 vrp_visit_assignment_or_call (stmt, output_p, vr);
2706 else if (gimple_code (stmt) == GIMPLE_COND)
2707 simplifier.vrp_visit_cond_stmt (as_a <gcond *> (stmt), taken_edge_p);
2708 else if (gimple_code (stmt) == GIMPLE_SWITCH)
2709 vrp_visit_switch_stmt (as_a <gswitch *> (stmt), taken_edge_p);
2712 /* Visit all arguments for PHI node PHI that flow through executable
2713 edges. If a valid value range can be derived from all the incoming
2714 value ranges, set a new range in VR_RESULT. */
2716 void
2717 vr_values::extract_range_from_phi_node (gphi *phi,
2718 value_range_equiv *vr_result)
2720 tree lhs = PHI_RESULT (phi);
2721 const value_range_equiv *lhs_vr = get_value_range (lhs);
2722 bool first = true;
2723 int old_edges;
2724 class loop *l;
2726 if (dump_file && (dump_flags & TDF_DETAILS))
2728 fprintf (dump_file, "\nVisiting PHI node: ");
2729 print_gimple_stmt (dump_file, phi, 0, dump_flags);
2732 bool may_simulate_backedge_again = false;
2733 int edges = 0;
2734 for (size_t i = 0; i < gimple_phi_num_args (phi); i++)
2736 edge e = gimple_phi_arg_edge (phi, i);
2738 if (dump_file && (dump_flags & TDF_DETAILS))
2740 fprintf (dump_file,
2741 " Argument #%d (%d -> %d %sexecutable)\n",
2742 (int) i, e->src->index, e->dest->index,
2743 (e->flags & EDGE_EXECUTABLE) ? "" : "not ");
2746 if (e->flags & EDGE_EXECUTABLE)
2748 value_range_equiv vr_arg_tem;
2749 const value_range_equiv *vr_arg = &vr_arg_tem;
2751 ++edges;
2753 tree arg = PHI_ARG_DEF (phi, i);
2754 if (TREE_CODE (arg) == SSA_NAME)
2756 /* See if we are eventually going to change one of the args. */
2757 gimple *def_stmt = SSA_NAME_DEF_STMT (arg);
2758 if (! gimple_nop_p (def_stmt)
2759 && prop_simulate_again_p (def_stmt)
2760 && e->flags & EDGE_DFS_BACK)
2761 may_simulate_backedge_again = true;
2763 const value_range_equiv *vr_arg_ = get_value_range (arg);
2764 /* Do not allow equivalences or symbolic ranges to leak in from
2765 backedges. That creates invalid equivalencies.
2766 See PR53465 and PR54767. */
2767 if (e->flags & EDGE_DFS_BACK)
2769 if (!vr_arg_->varying_p () && !vr_arg_->undefined_p ())
2771 vr_arg_tem.set (vr_arg_->min (), vr_arg_->max (), NULL,
2772 vr_arg_->kind ());
2773 if (vr_arg_tem.symbolic_p ())
2774 vr_arg_tem.set_varying (TREE_TYPE (arg));
2776 else
2777 vr_arg = vr_arg_;
2779 /* If the non-backedge arguments range is VR_VARYING then
2780 we can still try recording a simple equivalence. */
2781 else if (vr_arg_->varying_p ())
2782 vr_arg_tem.set (arg);
2783 else
2784 vr_arg = vr_arg_;
2786 else
2788 if (TREE_OVERFLOW_P (arg))
2789 arg = drop_tree_overflow (arg);
2791 vr_arg_tem.set (arg);
2794 if (dump_file && (dump_flags & TDF_DETAILS))
2796 fprintf (dump_file, "\t");
2797 print_generic_expr (dump_file, arg, dump_flags);
2798 fprintf (dump_file, ": ");
2799 dump_value_range (dump_file, vr_arg);
2800 fprintf (dump_file, "\n");
2803 if (first)
2804 vr_result->deep_copy (vr_arg);
2805 else
2806 vr_result->union_ (vr_arg);
2807 first = false;
2809 if (vr_result->varying_p ())
2810 break;
2814 if (vr_result->varying_p ())
2815 goto varying;
2816 else if (vr_result->undefined_p ())
2817 goto update_range;
2819 old_edges = vr_phi_edge_counts[SSA_NAME_VERSION (lhs)];
2820 vr_phi_edge_counts[SSA_NAME_VERSION (lhs)] = edges;
2822 /* To prevent infinite iterations in the algorithm, derive ranges
2823 when the new value is slightly bigger or smaller than the
2824 previous one. We don't do this if we have seen a new executable
2825 edge; this helps us avoid an infinity for conditionals
2826 which are not in a loop. If the old value-range was VR_UNDEFINED
2827 use the updated range and iterate one more time. If we will not
2828 simulate this PHI again via the backedge allow us to iterate. */
2829 if (edges > 0
2830 && gimple_phi_num_args (phi) > 1
2831 && edges == old_edges
2832 && !lhs_vr->undefined_p ()
2833 && may_simulate_backedge_again)
2835 /* Compare old and new ranges, fall back to varying if the
2836 values are not comparable. */
2837 int cmp_min = compare_values (lhs_vr->min (), vr_result->min ());
2838 if (cmp_min == -2)
2839 goto varying;
2840 int cmp_max = compare_values (lhs_vr->max (), vr_result->max ());
2841 if (cmp_max == -2)
2842 goto varying;
2844 /* For non VR_RANGE or for pointers fall back to varying if
2845 the range changed. */
2846 if ((lhs_vr->kind () != VR_RANGE || vr_result->kind () != VR_RANGE
2847 || POINTER_TYPE_P (TREE_TYPE (lhs)))
2848 && (cmp_min != 0 || cmp_max != 0))
2849 goto varying;
2851 /* If the new minimum is larger than the previous one
2852 retain the old value. If the new minimum value is smaller
2853 than the previous one and not -INF go all the way to -INF + 1.
2854 In the first case, to avoid infinite bouncing between different
2855 minimums, and in the other case to avoid iterating millions of
2856 times to reach -INF. Going to -INF + 1 also lets the following
2857 iteration compute whether there will be any overflow, at the
2858 expense of one additional iteration. */
2859 tree new_min = vr_result->min ();
2860 tree new_max = vr_result->max ();
2861 if (cmp_min < 0)
2862 new_min = lhs_vr->min ();
2863 else if (cmp_min > 0
2864 && (TREE_CODE (vr_result->min ()) != INTEGER_CST
2865 || tree_int_cst_lt (vrp_val_min (vr_result->type ()),
2866 vr_result->min ())))
2867 new_min = int_const_binop (PLUS_EXPR,
2868 vrp_val_min (vr_result->type ()),
2869 build_int_cst (vr_result->type (), 1));
2871 /* Similarly for the maximum value. */
2872 if (cmp_max > 0)
2873 new_max = lhs_vr->max ();
2874 else if (cmp_max < 0
2875 && (TREE_CODE (vr_result->max ()) != INTEGER_CST
2876 || tree_int_cst_lt (vr_result->max (),
2877 vrp_val_max (vr_result->type ()))))
2878 new_max = int_const_binop (MINUS_EXPR,
2879 vrp_val_max (vr_result->type ()),
2880 build_int_cst (vr_result->type (), 1));
2882 vr_result->update (new_min, new_max, vr_result->kind ());
2884 /* If we dropped either bound to +-INF then if this is a loop
2885 PHI node SCEV may known more about its value-range. */
2886 if (cmp_min > 0 || cmp_min < 0
2887 || cmp_max < 0 || cmp_max > 0)
2888 goto scev_check;
2890 goto infinite_check;
2893 goto update_range;
2895 varying:
2896 vr_result->set_varying (TREE_TYPE (lhs));
2898 scev_check:
2899 /* If this is a loop PHI node SCEV may known more about its value-range.
2900 scev_check can be reached from two paths, one is a fall through from above
2901 "varying" label, the other is direct goto from code block which tries to
2902 avoid infinite simulation. */
2903 if (scev_initialized_p ()
2904 && (l = loop_containing_stmt (phi))
2905 && l->header == gimple_bb (phi))
2906 adjust_range_with_scev (vr_result, l, phi, lhs);
2908 infinite_check:
2909 /* If we will end up with a (-INF, +INF) range, set it to
2910 VARYING. Same if the previous max value was invalid for
2911 the type and we end up with vr_result.min > vr_result.max. */
2912 if ((!vr_result->varying_p () && !vr_result->undefined_p ())
2913 && !((vrp_val_is_max (vr_result->max ()) && vrp_val_is_min (vr_result->min ()))
2914 || compare_values (vr_result->min (), vr_result->max ()) > 0))
2916 else
2917 vr_result->set_varying (TREE_TYPE (lhs));
2919 /* If the new range is different than the previous value, keep
2920 iterating. */
2921 update_range:
2922 return;
2925 /* Simplify boolean operations if the source is known
2926 to be already a boolean. */
2927 bool
2928 simplify_using_ranges::simplify_truth_ops_using_ranges
2929 (gimple_stmt_iterator *gsi,
2930 gimple *stmt)
2932 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
2933 tree lhs, op0, op1;
2934 bool need_conversion;
2936 /* We handle only !=/== case here. */
2937 gcc_assert (rhs_code == EQ_EXPR || rhs_code == NE_EXPR);
2939 op0 = gimple_assign_rhs1 (stmt);
2940 if (!op_with_boolean_value_range_p (op0, stmt))
2941 return false;
2943 op1 = gimple_assign_rhs2 (stmt);
2944 if (!op_with_boolean_value_range_p (op1, stmt))
2945 return false;
2947 /* Reduce number of cases to handle to NE_EXPR. As there is no
2948 BIT_XNOR_EXPR we cannot replace A == B with a single statement. */
2949 if (rhs_code == EQ_EXPR)
2951 if (TREE_CODE (op1) == INTEGER_CST)
2952 op1 = int_const_binop (BIT_XOR_EXPR, op1,
2953 build_int_cst (TREE_TYPE (op1), 1));
2954 else
2955 return false;
2958 lhs = gimple_assign_lhs (stmt);
2959 need_conversion
2960 = !useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (op0));
2962 /* Make sure to not sign-extend a 1-bit 1 when converting the result. */
2963 if (need_conversion
2964 && !TYPE_UNSIGNED (TREE_TYPE (op0))
2965 && TYPE_PRECISION (TREE_TYPE (op0)) == 1
2966 && TYPE_PRECISION (TREE_TYPE (lhs)) > 1)
2967 return false;
2969 /* For A != 0 we can substitute A itself. */
2970 if (integer_zerop (op1))
2971 gimple_assign_set_rhs_with_ops (gsi,
2972 need_conversion
2973 ? NOP_EXPR : TREE_CODE (op0), op0);
2974 /* For A != B we substitute A ^ B. Either with conversion. */
2975 else if (need_conversion)
2977 tree tem = make_ssa_name (TREE_TYPE (op0));
2978 gassign *newop
2979 = gimple_build_assign (tem, BIT_XOR_EXPR, op0, op1);
2980 gsi_insert_before (gsi, newop, GSI_SAME_STMT);
2981 if (INTEGRAL_TYPE_P (TREE_TYPE (tem))
2982 && TYPE_PRECISION (TREE_TYPE (tem)) > 1)
2983 set_range_info (tem, VR_RANGE,
2984 wi::zero (TYPE_PRECISION (TREE_TYPE (tem))),
2985 wi::one (TYPE_PRECISION (TREE_TYPE (tem))));
2986 gimple_assign_set_rhs_with_ops (gsi, NOP_EXPR, tem);
2988 /* Or without. */
2989 else
2990 gimple_assign_set_rhs_with_ops (gsi, BIT_XOR_EXPR, op0, op1);
2991 update_stmt (gsi_stmt (*gsi));
2992 fold_stmt (gsi, follow_single_use_edges);
2994 return true;
2997 /* Simplify a division or modulo operator to a right shift or bitwise and
2998 if the first operand is unsigned or is greater than zero and the second
2999 operand is an exact power of two. For TRUNC_MOD_EXPR op0 % op1 with
3000 constant op1 (op1min = op1) or with op1 in [op1min, op1max] range,
3001 optimize it into just op0 if op0's range is known to be a subset of
3002 [-op1min + 1, op1min - 1] for signed and [0, op1min - 1] for unsigned
3003 modulo. */
3005 bool
3006 simplify_using_ranges::simplify_div_or_mod_using_ranges
3007 (gimple_stmt_iterator *gsi,
3008 gimple *stmt)
3010 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
3011 tree val = NULL;
3012 tree op0 = gimple_assign_rhs1 (stmt);
3013 tree op1 = gimple_assign_rhs2 (stmt);
3014 tree op0min = NULL_TREE, op0max = NULL_TREE;
3015 tree op1min = op1;
3016 const value_range *vr = NULL;
3018 if (TREE_CODE (op0) == INTEGER_CST)
3020 op0min = op0;
3021 op0max = op0;
3023 else
3025 vr = query->get_value_range (op0, stmt);
3026 if (range_int_cst_p (vr))
3028 op0min = vr->min ();
3029 op0max = vr->max ();
3033 if (rhs_code == TRUNC_MOD_EXPR
3034 && TREE_CODE (op1) == SSA_NAME)
3036 const value_range_equiv *vr1 = query->get_value_range (op1, stmt);
3037 if (range_int_cst_p (vr1))
3038 op1min = vr1->min ();
3040 if (rhs_code == TRUNC_MOD_EXPR
3041 && TREE_CODE (op1min) == INTEGER_CST
3042 && tree_int_cst_sgn (op1min) == 1
3043 && op0max
3044 && tree_int_cst_lt (op0max, op1min))
3046 if (TYPE_UNSIGNED (TREE_TYPE (op0))
3047 || tree_int_cst_sgn (op0min) >= 0
3048 || tree_int_cst_lt (fold_unary (NEGATE_EXPR, TREE_TYPE (op1min), op1min),
3049 op0min))
3051 /* If op0 already has the range op0 % op1 has,
3052 then TRUNC_MOD_EXPR won't change anything. */
3053 gimple_assign_set_rhs_from_tree (gsi, op0);
3054 return true;
3058 if (TREE_CODE (op0) != SSA_NAME)
3059 return false;
3061 if (!integer_pow2p (op1))
3063 /* X % -Y can be only optimized into X % Y either if
3064 X is not INT_MIN, or Y is not -1. Fold it now, as after
3065 remove_range_assertions the range info might be not available
3066 anymore. */
3067 if (rhs_code == TRUNC_MOD_EXPR
3068 && fold_stmt (gsi, follow_single_use_edges))
3069 return true;
3070 return false;
3073 if (TYPE_UNSIGNED (TREE_TYPE (op0)))
3074 val = integer_one_node;
3075 else
3077 bool sop = false;
3079 val = compare_range_with_value (GE_EXPR, vr, integer_zero_node, &sop);
3081 if (val
3082 && sop
3083 && integer_onep (val)
3084 && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
3086 location_t location;
3088 if (!gimple_has_location (stmt))
3089 location = input_location;
3090 else
3091 location = gimple_location (stmt);
3092 warning_at (location, OPT_Wstrict_overflow,
3093 "assuming signed overflow does not occur when "
3094 "simplifying %</%> or %<%%%> to %<>>%> or %<&%>");
3098 if (val && integer_onep (val))
3100 tree t;
3102 if (rhs_code == TRUNC_DIV_EXPR)
3104 t = build_int_cst (integer_type_node, tree_log2 (op1));
3105 gimple_assign_set_rhs_code (stmt, RSHIFT_EXPR);
3106 gimple_assign_set_rhs1 (stmt, op0);
3107 gimple_assign_set_rhs2 (stmt, t);
3109 else
3111 t = build_int_cst (TREE_TYPE (op1), 1);
3112 t = int_const_binop (MINUS_EXPR, op1, t);
3113 t = fold_convert (TREE_TYPE (op0), t);
3115 gimple_assign_set_rhs_code (stmt, BIT_AND_EXPR);
3116 gimple_assign_set_rhs1 (stmt, op0);
3117 gimple_assign_set_rhs2 (stmt, t);
3120 update_stmt (stmt);
3121 fold_stmt (gsi, follow_single_use_edges);
3122 return true;
3125 return false;
3128 /* Simplify a min or max if the ranges of the two operands are
3129 disjoint. Return true if we do simplify. */
3131 bool
3132 simplify_using_ranges::simplify_min_or_max_using_ranges
3133 (gimple_stmt_iterator *gsi,
3134 gimple *stmt)
3136 tree op0 = gimple_assign_rhs1 (stmt);
3137 tree op1 = gimple_assign_rhs2 (stmt);
3138 bool sop = false;
3139 tree val;
3141 val = (vrp_evaluate_conditional_warnv_with_ops_using_ranges
3142 (LE_EXPR, op0, op1, &sop, stmt));
3143 if (!val)
3145 sop = false;
3146 val = (vrp_evaluate_conditional_warnv_with_ops_using_ranges
3147 (LT_EXPR, op0, op1, &sop, stmt));
3150 if (val)
3152 if (sop && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
3154 location_t location;
3156 if (!gimple_has_location (stmt))
3157 location = input_location;
3158 else
3159 location = gimple_location (stmt);
3160 warning_at (location, OPT_Wstrict_overflow,
3161 "assuming signed overflow does not occur when "
3162 "simplifying %<min/max (X,Y)%> to %<X%> or %<Y%>");
3165 /* VAL == TRUE -> OP0 < or <= op1
3166 VAL == FALSE -> OP0 > or >= op1. */
3167 tree res = ((gimple_assign_rhs_code (stmt) == MAX_EXPR)
3168 == integer_zerop (val)) ? op0 : op1;
3169 gimple_assign_set_rhs_from_tree (gsi, res);
3170 return true;
3173 return false;
3176 /* If the operand to an ABS_EXPR is >= 0, then eliminate the
3177 ABS_EXPR. If the operand is <= 0, then simplify the
3178 ABS_EXPR into a NEGATE_EXPR. */
3180 bool
3181 simplify_using_ranges::simplify_abs_using_ranges (gimple_stmt_iterator *gsi,
3182 gimple *stmt)
3184 tree op = gimple_assign_rhs1 (stmt);
3185 const value_range *vr = query->get_value_range (op, stmt);
3187 if (vr)
3189 tree val = NULL;
3190 bool sop = false;
3192 val = compare_range_with_value (LE_EXPR, vr, integer_zero_node, &sop);
3193 if (!val)
3195 /* The range is neither <= 0 nor > 0. Now see if it is
3196 either < 0 or >= 0. */
3197 sop = false;
3198 val = compare_range_with_value (LT_EXPR, vr, integer_zero_node,
3199 &sop);
3202 if (val)
3204 if (sop && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
3206 location_t location;
3208 if (!gimple_has_location (stmt))
3209 location = input_location;
3210 else
3211 location = gimple_location (stmt);
3212 warning_at (location, OPT_Wstrict_overflow,
3213 "assuming signed overflow does not occur when "
3214 "simplifying %<abs (X)%> to %<X%> or %<-X%>");
3217 gimple_assign_set_rhs1 (stmt, op);
3218 if (integer_zerop (val))
3219 gimple_assign_set_rhs_code (stmt, SSA_NAME);
3220 else
3221 gimple_assign_set_rhs_code (stmt, NEGATE_EXPR);
3222 update_stmt (stmt);
3223 fold_stmt (gsi, follow_single_use_edges);
3224 return true;
3228 return false;
3231 /* value_range wrapper for wi_set_zero_nonzero_bits.
3233 Return TRUE if VR was a constant range and we were able to compute
3234 the bit masks. */
3236 static bool
3237 vr_set_zero_nonzero_bits (const tree expr_type,
3238 const value_range *vr,
3239 wide_int *may_be_nonzero,
3240 wide_int *must_be_nonzero)
3242 if (range_int_cst_p (vr))
3244 wi_set_zero_nonzero_bits (expr_type,
3245 wi::to_wide (vr->min ()),
3246 wi::to_wide (vr->max ()),
3247 *may_be_nonzero, *must_be_nonzero);
3248 return true;
3250 *may_be_nonzero = wi::minus_one (TYPE_PRECISION (expr_type));
3251 *must_be_nonzero = wi::zero (TYPE_PRECISION (expr_type));
3252 return false;
3255 /* Optimize away redundant BIT_AND_EXPR and BIT_IOR_EXPR.
3256 If all the bits that are being cleared by & are already
3257 known to be zero from VR, or all the bits that are being
3258 set by | are already known to be one from VR, the bit
3259 operation is redundant. */
3261 bool
3262 simplify_using_ranges::simplify_bit_ops_using_ranges
3263 (gimple_stmt_iterator *gsi,
3264 gimple *stmt)
3266 tree op0 = gimple_assign_rhs1 (stmt);
3267 tree op1 = gimple_assign_rhs2 (stmt);
3268 tree op = NULL_TREE;
3269 value_range vr0, vr1;
3270 wide_int may_be_nonzero0, may_be_nonzero1;
3271 wide_int must_be_nonzero0, must_be_nonzero1;
3272 wide_int mask;
3274 if (TREE_CODE (op0) == SSA_NAME)
3275 vr0 = *(query->get_value_range (op0, stmt));
3276 else if (is_gimple_min_invariant (op0))
3277 vr0.set (op0);
3278 else
3279 return false;
3281 if (TREE_CODE (op1) == SSA_NAME)
3282 vr1 = *(query->get_value_range (op1, stmt));
3283 else if (is_gimple_min_invariant (op1))
3284 vr1.set (op1);
3285 else
3286 return false;
3288 if (!vr_set_zero_nonzero_bits (TREE_TYPE (op0), &vr0, &may_be_nonzero0,
3289 &must_be_nonzero0))
3290 return false;
3291 if (!vr_set_zero_nonzero_bits (TREE_TYPE (op1), &vr1, &may_be_nonzero1,
3292 &must_be_nonzero1))
3293 return false;
3295 switch (gimple_assign_rhs_code (stmt))
3297 case BIT_AND_EXPR:
3298 mask = wi::bit_and_not (may_be_nonzero0, must_be_nonzero1);
3299 if (mask == 0)
3301 op = op0;
3302 break;
3304 mask = wi::bit_and_not (may_be_nonzero1, must_be_nonzero0);
3305 if (mask == 0)
3307 op = op1;
3308 break;
3310 break;
3311 case BIT_IOR_EXPR:
3312 mask = wi::bit_and_not (may_be_nonzero0, must_be_nonzero1);
3313 if (mask == 0)
3315 op = op1;
3316 break;
3318 mask = wi::bit_and_not (may_be_nonzero1, must_be_nonzero0);
3319 if (mask == 0)
3321 op = op0;
3322 break;
3324 break;
3325 default:
3326 gcc_unreachable ();
3329 if (op == NULL_TREE)
3330 return false;
3332 gimple_assign_set_rhs_with_ops (gsi, TREE_CODE (op), op);
3333 update_stmt (gsi_stmt (*gsi));
3334 return true;
3337 /* We are comparing trees OP0 and OP1 using COND_CODE. OP0 has
3338 a known value range VR.
3340 If there is one and only one value which will satisfy the
3341 conditional, then return that value. Else return NULL.
3343 If signed overflow must be undefined for the value to satisfy
3344 the conditional, then set *STRICT_OVERFLOW_P to true. */
3346 static tree
3347 test_for_singularity (enum tree_code cond_code, tree op0,
3348 tree op1, const value_range *vr)
3350 tree min = NULL;
3351 tree max = NULL;
3353 /* Extract minimum/maximum values which satisfy the conditional as it was
3354 written. */
3355 if (cond_code == LE_EXPR || cond_code == LT_EXPR)
3357 min = TYPE_MIN_VALUE (TREE_TYPE (op0));
3359 max = op1;
3360 if (cond_code == LT_EXPR)
3362 tree one = build_int_cst (TREE_TYPE (op0), 1);
3363 max = fold_build2 (MINUS_EXPR, TREE_TYPE (op0), max, one);
3364 /* Signal to compare_values_warnv this expr doesn't overflow. */
3365 if (EXPR_P (max))
3366 suppress_warning (max, OPT_Woverflow);
3369 else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
3371 max = TYPE_MAX_VALUE (TREE_TYPE (op0));
3373 min = op1;
3374 if (cond_code == GT_EXPR)
3376 tree one = build_int_cst (TREE_TYPE (op0), 1);
3377 min = fold_build2 (PLUS_EXPR, TREE_TYPE (op0), min, one);
3378 /* Signal to compare_values_warnv this expr doesn't overflow. */
3379 if (EXPR_P (min))
3380 suppress_warning (min, OPT_Woverflow);
3384 /* Now refine the minimum and maximum values using any
3385 value range information we have for op0. */
3386 if (min && max)
3388 tree type = TREE_TYPE (op0);
3389 tree tmin = wide_int_to_tree (type, vr->lower_bound ());
3390 tree tmax = wide_int_to_tree (type, vr->upper_bound ());
3391 if (compare_values (tmin, min) == 1)
3392 min = tmin;
3393 if (compare_values (tmax, max) == -1)
3394 max = tmax;
3396 /* If the new min/max values have converged to a single value,
3397 then there is only one value which can satisfy the condition,
3398 return that value. */
3399 if (operand_equal_p (min, max, 0) && is_gimple_min_invariant (min))
3400 return min;
3402 return NULL;
3405 /* Return whether the value range *VR fits in an integer type specified
3406 by PRECISION and UNSIGNED_P. */
3408 bool
3409 range_fits_type_p (const value_range *vr,
3410 unsigned dest_precision, signop dest_sgn)
3412 tree src_type;
3413 unsigned src_precision;
3414 widest_int tem;
3415 signop src_sgn;
3417 /* We can only handle integral and pointer types. */
3418 src_type = vr->type ();
3419 if (!INTEGRAL_TYPE_P (src_type)
3420 && !POINTER_TYPE_P (src_type))
3421 return false;
3423 /* An extension is fine unless VR is SIGNED and dest_sgn is UNSIGNED,
3424 and so is an identity transform. */
3425 src_precision = TYPE_PRECISION (vr->type ());
3426 src_sgn = TYPE_SIGN (src_type);
3427 if ((src_precision < dest_precision
3428 && !(dest_sgn == UNSIGNED && src_sgn == SIGNED))
3429 || (src_precision == dest_precision && src_sgn == dest_sgn))
3430 return true;
3432 /* Now we can only handle ranges with constant bounds. */
3433 if (!range_int_cst_p (vr))
3434 return false;
3436 /* For sign changes, the MSB of the wide_int has to be clear.
3437 An unsigned value with its MSB set cannot be represented by
3438 a signed wide_int, while a negative value cannot be represented
3439 by an unsigned wide_int. */
3440 if (src_sgn != dest_sgn
3441 && (wi::lts_p (wi::to_wide (vr->min ()), 0)
3442 || wi::lts_p (wi::to_wide (vr->max ()), 0)))
3443 return false;
3445 /* Then we can perform the conversion on both ends and compare
3446 the result for equality. */
3447 tem = wi::ext (wi::to_widest (vr->min ()), dest_precision, dest_sgn);
3448 if (tem != wi::to_widest (vr->min ()))
3449 return false;
3450 tem = wi::ext (wi::to_widest (vr->max ()), dest_precision, dest_sgn);
3451 if (tem != wi::to_widest (vr->max ()))
3452 return false;
3454 return true;
3457 // Clear edge E of EDGE_EXECUTABLE (it is unexecutable). If it wasn't
3458 // previously clear, propagate to successor blocks if appropriate.
3460 void
3461 simplify_using_ranges::set_and_propagate_unexecutable (edge e)
3463 // If not_executable is already set, we're done.
3464 // This works in the absence of a flag as well.
3465 if ((e->flags & m_not_executable_flag) == m_not_executable_flag)
3466 return;
3468 e->flags |= m_not_executable_flag;
3469 m_flag_set_edges.safe_push (e);
3471 // Check if the destination block needs to propagate the property.
3472 basic_block bb = e->dest;
3474 // If any incoming edge is executable, we are done.
3475 edge_iterator ei;
3476 FOR_EACH_EDGE (e, ei, bb->preds)
3477 if ((e->flags & m_not_executable_flag) == 0)
3478 return;
3480 // This block is also unexecutable, propagate to all exit edges as well.
3481 FOR_EACH_EDGE (e, ei, bb->succs)
3482 set_and_propagate_unexecutable (e);
3485 /* If COND can be folded entirely as TRUE or FALSE, rewrite the
3486 conditional as such, and return TRUE. */
3488 bool
3489 simplify_using_ranges::fold_cond (gcond *cond)
3491 int_range_max r;
3492 if (query->range_of_stmt (r, cond) && r.singleton_p ())
3494 // COND has already been folded if arguments are constant.
3495 if (TREE_CODE (gimple_cond_lhs (cond)) != SSA_NAME
3496 && TREE_CODE (gimple_cond_rhs (cond)) != SSA_NAME)
3497 return false;
3498 if (dump_file)
3500 fprintf (dump_file, "Folding predicate ");
3501 print_gimple_expr (dump_file, cond, 0);
3502 fprintf (dump_file, " to ");
3504 edge e0 = EDGE_SUCC (gimple_bb (cond), 0);
3505 edge e1 = EDGE_SUCC (gimple_bb (cond), 1);
3506 if (r.zero_p ())
3508 if (dump_file)
3509 fprintf (dump_file, "0\n");
3510 gimple_cond_make_false (cond);
3511 if (e0->flags & EDGE_TRUE_VALUE)
3512 set_and_propagate_unexecutable (e0);
3513 else
3514 set_and_propagate_unexecutable (e1);
3516 else
3518 if (dump_file)
3519 fprintf (dump_file, "1\n");
3520 gimple_cond_make_true (cond);
3521 if (e0->flags & EDGE_FALSE_VALUE)
3522 set_and_propagate_unexecutable (e0);
3523 else
3524 set_and_propagate_unexecutable (e1);
3526 update_stmt (cond);
3527 return true;
3530 /* ?? vrp_folder::fold_predicate_in() is a superset of this. At
3531 some point we should merge all variants of this code. */
3532 edge taken_edge;
3533 vrp_visit_cond_stmt (cond, &taken_edge);
3535 if (taken_edge)
3537 if (taken_edge->flags & EDGE_TRUE_VALUE)
3539 if (dump_file && (dump_flags & TDF_DETAILS))
3540 fprintf (dump_file, "\nVRP Predicate evaluates to: 1\n");
3541 gimple_cond_make_true (cond);
3543 else if (taken_edge->flags & EDGE_FALSE_VALUE)
3545 if (dump_file && (dump_flags & TDF_DETAILS))
3546 fprintf (dump_file, "\nVRP Predicate evaluates to: 0\n");
3547 gimple_cond_make_false (cond);
3549 else
3550 gcc_unreachable ();
3551 update_stmt (cond);
3552 return true;
3554 return false;
3557 /* Simplify a conditional using a relational operator to an equality
3558 test if the range information indicates only one value can satisfy
3559 the original conditional. */
3561 bool
3562 simplify_using_ranges::simplify_cond_using_ranges_1 (gcond *stmt)
3564 tree op0 = gimple_cond_lhs (stmt);
3565 tree op1 = gimple_cond_rhs (stmt);
3566 enum tree_code cond_code = gimple_cond_code (stmt);
3568 if (fold_cond (stmt))
3569 return true;
3571 if (cond_code != NE_EXPR
3572 && cond_code != EQ_EXPR
3573 && TREE_CODE (op0) == SSA_NAME
3574 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
3575 && is_gimple_min_invariant (op1))
3577 const value_range *vr = query->get_value_range (op0, stmt);
3579 /* If we have range information for OP0, then we might be
3580 able to simplify this conditional. */
3581 if (!vr->undefined_p () && !vr->varying_p ())
3583 tree new_tree = test_for_singularity (cond_code, op0, op1, vr);
3584 if (new_tree)
3586 if (dump_file)
3588 fprintf (dump_file, "Simplified relational ");
3589 print_gimple_stmt (dump_file, stmt, 0);
3590 fprintf (dump_file, " into ");
3593 gimple_cond_set_code (stmt, EQ_EXPR);
3594 gimple_cond_set_lhs (stmt, op0);
3595 gimple_cond_set_rhs (stmt, new_tree);
3597 update_stmt (stmt);
3599 if (dump_file)
3601 print_gimple_stmt (dump_file, stmt, 0);
3602 fprintf (dump_file, "\n");
3605 return true;
3608 /* Try again after inverting the condition. We only deal
3609 with integral types here, so no need to worry about
3610 issues with inverting FP comparisons. */
3611 new_tree = test_for_singularity
3612 (invert_tree_comparison (cond_code, false),
3613 op0, op1, vr);
3614 if (new_tree)
3616 if (dump_file)
3618 fprintf (dump_file, "Simplified relational ");
3619 print_gimple_stmt (dump_file, stmt, 0);
3620 fprintf (dump_file, " into ");
3623 gimple_cond_set_code (stmt, NE_EXPR);
3624 gimple_cond_set_lhs (stmt, op0);
3625 gimple_cond_set_rhs (stmt, new_tree);
3627 update_stmt (stmt);
3629 if (dump_file)
3631 print_gimple_stmt (dump_file, stmt, 0);
3632 fprintf (dump_file, "\n");
3635 return true;
3639 // Try to simplify casted conditions.
3640 return simplify_casted_cond (stmt);
3643 /* STMT is a conditional at the end of a basic block.
3645 If the conditional is of the form SSA_NAME op constant and the SSA_NAME
3646 was set via a type conversion, try to replace the SSA_NAME with the RHS
3647 of the type conversion. Doing so makes the conversion dead which helps
3648 subsequent passes. */
3650 bool
3651 simplify_using_ranges::simplify_casted_cond (gcond *stmt)
3653 tree op0 = gimple_cond_lhs (stmt);
3654 tree op1 = gimple_cond_rhs (stmt);
3656 /* If we have a comparison of an SSA_NAME (OP0) against a constant,
3657 see if OP0 was set by a type conversion where the source of
3658 the conversion is another SSA_NAME with a range that fits
3659 into the range of OP0's type.
3661 If so, the conversion is redundant as the earlier SSA_NAME can be
3662 used for the comparison directly if we just massage the constant in the
3663 comparison. */
3664 if (TREE_CODE (op0) == SSA_NAME
3665 && TREE_CODE (op1) == INTEGER_CST)
3667 gimple *def_stmt = SSA_NAME_DEF_STMT (op0);
3668 tree innerop;
3670 if (!is_gimple_assign (def_stmt))
3671 return false;
3673 switch (gimple_assign_rhs_code (def_stmt))
3675 CASE_CONVERT:
3676 innerop = gimple_assign_rhs1 (def_stmt);
3677 break;
3678 case VIEW_CONVERT_EXPR:
3679 innerop = TREE_OPERAND (gimple_assign_rhs1 (def_stmt), 0);
3680 if (!INTEGRAL_TYPE_P (TREE_TYPE (innerop)))
3681 return false;
3682 break;
3683 default:
3684 return false;
3687 if (TREE_CODE (innerop) == SSA_NAME
3688 && !POINTER_TYPE_P (TREE_TYPE (innerop))
3689 && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (innerop)
3690 && desired_pro_or_demotion_p (TREE_TYPE (innerop), TREE_TYPE (op0)))
3692 const value_range *vr = query->get_value_range (innerop);
3694 if (range_int_cst_p (vr)
3695 && range_fits_type_p (vr,
3696 TYPE_PRECISION (TREE_TYPE (op0)),
3697 TYPE_SIGN (TREE_TYPE (op0)))
3698 && int_fits_type_p (op1, TREE_TYPE (innerop)))
3700 tree newconst = fold_convert (TREE_TYPE (innerop), op1);
3701 gimple_cond_set_lhs (stmt, innerop);
3702 gimple_cond_set_rhs (stmt, newconst);
3703 update_stmt (stmt);
3704 return true;
3708 return false;
3711 /* Simplify a switch statement using the value range of the switch
3712 argument. */
3714 bool
3715 simplify_using_ranges::simplify_switch_using_ranges (gswitch *stmt)
3717 tree op = gimple_switch_index (stmt);
3718 const value_range *vr = NULL;
3719 bool take_default;
3720 edge e;
3721 edge_iterator ei;
3722 size_t i = 0, j = 0, n, n2;
3723 tree vec2;
3724 switch_update su;
3725 size_t k = 1, l = 0;
3727 if (TREE_CODE (op) == SSA_NAME)
3729 vr = query->get_value_range (op, stmt);
3731 /* We can only handle integer ranges. */
3732 if (vr->varying_p ()
3733 || vr->undefined_p ()
3734 || vr->symbolic_p ())
3735 return false;
3737 /* Find case label for min/max of the value range. */
3738 take_default = !find_case_label_ranges (stmt, vr, &i, &j, &k, &l);
3740 else if (TREE_CODE (op) == INTEGER_CST)
3742 take_default = !find_case_label_index (stmt, 1, op, &i);
3743 if (take_default)
3745 i = 1;
3746 j = 0;
3748 else
3750 j = i;
3753 else
3754 return false;
3756 n = gimple_switch_num_labels (stmt);
3758 /* We can truncate the case label ranges that partially overlap with OP's
3759 value range. */
3760 size_t min_idx = 1, max_idx = 0;
3761 if (vr != NULL)
3762 find_case_label_range (stmt, vr->min (), vr->max (), &min_idx, &max_idx);
3763 if (min_idx <= max_idx)
3765 tree min_label = gimple_switch_label (stmt, min_idx);
3766 tree max_label = gimple_switch_label (stmt, max_idx);
3768 /* Avoid changing the type of the case labels when truncating. */
3769 tree case_label_type = TREE_TYPE (CASE_LOW (min_label));
3770 tree vr_min = fold_convert (case_label_type, vr->min ());
3771 tree vr_max = fold_convert (case_label_type, vr->max ());
3773 if (vr->kind () == VR_RANGE)
3775 /* If OP's value range is [2,8] and the low label range is
3776 0 ... 3, truncate the label's range to 2 .. 3. */
3777 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
3778 && CASE_HIGH (min_label) != NULL_TREE
3779 && tree_int_cst_compare (CASE_HIGH (min_label), vr_min) >= 0)
3780 CASE_LOW (min_label) = vr_min;
3782 /* If OP's value range is [2,8] and the high label range is
3783 7 ... 10, truncate the label's range to 7 .. 8. */
3784 if (tree_int_cst_compare (CASE_LOW (max_label), vr_max) <= 0
3785 && CASE_HIGH (max_label) != NULL_TREE
3786 && tree_int_cst_compare (CASE_HIGH (max_label), vr_max) > 0)
3787 CASE_HIGH (max_label) = vr_max;
3789 else if (vr->kind () == VR_ANTI_RANGE)
3791 tree one_cst = build_one_cst (case_label_type);
3793 if (min_label == max_label)
3795 /* If OP's value range is ~[7,8] and the label's range is
3796 7 ... 10, truncate the label's range to 9 ... 10. */
3797 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) == 0
3798 && CASE_HIGH (min_label) != NULL_TREE
3799 && tree_int_cst_compare (CASE_HIGH (min_label), vr_max) > 0)
3800 CASE_LOW (min_label)
3801 = int_const_binop (PLUS_EXPR, vr_max, one_cst);
3803 /* If OP's value range is ~[7,8] and the label's range is
3804 5 ... 8, truncate the label's range to 5 ... 6. */
3805 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
3806 && CASE_HIGH (min_label) != NULL_TREE
3807 && tree_int_cst_compare (CASE_HIGH (min_label), vr_max) == 0)
3808 CASE_HIGH (min_label)
3809 = int_const_binop (MINUS_EXPR, vr_min, one_cst);
3811 else
3813 /* If OP's value range is ~[2,8] and the low label range is
3814 0 ... 3, truncate the label's range to 0 ... 1. */
3815 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
3816 && CASE_HIGH (min_label) != NULL_TREE
3817 && tree_int_cst_compare (CASE_HIGH (min_label), vr_min) >= 0)
3818 CASE_HIGH (min_label)
3819 = int_const_binop (MINUS_EXPR, vr_min, one_cst);
3821 /* If OP's value range is ~[2,8] and the high label range is
3822 7 ... 10, truncate the label's range to 9 ... 10. */
3823 if (tree_int_cst_compare (CASE_LOW (max_label), vr_max) <= 0
3824 && CASE_HIGH (max_label) != NULL_TREE
3825 && tree_int_cst_compare (CASE_HIGH (max_label), vr_max) > 0)
3826 CASE_LOW (max_label)
3827 = int_const_binop (PLUS_EXPR, vr_max, one_cst);
3831 /* Canonicalize singleton case ranges. */
3832 if (tree_int_cst_equal (CASE_LOW (min_label), CASE_HIGH (min_label)))
3833 CASE_HIGH (min_label) = NULL_TREE;
3834 if (tree_int_cst_equal (CASE_LOW (max_label), CASE_HIGH (max_label)))
3835 CASE_HIGH (max_label) = NULL_TREE;
3838 /* We can also eliminate case labels that lie completely outside OP's value
3839 range. */
3841 /* Bail out if this is just all edges taken. */
3842 if (i == 1
3843 && j == n - 1
3844 && take_default)
3845 return false;
3847 /* Build a new vector of taken case labels. */
3848 vec2 = make_tree_vec (j - i + 1 + l - k + 1 + (int)take_default);
3849 n2 = 0;
3851 /* Add the default edge, if necessary. */
3852 if (take_default)
3853 TREE_VEC_ELT (vec2, n2++) = gimple_switch_default_label (stmt);
3855 for (; i <= j; ++i, ++n2)
3856 TREE_VEC_ELT (vec2, n2) = gimple_switch_label (stmt, i);
3858 for (; k <= l; ++k, ++n2)
3859 TREE_VEC_ELT (vec2, n2) = gimple_switch_label (stmt, k);
3861 /* Mark needed edges. */
3862 for (i = 0; i < n2; ++i)
3864 e = find_edge (gimple_bb (stmt),
3865 label_to_block (cfun,
3866 CASE_LABEL (TREE_VEC_ELT (vec2, i))));
3867 e->aux = (void *)-1;
3870 /* Queue not needed edges for later removal. */
3871 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
3873 if (e->aux == (void *)-1)
3875 e->aux = NULL;
3876 continue;
3879 if (dump_file && (dump_flags & TDF_DETAILS))
3881 fprintf (dump_file, "removing unreachable case label\n");
3883 to_remove_edges.safe_push (e);
3884 set_and_propagate_unexecutable (e);
3885 e->flags &= ~EDGE_EXECUTABLE;
3886 e->flags |= EDGE_IGNORE;
3889 /* And queue an update for the stmt. */
3890 su.stmt = stmt;
3891 su.vec = vec2;
3892 to_update_switch_stmts.safe_push (su);
3893 return true;
3896 void
3897 simplify_using_ranges::cleanup_edges_and_switches (void)
3899 int i;
3900 edge e;
3901 switch_update *su;
3903 /* Clear any edges marked as not executable. */
3904 if (m_not_executable_flag)
3906 FOR_EACH_VEC_ELT (m_flag_set_edges, i, e)
3907 e->flags &= ~m_not_executable_flag;
3909 /* Remove dead edges from SWITCH_EXPR optimization. This leaves the
3910 CFG in a broken state and requires a cfg_cleanup run. */
3911 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
3912 remove_edge (e);
3914 /* Update SWITCH_EXPR case label vector. */
3915 FOR_EACH_VEC_ELT (to_update_switch_stmts, i, su)
3917 size_t j;
3918 size_t n = TREE_VEC_LENGTH (su->vec);
3919 tree label;
3920 gimple_switch_set_num_labels (su->stmt, n);
3921 for (j = 0; j < n; j++)
3922 gimple_switch_set_label (su->stmt, j, TREE_VEC_ELT (su->vec, j));
3923 /* As we may have replaced the default label with a regular one
3924 make sure to make it a real default label again. This ensures
3925 optimal expansion. */
3926 label = gimple_switch_label (su->stmt, 0);
3927 CASE_LOW (label) = NULL_TREE;
3928 CASE_HIGH (label) = NULL_TREE;
3931 if (!to_remove_edges.is_empty ())
3933 free_dominance_info (CDI_DOMINATORS);
3934 loops_state_set (LOOPS_NEED_FIXUP);
3937 to_remove_edges.release ();
3938 to_update_switch_stmts.release ();
3941 /* Simplify an integral conversion from an SSA name in STMT. */
3943 static bool
3944 simplify_conversion_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
3946 tree innerop, middleop, finaltype;
3947 gimple *def_stmt;
3948 signop inner_sgn, middle_sgn, final_sgn;
3949 unsigned inner_prec, middle_prec, final_prec;
3950 widest_int innermin, innermed, innermax, middlemin, middlemed, middlemax;
3952 finaltype = TREE_TYPE (gimple_assign_lhs (stmt));
3953 if (!INTEGRAL_TYPE_P (finaltype))
3954 return false;
3955 middleop = gimple_assign_rhs1 (stmt);
3956 def_stmt = SSA_NAME_DEF_STMT (middleop);
3957 if (!is_gimple_assign (def_stmt)
3958 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)))
3959 return false;
3960 innerop = gimple_assign_rhs1 (def_stmt);
3961 if (TREE_CODE (innerop) != SSA_NAME
3962 || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (innerop))
3963 return false;
3965 /* Get the value-range of the inner operand. Use global ranges in
3966 case innerop was created during substitute-and-fold. */
3967 wide_int imin, imax;
3968 value_range vr;
3969 if (!INTEGRAL_TYPE_P (TREE_TYPE (innerop)))
3970 return false;
3971 get_range_query (cfun)->range_of_expr (vr, innerop, stmt);
3972 if (vr.undefined_p () || vr.varying_p ())
3973 return false;
3974 innermin = widest_int::from (vr.lower_bound (), TYPE_SIGN (TREE_TYPE (innerop)));
3975 innermax = widest_int::from (vr.upper_bound (), TYPE_SIGN (TREE_TYPE (innerop)));
3977 /* Simulate the conversion chain to check if the result is equal if
3978 the middle conversion is removed. */
3979 inner_prec = TYPE_PRECISION (TREE_TYPE (innerop));
3980 middle_prec = TYPE_PRECISION (TREE_TYPE (middleop));
3981 final_prec = TYPE_PRECISION (finaltype);
3983 /* If the first conversion is not injective, the second must not
3984 be widening. */
3985 if (wi::gtu_p (innermax - innermin,
3986 wi::mask <widest_int> (middle_prec, false))
3987 && middle_prec < final_prec)
3988 return false;
3989 /* We also want a medium value so that we can track the effect that
3990 narrowing conversions with sign change have. */
3991 inner_sgn = TYPE_SIGN (TREE_TYPE (innerop));
3992 if (inner_sgn == UNSIGNED)
3993 innermed = wi::shifted_mask <widest_int> (1, inner_prec - 1, false);
3994 else
3995 innermed = 0;
3996 if (wi::cmp (innermin, innermed, inner_sgn) >= 0
3997 || wi::cmp (innermed, innermax, inner_sgn) >= 0)
3998 innermed = innermin;
4000 middle_sgn = TYPE_SIGN (TREE_TYPE (middleop));
4001 middlemin = wi::ext (innermin, middle_prec, middle_sgn);
4002 middlemed = wi::ext (innermed, middle_prec, middle_sgn);
4003 middlemax = wi::ext (innermax, middle_prec, middle_sgn);
4005 /* Require that the final conversion applied to both the original
4006 and the intermediate range produces the same result. */
4007 final_sgn = TYPE_SIGN (finaltype);
4008 if (wi::ext (middlemin, final_prec, final_sgn)
4009 != wi::ext (innermin, final_prec, final_sgn)
4010 || wi::ext (middlemed, final_prec, final_sgn)
4011 != wi::ext (innermed, final_prec, final_sgn)
4012 || wi::ext (middlemax, final_prec, final_sgn)
4013 != wi::ext (innermax, final_prec, final_sgn))
4014 return false;
4016 gimple_assign_set_rhs1 (stmt, innerop);
4017 fold_stmt (gsi, follow_single_use_edges);
4018 return true;
4021 /* Simplify a conversion from integral SSA name to float in STMT. */
4023 bool
4024 simplify_using_ranges::simplify_float_conversion_using_ranges
4025 (gimple_stmt_iterator *gsi,
4026 gimple *stmt)
4028 tree rhs1 = gimple_assign_rhs1 (stmt);
4029 const value_range *vr = query->get_value_range (rhs1, stmt);
4030 scalar_float_mode fltmode
4031 = SCALAR_FLOAT_TYPE_MODE (TREE_TYPE (gimple_assign_lhs (stmt)));
4032 scalar_int_mode mode;
4033 tree tem;
4034 gassign *conv;
4036 /* We can only handle constant ranges. */
4037 if (!range_int_cst_p (vr))
4038 return false;
4040 /* First check if we can use a signed type in place of an unsigned. */
4041 scalar_int_mode rhs_mode = SCALAR_INT_TYPE_MODE (TREE_TYPE (rhs1));
4042 if (TYPE_UNSIGNED (TREE_TYPE (rhs1))
4043 && can_float_p (fltmode, rhs_mode, 0) != CODE_FOR_nothing
4044 && range_fits_type_p (vr, TYPE_PRECISION (TREE_TYPE (rhs1)), SIGNED))
4045 mode = rhs_mode;
4046 /* If we can do the conversion in the current input mode do nothing. */
4047 else if (can_float_p (fltmode, rhs_mode,
4048 TYPE_UNSIGNED (TREE_TYPE (rhs1))) != CODE_FOR_nothing)
4049 return false;
4050 /* Otherwise search for a mode we can use, starting from the narrowest
4051 integer mode available. */
4052 else
4054 mode = NARROWEST_INT_MODE;
4055 for (;;)
4057 /* If we cannot do a signed conversion to float from mode
4058 or if the value-range does not fit in the signed type
4059 try with a wider mode. */
4060 if (can_float_p (fltmode, mode, 0) != CODE_FOR_nothing
4061 && range_fits_type_p (vr, GET_MODE_PRECISION (mode), SIGNED))
4062 break;
4064 /* But do not widen the input. Instead leave that to the
4065 optabs expansion code. */
4066 if (!GET_MODE_WIDER_MODE (mode).exists (&mode)
4067 || GET_MODE_PRECISION (mode) > TYPE_PRECISION (TREE_TYPE (rhs1)))
4068 return false;
4072 /* It works, insert a truncation or sign-change before the
4073 float conversion. */
4074 tem = make_ssa_name (build_nonstandard_integer_type
4075 (GET_MODE_PRECISION (mode), 0));
4076 conv = gimple_build_assign (tem, NOP_EXPR, rhs1);
4077 gsi_insert_before (gsi, conv, GSI_SAME_STMT);
4078 gimple_assign_set_rhs1 (stmt, tem);
4079 fold_stmt (gsi, follow_single_use_edges);
4081 return true;
4084 /* Simplify an internal fn call using ranges if possible. */
4086 bool
4087 simplify_using_ranges::simplify_internal_call_using_ranges
4088 (gimple_stmt_iterator *gsi,
4089 gimple *stmt)
4091 enum tree_code subcode;
4092 bool is_ubsan = false;
4093 bool ovf = false;
4094 switch (gimple_call_internal_fn (stmt))
4096 case IFN_UBSAN_CHECK_ADD:
4097 subcode = PLUS_EXPR;
4098 is_ubsan = true;
4099 break;
4100 case IFN_UBSAN_CHECK_SUB:
4101 subcode = MINUS_EXPR;
4102 is_ubsan = true;
4103 break;
4104 case IFN_UBSAN_CHECK_MUL:
4105 subcode = MULT_EXPR;
4106 is_ubsan = true;
4107 break;
4108 case IFN_ADD_OVERFLOW:
4109 subcode = PLUS_EXPR;
4110 break;
4111 case IFN_SUB_OVERFLOW:
4112 subcode = MINUS_EXPR;
4113 break;
4114 case IFN_MUL_OVERFLOW:
4115 subcode = MULT_EXPR;
4116 break;
4117 default:
4118 return false;
4121 tree op0 = gimple_call_arg (stmt, 0);
4122 tree op1 = gimple_call_arg (stmt, 1);
4123 tree type;
4124 if (is_ubsan)
4126 type = TREE_TYPE (op0);
4127 if (VECTOR_TYPE_P (type))
4128 return false;
4130 else if (gimple_call_lhs (stmt) == NULL_TREE)
4131 return false;
4132 else
4133 type = TREE_TYPE (TREE_TYPE (gimple_call_lhs (stmt)));
4134 if (!check_for_binary_op_overflow (query, subcode, type, op0, op1, &ovf, stmt)
4135 || (is_ubsan && ovf))
4136 return false;
4138 gimple *g;
4139 location_t loc = gimple_location (stmt);
4140 if (is_ubsan)
4141 g = gimple_build_assign (gimple_call_lhs (stmt), subcode, op0, op1);
4142 else
4144 int prec = TYPE_PRECISION (type);
4145 tree utype = type;
4146 if (ovf
4147 || !useless_type_conversion_p (type, TREE_TYPE (op0))
4148 || !useless_type_conversion_p (type, TREE_TYPE (op1)))
4149 utype = build_nonstandard_integer_type (prec, 1);
4150 if (TREE_CODE (op0) == INTEGER_CST)
4151 op0 = fold_convert (utype, op0);
4152 else if (!useless_type_conversion_p (utype, TREE_TYPE (op0)))
4154 g = gimple_build_assign (make_ssa_name (utype), NOP_EXPR, op0);
4155 gimple_set_location (g, loc);
4156 gsi_insert_before (gsi, g, GSI_SAME_STMT);
4157 op0 = gimple_assign_lhs (g);
4159 if (TREE_CODE (op1) == INTEGER_CST)
4160 op1 = fold_convert (utype, op1);
4161 else if (!useless_type_conversion_p (utype, TREE_TYPE (op1)))
4163 g = gimple_build_assign (make_ssa_name (utype), NOP_EXPR, op1);
4164 gimple_set_location (g, loc);
4165 gsi_insert_before (gsi, g, GSI_SAME_STMT);
4166 op1 = gimple_assign_lhs (g);
4168 g = gimple_build_assign (make_ssa_name (utype), subcode, op0, op1);
4169 gimple_set_location (g, loc);
4170 gsi_insert_before (gsi, g, GSI_SAME_STMT);
4171 if (utype != type)
4173 g = gimple_build_assign (make_ssa_name (type), NOP_EXPR,
4174 gimple_assign_lhs (g));
4175 gimple_set_location (g, loc);
4176 gsi_insert_before (gsi, g, GSI_SAME_STMT);
4178 g = gimple_build_assign (gimple_call_lhs (stmt), COMPLEX_EXPR,
4179 gimple_assign_lhs (g),
4180 build_int_cst (type, ovf));
4182 gimple_set_location (g, loc);
4183 gsi_replace (gsi, g, false);
4184 return true;
4187 /* Return true if VAR is a two-valued variable. Set a and b with the
4188 two-values when it is true. Return false otherwise. */
4190 bool
4191 simplify_using_ranges::two_valued_val_range_p (tree var, tree *a, tree *b,
4192 gimple *s)
4194 value_range vr = *query->get_value_range (var, s);
4195 vr.normalize_symbolics ();
4196 if (vr.varying_p () || vr.undefined_p ())
4197 return false;
4199 if ((vr.num_pairs () == 1 && vr.upper_bound () - vr.lower_bound () == 1)
4200 || (vr.num_pairs () == 2
4201 && vr.lower_bound (0) == vr.upper_bound (0)
4202 && vr.lower_bound (1) == vr.upper_bound (1)))
4204 *a = wide_int_to_tree (TREE_TYPE (var), vr.lower_bound ());
4205 *b = wide_int_to_tree (TREE_TYPE (var), vr.upper_bound ());
4206 return true;
4208 return false;
4211 simplify_using_ranges::simplify_using_ranges (range_query *query,
4212 int not_executable_flag)
4213 : query (query)
4215 to_remove_edges = vNULL;
4216 to_update_switch_stmts = vNULL;
4217 m_not_executable_flag = not_executable_flag;
4218 m_flag_set_edges = vNULL;
4221 simplify_using_ranges::~simplify_using_ranges ()
4223 cleanup_edges_and_switches ();
4224 m_flag_set_edges.release ();
4227 /* Simplify STMT using ranges if possible. */
4229 bool
4230 simplify_using_ranges::simplify (gimple_stmt_iterator *gsi)
4232 gcc_checking_assert (query);
4234 gimple *stmt = gsi_stmt (*gsi);
4235 if (is_gimple_assign (stmt))
4237 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
4238 tree rhs1 = gimple_assign_rhs1 (stmt);
4239 tree rhs2 = gimple_assign_rhs2 (stmt);
4240 tree lhs = gimple_assign_lhs (stmt);
4241 tree val1 = NULL_TREE, val2 = NULL_TREE;
4242 use_operand_p use_p;
4243 gimple *use_stmt;
4245 /* Convert:
4246 LHS = CST BINOP VAR
4247 Where VAR is two-valued and LHS is used in GIMPLE_COND only
4249 LHS = VAR == VAL1 ? (CST BINOP VAL1) : (CST BINOP VAL2)
4251 Also handles:
4252 LHS = VAR BINOP CST
4253 Where VAR is two-valued and LHS is used in GIMPLE_COND only
4255 LHS = VAR == VAL1 ? (VAL1 BINOP CST) : (VAL2 BINOP CST) */
4257 if (TREE_CODE_CLASS (rhs_code) == tcc_binary
4258 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1))
4259 && ((TREE_CODE (rhs1) == INTEGER_CST
4260 && TREE_CODE (rhs2) == SSA_NAME)
4261 || (TREE_CODE (rhs2) == INTEGER_CST
4262 && TREE_CODE (rhs1) == SSA_NAME))
4263 && single_imm_use (lhs, &use_p, &use_stmt)
4264 && gimple_code (use_stmt) == GIMPLE_COND)
4267 tree new_rhs1 = NULL_TREE;
4268 tree new_rhs2 = NULL_TREE;
4269 tree cmp_var = NULL_TREE;
4271 if (TREE_CODE (rhs2) == SSA_NAME
4272 && two_valued_val_range_p (rhs2, &val1, &val2, stmt))
4274 /* Optimize RHS1 OP [VAL1, VAL2]. */
4275 new_rhs1 = int_const_binop (rhs_code, rhs1, val1);
4276 new_rhs2 = int_const_binop (rhs_code, rhs1, val2);
4277 cmp_var = rhs2;
4279 else if (TREE_CODE (rhs1) == SSA_NAME
4280 && two_valued_val_range_p (rhs1, &val1, &val2, stmt))
4282 /* Optimize [VAL1, VAL2] OP RHS2. */
4283 new_rhs1 = int_const_binop (rhs_code, val1, rhs2);
4284 new_rhs2 = int_const_binop (rhs_code, val2, rhs2);
4285 cmp_var = rhs1;
4288 /* If we could not find two-vals or the optimzation is invalid as
4289 in divide by zero, new_rhs1 / new_rhs will be NULL_TREE. */
4290 if (new_rhs1 && new_rhs2)
4292 tree cond = build2 (EQ_EXPR, boolean_type_node, cmp_var, val1);
4293 gimple_assign_set_rhs_with_ops (gsi,
4294 COND_EXPR, cond,
4295 new_rhs1,
4296 new_rhs2);
4297 update_stmt (gsi_stmt (*gsi));
4298 fold_stmt (gsi, follow_single_use_edges);
4299 return true;
4303 switch (rhs_code)
4305 case EQ_EXPR:
4306 case NE_EXPR:
4307 /* Transform EQ_EXPR, NE_EXPR into BIT_XOR_EXPR or identity
4308 if the RHS is zero or one, and the LHS are known to be boolean
4309 values. */
4310 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
4311 return simplify_truth_ops_using_ranges (gsi, stmt);
4312 break;
4314 /* Transform TRUNC_DIV_EXPR and TRUNC_MOD_EXPR into RSHIFT_EXPR
4315 and BIT_AND_EXPR respectively if the first operand is greater
4316 than zero and the second operand is an exact power of two.
4317 Also optimize TRUNC_MOD_EXPR away if the second operand is
4318 constant and the first operand already has the right value
4319 range. */
4320 case TRUNC_DIV_EXPR:
4321 case TRUNC_MOD_EXPR:
4322 if ((TREE_CODE (rhs1) == SSA_NAME
4323 || TREE_CODE (rhs1) == INTEGER_CST)
4324 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
4325 return simplify_div_or_mod_using_ranges (gsi, stmt);
4326 break;
4328 /* Transform ABS (X) into X or -X as appropriate. */
4329 case ABS_EXPR:
4330 if (TREE_CODE (rhs1) == SSA_NAME
4331 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
4332 return simplify_abs_using_ranges (gsi, stmt);
4333 break;
4335 case BIT_AND_EXPR:
4336 case BIT_IOR_EXPR:
4337 /* Optimize away BIT_AND_EXPR and BIT_IOR_EXPR
4338 if all the bits being cleared are already cleared or
4339 all the bits being set are already set. */
4340 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
4341 return simplify_bit_ops_using_ranges (gsi, stmt);
4342 break;
4344 CASE_CONVERT:
4345 if (TREE_CODE (rhs1) == SSA_NAME
4346 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
4347 return simplify_conversion_using_ranges (gsi, stmt);
4348 break;
4350 case FLOAT_EXPR:
4351 if (TREE_CODE (rhs1) == SSA_NAME
4352 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
4353 return simplify_float_conversion_using_ranges (gsi, stmt);
4354 break;
4356 case MIN_EXPR:
4357 case MAX_EXPR:
4358 return simplify_min_or_max_using_ranges (gsi, stmt);
4360 case RSHIFT_EXPR:
4362 tree op0 = gimple_assign_rhs1 (stmt);
4363 tree type = TREE_TYPE (op0);
4364 int_range_max range;
4365 if (TYPE_SIGN (type) == SIGNED
4366 && query->range_of_expr (range, op0, stmt))
4368 unsigned prec = TYPE_PRECISION (TREE_TYPE (op0));
4369 int_range<2> nzm1 (type, wi::minus_one (prec), wi::zero (prec),
4370 VR_ANTI_RANGE);
4371 range.intersect (nzm1);
4372 // If there are no ranges other than [-1, 0] remove the shift.
4373 if (range.undefined_p ())
4375 gimple_assign_set_rhs_from_tree (gsi, op0);
4376 return true;
4378 return false;
4380 break;
4382 default:
4383 break;
4386 else if (gimple_code (stmt) == GIMPLE_COND)
4387 return simplify_cond_using_ranges_1 (as_a <gcond *> (stmt));
4388 else if (gimple_code (stmt) == GIMPLE_SWITCH)
4389 return simplify_switch_using_ranges (as_a <gswitch *> (stmt));
4390 else if (is_gimple_call (stmt)
4391 && gimple_call_internal_p (stmt))
4392 return simplify_internal_call_using_ranges (gsi, stmt);
4394 return false;
4397 /* Set the lattice entry for VAR to VR. */
4399 void
4400 vr_values::set_vr_value (tree var, value_range_equiv *vr)
4402 if (SSA_NAME_VERSION (var) >= num_vr_values)
4403 return;
4404 vr_value[SSA_NAME_VERSION (var)] = vr;
4407 /* Swap the lattice entry for VAR with VR and return the old entry. */
4409 value_range_equiv *
4410 vr_values::swap_vr_value (tree var, value_range_equiv *vr)
4412 if (SSA_NAME_VERSION (var) >= num_vr_values)
4413 return NULL;
4414 std::swap (vr_value[SSA_NAME_VERSION (var)], vr);
4415 return vr;