DWARF array bounds missing from C++ array definitions
[official-gcc.git] / gcc / vr-values.c
blob0ebb6e3bbd42964f127e173dd4ea8bdb380e0577
1 /* Support routines for Value Range Propagation (VRP).
2 Copyright (C) 2005-2019 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 "vr-values.h"
50 #include "cfghooks.h"
52 /* Set value range VR to a non-negative range of type TYPE. */
54 static inline void
55 set_value_range_to_nonnegative (value_range *vr, tree type)
57 tree zero = build_int_cst (type, 0);
58 vr->update (VR_RANGE, zero, vrp_val_max (type));
61 /* Set value range VR to a range of a truthvalue of type TYPE. */
63 static inline void
64 set_value_range_to_truthvalue (value_range *vr, tree type)
66 if (TYPE_PRECISION (type) == 1)
67 vr->set_varying (type);
68 else
69 vr->update (VR_RANGE, build_int_cst (type, 0), build_int_cst (type, 1));
72 /* Return the lattice entry for VAR or NULL if it doesn't exist or cannot
73 be initialized. */
75 value_range *
76 vr_values::get_lattice_entry (const_tree var)
78 value_range *vr;
79 tree sym;
80 unsigned ver = SSA_NAME_VERSION (var);
82 /* If we query the entry for a new SSA name avoid reallocating the lattice
83 since we should get here at most from the substitute-and-fold stage which
84 will never try to change values. */
85 if (ver >= num_vr_values)
86 return NULL;
88 vr = vr_value[ver];
89 if (vr)
90 return vr;
92 /* Create a default value range. */
93 vr_value[ver] = vr = vrp_value_range_pool.allocate ();
95 /* After propagation finished return varying. */
96 if (values_propagated)
98 vr->set_varying (TREE_TYPE (var));
99 return vr;
102 vr->set_undefined ();
104 /* If VAR is a default definition of a parameter, the variable can
105 take any value in VAR's type. */
106 if (SSA_NAME_IS_DEFAULT_DEF (var))
108 sym = SSA_NAME_VAR (var);
109 if (TREE_CODE (sym) == PARM_DECL)
111 /* Try to use the "nonnull" attribute to create ~[0, 0]
112 anti-ranges for pointers. Note that this is only valid with
113 default definitions of PARM_DECLs. */
114 if (POINTER_TYPE_P (TREE_TYPE (sym))
115 && (nonnull_arg_p (sym)
116 || get_ptr_nonnull (var)))
118 vr->set_nonzero (TREE_TYPE (sym));
119 vr->equiv_clear ();
121 else if (INTEGRAL_TYPE_P (TREE_TYPE (sym)))
123 get_range_info (var, *vr);
124 if (vr->undefined_p ())
125 vr->set_varying (TREE_TYPE (sym));
127 else
128 vr->set_varying (TREE_TYPE (sym));
130 else if (TREE_CODE (sym) == RESULT_DECL
131 && DECL_BY_REFERENCE (sym))
133 vr->set_nonzero (TREE_TYPE (sym));
134 vr->equiv_clear ();
138 return vr;
141 /* Return value range information for VAR.
143 If we have no values ranges recorded (ie, VRP is not running), then
144 return NULL. Otherwise create an empty range if none existed for VAR. */
146 const value_range *
147 vr_values::get_value_range (const_tree var)
149 /* If we have no recorded ranges, then return NULL. */
150 if (!vr_value)
151 return NULL;
153 value_range *vr = get_lattice_entry (var);
155 /* Reallocate the lattice if needed. */
156 if (!vr)
158 unsigned int old_sz = num_vr_values;
159 num_vr_values = num_ssa_names + num_ssa_names / 10;
160 vr_value = XRESIZEVEC (value_range *, vr_value, num_vr_values);
161 for ( ; old_sz < num_vr_values; old_sz++)
162 vr_value [old_sz] = NULL;
164 /* Now that the lattice has been resized, we should never fail. */
165 vr = get_lattice_entry (var);
166 gcc_assert (vr);
169 return vr;
172 /* Set the lattice entry for DEF to VARYING. */
174 void
175 vr_values::set_def_to_varying (const_tree def)
177 value_range *vr = get_lattice_entry (def);
178 if (vr)
179 vr->set_varying (TREE_TYPE (def));
182 /* Set value-ranges of all SSA names defined by STMT to varying. */
184 void
185 vr_values::set_defs_to_varying (gimple *stmt)
187 ssa_op_iter i;
188 tree def;
189 FOR_EACH_SSA_TREE_OPERAND (def, stmt, i, SSA_OP_DEF)
190 set_def_to_varying (def);
193 /* Update the value range and equivalence set for variable VAR to
194 NEW_VR. Return true if NEW_VR is different from VAR's previous
195 value.
197 NOTE: This function assumes that NEW_VR is a temporary value range
198 object created for the sole purpose of updating VAR's range. The
199 storage used by the equivalence set from NEW_VR will be freed by
200 this function. Do not call update_value_range when NEW_VR
201 is the range object associated with another SSA name. */
203 bool
204 vr_values::update_value_range (const_tree var, value_range *new_vr)
206 value_range *old_vr;
207 bool is_new;
209 /* If there is a value-range on the SSA name from earlier analysis
210 factor that in. */
211 if (INTEGRAL_TYPE_P (TREE_TYPE (var)))
213 value_range nr;
214 value_range_kind rtype = get_range_info (var, nr);
215 if (rtype == VR_RANGE || rtype == VR_ANTI_RANGE)
216 new_vr->intersect (&nr);
219 /* Update the value range, if necessary. If we cannot allocate a lattice
220 entry for VAR keep it at VARYING. This happens when DOM feeds us stmts
221 with SSA names allocated after setting up the lattice. */
222 old_vr = get_lattice_entry (var);
223 if (!old_vr)
224 return false;
225 is_new = !old_vr->equal_p (*new_vr, /*ignore_equivs=*/false);
227 if (is_new)
229 /* Do not allow transitions up the lattice. The following
230 is slightly more awkward than just new_vr->type < old_vr->type
231 because VR_RANGE and VR_ANTI_RANGE need to be considered
232 the same. We may not have is_new when transitioning to
233 UNDEFINED. If old_vr->type is VARYING, we shouldn't be
234 called, if we are anyway, keep it VARYING. */
235 if (old_vr->varying_p ())
237 new_vr->set_varying (TREE_TYPE (var));
238 is_new = false;
240 else if (new_vr->undefined_p ())
242 old_vr->set_varying (TREE_TYPE (var));
243 new_vr->set_varying (TREE_TYPE (var));
244 return true;
246 else
247 old_vr->set (new_vr->kind (),
248 new_vr->min (), new_vr->max (), new_vr->equiv ());
251 new_vr->equiv_clear ();
253 return is_new;
256 /* Return true if value range VR involves exactly one symbol SYM. */
258 static bool
259 symbolic_range_based_on_p (value_range_base *vr, const_tree sym)
261 bool neg, min_has_symbol, max_has_symbol;
262 tree inv;
264 if (is_gimple_min_invariant (vr->min ()))
265 min_has_symbol = false;
266 else if (get_single_symbol (vr->min (), &neg, &inv) == sym)
267 min_has_symbol = true;
268 else
269 return false;
271 if (is_gimple_min_invariant (vr->max ()))
272 max_has_symbol = false;
273 else if (get_single_symbol (vr->max (), &neg, &inv) == sym)
274 max_has_symbol = true;
275 else
276 return false;
278 return (min_has_symbol || max_has_symbol);
281 /* Return true if the result of assignment STMT is know to be non-zero. */
283 static bool
284 gimple_assign_nonzero_p (gimple *stmt)
286 enum tree_code code = gimple_assign_rhs_code (stmt);
287 bool strict_overflow_p;
288 switch (get_gimple_rhs_class (code))
290 case GIMPLE_UNARY_RHS:
291 return tree_unary_nonzero_warnv_p (gimple_assign_rhs_code (stmt),
292 gimple_expr_type (stmt),
293 gimple_assign_rhs1 (stmt),
294 &strict_overflow_p);
295 case GIMPLE_BINARY_RHS:
296 return tree_binary_nonzero_warnv_p (gimple_assign_rhs_code (stmt),
297 gimple_expr_type (stmt),
298 gimple_assign_rhs1 (stmt),
299 gimple_assign_rhs2 (stmt),
300 &strict_overflow_p);
301 case GIMPLE_TERNARY_RHS:
302 return false;
303 case GIMPLE_SINGLE_RHS:
304 return tree_single_nonzero_warnv_p (gimple_assign_rhs1 (stmt),
305 &strict_overflow_p);
306 case GIMPLE_INVALID_RHS:
307 gcc_unreachable ();
308 default:
309 gcc_unreachable ();
313 /* Return true if STMT is known to compute a non-zero value. */
315 static bool
316 gimple_stmt_nonzero_p (gimple *stmt)
318 switch (gimple_code (stmt))
320 case GIMPLE_ASSIGN:
321 return gimple_assign_nonzero_p (stmt);
322 case GIMPLE_CALL:
324 gcall *call_stmt = as_a<gcall *> (stmt);
325 return (gimple_call_nonnull_result_p (call_stmt)
326 || gimple_call_nonnull_arg (call_stmt));
328 default:
329 gcc_unreachable ();
332 /* Like tree_expr_nonzero_p, but this function uses value ranges
333 obtained so far. */
335 bool
336 vr_values::vrp_stmt_computes_nonzero (gimple *stmt)
338 if (gimple_stmt_nonzero_p (stmt))
339 return true;
341 /* If we have an expression of the form &X->a, then the expression
342 is nonnull if X is nonnull. */
343 if (is_gimple_assign (stmt)
344 && gimple_assign_rhs_code (stmt) == ADDR_EXPR)
346 tree expr = gimple_assign_rhs1 (stmt);
347 poly_int64 bitsize, bitpos;
348 tree offset;
349 machine_mode mode;
350 int unsignedp, reversep, volatilep;
351 tree base = get_inner_reference (TREE_OPERAND (expr, 0), &bitsize,
352 &bitpos, &offset, &mode, &unsignedp,
353 &reversep, &volatilep);
355 if (base != NULL_TREE
356 && TREE_CODE (base) == MEM_REF
357 && TREE_CODE (TREE_OPERAND (base, 0)) == SSA_NAME)
359 poly_offset_int off = 0;
360 bool off_cst = false;
361 if (offset == NULL_TREE || TREE_CODE (offset) == INTEGER_CST)
363 off = mem_ref_offset (base);
364 if (offset)
365 off += poly_offset_int::from (wi::to_poly_wide (offset),
366 SIGNED);
367 off <<= LOG2_BITS_PER_UNIT;
368 off += bitpos;
369 off_cst = true;
371 /* If &X->a is equal to X and X is ~[0, 0], the result is too.
372 For -fdelete-null-pointer-checks -fno-wrapv-pointer we don't
373 allow going from non-NULL pointer to NULL. */
374 if ((off_cst && known_eq (off, 0))
375 || (flag_delete_null_pointer_checks
376 && !TYPE_OVERFLOW_WRAPS (TREE_TYPE (expr))))
378 const value_range *vr = get_value_range (TREE_OPERAND (base, 0));
379 if (!range_includes_zero_p (vr))
380 return true;
382 /* If MEM_REF has a "positive" offset, consider it non-NULL
383 always, for -fdelete-null-pointer-checks also "negative"
384 ones. Punt for unknown offsets (e.g. variable ones). */
385 if (!TYPE_OVERFLOW_WRAPS (TREE_TYPE (expr))
386 && off_cst
387 && known_ne (off, 0)
388 && (flag_delete_null_pointer_checks || known_gt (off, 0)))
389 return true;
393 return false;
396 /* Returns true if EXPR is a valid value (as expected by compare_values) --
397 a gimple invariant, or SSA_NAME +- CST. */
399 static bool
400 valid_value_p (tree expr)
402 if (TREE_CODE (expr) == SSA_NAME)
403 return true;
405 if (TREE_CODE (expr) == PLUS_EXPR
406 || TREE_CODE (expr) == MINUS_EXPR)
407 return (TREE_CODE (TREE_OPERAND (expr, 0)) == SSA_NAME
408 && TREE_CODE (TREE_OPERAND (expr, 1)) == INTEGER_CST);
410 return is_gimple_min_invariant (expr);
413 /* If OP has a value range with a single constant value return that,
414 otherwise return NULL_TREE. This returns OP itself if OP is a
415 constant. */
417 tree
418 vr_values::op_with_constant_singleton_value_range (tree op)
420 if (is_gimple_min_invariant (op))
421 return op;
423 if (TREE_CODE (op) != SSA_NAME)
424 return NULL_TREE;
426 tree t;
427 if (get_value_range (op)->singleton_p (&t))
428 return t;
429 return NULL;
432 /* Return true if op is in a boolean [0, 1] value-range. */
434 bool
435 vr_values::op_with_boolean_value_range_p (tree op)
437 const value_range *vr;
439 if (TYPE_PRECISION (TREE_TYPE (op)) == 1)
440 return true;
442 if (integer_zerop (op)
443 || integer_onep (op))
444 return true;
446 if (TREE_CODE (op) != SSA_NAME)
447 return false;
449 vr = get_value_range (op);
450 return (vr->kind () == VR_RANGE
451 && integer_zerop (vr->min ())
452 && integer_onep (vr->max ()));
455 /* Extract value range information for VAR when (OP COND_CODE LIMIT) is
456 true and store it in *VR_P. */
458 void
459 vr_values::extract_range_for_var_from_comparison_expr (tree var,
460 enum tree_code cond_code,
461 tree op, tree limit,
462 value_range *vr_p)
464 tree min, max, type;
465 const value_range *limit_vr;
466 type = TREE_TYPE (var);
468 /* For pointer arithmetic, we only keep track of pointer equality
469 and inequality. If we arrive here with unfolded conditions like
470 _1 > _1 do not derive anything. */
471 if ((POINTER_TYPE_P (type) && cond_code != NE_EXPR && cond_code != EQ_EXPR)
472 || limit == var)
474 vr_p->set_varying (type);
475 return;
478 /* If LIMIT is another SSA name and LIMIT has a range of its own,
479 try to use LIMIT's range to avoid creating symbolic ranges
480 unnecessarily. */
481 limit_vr = (TREE_CODE (limit) == SSA_NAME) ? get_value_range (limit) : NULL;
483 /* LIMIT's range is only interesting if it has any useful information. */
484 if (! limit_vr
485 || limit_vr->undefined_p ()
486 || limit_vr->varying_p ()
487 || (limit_vr->symbolic_p ()
488 && ! (limit_vr->kind () == VR_RANGE
489 && (limit_vr->min () == limit_vr->max ()
490 || operand_equal_p (limit_vr->min (),
491 limit_vr->max (), 0)))))
492 limit_vr = NULL;
494 /* Initially, the new range has the same set of equivalences of
495 VAR's range. This will be revised before returning the final
496 value. Since assertions may be chained via mutually exclusive
497 predicates, we will need to trim the set of equivalences before
498 we are done. */
499 gcc_assert (vr_p->equiv () == NULL);
500 vr_p->equiv_add (var, get_value_range (var), &vrp_equiv_obstack);
502 /* Extract a new range based on the asserted comparison for VAR and
503 LIMIT's value range. Notice that if LIMIT has an anti-range, we
504 will only use it for equality comparisons (EQ_EXPR). For any
505 other kind of assertion, we cannot derive a range from LIMIT's
506 anti-range that can be used to describe the new range. For
507 instance, ASSERT_EXPR <x_2, x_2 <= b_4>. If b_4 is ~[2, 10],
508 then b_4 takes on the ranges [-INF, 1] and [11, +INF]. There is
509 no single range for x_2 that could describe LE_EXPR, so we might
510 as well build the range [b_4, +INF] for it.
511 One special case we handle is extracting a range from a
512 range test encoded as (unsigned)var + CST <= limit. */
513 if (TREE_CODE (op) == NOP_EXPR
514 || TREE_CODE (op) == PLUS_EXPR)
516 if (TREE_CODE (op) == PLUS_EXPR)
518 min = fold_build1 (NEGATE_EXPR, TREE_TYPE (TREE_OPERAND (op, 1)),
519 TREE_OPERAND (op, 1));
520 max = int_const_binop (PLUS_EXPR, limit, min);
521 op = TREE_OPERAND (op, 0);
523 else
525 min = build_int_cst (TREE_TYPE (var), 0);
526 max = limit;
529 /* Make sure to not set TREE_OVERFLOW on the final type
530 conversion. We are willingly interpreting large positive
531 unsigned values as negative signed values here. */
532 min = force_fit_type (TREE_TYPE (var), wi::to_widest (min), 0, false);
533 max = force_fit_type (TREE_TYPE (var), wi::to_widest (max), 0, false);
535 /* We can transform a max, min range to an anti-range or
536 vice-versa. Use set_and_canonicalize which does this for
537 us. */
538 if (cond_code == LE_EXPR)
539 vr_p->set (VR_RANGE, min, max, vr_p->equiv ());
540 else if (cond_code == GT_EXPR)
541 vr_p->set (VR_ANTI_RANGE, min, max, vr_p->equiv ());
542 else
543 gcc_unreachable ();
545 else if (cond_code == EQ_EXPR)
547 enum value_range_kind range_type;
549 if (limit_vr)
551 range_type = limit_vr->kind ();
552 min = limit_vr->min ();
553 max = limit_vr->max ();
555 else
557 range_type = VR_RANGE;
558 min = limit;
559 max = limit;
562 vr_p->update (range_type, min, max);
564 /* When asserting the equality VAR == LIMIT and LIMIT is another
565 SSA name, the new range will also inherit the equivalence set
566 from LIMIT. */
567 if (TREE_CODE (limit) == SSA_NAME)
568 vr_p->equiv_add (limit, get_value_range (limit), &vrp_equiv_obstack);
570 else if (cond_code == NE_EXPR)
572 /* As described above, when LIMIT's range is an anti-range and
573 this assertion is an inequality (NE_EXPR), then we cannot
574 derive anything from the anti-range. For instance, if
575 LIMIT's range was ~[0, 0], the assertion 'VAR != LIMIT' does
576 not imply that VAR's range is [0, 0]. So, in the case of
577 anti-ranges, we just assert the inequality using LIMIT and
578 not its anti-range.
580 If LIMIT_VR is a range, we can only use it to build a new
581 anti-range if LIMIT_VR is a single-valued range. For
582 instance, if LIMIT_VR is [0, 1], the predicate
583 VAR != [0, 1] does not mean that VAR's range is ~[0, 1].
584 Rather, it means that for value 0 VAR should be ~[0, 0]
585 and for value 1, VAR should be ~[1, 1]. We cannot
586 represent these ranges.
588 The only situation in which we can build a valid
589 anti-range is when LIMIT_VR is a single-valued range
590 (i.e., LIMIT_VR->MIN == LIMIT_VR->MAX). In that case,
591 build the anti-range ~[LIMIT_VR->MIN, LIMIT_VR->MAX]. */
592 if (limit_vr
593 && limit_vr->kind () == VR_RANGE
594 && compare_values (limit_vr->min (), limit_vr->max ()) == 0)
596 min = limit_vr->min ();
597 max = limit_vr->max ();
599 else
601 /* In any other case, we cannot use LIMIT's range to build a
602 valid anti-range. */
603 min = max = limit;
606 /* If MIN and MAX cover the whole range for their type, then
607 just use the original LIMIT. */
608 if (INTEGRAL_TYPE_P (type)
609 && vrp_val_is_min (min)
610 && vrp_val_is_max (max))
611 min = max = limit;
613 vr_p->set (VR_ANTI_RANGE, min, max, vr_p->equiv ());
615 else if (cond_code == LE_EXPR || cond_code == LT_EXPR)
617 min = TYPE_MIN_VALUE (type);
619 if (limit_vr == NULL || limit_vr->kind () == VR_ANTI_RANGE)
620 max = limit;
621 else
623 /* If LIMIT_VR is of the form [N1, N2], we need to build the
624 range [MIN, N2] for LE_EXPR and [MIN, N2 - 1] for
625 LT_EXPR. */
626 max = limit_vr->max ();
629 /* If the maximum value forces us to be out of bounds, simply punt.
630 It would be pointless to try and do anything more since this
631 all should be optimized away above us. */
632 if (cond_code == LT_EXPR
633 && compare_values (max, min) == 0)
634 vr_p->set_varying (TREE_TYPE (min));
635 else
637 /* For LT_EXPR, we create the range [MIN, MAX - 1]. */
638 if (cond_code == LT_EXPR)
640 if (TYPE_PRECISION (TREE_TYPE (max)) == 1
641 && !TYPE_UNSIGNED (TREE_TYPE (max)))
642 max = fold_build2 (PLUS_EXPR, TREE_TYPE (max), max,
643 build_int_cst (TREE_TYPE (max), -1));
644 else
645 max = fold_build2 (MINUS_EXPR, TREE_TYPE (max), max,
646 build_int_cst (TREE_TYPE (max), 1));
647 /* Signal to compare_values_warnv this expr doesn't overflow. */
648 if (EXPR_P (max))
649 TREE_NO_WARNING (max) = 1;
652 vr_p->update (VR_RANGE, min, max);
655 else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
657 max = TYPE_MAX_VALUE (type);
659 if (limit_vr == NULL || limit_vr->kind () == VR_ANTI_RANGE)
660 min = limit;
661 else
663 /* If LIMIT_VR is of the form [N1, N2], we need to build the
664 range [N1, MAX] for GE_EXPR and [N1 + 1, MAX] for
665 GT_EXPR. */
666 min = limit_vr->min ();
669 /* If the minimum value forces us to be out of bounds, simply punt.
670 It would be pointless to try and do anything more since this
671 all should be optimized away above us. */
672 if (cond_code == GT_EXPR
673 && compare_values (min, max) == 0)
674 vr_p->set_varying (TREE_TYPE (min));
675 else
677 /* For GT_EXPR, we create the range [MIN + 1, MAX]. */
678 if (cond_code == GT_EXPR)
680 if (TYPE_PRECISION (TREE_TYPE (min)) == 1
681 && !TYPE_UNSIGNED (TREE_TYPE (min)))
682 min = fold_build2 (MINUS_EXPR, TREE_TYPE (min), min,
683 build_int_cst (TREE_TYPE (min), -1));
684 else
685 min = fold_build2 (PLUS_EXPR, TREE_TYPE (min), min,
686 build_int_cst (TREE_TYPE (min), 1));
687 /* Signal to compare_values_warnv this expr doesn't overflow. */
688 if (EXPR_P (min))
689 TREE_NO_WARNING (min) = 1;
692 vr_p->update (VR_RANGE, min, max);
695 else
696 gcc_unreachable ();
698 /* Finally intersect the new range with what we already know about var. */
699 vr_p->intersect (get_value_range (var));
702 /* Extract value range information from an ASSERT_EXPR EXPR and store
703 it in *VR_P. */
705 void
706 vr_values::extract_range_from_assert (value_range *vr_p, tree expr)
708 tree var = ASSERT_EXPR_VAR (expr);
709 tree cond = ASSERT_EXPR_COND (expr);
710 tree limit, op;
711 enum tree_code cond_code;
712 gcc_assert (COMPARISON_CLASS_P (cond));
714 /* Find VAR in the ASSERT_EXPR conditional. */
715 if (var == TREE_OPERAND (cond, 0)
716 || TREE_CODE (TREE_OPERAND (cond, 0)) == PLUS_EXPR
717 || TREE_CODE (TREE_OPERAND (cond, 0)) == NOP_EXPR)
719 /* If the predicate is of the form VAR COMP LIMIT, then we just
720 take LIMIT from the RHS and use the same comparison code. */
721 cond_code = TREE_CODE (cond);
722 limit = TREE_OPERAND (cond, 1);
723 op = TREE_OPERAND (cond, 0);
725 else
727 /* If the predicate is of the form LIMIT COMP VAR, then we need
728 to flip around the comparison code to create the proper range
729 for VAR. */
730 cond_code = swap_tree_comparison (TREE_CODE (cond));
731 limit = TREE_OPERAND (cond, 0);
732 op = TREE_OPERAND (cond, 1);
734 extract_range_for_var_from_comparison_expr (var, cond_code, op,
735 limit, vr_p);
738 /* Extract range information from SSA name VAR and store it in VR. If
739 VAR has an interesting range, use it. Otherwise, create the
740 range [VAR, VAR] and return it. This is useful in situations where
741 we may have conditionals testing values of VARYING names. For
742 instance,
744 x_3 = y_5;
745 if (x_3 > y_5)
748 Even if y_5 is deemed VARYING, we can determine that x_3 > y_5 is
749 always false. */
751 void
752 vr_values::extract_range_from_ssa_name (value_range *vr, tree var)
754 const value_range *var_vr = get_value_range (var);
756 if (!var_vr->varying_p ())
757 vr->deep_copy (var_vr);
758 else
759 vr->set (var);
761 if (!vr->undefined_p ())
762 vr->equiv_add (var, get_value_range (var), &vrp_equiv_obstack);
765 /* Extract range information from a binary expression OP0 CODE OP1 based on
766 the ranges of each of its operands with resulting type EXPR_TYPE.
767 The resulting range is stored in *VR. */
769 void
770 vr_values::extract_range_from_binary_expr (value_range *vr,
771 enum tree_code code,
772 tree expr_type, tree op0, tree op1)
774 /* Get value ranges for each operand. For constant operands, create
775 a new value range with the operand to simplify processing. */
776 value_range_base vr0, vr1;
777 if (TREE_CODE (op0) == SSA_NAME)
778 vr0 = *(get_value_range (op0));
779 else if (is_gimple_min_invariant (op0))
780 vr0.set (op0);
781 else
782 vr0.set_varying (TREE_TYPE (op0));
784 if (TREE_CODE (op1) == SSA_NAME)
785 vr1 = *(get_value_range (op1));
786 else if (is_gimple_min_invariant (op1))
787 vr1.set (op1);
788 else
789 vr1.set_varying (TREE_TYPE (op1));
791 /* If one argument is varying, we can sometimes still deduce a
792 range for the output: any + [3, +INF] is in [MIN+3, +INF]. */
793 if (INTEGRAL_TYPE_P (TREE_TYPE (op0))
794 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (op0)))
796 if (vr0.varying_p () && !vr1.varying_p ())
797 vr0 = value_range (VR_RANGE,
798 vrp_val_min (expr_type),
799 vrp_val_max (expr_type));
800 else if (vr1.varying_p () && !vr0.varying_p ())
801 vr1 = value_range (VR_RANGE,
802 vrp_val_min (expr_type),
803 vrp_val_max (expr_type));
806 ::extract_range_from_binary_expr (vr, code, expr_type, &vr0, &vr1);
808 /* Set value_range for n in following sequence:
809 def = __builtin_memchr (arg, 0, sz)
810 n = def - arg
811 Here the range for n can be set to [0, PTRDIFF_MAX - 1]. */
813 if (vr->varying_p ()
814 && code == POINTER_DIFF_EXPR
815 && TREE_CODE (op0) == SSA_NAME
816 && TREE_CODE (op1) == SSA_NAME)
818 tree op0_ptype = TREE_TYPE (TREE_TYPE (op0));
819 tree op1_ptype = TREE_TYPE (TREE_TYPE (op1));
820 gcall *call_stmt = NULL;
822 if (TYPE_MODE (op0_ptype) == TYPE_MODE (char_type_node)
823 && TYPE_PRECISION (op0_ptype) == TYPE_PRECISION (char_type_node)
824 && TYPE_MODE (op1_ptype) == TYPE_MODE (char_type_node)
825 && TYPE_PRECISION (op1_ptype) == TYPE_PRECISION (char_type_node)
826 && (call_stmt = dyn_cast<gcall *>(SSA_NAME_DEF_STMT (op0)))
827 && gimple_call_builtin_p (call_stmt, BUILT_IN_MEMCHR)
828 && operand_equal_p (op0, gimple_call_lhs (call_stmt), 0)
829 && operand_equal_p (op1, gimple_call_arg (call_stmt, 0), 0)
830 && integer_zerop (gimple_call_arg (call_stmt, 1)))
832 tree max = vrp_val_max (ptrdiff_type_node);
833 wide_int wmax = wi::to_wide (max, TYPE_PRECISION (TREE_TYPE (max)));
834 tree range_min = build_zero_cst (expr_type);
835 tree range_max = wide_int_to_tree (expr_type, wmax - 1);
836 vr->set (VR_RANGE, range_min, range_max);
837 return;
841 /* Try harder for PLUS and MINUS if the range of one operand is symbolic
842 and based on the other operand, for example if it was deduced from a
843 symbolic comparison. When a bound of the range of the first operand
844 is invariant, we set the corresponding bound of the new range to INF
845 in order to avoid recursing on the range of the second operand. */
846 if (vr->varying_p ()
847 && (code == PLUS_EXPR || code == MINUS_EXPR)
848 && TREE_CODE (op1) == SSA_NAME
849 && vr0.kind () == VR_RANGE
850 && symbolic_range_based_on_p (&vr0, op1))
852 const bool minus_p = (code == MINUS_EXPR);
853 value_range n_vr1;
855 /* Try with VR0 and [-INF, OP1]. */
856 if (is_gimple_min_invariant (minus_p ? vr0.max () : vr0.min ()))
857 n_vr1.set (VR_RANGE, vrp_val_min (expr_type), op1);
859 /* Try with VR0 and [OP1, +INF]. */
860 else if (is_gimple_min_invariant (minus_p ? vr0.min () : vr0.max ()))
861 n_vr1.set (VR_RANGE, op1, vrp_val_max (expr_type));
863 /* Try with VR0 and [OP1, OP1]. */
864 else
865 n_vr1.set (VR_RANGE, op1, op1);
867 ::extract_range_from_binary_expr (vr, code, expr_type, &vr0, &n_vr1);
870 if (vr->varying_p ()
871 && (code == PLUS_EXPR || code == MINUS_EXPR)
872 && TREE_CODE (op0) == SSA_NAME
873 && vr1.kind () == VR_RANGE
874 && symbolic_range_based_on_p (&vr1, op0))
876 const bool minus_p = (code == MINUS_EXPR);
877 value_range n_vr0;
879 /* Try with [-INF, OP0] and VR1. */
880 if (is_gimple_min_invariant (minus_p ? vr1.max () : vr1.min ()))
881 n_vr0.set (VR_RANGE, vrp_val_min (expr_type), op0);
883 /* Try with [OP0, +INF] and VR1. */
884 else if (is_gimple_min_invariant (minus_p ? vr1.min (): vr1.max ()))
885 n_vr0.set (VR_RANGE, op0, vrp_val_max (expr_type));
887 /* Try with [OP0, OP0] and VR1. */
888 else
889 n_vr0.set (op0);
891 ::extract_range_from_binary_expr (vr, code, expr_type, &n_vr0, &vr1);
894 /* If we didn't derive a range for MINUS_EXPR, and
895 op1's range is ~[op0,op0] or vice-versa, then we
896 can derive a non-null range. This happens often for
897 pointer subtraction. */
898 if (vr->varying_p ()
899 && (code == MINUS_EXPR || code == POINTER_DIFF_EXPR)
900 && TREE_CODE (op0) == SSA_NAME
901 && ((vr0.kind () == VR_ANTI_RANGE
902 && vr0.min () == op1
903 && vr0.min () == vr0.max ())
904 || (vr1.kind () == VR_ANTI_RANGE
905 && vr1.min () == op0
906 && vr1.min () == vr1.max ())))
908 vr->set_nonzero (expr_type);
909 vr->equiv_clear ();
913 /* Extract range information from a unary expression CODE OP0 based on
914 the range of its operand with resulting type TYPE.
915 The resulting range is stored in *VR. */
917 void
918 vr_values::extract_range_from_unary_expr (value_range *vr, enum tree_code code,
919 tree type, tree op0)
921 value_range_base vr0;
923 /* Get value ranges for the operand. For constant operands, create
924 a new value range with the operand to simplify processing. */
925 if (TREE_CODE (op0) == SSA_NAME)
926 vr0 = *(get_value_range (op0));
927 else if (is_gimple_min_invariant (op0))
928 vr0.set (op0);
929 else
930 vr0.set_varying (type);
932 ::extract_range_from_unary_expr (vr, code, type, &vr0, TREE_TYPE (op0));
936 /* Extract range information from a conditional expression STMT based on
937 the ranges of each of its operands and the expression code. */
939 void
940 vr_values::extract_range_from_cond_expr (value_range *vr, gassign *stmt)
942 /* Get value ranges for each operand. For constant operands, create
943 a new value range with the operand to simplify processing. */
944 tree op0 = gimple_assign_rhs2 (stmt);
945 value_range tem0;
946 const value_range *vr0 = &tem0;
947 if (TREE_CODE (op0) == SSA_NAME)
948 vr0 = get_value_range (op0);
949 else if (is_gimple_min_invariant (op0))
950 tem0.set (op0);
951 else
952 tem0.set_varying (TREE_TYPE (op0));
954 tree op1 = gimple_assign_rhs3 (stmt);
955 value_range tem1;
956 const value_range *vr1 = &tem1;
957 if (TREE_CODE (op1) == SSA_NAME)
958 vr1 = get_value_range (op1);
959 else if (is_gimple_min_invariant (op1))
960 tem1.set (op1);
961 else
962 tem1.set_varying (TREE_TYPE (op1));
964 /* The resulting value range is the union of the operand ranges */
965 vr->deep_copy (vr0);
966 vr->union_ (vr1);
970 /* Extract range information from a comparison expression EXPR based
971 on the range of its operand and the expression code. */
973 void
974 vr_values::extract_range_from_comparison (value_range *vr, enum tree_code code,
975 tree type, tree op0, tree op1)
977 bool sop;
978 tree val;
980 val = vrp_evaluate_conditional_warnv_with_ops (code, op0, op1, false, &sop,
981 NULL);
982 if (val)
984 /* Since this expression was found on the RHS of an assignment,
985 its type may be different from _Bool. Convert VAL to EXPR's
986 type. */
987 val = fold_convert (type, val);
988 if (is_gimple_min_invariant (val))
989 vr->set (val);
990 else
991 vr->update (VR_RANGE, val, val);
993 else
994 /* The result of a comparison is always true or false. */
995 set_value_range_to_truthvalue (vr, type);
998 /* Helper function for simplify_internal_call_using_ranges and
999 extract_range_basic. Return true if OP0 SUBCODE OP1 for
1000 SUBCODE {PLUS,MINUS,MULT}_EXPR is known to never overflow or
1001 always overflow. Set *OVF to true if it is known to always
1002 overflow. */
1004 bool
1005 vr_values::check_for_binary_op_overflow (enum tree_code subcode, tree type,
1006 tree op0, tree op1, bool *ovf)
1008 value_range_base vr0, vr1;
1009 if (TREE_CODE (op0) == SSA_NAME)
1010 vr0 = *get_value_range (op0);
1011 else if (TREE_CODE (op0) == INTEGER_CST)
1012 vr0.set (op0);
1013 else
1014 vr0.set_varying (TREE_TYPE (op0));
1016 if (TREE_CODE (op1) == SSA_NAME)
1017 vr1 = *get_value_range (op1);
1018 else if (TREE_CODE (op1) == INTEGER_CST)
1019 vr1.set (op1);
1020 else
1021 vr1.set_varying (TREE_TYPE (op1));
1023 tree vr0min = vr0.min (), vr0max = vr0.max ();
1024 tree vr1min = vr1.min (), vr1max = vr1.max ();
1025 if (!range_int_cst_p (&vr0)
1026 || TREE_OVERFLOW (vr0min)
1027 || TREE_OVERFLOW (vr0max))
1029 vr0min = vrp_val_min (TREE_TYPE (op0));
1030 vr0max = vrp_val_max (TREE_TYPE (op0));
1032 if (!range_int_cst_p (&vr1)
1033 || TREE_OVERFLOW (vr1min)
1034 || TREE_OVERFLOW (vr1max))
1036 vr1min = vrp_val_min (TREE_TYPE (op1));
1037 vr1max = vrp_val_max (TREE_TYPE (op1));
1039 *ovf = arith_overflowed_p (subcode, type, vr0min,
1040 subcode == MINUS_EXPR ? vr1max : vr1min);
1041 if (arith_overflowed_p (subcode, type, vr0max,
1042 subcode == MINUS_EXPR ? vr1min : vr1max) != *ovf)
1043 return false;
1044 if (subcode == MULT_EXPR)
1046 if (arith_overflowed_p (subcode, type, vr0min, vr1max) != *ovf
1047 || arith_overflowed_p (subcode, type, vr0max, vr1min) != *ovf)
1048 return false;
1050 if (*ovf)
1052 /* So far we found that there is an overflow on the boundaries.
1053 That doesn't prove that there is an overflow even for all values
1054 in between the boundaries. For that compute widest_int range
1055 of the result and see if it doesn't overlap the range of
1056 type. */
1057 widest_int wmin, wmax;
1058 widest_int w[4];
1059 int i;
1060 w[0] = wi::to_widest (vr0min);
1061 w[1] = wi::to_widest (vr0max);
1062 w[2] = wi::to_widest (vr1min);
1063 w[3] = wi::to_widest (vr1max);
1064 for (i = 0; i < 4; i++)
1066 widest_int wt;
1067 switch (subcode)
1069 case PLUS_EXPR:
1070 wt = wi::add (w[i & 1], w[2 + (i & 2) / 2]);
1071 break;
1072 case MINUS_EXPR:
1073 wt = wi::sub (w[i & 1], w[2 + (i & 2) / 2]);
1074 break;
1075 case MULT_EXPR:
1076 wt = wi::mul (w[i & 1], w[2 + (i & 2) / 2]);
1077 break;
1078 default:
1079 gcc_unreachable ();
1081 if (i == 0)
1083 wmin = wt;
1084 wmax = wt;
1086 else
1088 wmin = wi::smin (wmin, wt);
1089 wmax = wi::smax (wmax, wt);
1092 /* The result of op0 CODE op1 is known to be in range
1093 [wmin, wmax]. */
1094 widest_int wtmin = wi::to_widest (vrp_val_min (type));
1095 widest_int wtmax = wi::to_widest (vrp_val_max (type));
1096 /* If all values in [wmin, wmax] are smaller than
1097 [wtmin, wtmax] or all are larger than [wtmin, wtmax],
1098 the arithmetic operation will always overflow. */
1099 if (wmax < wtmin || wmin > wtmax)
1100 return true;
1101 return false;
1103 return true;
1106 /* Try to derive a nonnegative or nonzero range out of STMT relying
1107 primarily on generic routines in fold in conjunction with range data.
1108 Store the result in *VR */
1110 void
1111 vr_values::extract_range_basic (value_range *vr, gimple *stmt)
1113 bool sop;
1114 tree type = gimple_expr_type (stmt);
1116 if (is_gimple_call (stmt))
1118 tree arg;
1119 int mini, maxi, zerov = 0, prec;
1120 enum tree_code subcode = ERROR_MARK;
1121 combined_fn cfn = gimple_call_combined_fn (stmt);
1122 scalar_int_mode mode;
1124 switch (cfn)
1126 case CFN_BUILT_IN_CONSTANT_P:
1127 /* Resolve calls to __builtin_constant_p after inlining. */
1128 if (cfun->after_inlining)
1130 vr->set_zero (type);
1131 vr->equiv_clear ();
1132 return;
1134 break;
1135 /* Both __builtin_ffs* and __builtin_popcount return
1136 [0, prec]. */
1137 CASE_CFN_FFS:
1138 CASE_CFN_POPCOUNT:
1139 arg = gimple_call_arg (stmt, 0);
1140 prec = TYPE_PRECISION (TREE_TYPE (arg));
1141 mini = 0;
1142 maxi = prec;
1143 if (TREE_CODE (arg) == SSA_NAME)
1145 const value_range *vr0 = get_value_range (arg);
1146 /* If arg is non-zero, then ffs or popcount are non-zero. */
1147 if (range_includes_zero_p (vr0) == 0)
1148 mini = 1;
1149 /* If some high bits are known to be zero,
1150 we can decrease the maximum. */
1151 if (vr0->kind () == VR_RANGE
1152 && TREE_CODE (vr0->max ()) == INTEGER_CST
1153 && !operand_less_p (vr0->min (),
1154 build_zero_cst (TREE_TYPE (vr0->min ()))))
1155 maxi = tree_floor_log2 (vr0->max ()) + 1;
1157 goto bitop_builtin;
1158 /* __builtin_parity* returns [0, 1]. */
1159 CASE_CFN_PARITY:
1160 mini = 0;
1161 maxi = 1;
1162 goto bitop_builtin;
1163 /* __builtin_c[lt]z* return [0, prec-1], except for
1164 when the argument is 0, but that is undefined behavior.
1165 On many targets where the CLZ RTL or optab value is defined
1166 for 0 the value is prec, so include that in the range
1167 by default. */
1168 CASE_CFN_CLZ:
1169 arg = gimple_call_arg (stmt, 0);
1170 prec = TYPE_PRECISION (TREE_TYPE (arg));
1171 mini = 0;
1172 maxi = prec;
1173 mode = SCALAR_INT_TYPE_MODE (TREE_TYPE (arg));
1174 if (optab_handler (clz_optab, mode) != CODE_FOR_nothing
1175 && CLZ_DEFINED_VALUE_AT_ZERO (mode, zerov)
1176 /* Handle only the single common value. */
1177 && zerov != prec)
1178 /* Magic value to give up, unless vr0 proves
1179 arg is non-zero. */
1180 mini = -2;
1181 if (TREE_CODE (arg) == SSA_NAME)
1183 const value_range *vr0 = get_value_range (arg);
1184 /* From clz of VR_RANGE minimum we can compute
1185 result maximum. */
1186 if (vr0->kind () == VR_RANGE
1187 && TREE_CODE (vr0->min ()) == INTEGER_CST)
1189 maxi = prec - 1 - tree_floor_log2 (vr0->min ());
1190 if (maxi != prec)
1191 mini = 0;
1193 else if (vr0->kind () == VR_ANTI_RANGE
1194 && integer_zerop (vr0->min ()))
1196 maxi = prec - 1;
1197 mini = 0;
1199 if (mini == -2)
1200 break;
1201 /* From clz of VR_RANGE maximum we can compute
1202 result minimum. */
1203 if (vr0->kind () == VR_RANGE
1204 && TREE_CODE (vr0->max ()) == INTEGER_CST)
1206 mini = prec - 1 - tree_floor_log2 (vr0->max ());
1207 if (mini == prec)
1208 break;
1211 if (mini == -2)
1212 break;
1213 goto bitop_builtin;
1214 /* __builtin_ctz* return [0, prec-1], except for
1215 when the argument is 0, but that is undefined behavior.
1216 If there is a ctz optab for this mode and
1217 CTZ_DEFINED_VALUE_AT_ZERO, include that in the range,
1218 otherwise just assume 0 won't be seen. */
1219 CASE_CFN_CTZ:
1220 arg = gimple_call_arg (stmt, 0);
1221 prec = TYPE_PRECISION (TREE_TYPE (arg));
1222 mini = 0;
1223 maxi = prec - 1;
1224 mode = SCALAR_INT_TYPE_MODE (TREE_TYPE (arg));
1225 if (optab_handler (ctz_optab, mode) != CODE_FOR_nothing
1226 && CTZ_DEFINED_VALUE_AT_ZERO (mode, zerov))
1228 /* Handle only the two common values. */
1229 if (zerov == -1)
1230 mini = -1;
1231 else if (zerov == prec)
1232 maxi = prec;
1233 else
1234 /* Magic value to give up, unless vr0 proves
1235 arg is non-zero. */
1236 mini = -2;
1238 if (TREE_CODE (arg) == SSA_NAME)
1240 const value_range *vr0 = get_value_range (arg);
1241 /* If arg is non-zero, then use [0, prec - 1]. */
1242 if ((vr0->kind () == VR_RANGE
1243 && integer_nonzerop (vr0->min ()))
1244 || (vr0->kind () == VR_ANTI_RANGE
1245 && integer_zerop (vr0->min ())))
1247 mini = 0;
1248 maxi = prec - 1;
1250 /* If some high bits are known to be zero,
1251 we can decrease the result maximum. */
1252 if (vr0->kind () == VR_RANGE
1253 && TREE_CODE (vr0->max ()) == INTEGER_CST)
1255 maxi = tree_floor_log2 (vr0->max ());
1256 /* For vr0 [0, 0] give up. */
1257 if (maxi == -1)
1258 break;
1261 if (mini == -2)
1262 break;
1263 goto bitop_builtin;
1264 /* __builtin_clrsb* returns [0, prec-1]. */
1265 CASE_CFN_CLRSB:
1266 arg = gimple_call_arg (stmt, 0);
1267 prec = TYPE_PRECISION (TREE_TYPE (arg));
1268 mini = 0;
1269 maxi = prec - 1;
1270 goto bitop_builtin;
1271 bitop_builtin:
1272 vr->set (VR_RANGE, build_int_cst (type, mini),
1273 build_int_cst (type, maxi));
1274 return;
1275 case CFN_UBSAN_CHECK_ADD:
1276 subcode = PLUS_EXPR;
1277 break;
1278 case CFN_UBSAN_CHECK_SUB:
1279 subcode = MINUS_EXPR;
1280 break;
1281 case CFN_UBSAN_CHECK_MUL:
1282 subcode = MULT_EXPR;
1283 break;
1284 case CFN_GOACC_DIM_SIZE:
1285 case CFN_GOACC_DIM_POS:
1286 /* Optimizing these two internal functions helps the loop
1287 optimizer eliminate outer comparisons. Size is [1,N]
1288 and pos is [0,N-1]. */
1290 bool is_pos = cfn == CFN_GOACC_DIM_POS;
1291 int axis = oacc_get_ifn_dim_arg (stmt);
1292 int size = oacc_get_fn_dim_size (current_function_decl, axis);
1294 if (!size)
1295 /* If it's dynamic, the backend might know a hardware
1296 limitation. */
1297 size = targetm.goacc.dim_limit (axis);
1299 tree type = TREE_TYPE (gimple_call_lhs (stmt));
1300 vr->set(VR_RANGE, build_int_cst (type, is_pos ? 0 : 1),
1301 size
1302 ? build_int_cst (type, size - is_pos) : vrp_val_max (type));
1304 return;
1305 case CFN_BUILT_IN_STRLEN:
1306 if (tree lhs = gimple_call_lhs (stmt))
1307 if (ptrdiff_type_node
1308 && (TYPE_PRECISION (ptrdiff_type_node)
1309 == TYPE_PRECISION (TREE_TYPE (lhs))))
1311 tree type = TREE_TYPE (lhs);
1312 tree max = vrp_val_max (ptrdiff_type_node);
1313 wide_int wmax = wi::to_wide (max, TYPE_PRECISION (TREE_TYPE (max)));
1314 tree range_min = build_zero_cst (type);
1315 /* To account for the terminating NUL, the maximum length
1316 is one less than the maximum array size, which in turn
1317 is one less than PTRDIFF_MAX (or SIZE_MAX where it's
1318 smaller than the former type).
1319 FIXME: Use max_object_size() - 1 here. */
1320 tree range_max = wide_int_to_tree (type, wmax - 2);
1321 vr->set (VR_RANGE, range_min, range_max);
1322 return;
1324 break;
1325 default:
1326 break;
1328 if (subcode != ERROR_MARK)
1330 bool saved_flag_wrapv = flag_wrapv;
1331 /* Pretend the arithmetics is wrapping. If there is
1332 any overflow, we'll complain, but will actually do
1333 wrapping operation. */
1334 flag_wrapv = 1;
1335 extract_range_from_binary_expr (vr, subcode, type,
1336 gimple_call_arg (stmt, 0),
1337 gimple_call_arg (stmt, 1));
1338 flag_wrapv = saved_flag_wrapv;
1340 /* If for both arguments vrp_valueize returned non-NULL,
1341 this should have been already folded and if not, it
1342 wasn't folded because of overflow. Avoid removing the
1343 UBSAN_CHECK_* calls in that case. */
1344 if (vr->kind () == VR_RANGE
1345 && (vr->min () == vr->max ()
1346 || operand_equal_p (vr->min (), vr->max (), 0)))
1347 vr->set_varying (vr->type ());
1348 return;
1351 /* Handle extraction of the two results (result of arithmetics and
1352 a flag whether arithmetics overflowed) from {ADD,SUB,MUL}_OVERFLOW
1353 internal function. Similarly from ATOMIC_COMPARE_EXCHANGE. */
1354 else if (is_gimple_assign (stmt)
1355 && (gimple_assign_rhs_code (stmt) == REALPART_EXPR
1356 || gimple_assign_rhs_code (stmt) == IMAGPART_EXPR)
1357 && INTEGRAL_TYPE_P (type))
1359 enum tree_code code = gimple_assign_rhs_code (stmt);
1360 tree op = gimple_assign_rhs1 (stmt);
1361 if (TREE_CODE (op) == code && TREE_CODE (TREE_OPERAND (op, 0)) == SSA_NAME)
1363 gimple *g = SSA_NAME_DEF_STMT (TREE_OPERAND (op, 0));
1364 if (is_gimple_call (g) && gimple_call_internal_p (g))
1366 enum tree_code subcode = ERROR_MARK;
1367 switch (gimple_call_internal_fn (g))
1369 case IFN_ADD_OVERFLOW:
1370 subcode = PLUS_EXPR;
1371 break;
1372 case IFN_SUB_OVERFLOW:
1373 subcode = MINUS_EXPR;
1374 break;
1375 case IFN_MUL_OVERFLOW:
1376 subcode = MULT_EXPR;
1377 break;
1378 case IFN_ATOMIC_COMPARE_EXCHANGE:
1379 if (code == IMAGPART_EXPR)
1381 /* This is the boolean return value whether compare and
1382 exchange changed anything or not. */
1383 vr->set (VR_RANGE, build_int_cst (type, 0),
1384 build_int_cst (type, 1));
1385 return;
1387 break;
1388 default:
1389 break;
1391 if (subcode != ERROR_MARK)
1393 tree op0 = gimple_call_arg (g, 0);
1394 tree op1 = gimple_call_arg (g, 1);
1395 if (code == IMAGPART_EXPR)
1397 bool ovf = false;
1398 if (check_for_binary_op_overflow (subcode, type,
1399 op0, op1, &ovf))
1400 vr->set (build_int_cst (type, ovf));
1401 else if (TYPE_PRECISION (type) == 1
1402 && !TYPE_UNSIGNED (type))
1403 vr->set_varying (type);
1404 else
1405 vr->set (VR_RANGE, build_int_cst (type, 0),
1406 build_int_cst (type, 1));
1408 else if (types_compatible_p (type, TREE_TYPE (op0))
1409 && types_compatible_p (type, TREE_TYPE (op1)))
1411 bool saved_flag_wrapv = flag_wrapv;
1412 /* Pretend the arithmetics is wrapping. If there is
1413 any overflow, IMAGPART_EXPR will be set. */
1414 flag_wrapv = 1;
1415 extract_range_from_binary_expr (vr, subcode, type,
1416 op0, op1);
1417 flag_wrapv = saved_flag_wrapv;
1419 else
1421 value_range vr0, vr1;
1422 bool saved_flag_wrapv = flag_wrapv;
1423 /* Pretend the arithmetics is wrapping. If there is
1424 any overflow, IMAGPART_EXPR will be set. */
1425 flag_wrapv = 1;
1426 extract_range_from_unary_expr (&vr0, NOP_EXPR,
1427 type, op0);
1428 extract_range_from_unary_expr (&vr1, NOP_EXPR,
1429 type, op1);
1430 ::extract_range_from_binary_expr (vr, subcode, type,
1431 &vr0, &vr1);
1432 flag_wrapv = saved_flag_wrapv;
1434 return;
1439 if (INTEGRAL_TYPE_P (type)
1440 && gimple_stmt_nonnegative_warnv_p (stmt, &sop))
1441 set_value_range_to_nonnegative (vr, type);
1442 else if (vrp_stmt_computes_nonzero (stmt))
1444 vr->set_nonzero (type);
1445 vr->equiv_clear ();
1447 else
1448 vr->set_varying (type);
1452 /* Try to compute a useful range out of assignment STMT and store it
1453 in *VR. */
1455 void
1456 vr_values::extract_range_from_assignment (value_range *vr, gassign *stmt)
1458 enum tree_code code = gimple_assign_rhs_code (stmt);
1460 if (code == ASSERT_EXPR)
1461 extract_range_from_assert (vr, gimple_assign_rhs1 (stmt));
1462 else if (code == SSA_NAME)
1463 extract_range_from_ssa_name (vr, gimple_assign_rhs1 (stmt));
1464 else if (TREE_CODE_CLASS (code) == tcc_binary)
1465 extract_range_from_binary_expr (vr, gimple_assign_rhs_code (stmt),
1466 gimple_expr_type (stmt),
1467 gimple_assign_rhs1 (stmt),
1468 gimple_assign_rhs2 (stmt));
1469 else if (TREE_CODE_CLASS (code) == tcc_unary)
1470 extract_range_from_unary_expr (vr, gimple_assign_rhs_code (stmt),
1471 gimple_expr_type (stmt),
1472 gimple_assign_rhs1 (stmt));
1473 else if (code == COND_EXPR)
1474 extract_range_from_cond_expr (vr, stmt);
1475 else if (TREE_CODE_CLASS (code) == tcc_comparison)
1476 extract_range_from_comparison (vr, gimple_assign_rhs_code (stmt),
1477 gimple_expr_type (stmt),
1478 gimple_assign_rhs1 (stmt),
1479 gimple_assign_rhs2 (stmt));
1480 else if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS
1481 && is_gimple_min_invariant (gimple_assign_rhs1 (stmt)))
1482 vr->set (gimple_assign_rhs1 (stmt));
1483 else
1484 vr->set_varying (TREE_TYPE (gimple_assign_lhs (stmt)));
1486 if (vr->varying_p ())
1487 extract_range_basic (vr, stmt);
1490 /* Given two numeric value ranges VR0, VR1 and a comparison code COMP:
1492 - Return BOOLEAN_TRUE_NODE if VR0 COMP VR1 always returns true for
1493 all the values in the ranges.
1495 - Return BOOLEAN_FALSE_NODE if the comparison always returns false.
1497 - Return NULL_TREE if it is not always possible to determine the
1498 value of the comparison.
1500 Also set *STRICT_OVERFLOW_P to indicate whether comparision evaluation
1501 assumed signed overflow is undefined. */
1504 static tree
1505 compare_ranges (enum tree_code comp, const value_range *vr0,
1506 const value_range *vr1, bool *strict_overflow_p)
1508 /* VARYING or UNDEFINED ranges cannot be compared. */
1509 if (vr0->varying_p ()
1510 || vr0->undefined_p ()
1511 || vr1->varying_p ()
1512 || vr1->undefined_p ())
1513 return NULL_TREE;
1515 /* Anti-ranges need to be handled separately. */
1516 if (vr0->kind () == VR_ANTI_RANGE || vr1->kind () == VR_ANTI_RANGE)
1518 /* If both are anti-ranges, then we cannot compute any
1519 comparison. */
1520 if (vr0->kind () == VR_ANTI_RANGE && vr1->kind () == VR_ANTI_RANGE)
1521 return NULL_TREE;
1523 /* These comparisons are never statically computable. */
1524 if (comp == GT_EXPR
1525 || comp == GE_EXPR
1526 || comp == LT_EXPR
1527 || comp == LE_EXPR)
1528 return NULL_TREE;
1530 /* Equality can be computed only between a range and an
1531 anti-range. ~[VAL1, VAL2] == [VAL1, VAL2] is always false. */
1532 if (vr0->kind () == VR_RANGE)
1533 /* To simplify processing, make VR0 the anti-range. */
1534 std::swap (vr0, vr1);
1536 gcc_assert (comp == NE_EXPR || comp == EQ_EXPR);
1538 if (compare_values_warnv (vr0->min (), vr1->min (), strict_overflow_p) == 0
1539 && compare_values_warnv (vr0->max (), vr1->max (), strict_overflow_p) == 0)
1540 return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
1542 return NULL_TREE;
1545 /* Simplify processing. If COMP is GT_EXPR or GE_EXPR, switch the
1546 operands around and change the comparison code. */
1547 if (comp == GT_EXPR || comp == GE_EXPR)
1549 comp = (comp == GT_EXPR) ? LT_EXPR : LE_EXPR;
1550 std::swap (vr0, vr1);
1553 if (comp == EQ_EXPR)
1555 /* Equality may only be computed if both ranges represent
1556 exactly one value. */
1557 if (compare_values_warnv (vr0->min (), vr0->max (), strict_overflow_p) == 0
1558 && compare_values_warnv (vr1->min (), vr1->max (), strict_overflow_p) == 0)
1560 int cmp_min = compare_values_warnv (vr0->min (), vr1->min (),
1561 strict_overflow_p);
1562 int cmp_max = compare_values_warnv (vr0->max (), vr1->max (),
1563 strict_overflow_p);
1564 if (cmp_min == 0 && cmp_max == 0)
1565 return boolean_true_node;
1566 else if (cmp_min != -2 && cmp_max != -2)
1567 return boolean_false_node;
1569 /* If [V0_MIN, V1_MAX] < [V1_MIN, V1_MAX] then V0 != V1. */
1570 else if (compare_values_warnv (vr0->min (), vr1->max (),
1571 strict_overflow_p) == 1
1572 || compare_values_warnv (vr1->min (), vr0->max (),
1573 strict_overflow_p) == 1)
1574 return boolean_false_node;
1576 return NULL_TREE;
1578 else if (comp == NE_EXPR)
1580 int cmp1, cmp2;
1582 /* If VR0 is completely to the left or completely to the right
1583 of VR1, they are always different. Notice that we need to
1584 make sure that both comparisons yield similar results to
1585 avoid comparing values that cannot be compared at
1586 compile-time. */
1587 cmp1 = compare_values_warnv (vr0->max (), vr1->min (), strict_overflow_p);
1588 cmp2 = compare_values_warnv (vr0->min (), vr1->max (), strict_overflow_p);
1589 if ((cmp1 == -1 && cmp2 == -1) || (cmp1 == 1 && cmp2 == 1))
1590 return boolean_true_node;
1592 /* If VR0 and VR1 represent a single value and are identical,
1593 return false. */
1594 else if (compare_values_warnv (vr0->min (), vr0->max (),
1595 strict_overflow_p) == 0
1596 && compare_values_warnv (vr1->min (), vr1->max (),
1597 strict_overflow_p) == 0
1598 && compare_values_warnv (vr0->min (), vr1->min (),
1599 strict_overflow_p) == 0
1600 && compare_values_warnv (vr0->max (), vr1->max (),
1601 strict_overflow_p) == 0)
1602 return boolean_false_node;
1604 /* Otherwise, they may or may not be different. */
1605 else
1606 return NULL_TREE;
1608 else if (comp == LT_EXPR || comp == LE_EXPR)
1610 int tst;
1612 /* If VR0 is to the left of VR1, return true. */
1613 tst = compare_values_warnv (vr0->max (), vr1->min (), strict_overflow_p);
1614 if ((comp == LT_EXPR && tst == -1)
1615 || (comp == LE_EXPR && (tst == -1 || tst == 0)))
1616 return boolean_true_node;
1618 /* If VR0 is to the right of VR1, return false. */
1619 tst = compare_values_warnv (vr0->min (), vr1->max (), strict_overflow_p);
1620 if ((comp == LT_EXPR && (tst == 0 || tst == 1))
1621 || (comp == LE_EXPR && tst == 1))
1622 return boolean_false_node;
1624 /* Otherwise, we don't know. */
1625 return NULL_TREE;
1628 gcc_unreachable ();
1631 /* Given a value range VR, a value VAL and a comparison code COMP, return
1632 BOOLEAN_TRUE_NODE if VR COMP VAL always returns true for all the
1633 values in VR. Return BOOLEAN_FALSE_NODE if the comparison
1634 always returns false. Return NULL_TREE if it is not always
1635 possible to determine the value of the comparison. Also set
1636 *STRICT_OVERFLOW_P to indicate whether comparision evaluation
1637 assumed signed overflow is undefined. */
1639 static tree
1640 compare_range_with_value (enum tree_code comp, const value_range *vr, tree val,
1641 bool *strict_overflow_p)
1643 if (vr->varying_p () || vr->undefined_p ())
1644 return NULL_TREE;
1646 /* Anti-ranges need to be handled separately. */
1647 if (vr->kind () == VR_ANTI_RANGE)
1649 /* For anti-ranges, the only predicates that we can compute at
1650 compile time are equality and inequality. */
1651 if (comp == GT_EXPR
1652 || comp == GE_EXPR
1653 || comp == LT_EXPR
1654 || comp == LE_EXPR)
1655 return NULL_TREE;
1657 /* ~[VAL_1, VAL_2] OP VAL is known if VAL_1 <= VAL <= VAL_2. */
1658 if (!vr->may_contain_p (val))
1659 return (comp == NE_EXPR) ? boolean_true_node : boolean_false_node;
1661 return NULL_TREE;
1664 if (comp == EQ_EXPR)
1666 /* EQ_EXPR may only be computed if VR represents exactly
1667 one value. */
1668 if (compare_values_warnv (vr->min (), vr->max (), strict_overflow_p) == 0)
1670 int cmp = compare_values_warnv (vr->min (), val, strict_overflow_p);
1671 if (cmp == 0)
1672 return boolean_true_node;
1673 else if (cmp == -1 || cmp == 1 || cmp == 2)
1674 return boolean_false_node;
1676 else if (compare_values_warnv (val, vr->min (), strict_overflow_p) == -1
1677 || compare_values_warnv (vr->max (), val, strict_overflow_p) == -1)
1678 return boolean_false_node;
1680 return NULL_TREE;
1682 else if (comp == NE_EXPR)
1684 /* If VAL is not inside VR, then they are always different. */
1685 if (compare_values_warnv (vr->max (), val, strict_overflow_p) == -1
1686 || compare_values_warnv (vr->min (), val, strict_overflow_p) == 1)
1687 return boolean_true_node;
1689 /* If VR represents exactly one value equal to VAL, then return
1690 false. */
1691 if (compare_values_warnv (vr->min (), vr->max (), strict_overflow_p) == 0
1692 && compare_values_warnv (vr->min (), val, strict_overflow_p) == 0)
1693 return boolean_false_node;
1695 /* Otherwise, they may or may not be different. */
1696 return NULL_TREE;
1698 else if (comp == LT_EXPR || comp == LE_EXPR)
1700 int tst;
1702 /* If VR is to the left of VAL, return true. */
1703 tst = compare_values_warnv (vr->max (), val, strict_overflow_p);
1704 if ((comp == LT_EXPR && tst == -1)
1705 || (comp == LE_EXPR && (tst == -1 || tst == 0)))
1706 return boolean_true_node;
1708 /* If VR is to the right of VAL, return false. */
1709 tst = compare_values_warnv (vr->min (), val, strict_overflow_p);
1710 if ((comp == LT_EXPR && (tst == 0 || tst == 1))
1711 || (comp == LE_EXPR && tst == 1))
1712 return boolean_false_node;
1714 /* Otherwise, we don't know. */
1715 return NULL_TREE;
1717 else if (comp == GT_EXPR || comp == GE_EXPR)
1719 int tst;
1721 /* If VR is to the right of VAL, return true. */
1722 tst = compare_values_warnv (vr->min (), val, strict_overflow_p);
1723 if ((comp == GT_EXPR && tst == 1)
1724 || (comp == GE_EXPR && (tst == 0 || tst == 1)))
1725 return boolean_true_node;
1727 /* If VR is to the left of VAL, return false. */
1728 tst = compare_values_warnv (vr->max (), val, strict_overflow_p);
1729 if ((comp == GT_EXPR && (tst == -1 || tst == 0))
1730 || (comp == GE_EXPR && tst == -1))
1731 return boolean_false_node;
1733 /* Otherwise, we don't know. */
1734 return NULL_TREE;
1737 gcc_unreachable ();
1739 /* Given a range VR, a LOOP and a variable VAR, determine whether it
1740 would be profitable to adjust VR using scalar evolution information
1741 for VAR. If so, update VR with the new limits. */
1743 void
1744 vr_values::adjust_range_with_scev (value_range *vr, class loop *loop,
1745 gimple *stmt, tree var)
1747 tree init, step, chrec, tmin, tmax, min, max, type, tem;
1748 enum ev_direction dir;
1750 /* TODO. Don't adjust anti-ranges. An anti-range may provide
1751 better opportunities than a regular range, but I'm not sure. */
1752 if (vr->kind () == VR_ANTI_RANGE)
1753 return;
1755 chrec = instantiate_parameters (loop, analyze_scalar_evolution (loop, var));
1757 /* Like in PR19590, scev can return a constant function. */
1758 if (is_gimple_min_invariant (chrec))
1760 vr->set (chrec);
1761 return;
1764 if (TREE_CODE (chrec) != POLYNOMIAL_CHREC)
1765 return;
1767 init = initial_condition_in_loop_num (chrec, loop->num);
1768 tem = op_with_constant_singleton_value_range (init);
1769 if (tem)
1770 init = tem;
1771 step = evolution_part_in_loop_num (chrec, loop->num);
1772 tem = op_with_constant_singleton_value_range (step);
1773 if (tem)
1774 step = tem;
1776 /* If STEP is symbolic, we can't know whether INIT will be the
1777 minimum or maximum value in the range. Also, unless INIT is
1778 a simple expression, compare_values and possibly other functions
1779 in tree-vrp won't be able to handle it. */
1780 if (step == NULL_TREE
1781 || !is_gimple_min_invariant (step)
1782 || !valid_value_p (init))
1783 return;
1785 dir = scev_direction (chrec);
1786 if (/* Do not adjust ranges if we do not know whether the iv increases
1787 or decreases, ... */
1788 dir == EV_DIR_UNKNOWN
1789 /* ... or if it may wrap. */
1790 || scev_probably_wraps_p (NULL_TREE, init, step, stmt,
1791 get_chrec_loop (chrec), true))
1792 return;
1794 type = TREE_TYPE (var);
1795 if (POINTER_TYPE_P (type) || !TYPE_MIN_VALUE (type))
1796 tmin = lower_bound_in_type (type, type);
1797 else
1798 tmin = TYPE_MIN_VALUE (type);
1799 if (POINTER_TYPE_P (type) || !TYPE_MAX_VALUE (type))
1800 tmax = upper_bound_in_type (type, type);
1801 else
1802 tmax = TYPE_MAX_VALUE (type);
1804 /* Try to use estimated number of iterations for the loop to constrain the
1805 final value in the evolution. */
1806 if (TREE_CODE (step) == INTEGER_CST
1807 && is_gimple_val (init)
1808 && (TREE_CODE (init) != SSA_NAME
1809 || get_value_range (init)->kind () == VR_RANGE))
1811 widest_int nit;
1813 /* We are only entering here for loop header PHI nodes, so using
1814 the number of latch executions is the correct thing to use. */
1815 if (max_loop_iterations (loop, &nit))
1817 value_range maxvr;
1818 signop sgn = TYPE_SIGN (TREE_TYPE (step));
1819 wi::overflow_type overflow;
1821 widest_int wtmp = wi::mul (wi::to_widest (step), nit, sgn,
1822 &overflow);
1823 /* If the multiplication overflowed we can't do a meaningful
1824 adjustment. Likewise if the result doesn't fit in the type
1825 of the induction variable. For a signed type we have to
1826 check whether the result has the expected signedness which
1827 is that of the step as number of iterations is unsigned. */
1828 if (!overflow
1829 && wi::fits_to_tree_p (wtmp, TREE_TYPE (init))
1830 && (sgn == UNSIGNED
1831 || wi::gts_p (wtmp, 0) == wi::gts_p (wi::to_wide (step), 0)))
1833 tem = wide_int_to_tree (TREE_TYPE (init), wtmp);
1834 extract_range_from_binary_expr (&maxvr, PLUS_EXPR,
1835 TREE_TYPE (init), init, tem);
1836 /* Likewise if the addition did. */
1837 if (maxvr.kind () == VR_RANGE)
1839 value_range_base initvr;
1841 if (TREE_CODE (init) == SSA_NAME)
1842 initvr = *(get_value_range (init));
1843 else if (is_gimple_min_invariant (init))
1844 initvr.set (init);
1845 else
1846 return;
1848 /* Check if init + nit * step overflows. Though we checked
1849 scev {init, step}_loop doesn't wrap, it is not enough
1850 because the loop may exit immediately. Overflow could
1851 happen in the plus expression in this case. */
1852 if ((dir == EV_DIR_DECREASES
1853 && compare_values (maxvr.min (), initvr.min ()) != -1)
1854 || (dir == EV_DIR_GROWS
1855 && compare_values (maxvr.max (), initvr.max ()) != 1))
1856 return;
1858 tmin = maxvr.min ();
1859 tmax = maxvr.max ();
1865 if (vr->varying_p () || vr->undefined_p ())
1867 min = tmin;
1868 max = tmax;
1870 /* For VARYING or UNDEFINED ranges, just about anything we get
1871 from scalar evolutions should be better. */
1873 if (dir == EV_DIR_DECREASES)
1874 max = init;
1875 else
1876 min = init;
1878 else if (vr->kind () == VR_RANGE)
1880 min = vr->min ();
1881 max = vr->max ();
1883 if (dir == EV_DIR_DECREASES)
1885 /* INIT is the maximum value. If INIT is lower than VR->MAX ()
1886 but no smaller than VR->MIN (), set VR->MAX () to INIT. */
1887 if (compare_values (init, max) == -1)
1888 max = init;
1890 /* According to the loop information, the variable does not
1891 overflow. */
1892 if (compare_values (min, tmin) == -1)
1893 min = tmin;
1896 else
1898 /* If INIT is bigger than VR->MIN (), set VR->MIN () to INIT. */
1899 if (compare_values (init, min) == 1)
1900 min = init;
1902 if (compare_values (tmax, max) == -1)
1903 max = tmax;
1906 else
1907 return;
1909 /* If we just created an invalid range with the minimum
1910 greater than the maximum, we fail conservatively.
1911 This should happen only in unreachable
1912 parts of code, or for invalid programs. */
1913 if (compare_values (min, max) == 1)
1914 return;
1916 /* Even for valid range info, sometimes overflow flag will leak in.
1917 As GIMPLE IL should have no constants with TREE_OVERFLOW set, we
1918 drop them. */
1919 if (TREE_OVERFLOW_P (min))
1920 min = drop_tree_overflow (min);
1921 if (TREE_OVERFLOW_P (max))
1922 max = drop_tree_overflow (max);
1924 vr->update (VR_RANGE, min, max);
1927 /* Dump value ranges of all SSA_NAMEs to FILE. */
1929 void
1930 vr_values::dump_all_value_ranges (FILE *file)
1932 size_t i;
1934 for (i = 0; i < num_vr_values; i++)
1936 if (vr_value[i])
1938 print_generic_expr (file, ssa_name (i));
1939 fprintf (file, ": ");
1940 dump_value_range (file, vr_value[i]);
1941 fprintf (file, "\n");
1945 fprintf (file, "\n");
1948 /* Initialize VRP lattice. */
1950 vr_values::vr_values () : vrp_value_range_pool ("Tree VRP value ranges")
1952 values_propagated = false;
1953 num_vr_values = num_ssa_names * 2;
1954 vr_value = XCNEWVEC (value_range *, num_vr_values);
1955 vr_phi_edge_counts = XCNEWVEC (int, num_ssa_names);
1956 bitmap_obstack_initialize (&vrp_equiv_obstack);
1957 to_remove_edges = vNULL;
1958 to_update_switch_stmts = vNULL;
1961 /* Free VRP lattice. */
1963 vr_values::~vr_values ()
1965 /* Free allocated memory. */
1966 free (vr_value);
1967 free (vr_phi_edge_counts);
1968 bitmap_obstack_release (&vrp_equiv_obstack);
1969 vrp_value_range_pool.release ();
1971 /* So that we can distinguish between VRP data being available
1972 and not available. */
1973 vr_value = NULL;
1974 vr_phi_edge_counts = NULL;
1976 /* If there are entries left in TO_REMOVE_EDGES or TO_UPDATE_SWITCH_STMTS
1977 then an EVRP client did not clean up properly. Catch it now rather
1978 than seeing something more obscure later. */
1979 gcc_assert (to_remove_edges.is_empty ()
1980 && to_update_switch_stmts.is_empty ());
1984 /* A hack. */
1985 static class vr_values *x_vr_values;
1987 /* Return the singleton value-range for NAME or NAME. */
1989 static inline tree
1990 vrp_valueize (tree name)
1992 if (TREE_CODE (name) == SSA_NAME)
1994 const value_range *vr = x_vr_values->get_value_range (name);
1995 if (vr->kind () == VR_RANGE
1996 && (TREE_CODE (vr->min ()) == SSA_NAME
1997 || is_gimple_min_invariant (vr->min ()))
1998 && vrp_operand_equal_p (vr->min (), vr->max ()))
1999 return vr->min ();
2001 return name;
2004 /* Return the singleton value-range for NAME if that is a constant
2005 but signal to not follow SSA edges. */
2007 static inline tree
2008 vrp_valueize_1 (tree name)
2010 if (TREE_CODE (name) == SSA_NAME)
2012 /* If the definition may be simulated again we cannot follow
2013 this SSA edge as the SSA propagator does not necessarily
2014 re-visit the use. */
2015 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
2016 if (!gimple_nop_p (def_stmt)
2017 && prop_simulate_again_p (def_stmt))
2018 return NULL_TREE;
2019 const value_range *vr = x_vr_values->get_value_range (name);
2020 tree singleton;
2021 if (vr->singleton_p (&singleton))
2022 return singleton;
2024 return name;
2027 /* Given STMT, an assignment or call, return its LHS if the type
2028 of the LHS is suitable for VRP analysis, else return NULL_TREE. */
2030 tree
2031 get_output_for_vrp (gimple *stmt)
2033 if (!is_gimple_assign (stmt) && !is_gimple_call (stmt))
2034 return NULL_TREE;
2036 /* We only keep track of ranges in integral and pointer types. */
2037 tree lhs = gimple_get_lhs (stmt);
2038 if (TREE_CODE (lhs) == SSA_NAME
2039 && ((INTEGRAL_TYPE_P (TREE_TYPE (lhs))
2040 /* It is valid to have NULL MIN/MAX values on a type. See
2041 build_range_type. */
2042 && TYPE_MIN_VALUE (TREE_TYPE (lhs))
2043 && TYPE_MAX_VALUE (TREE_TYPE (lhs)))
2044 || POINTER_TYPE_P (TREE_TYPE (lhs))))
2045 return lhs;
2047 return NULL_TREE;
2050 /* Visit assignment STMT. If it produces an interesting range, record
2051 the range in VR and set LHS to OUTPUT_P. */
2053 void
2054 vr_values::vrp_visit_assignment_or_call (gimple *stmt, tree *output_p,
2055 value_range *vr)
2057 tree lhs = get_output_for_vrp (stmt);
2058 *output_p = lhs;
2060 /* We only keep track of ranges in integral and pointer types. */
2061 if (lhs)
2063 enum gimple_code code = gimple_code (stmt);
2065 /* Try folding the statement to a constant first. */
2066 x_vr_values = this;
2067 tree tem = gimple_fold_stmt_to_constant_1 (stmt, vrp_valueize,
2068 vrp_valueize_1);
2069 x_vr_values = NULL;
2070 if (tem)
2072 if (TREE_CODE (tem) == SSA_NAME
2073 && (SSA_NAME_IS_DEFAULT_DEF (tem)
2074 || ! prop_simulate_again_p (SSA_NAME_DEF_STMT (tem))))
2076 extract_range_from_ssa_name (vr, tem);
2077 return;
2079 else if (is_gimple_min_invariant (tem))
2081 vr->set (tem);
2082 return;
2085 /* Then dispatch to value-range extracting functions. */
2086 if (code == GIMPLE_CALL)
2087 extract_range_basic (vr, stmt);
2088 else
2089 extract_range_from_assignment (vr, as_a <gassign *> (stmt));
2093 /* Helper that gets the value range of the SSA_NAME with version I
2094 or a symbolic range containing the SSA_NAME only if the value range
2095 is varying or undefined. Uses TEM as storage for the alternate range. */
2097 const value_range *
2098 vr_values::get_vr_for_comparison (int i, value_range *tem)
2100 /* Shallow-copy equiv bitmap. */
2101 const value_range *vr = get_value_range (ssa_name (i));
2103 /* If name N_i does not have a valid range, use N_i as its own
2104 range. This allows us to compare against names that may
2105 have N_i in their ranges. */
2106 if (vr->varying_p () || vr->undefined_p ())
2108 tem->set (ssa_name (i));
2109 return tem;
2112 return vr;
2115 /* Compare all the value ranges for names equivalent to VAR with VAL
2116 using comparison code COMP. Return the same value returned by
2117 compare_range_with_value, including the setting of
2118 *STRICT_OVERFLOW_P. */
2120 tree
2121 vr_values::compare_name_with_value (enum tree_code comp, tree var, tree val,
2122 bool *strict_overflow_p, bool use_equiv_p)
2124 bitmap_iterator bi;
2125 unsigned i;
2126 bitmap e;
2127 tree retval, t;
2128 int used_strict_overflow;
2129 bool sop;
2130 const value_range *equiv_vr;
2131 value_range tem_vr;
2133 /* Get the set of equivalences for VAR. */
2134 e = get_value_range (var)->equiv ();
2136 /* Start at -1. Set it to 0 if we do a comparison without relying
2137 on overflow, or 1 if all comparisons rely on overflow. */
2138 used_strict_overflow = -1;
2140 /* Compare vars' value range with val. */
2141 equiv_vr = get_vr_for_comparison (SSA_NAME_VERSION (var), &tem_vr);
2142 sop = false;
2143 retval = compare_range_with_value (comp, equiv_vr, val, &sop);
2144 if (retval)
2145 used_strict_overflow = sop ? 1 : 0;
2147 /* If the equiv set is empty we have done all work we need to do. */
2148 if (e == NULL)
2150 if (retval
2151 && used_strict_overflow > 0)
2152 *strict_overflow_p = true;
2153 return retval;
2156 EXECUTE_IF_SET_IN_BITMAP (e, 0, i, bi)
2158 tree name = ssa_name (i);
2159 if (! name)
2160 continue;
2162 if (! use_equiv_p
2163 && ! SSA_NAME_IS_DEFAULT_DEF (name)
2164 && prop_simulate_again_p (SSA_NAME_DEF_STMT (name)))
2165 continue;
2167 equiv_vr = get_vr_for_comparison (i, &tem_vr);
2168 sop = false;
2169 t = compare_range_with_value (comp, equiv_vr, val, &sop);
2170 if (t)
2172 /* If we get different answers from different members
2173 of the equivalence set this check must be in a dead
2174 code region. Folding it to a trap representation
2175 would be correct here. For now just return don't-know. */
2176 if (retval != NULL
2177 && t != retval)
2179 retval = NULL_TREE;
2180 break;
2182 retval = t;
2184 if (!sop)
2185 used_strict_overflow = 0;
2186 else if (used_strict_overflow < 0)
2187 used_strict_overflow = 1;
2191 if (retval
2192 && used_strict_overflow > 0)
2193 *strict_overflow_p = true;
2195 return retval;
2199 /* Given a comparison code COMP and names N1 and N2, compare all the
2200 ranges equivalent to N1 against all the ranges equivalent to N2
2201 to determine the value of N1 COMP N2. Return the same value
2202 returned by compare_ranges. Set *STRICT_OVERFLOW_P to indicate
2203 whether we relied on undefined signed overflow in the comparison. */
2206 tree
2207 vr_values::compare_names (enum tree_code comp, tree n1, tree n2,
2208 bool *strict_overflow_p)
2210 tree t, retval;
2211 bitmap e1, e2;
2212 bitmap_iterator bi1, bi2;
2213 unsigned i1, i2;
2214 int used_strict_overflow;
2215 static bitmap_obstack *s_obstack = NULL;
2216 static bitmap s_e1 = NULL, s_e2 = NULL;
2218 /* Compare the ranges of every name equivalent to N1 against the
2219 ranges of every name equivalent to N2. */
2220 e1 = get_value_range (n1)->equiv ();
2221 e2 = get_value_range (n2)->equiv ();
2223 /* Use the fake bitmaps if e1 or e2 are not available. */
2224 if (s_obstack == NULL)
2226 s_obstack = XNEW (bitmap_obstack);
2227 bitmap_obstack_initialize (s_obstack);
2228 s_e1 = BITMAP_ALLOC (s_obstack);
2229 s_e2 = BITMAP_ALLOC (s_obstack);
2231 if (e1 == NULL)
2232 e1 = s_e1;
2233 if (e2 == NULL)
2234 e2 = s_e2;
2236 /* Add N1 and N2 to their own set of equivalences to avoid
2237 duplicating the body of the loop just to check N1 and N2
2238 ranges. */
2239 bitmap_set_bit (e1, SSA_NAME_VERSION (n1));
2240 bitmap_set_bit (e2, SSA_NAME_VERSION (n2));
2242 /* If the equivalence sets have a common intersection, then the two
2243 names can be compared without checking their ranges. */
2244 if (bitmap_intersect_p (e1, e2))
2246 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
2247 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
2249 return (comp == EQ_EXPR || comp == GE_EXPR || comp == LE_EXPR)
2250 ? boolean_true_node
2251 : boolean_false_node;
2254 /* Start at -1. Set it to 0 if we do a comparison without relying
2255 on overflow, or 1 if all comparisons rely on overflow. */
2256 used_strict_overflow = -1;
2258 /* Otherwise, compare all the equivalent ranges. First, add N1 and
2259 N2 to their own set of equivalences to avoid duplicating the body
2260 of the loop just to check N1 and N2 ranges. */
2261 EXECUTE_IF_SET_IN_BITMAP (e1, 0, i1, bi1)
2263 if (! ssa_name (i1))
2264 continue;
2266 value_range tem_vr1;
2267 const value_range *vr1 = get_vr_for_comparison (i1, &tem_vr1);
2269 t = retval = NULL_TREE;
2270 EXECUTE_IF_SET_IN_BITMAP (e2, 0, i2, bi2)
2272 if (! ssa_name (i2))
2273 continue;
2275 bool sop = false;
2277 value_range tem_vr2;
2278 const value_range *vr2 = get_vr_for_comparison (i2, &tem_vr2);
2280 t = compare_ranges (comp, vr1, vr2, &sop);
2281 if (t)
2283 /* If we get different answers from different members
2284 of the equivalence set this check must be in a dead
2285 code region. Folding it to a trap representation
2286 would be correct here. For now just return don't-know. */
2287 if (retval != NULL
2288 && t != retval)
2290 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
2291 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
2292 return NULL_TREE;
2294 retval = t;
2296 if (!sop)
2297 used_strict_overflow = 0;
2298 else if (used_strict_overflow < 0)
2299 used_strict_overflow = 1;
2303 if (retval)
2305 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
2306 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
2307 if (used_strict_overflow > 0)
2308 *strict_overflow_p = true;
2309 return retval;
2313 /* None of the equivalent ranges are useful in computing this
2314 comparison. */
2315 bitmap_clear_bit (e1, SSA_NAME_VERSION (n1));
2316 bitmap_clear_bit (e2, SSA_NAME_VERSION (n2));
2317 return NULL_TREE;
2320 /* Helper function for vrp_evaluate_conditional_warnv & other
2321 optimizers. */
2323 tree
2324 vr_values::vrp_evaluate_conditional_warnv_with_ops_using_ranges
2325 (enum tree_code code, tree op0, tree op1, bool * strict_overflow_p)
2327 const value_range *vr0, *vr1;
2329 vr0 = (TREE_CODE (op0) == SSA_NAME) ? get_value_range (op0) : NULL;
2330 vr1 = (TREE_CODE (op1) == SSA_NAME) ? get_value_range (op1) : NULL;
2332 tree res = NULL_TREE;
2333 if (vr0 && vr1)
2334 res = compare_ranges (code, vr0, vr1, strict_overflow_p);
2335 if (!res && vr0)
2336 res = compare_range_with_value (code, vr0, op1, strict_overflow_p);
2337 if (!res && vr1)
2338 res = (compare_range_with_value
2339 (swap_tree_comparison (code), vr1, op0, strict_overflow_p));
2340 return res;
2343 /* Helper function for vrp_evaluate_conditional_warnv. */
2345 tree
2346 vr_values::vrp_evaluate_conditional_warnv_with_ops (enum tree_code code,
2347 tree op0, tree op1,
2348 bool use_equiv_p,
2349 bool *strict_overflow_p,
2350 bool *only_ranges)
2352 tree ret;
2353 if (only_ranges)
2354 *only_ranges = true;
2356 /* We only deal with integral and pointer types. */
2357 if (!INTEGRAL_TYPE_P (TREE_TYPE (op0))
2358 && !POINTER_TYPE_P (TREE_TYPE (op0)))
2359 return NULL_TREE;
2361 /* If OP0 CODE OP1 is an overflow comparison, if it can be expressed
2362 as a simple equality test, then prefer that over its current form
2363 for evaluation.
2365 An overflow test which collapses to an equality test can always be
2366 expressed as a comparison of one argument against zero. Overflow
2367 occurs when the chosen argument is zero and does not occur if the
2368 chosen argument is not zero. */
2369 tree x;
2370 if (overflow_comparison_p (code, op0, op1, use_equiv_p, &x))
2372 wide_int max = wi::max_value (TYPE_PRECISION (TREE_TYPE (op0)), UNSIGNED);
2373 /* B = A - 1; if (A < B) -> B = A - 1; if (A == 0)
2374 B = A - 1; if (A > B) -> B = A - 1; if (A != 0)
2375 B = A + 1; if (B < A) -> B = A + 1; if (B == 0)
2376 B = A + 1; if (B > A) -> B = A + 1; if (B != 0) */
2377 if (integer_zerop (x))
2379 op1 = x;
2380 code = (code == LT_EXPR || code == LE_EXPR) ? EQ_EXPR : NE_EXPR;
2382 /* B = A + 1; if (A > B) -> B = A + 1; if (B == 0)
2383 B = A + 1; if (A < B) -> B = A + 1; if (B != 0)
2384 B = A - 1; if (B > A) -> B = A - 1; if (A == 0)
2385 B = A - 1; if (B < A) -> B = A - 1; if (A != 0) */
2386 else if (wi::to_wide (x) == max - 1)
2388 op0 = op1;
2389 op1 = wide_int_to_tree (TREE_TYPE (op0), 0);
2390 code = (code == GT_EXPR || code == GE_EXPR) ? EQ_EXPR : NE_EXPR;
2392 else
2394 value_range_base vro, vri;
2395 if (code == GT_EXPR || code == GE_EXPR)
2397 vro.set (VR_ANTI_RANGE, TYPE_MIN_VALUE (TREE_TYPE (op0)), x);
2398 vri.set (VR_RANGE, TYPE_MIN_VALUE (TREE_TYPE (op0)), x);
2400 else if (code == LT_EXPR || code == LE_EXPR)
2402 vro.set (VR_RANGE, TYPE_MIN_VALUE (TREE_TYPE (op0)), x);
2403 vri.set (VR_ANTI_RANGE, TYPE_MIN_VALUE (TREE_TYPE (op0)), x);
2405 else
2406 gcc_unreachable ();
2407 const value_range *vr0 = get_value_range (op0);
2408 /* If vro, the range for OP0 to pass the overflow test, has
2409 no intersection with *vr0, OP0's known range, then the
2410 overflow test can't pass, so return the node for false.
2411 If it is the inverted range, vri, that has no
2412 intersection, then the overflow test must pass, so return
2413 the node for true. In other cases, we could proceed with
2414 a simplified condition comparing OP0 and X, with LE_EXPR
2415 for previously LE_ or LT_EXPR and GT_EXPR otherwise, but
2416 the comments next to the enclosing if suggest it's not
2417 generally profitable to do so. */
2418 vro.intersect (vr0);
2419 if (vro.undefined_p ())
2420 return boolean_false_node;
2421 vri.intersect (vr0);
2422 if (vri.undefined_p ())
2423 return boolean_true_node;
2427 if ((ret = vrp_evaluate_conditional_warnv_with_ops_using_ranges
2428 (code, op0, op1, strict_overflow_p)))
2429 return ret;
2430 if (only_ranges)
2431 *only_ranges = false;
2432 /* Do not use compare_names during propagation, it's quadratic. */
2433 if (TREE_CODE (op0) == SSA_NAME && TREE_CODE (op1) == SSA_NAME
2434 && use_equiv_p)
2435 return compare_names (code, op0, op1, strict_overflow_p);
2436 else if (TREE_CODE (op0) == SSA_NAME)
2437 return compare_name_with_value (code, op0, op1,
2438 strict_overflow_p, use_equiv_p);
2439 else if (TREE_CODE (op1) == SSA_NAME)
2440 return compare_name_with_value (swap_tree_comparison (code), op1, op0,
2441 strict_overflow_p, use_equiv_p);
2442 return NULL_TREE;
2445 /* Given (CODE OP0 OP1) within STMT, try to simplify it based on value range
2446 information. Return NULL if the conditional cannot be evaluated.
2447 The ranges of all the names equivalent with the operands in COND
2448 will be used when trying to compute the value. If the result is
2449 based on undefined signed overflow, issue a warning if
2450 appropriate. */
2452 tree
2453 vr_values::vrp_evaluate_conditional (tree_code code, tree op0,
2454 tree op1, gimple *stmt)
2456 bool sop;
2457 tree ret;
2458 bool only_ranges;
2460 /* Some passes and foldings leak constants with overflow flag set
2461 into the IL. Avoid doing wrong things with these and bail out. */
2462 if ((TREE_CODE (op0) == INTEGER_CST
2463 && TREE_OVERFLOW (op0))
2464 || (TREE_CODE (op1) == INTEGER_CST
2465 && TREE_OVERFLOW (op1)))
2466 return NULL_TREE;
2468 sop = false;
2469 ret = vrp_evaluate_conditional_warnv_with_ops (code, op0, op1, true, &sop,
2470 &only_ranges);
2472 if (ret && sop)
2474 enum warn_strict_overflow_code wc;
2475 const char* warnmsg;
2477 if (is_gimple_min_invariant (ret))
2479 wc = WARN_STRICT_OVERFLOW_CONDITIONAL;
2480 warnmsg = G_("assuming signed overflow does not occur when "
2481 "simplifying conditional to constant");
2483 else
2485 wc = WARN_STRICT_OVERFLOW_COMPARISON;
2486 warnmsg = G_("assuming signed overflow does not occur when "
2487 "simplifying conditional");
2490 if (issue_strict_overflow_warning (wc))
2492 location_t location;
2494 if (!gimple_has_location (stmt))
2495 location = input_location;
2496 else
2497 location = gimple_location (stmt);
2498 warning_at (location, OPT_Wstrict_overflow, "%s", warnmsg);
2502 if (warn_type_limits
2503 && ret && only_ranges
2504 && TREE_CODE_CLASS (code) == tcc_comparison
2505 && TREE_CODE (op0) == SSA_NAME)
2507 /* If the comparison is being folded and the operand on the LHS
2508 is being compared against a constant value that is outside of
2509 the natural range of OP0's type, then the predicate will
2510 always fold regardless of the value of OP0. If -Wtype-limits
2511 was specified, emit a warning. */
2512 tree type = TREE_TYPE (op0);
2513 const value_range *vr0 = get_value_range (op0);
2515 if (vr0->kind () == VR_RANGE
2516 && INTEGRAL_TYPE_P (type)
2517 && vrp_val_is_min (vr0->min ())
2518 && vrp_val_is_max (vr0->max ())
2519 && is_gimple_min_invariant (op1))
2521 location_t location;
2523 if (!gimple_has_location (stmt))
2524 location = input_location;
2525 else
2526 location = gimple_location (stmt);
2528 warning_at (location, OPT_Wtype_limits,
2529 integer_zerop (ret)
2530 ? G_("comparison always false "
2531 "due to limited range of data type")
2532 : G_("comparison always true "
2533 "due to limited range of data type"));
2537 return ret;
2541 /* Visit conditional statement STMT. If we can determine which edge
2542 will be taken out of STMT's basic block, record it in
2543 *TAKEN_EDGE_P. Otherwise, set *TAKEN_EDGE_P to NULL. */
2545 void
2546 vr_values::vrp_visit_cond_stmt (gcond *stmt, edge *taken_edge_p)
2548 tree val;
2550 *taken_edge_p = NULL;
2552 if (dump_file && (dump_flags & TDF_DETAILS))
2554 tree use;
2555 ssa_op_iter i;
2557 fprintf (dump_file, "\nVisiting conditional with predicate: ");
2558 print_gimple_stmt (dump_file, stmt, 0);
2559 fprintf (dump_file, "\nWith known ranges\n");
2561 FOR_EACH_SSA_TREE_OPERAND (use, stmt, i, SSA_OP_USE)
2563 fprintf (dump_file, "\t");
2564 print_generic_expr (dump_file, use);
2565 fprintf (dump_file, ": ");
2566 dump_value_range (dump_file, vr_value[SSA_NAME_VERSION (use)]);
2569 fprintf (dump_file, "\n");
2572 /* Compute the value of the predicate COND by checking the known
2573 ranges of each of its operands.
2575 Note that we cannot evaluate all the equivalent ranges here
2576 because those ranges may not yet be final and with the current
2577 propagation strategy, we cannot determine when the value ranges
2578 of the names in the equivalence set have changed.
2580 For instance, given the following code fragment
2582 i_5 = PHI <8, i_13>
2584 i_14 = ASSERT_EXPR <i_5, i_5 != 0>
2585 if (i_14 == 1)
2588 Assume that on the first visit to i_14, i_5 has the temporary
2589 range [8, 8] because the second argument to the PHI function is
2590 not yet executable. We derive the range ~[0, 0] for i_14 and the
2591 equivalence set { i_5 }. So, when we visit 'if (i_14 == 1)' for
2592 the first time, since i_14 is equivalent to the range [8, 8], we
2593 determine that the predicate is always false.
2595 On the next round of propagation, i_13 is determined to be
2596 VARYING, which causes i_5 to drop down to VARYING. So, another
2597 visit to i_14 is scheduled. In this second visit, we compute the
2598 exact same range and equivalence set for i_14, namely ~[0, 0] and
2599 { i_5 }. But we did not have the previous range for i_5
2600 registered, so vrp_visit_assignment thinks that the range for
2601 i_14 has not changed. Therefore, the predicate 'if (i_14 == 1)'
2602 is not visited again, which stops propagation from visiting
2603 statements in the THEN clause of that if().
2605 To properly fix this we would need to keep the previous range
2606 value for the names in the equivalence set. This way we would've
2607 discovered that from one visit to the other i_5 changed from
2608 range [8, 8] to VR_VARYING.
2610 However, fixing this apparent limitation may not be worth the
2611 additional checking. Testing on several code bases (GCC, DLV,
2612 MICO, TRAMP3D and SPEC2000) showed that doing this results in
2613 4 more predicates folded in SPEC. */
2615 bool sop;
2616 val = vrp_evaluate_conditional_warnv_with_ops (gimple_cond_code (stmt),
2617 gimple_cond_lhs (stmt),
2618 gimple_cond_rhs (stmt),
2619 false, &sop, NULL);
2620 if (val)
2621 *taken_edge_p = find_taken_edge (gimple_bb (stmt), val);
2623 if (dump_file && (dump_flags & TDF_DETAILS))
2625 fprintf (dump_file, "\nPredicate evaluates to: ");
2626 if (val == NULL_TREE)
2627 fprintf (dump_file, "DON'T KNOW\n");
2628 else
2629 print_generic_stmt (dump_file, val);
2633 /* Searches the case label vector VEC for the ranges of CASE_LABELs that are
2634 used in range VR. The indices are placed in MIN_IDX1, MAX_IDX, MIN_IDX2 and
2635 MAX_IDX2. If the ranges of CASE_LABELs are empty then MAX_IDX1 < MIN_IDX1.
2636 Returns true if the default label is not needed. */
2638 static bool
2639 find_case_label_ranges (gswitch *stmt, const value_range *vr, size_t *min_idx1,
2640 size_t *max_idx1, size_t *min_idx2,
2641 size_t *max_idx2)
2643 size_t i, j, k, l;
2644 unsigned int n = gimple_switch_num_labels (stmt);
2645 bool take_default;
2646 tree case_low, case_high;
2647 tree min = vr->min (), max = vr->max ();
2649 gcc_checking_assert (!vr->varying_p () && !vr->undefined_p ());
2651 take_default = !find_case_label_range (stmt, min, max, &i, &j);
2653 /* Set second range to empty. */
2654 *min_idx2 = 1;
2655 *max_idx2 = 0;
2657 if (vr->kind () == VR_RANGE)
2659 *min_idx1 = i;
2660 *max_idx1 = j;
2661 return !take_default;
2664 /* Set first range to all case labels. */
2665 *min_idx1 = 1;
2666 *max_idx1 = n - 1;
2668 if (i > j)
2669 return false;
2671 /* Make sure all the values of case labels [i , j] are contained in
2672 range [MIN, MAX]. */
2673 case_low = CASE_LOW (gimple_switch_label (stmt, i));
2674 case_high = CASE_HIGH (gimple_switch_label (stmt, j));
2675 if (tree_int_cst_compare (case_low, min) < 0)
2676 i += 1;
2677 if (case_high != NULL_TREE
2678 && tree_int_cst_compare (max, case_high) < 0)
2679 j -= 1;
2681 if (i > j)
2682 return false;
2684 /* If the range spans case labels [i, j], the corresponding anti-range spans
2685 the labels [1, i - 1] and [j + 1, n - 1]. */
2686 k = j + 1;
2687 l = n - 1;
2688 if (k > l)
2690 k = 1;
2691 l = 0;
2694 j = i - 1;
2695 i = 1;
2696 if (i > j)
2698 i = k;
2699 j = l;
2700 k = 1;
2701 l = 0;
2704 *min_idx1 = i;
2705 *max_idx1 = j;
2706 *min_idx2 = k;
2707 *max_idx2 = l;
2708 return false;
2711 /* Visit switch statement STMT. If we can determine which edge
2712 will be taken out of STMT's basic block, record it in
2713 *TAKEN_EDGE_P. Otherwise, *TAKEN_EDGE_P set to NULL. */
2715 void
2716 vr_values::vrp_visit_switch_stmt (gswitch *stmt, edge *taken_edge_p)
2718 tree op, val;
2719 const value_range *vr;
2720 size_t i = 0, j = 0, k, l;
2721 bool take_default;
2723 *taken_edge_p = NULL;
2724 op = gimple_switch_index (stmt);
2725 if (TREE_CODE (op) != SSA_NAME)
2726 return;
2728 vr = get_value_range (op);
2729 if (dump_file && (dump_flags & TDF_DETAILS))
2731 fprintf (dump_file, "\nVisiting switch expression with operand ");
2732 print_generic_expr (dump_file, op);
2733 fprintf (dump_file, " with known range ");
2734 dump_value_range (dump_file, vr);
2735 fprintf (dump_file, "\n");
2738 if (vr->undefined_p ()
2739 || vr->varying_p ()
2740 || vr->symbolic_p ())
2741 return;
2743 /* Find the single edge that is taken from the switch expression. */
2744 take_default = !find_case_label_ranges (stmt, vr, &i, &j, &k, &l);
2746 /* Check if the range spans no CASE_LABEL. If so, we only reach the default
2747 label */
2748 if (j < i)
2750 gcc_assert (take_default);
2751 val = gimple_switch_default_label (stmt);
2753 else
2755 /* Check if labels with index i to j and maybe the default label
2756 are all reaching the same label. */
2758 val = gimple_switch_label (stmt, i);
2759 if (take_default
2760 && CASE_LABEL (gimple_switch_default_label (stmt))
2761 != CASE_LABEL (val))
2763 if (dump_file && (dump_flags & TDF_DETAILS))
2764 fprintf (dump_file, " not a single destination for this "
2765 "range\n");
2766 return;
2768 for (++i; i <= j; ++i)
2770 if (CASE_LABEL (gimple_switch_label (stmt, i)) != CASE_LABEL (val))
2772 if (dump_file && (dump_flags & TDF_DETAILS))
2773 fprintf (dump_file, " not a single destination for this "
2774 "range\n");
2775 return;
2778 for (; k <= l; ++k)
2780 if (CASE_LABEL (gimple_switch_label (stmt, k)) != CASE_LABEL (val))
2782 if (dump_file && (dump_flags & TDF_DETAILS))
2783 fprintf (dump_file, " not a single destination for this "
2784 "range\n");
2785 return;
2790 *taken_edge_p = find_edge (gimple_bb (stmt),
2791 label_to_block (cfun, CASE_LABEL (val)));
2793 if (dump_file && (dump_flags & TDF_DETAILS))
2795 fprintf (dump_file, " will take edge to ");
2796 print_generic_stmt (dump_file, CASE_LABEL (val));
2801 /* Evaluate statement STMT. If the statement produces a useful range,
2802 set VR and corepsponding OUTPUT_P.
2804 If STMT is a conditional branch and we can determine its truth
2805 value, the taken edge is recorded in *TAKEN_EDGE_P. */
2807 void
2808 vr_values::extract_range_from_stmt (gimple *stmt, edge *taken_edge_p,
2809 tree *output_p, value_range *vr)
2812 if (dump_file && (dump_flags & TDF_DETAILS))
2814 fprintf (dump_file, "\nVisiting statement:\n");
2815 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
2818 if (!stmt_interesting_for_vrp (stmt))
2819 gcc_assert (stmt_ends_bb_p (stmt));
2820 else if (is_gimple_assign (stmt) || is_gimple_call (stmt))
2821 vrp_visit_assignment_or_call (stmt, output_p, vr);
2822 else if (gimple_code (stmt) == GIMPLE_COND)
2823 vrp_visit_cond_stmt (as_a <gcond *> (stmt), taken_edge_p);
2824 else if (gimple_code (stmt) == GIMPLE_SWITCH)
2825 vrp_visit_switch_stmt (as_a <gswitch *> (stmt), taken_edge_p);
2828 /* Visit all arguments for PHI node PHI that flow through executable
2829 edges. If a valid value range can be derived from all the incoming
2830 value ranges, set a new range in VR_RESULT. */
2832 void
2833 vr_values::extract_range_from_phi_node (gphi *phi, value_range *vr_result)
2835 size_t i;
2836 tree lhs = PHI_RESULT (phi);
2837 const value_range *lhs_vr = get_value_range (lhs);
2838 bool first = true;
2839 int edges, old_edges;
2840 class loop *l;
2842 if (dump_file && (dump_flags & TDF_DETAILS))
2844 fprintf (dump_file, "\nVisiting PHI node: ");
2845 print_gimple_stmt (dump_file, phi, 0, dump_flags);
2848 bool may_simulate_backedge_again = false;
2849 edges = 0;
2850 for (i = 0; i < gimple_phi_num_args (phi); i++)
2852 edge e = gimple_phi_arg_edge (phi, i);
2854 if (dump_file && (dump_flags & TDF_DETAILS))
2856 fprintf (dump_file,
2857 " Argument #%d (%d -> %d %sexecutable)\n",
2858 (int) i, e->src->index, e->dest->index,
2859 (e->flags & EDGE_EXECUTABLE) ? "" : "not ");
2862 if (e->flags & EDGE_EXECUTABLE)
2864 tree arg = PHI_ARG_DEF (phi, i);
2865 value_range vr_arg_tem;
2866 const value_range *vr_arg = &vr_arg_tem;
2868 ++edges;
2870 if (TREE_CODE (arg) == SSA_NAME)
2872 /* See if we are eventually going to change one of the args. */
2873 gimple *def_stmt = SSA_NAME_DEF_STMT (arg);
2874 if (! gimple_nop_p (def_stmt)
2875 && prop_simulate_again_p (def_stmt)
2876 && e->flags & EDGE_DFS_BACK)
2877 may_simulate_backedge_again = true;
2879 const value_range *vr_arg_ = get_value_range (arg);
2880 /* Do not allow equivalences or symbolic ranges to leak in from
2881 backedges. That creates invalid equivalencies.
2882 See PR53465 and PR54767. */
2883 if (e->flags & EDGE_DFS_BACK)
2885 if (!vr_arg_->varying_p () && !vr_arg_->undefined_p ())
2887 vr_arg_tem.set (vr_arg_->kind (), vr_arg_->min (),
2888 vr_arg_->max (), NULL);
2889 if (vr_arg_tem.symbolic_p ())
2890 vr_arg_tem.set_varying (TREE_TYPE (arg));
2892 else
2893 vr_arg = vr_arg_;
2895 /* If the non-backedge arguments range is VR_VARYING then
2896 we can still try recording a simple equivalence. */
2897 else if (vr_arg_->varying_p ())
2898 vr_arg_tem.set (arg);
2899 else
2900 vr_arg = vr_arg_;
2902 else
2904 if (TREE_OVERFLOW_P (arg))
2905 arg = drop_tree_overflow (arg);
2907 vr_arg_tem.set (arg);
2910 if (dump_file && (dump_flags & TDF_DETAILS))
2912 fprintf (dump_file, "\t");
2913 print_generic_expr (dump_file, arg, dump_flags);
2914 fprintf (dump_file, ": ");
2915 dump_value_range (dump_file, vr_arg);
2916 fprintf (dump_file, "\n");
2919 if (first)
2920 vr_result->deep_copy (vr_arg);
2921 else
2922 vr_result->union_ (vr_arg);
2923 first = false;
2925 if (vr_result->varying_p ())
2926 break;
2930 if (vr_result->varying_p ())
2931 goto varying;
2932 else if (vr_result->undefined_p ())
2933 goto update_range;
2935 old_edges = vr_phi_edge_counts[SSA_NAME_VERSION (lhs)];
2936 vr_phi_edge_counts[SSA_NAME_VERSION (lhs)] = edges;
2938 /* To prevent infinite iterations in the algorithm, derive ranges
2939 when the new value is slightly bigger or smaller than the
2940 previous one. We don't do this if we have seen a new executable
2941 edge; this helps us avoid an infinity for conditionals
2942 which are not in a loop. If the old value-range was VR_UNDEFINED
2943 use the updated range and iterate one more time. If we will not
2944 simulate this PHI again via the backedge allow us to iterate. */
2945 if (edges > 0
2946 && gimple_phi_num_args (phi) > 1
2947 && edges == old_edges
2948 && !lhs_vr->undefined_p ()
2949 && may_simulate_backedge_again)
2951 /* Compare old and new ranges, fall back to varying if the
2952 values are not comparable. */
2953 int cmp_min = compare_values (lhs_vr->min (), vr_result->min ());
2954 if (cmp_min == -2)
2955 goto varying;
2956 int cmp_max = compare_values (lhs_vr->max (), vr_result->max ());
2957 if (cmp_max == -2)
2958 goto varying;
2960 /* For non VR_RANGE or for pointers fall back to varying if
2961 the range changed. */
2962 if ((lhs_vr->kind () != VR_RANGE || vr_result->kind () != VR_RANGE
2963 || POINTER_TYPE_P (TREE_TYPE (lhs)))
2964 && (cmp_min != 0 || cmp_max != 0))
2965 goto varying;
2967 /* If the new minimum is larger than the previous one
2968 retain the old value. If the new minimum value is smaller
2969 than the previous one and not -INF go all the way to -INF + 1.
2970 In the first case, to avoid infinite bouncing between different
2971 minimums, and in the other case to avoid iterating millions of
2972 times to reach -INF. Going to -INF + 1 also lets the following
2973 iteration compute whether there will be any overflow, at the
2974 expense of one additional iteration. */
2975 tree new_min = vr_result->min ();
2976 tree new_max = vr_result->max ();
2977 if (cmp_min < 0)
2978 new_min = lhs_vr->min ();
2979 else if (cmp_min > 0
2980 && (TREE_CODE (vr_result->min ()) != INTEGER_CST
2981 || tree_int_cst_lt (vrp_val_min (vr_result->type ()),
2982 vr_result->min ())))
2983 new_min = int_const_binop (PLUS_EXPR,
2984 vrp_val_min (vr_result->type ()),
2985 build_int_cst (vr_result->type (), 1));
2987 /* Similarly for the maximum value. */
2988 if (cmp_max > 0)
2989 new_max = lhs_vr->max ();
2990 else if (cmp_max < 0
2991 && (TREE_CODE (vr_result->max ()) != INTEGER_CST
2992 || tree_int_cst_lt (vr_result->max (),
2993 vrp_val_max (vr_result->type ()))))
2994 new_max = int_const_binop (MINUS_EXPR,
2995 vrp_val_max (vr_result->type ()),
2996 build_int_cst (vr_result->type (), 1));
2998 vr_result->update (vr_result->kind (), new_min, new_max);
3000 /* If we dropped either bound to +-INF then if this is a loop
3001 PHI node SCEV may known more about its value-range. */
3002 if (cmp_min > 0 || cmp_min < 0
3003 || cmp_max < 0 || cmp_max > 0)
3004 goto scev_check;
3006 goto infinite_check;
3009 goto update_range;
3011 varying:
3012 vr_result->set_varying (TREE_TYPE (lhs));
3014 scev_check:
3015 /* If this is a loop PHI node SCEV may known more about its value-range.
3016 scev_check can be reached from two paths, one is a fall through from above
3017 "varying" label, the other is direct goto from code block which tries to
3018 avoid infinite simulation. */
3019 if (scev_initialized_p ()
3020 && (l = loop_containing_stmt (phi))
3021 && l->header == gimple_bb (phi))
3022 adjust_range_with_scev (vr_result, l, phi, lhs);
3024 infinite_check:
3025 /* If we will end up with a (-INF, +INF) range, set it to
3026 VARYING. Same if the previous max value was invalid for
3027 the type and we end up with vr_result.min > vr_result.max. */
3028 if ((!vr_result->varying_p () && !vr_result->undefined_p ())
3029 && !((vrp_val_is_max (vr_result->max ()) && vrp_val_is_min (vr_result->min ()))
3030 || compare_values (vr_result->min (), vr_result->max ()) > 0))
3032 else
3033 vr_result->set_varying (TREE_TYPE (lhs));
3035 /* If the new range is different than the previous value, keep
3036 iterating. */
3037 update_range:
3038 return;
3041 /* Simplify boolean operations if the source is known
3042 to be already a boolean. */
3043 bool
3044 vr_values::simplify_truth_ops_using_ranges (gimple_stmt_iterator *gsi,
3045 gimple *stmt)
3047 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
3048 tree lhs, op0, op1;
3049 bool need_conversion;
3051 /* We handle only !=/== case here. */
3052 gcc_assert (rhs_code == EQ_EXPR || rhs_code == NE_EXPR);
3054 op0 = gimple_assign_rhs1 (stmt);
3055 if (!op_with_boolean_value_range_p (op0))
3056 return false;
3058 op1 = gimple_assign_rhs2 (stmt);
3059 if (!op_with_boolean_value_range_p (op1))
3060 return false;
3062 /* Reduce number of cases to handle to NE_EXPR. As there is no
3063 BIT_XNOR_EXPR we cannot replace A == B with a single statement. */
3064 if (rhs_code == EQ_EXPR)
3066 if (TREE_CODE (op1) == INTEGER_CST)
3067 op1 = int_const_binop (BIT_XOR_EXPR, op1,
3068 build_int_cst (TREE_TYPE (op1), 1));
3069 else
3070 return false;
3073 lhs = gimple_assign_lhs (stmt);
3074 need_conversion
3075 = !useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (op0));
3077 /* Make sure to not sign-extend a 1-bit 1 when converting the result. */
3078 if (need_conversion
3079 && !TYPE_UNSIGNED (TREE_TYPE (op0))
3080 && TYPE_PRECISION (TREE_TYPE (op0)) == 1
3081 && TYPE_PRECISION (TREE_TYPE (lhs)) > 1)
3082 return false;
3084 /* For A != 0 we can substitute A itself. */
3085 if (integer_zerop (op1))
3086 gimple_assign_set_rhs_with_ops (gsi,
3087 need_conversion
3088 ? NOP_EXPR : TREE_CODE (op0), op0);
3089 /* For A != B we substitute A ^ B. Either with conversion. */
3090 else if (need_conversion)
3092 tree tem = make_ssa_name (TREE_TYPE (op0));
3093 gassign *newop
3094 = gimple_build_assign (tem, BIT_XOR_EXPR, op0, op1);
3095 gsi_insert_before (gsi, newop, GSI_SAME_STMT);
3096 if (INTEGRAL_TYPE_P (TREE_TYPE (tem))
3097 && TYPE_PRECISION (TREE_TYPE (tem)) > 1)
3098 set_range_info (tem, VR_RANGE,
3099 wi::zero (TYPE_PRECISION (TREE_TYPE (tem))),
3100 wi::one (TYPE_PRECISION (TREE_TYPE (tem))));
3101 gimple_assign_set_rhs_with_ops (gsi, NOP_EXPR, tem);
3103 /* Or without. */
3104 else
3105 gimple_assign_set_rhs_with_ops (gsi, BIT_XOR_EXPR, op0, op1);
3106 update_stmt (gsi_stmt (*gsi));
3107 fold_stmt (gsi, follow_single_use_edges);
3109 return true;
3112 /* Simplify a division or modulo operator to a right shift or bitwise and
3113 if the first operand is unsigned or is greater than zero and the second
3114 operand is an exact power of two. For TRUNC_MOD_EXPR op0 % op1 with
3115 constant op1 (op1min = op1) or with op1 in [op1min, op1max] range,
3116 optimize it into just op0 if op0's range is known to be a subset of
3117 [-op1min + 1, op1min - 1] for signed and [0, op1min - 1] for unsigned
3118 modulo. */
3120 bool
3121 vr_values::simplify_div_or_mod_using_ranges (gimple_stmt_iterator *gsi,
3122 gimple *stmt)
3124 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
3125 tree val = NULL;
3126 tree op0 = gimple_assign_rhs1 (stmt);
3127 tree op1 = gimple_assign_rhs2 (stmt);
3128 tree op0min = NULL_TREE, op0max = NULL_TREE;
3129 tree op1min = op1;
3130 const value_range *vr = NULL;
3132 if (TREE_CODE (op0) == INTEGER_CST)
3134 op0min = op0;
3135 op0max = op0;
3137 else
3139 vr = get_value_range (op0);
3140 if (range_int_cst_p (vr))
3142 op0min = vr->min ();
3143 op0max = vr->max ();
3147 if (rhs_code == TRUNC_MOD_EXPR
3148 && TREE_CODE (op1) == SSA_NAME)
3150 const value_range *vr1 = get_value_range (op1);
3151 if (range_int_cst_p (vr1))
3152 op1min = vr1->min ();
3154 if (rhs_code == TRUNC_MOD_EXPR
3155 && TREE_CODE (op1min) == INTEGER_CST
3156 && tree_int_cst_sgn (op1min) == 1
3157 && op0max
3158 && tree_int_cst_lt (op0max, op1min))
3160 if (TYPE_UNSIGNED (TREE_TYPE (op0))
3161 || tree_int_cst_sgn (op0min) >= 0
3162 || tree_int_cst_lt (fold_unary (NEGATE_EXPR, TREE_TYPE (op1min), op1min),
3163 op0min))
3165 /* If op0 already has the range op0 % op1 has,
3166 then TRUNC_MOD_EXPR won't change anything. */
3167 gimple_assign_set_rhs_from_tree (gsi, op0);
3168 return true;
3172 if (TREE_CODE (op0) != SSA_NAME)
3173 return false;
3175 if (!integer_pow2p (op1))
3177 /* X % -Y can be only optimized into X % Y either if
3178 X is not INT_MIN, or Y is not -1. Fold it now, as after
3179 remove_range_assertions the range info might be not available
3180 anymore. */
3181 if (rhs_code == TRUNC_MOD_EXPR
3182 && fold_stmt (gsi, follow_single_use_edges))
3183 return true;
3184 return false;
3187 if (TYPE_UNSIGNED (TREE_TYPE (op0)))
3188 val = integer_one_node;
3189 else
3191 bool sop = false;
3193 val = compare_range_with_value (GE_EXPR, vr, integer_zero_node, &sop);
3195 if (val
3196 && sop
3197 && integer_onep (val)
3198 && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
3200 location_t location;
3202 if (!gimple_has_location (stmt))
3203 location = input_location;
3204 else
3205 location = gimple_location (stmt);
3206 warning_at (location, OPT_Wstrict_overflow,
3207 "assuming signed overflow does not occur when "
3208 "simplifying %</%> or %<%%%> to %<>>%> or %<&%>");
3212 if (val && integer_onep (val))
3214 tree t;
3216 if (rhs_code == TRUNC_DIV_EXPR)
3218 t = build_int_cst (integer_type_node, tree_log2 (op1));
3219 gimple_assign_set_rhs_code (stmt, RSHIFT_EXPR);
3220 gimple_assign_set_rhs1 (stmt, op0);
3221 gimple_assign_set_rhs2 (stmt, t);
3223 else
3225 t = build_int_cst (TREE_TYPE (op1), 1);
3226 t = int_const_binop (MINUS_EXPR, op1, t);
3227 t = fold_convert (TREE_TYPE (op0), t);
3229 gimple_assign_set_rhs_code (stmt, BIT_AND_EXPR);
3230 gimple_assign_set_rhs1 (stmt, op0);
3231 gimple_assign_set_rhs2 (stmt, t);
3234 update_stmt (stmt);
3235 fold_stmt (gsi, follow_single_use_edges);
3236 return true;
3239 return false;
3242 /* Simplify a min or max if the ranges of the two operands are
3243 disjoint. Return true if we do simplify. */
3245 bool
3246 vr_values::simplify_min_or_max_using_ranges (gimple_stmt_iterator *gsi,
3247 gimple *stmt)
3249 tree op0 = gimple_assign_rhs1 (stmt);
3250 tree op1 = gimple_assign_rhs2 (stmt);
3251 bool sop = false;
3252 tree val;
3254 val = (vrp_evaluate_conditional_warnv_with_ops_using_ranges
3255 (LE_EXPR, op0, op1, &sop));
3256 if (!val)
3258 sop = false;
3259 val = (vrp_evaluate_conditional_warnv_with_ops_using_ranges
3260 (LT_EXPR, op0, op1, &sop));
3263 if (val)
3265 if (sop && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
3267 location_t location;
3269 if (!gimple_has_location (stmt))
3270 location = input_location;
3271 else
3272 location = gimple_location (stmt);
3273 warning_at (location, OPT_Wstrict_overflow,
3274 "assuming signed overflow does not occur when "
3275 "simplifying %<min/max (X,Y)%> to %<X%> or %<Y%>");
3278 /* VAL == TRUE -> OP0 < or <= op1
3279 VAL == FALSE -> OP0 > or >= op1. */
3280 tree res = ((gimple_assign_rhs_code (stmt) == MAX_EXPR)
3281 == integer_zerop (val)) ? op0 : op1;
3282 gimple_assign_set_rhs_from_tree (gsi, res);
3283 return true;
3286 return false;
3289 /* If the operand to an ABS_EXPR is >= 0, then eliminate the
3290 ABS_EXPR. If the operand is <= 0, then simplify the
3291 ABS_EXPR into a NEGATE_EXPR. */
3293 bool
3294 vr_values::simplify_abs_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
3296 tree op = gimple_assign_rhs1 (stmt);
3297 const value_range *vr = get_value_range (op);
3299 if (vr)
3301 tree val = NULL;
3302 bool sop = false;
3304 val = compare_range_with_value (LE_EXPR, vr, integer_zero_node, &sop);
3305 if (!val)
3307 /* The range is neither <= 0 nor > 0. Now see if it is
3308 either < 0 or >= 0. */
3309 sop = false;
3310 val = compare_range_with_value (LT_EXPR, vr, integer_zero_node,
3311 &sop);
3314 if (val)
3316 if (sop && issue_strict_overflow_warning (WARN_STRICT_OVERFLOW_MISC))
3318 location_t location;
3320 if (!gimple_has_location (stmt))
3321 location = input_location;
3322 else
3323 location = gimple_location (stmt);
3324 warning_at (location, OPT_Wstrict_overflow,
3325 "assuming signed overflow does not occur when "
3326 "simplifying %<abs (X)%> to %<X%> or %<-X%>");
3329 gimple_assign_set_rhs1 (stmt, op);
3330 if (integer_zerop (val))
3331 gimple_assign_set_rhs_code (stmt, SSA_NAME);
3332 else
3333 gimple_assign_set_rhs_code (stmt, NEGATE_EXPR);
3334 update_stmt (stmt);
3335 fold_stmt (gsi, follow_single_use_edges);
3336 return true;
3340 return false;
3343 /* Optimize away redundant BIT_AND_EXPR and BIT_IOR_EXPR.
3344 If all the bits that are being cleared by & are already
3345 known to be zero from VR, or all the bits that are being
3346 set by | are already known to be one from VR, the bit
3347 operation is redundant. */
3349 bool
3350 vr_values::simplify_bit_ops_using_ranges (gimple_stmt_iterator *gsi,
3351 gimple *stmt)
3353 tree op0 = gimple_assign_rhs1 (stmt);
3354 tree op1 = gimple_assign_rhs2 (stmt);
3355 tree op = NULL_TREE;
3356 value_range_base vr0, vr1;
3357 wide_int may_be_nonzero0, may_be_nonzero1;
3358 wide_int must_be_nonzero0, must_be_nonzero1;
3359 wide_int mask;
3361 if (TREE_CODE (op0) == SSA_NAME)
3362 vr0 = *(get_value_range (op0));
3363 else if (is_gimple_min_invariant (op0))
3364 vr0.set (op0);
3365 else
3366 return false;
3368 if (TREE_CODE (op1) == SSA_NAME)
3369 vr1 = *(get_value_range (op1));
3370 else if (is_gimple_min_invariant (op1))
3371 vr1.set (op1);
3372 else
3373 return false;
3375 if (!vrp_set_zero_nonzero_bits (TREE_TYPE (op0), &vr0, &may_be_nonzero0,
3376 &must_be_nonzero0))
3377 return false;
3378 if (!vrp_set_zero_nonzero_bits (TREE_TYPE (op1), &vr1, &may_be_nonzero1,
3379 &must_be_nonzero1))
3380 return false;
3382 switch (gimple_assign_rhs_code (stmt))
3384 case BIT_AND_EXPR:
3385 mask = wi::bit_and_not (may_be_nonzero0, must_be_nonzero1);
3386 if (mask == 0)
3388 op = op0;
3389 break;
3391 mask = wi::bit_and_not (may_be_nonzero1, must_be_nonzero0);
3392 if (mask == 0)
3394 op = op1;
3395 break;
3397 break;
3398 case BIT_IOR_EXPR:
3399 mask = wi::bit_and_not (may_be_nonzero0, must_be_nonzero1);
3400 if (mask == 0)
3402 op = op1;
3403 break;
3405 mask = wi::bit_and_not (may_be_nonzero1, must_be_nonzero0);
3406 if (mask == 0)
3408 op = op0;
3409 break;
3411 break;
3412 default:
3413 gcc_unreachable ();
3416 if (op == NULL_TREE)
3417 return false;
3419 gimple_assign_set_rhs_with_ops (gsi, TREE_CODE (op), op);
3420 update_stmt (gsi_stmt (*gsi));
3421 return true;
3424 /* We are comparing trees OP0 and OP1 using COND_CODE. OP0 has
3425 a known value range VR.
3427 If there is one and only one value which will satisfy the
3428 conditional, then return that value. Else return NULL.
3430 If signed overflow must be undefined for the value to satisfy
3431 the conditional, then set *STRICT_OVERFLOW_P to true. */
3433 static tree
3434 test_for_singularity (enum tree_code cond_code, tree op0,
3435 tree op1, const value_range *vr)
3437 tree min = NULL;
3438 tree max = NULL;
3440 /* Extract minimum/maximum values which satisfy the conditional as it was
3441 written. */
3442 if (cond_code == LE_EXPR || cond_code == LT_EXPR)
3444 min = TYPE_MIN_VALUE (TREE_TYPE (op0));
3446 max = op1;
3447 if (cond_code == LT_EXPR)
3449 tree one = build_int_cst (TREE_TYPE (op0), 1);
3450 max = fold_build2 (MINUS_EXPR, TREE_TYPE (op0), max, one);
3451 /* Signal to compare_values_warnv this expr doesn't overflow. */
3452 if (EXPR_P (max))
3453 TREE_NO_WARNING (max) = 1;
3456 else if (cond_code == GE_EXPR || cond_code == GT_EXPR)
3458 max = TYPE_MAX_VALUE (TREE_TYPE (op0));
3460 min = op1;
3461 if (cond_code == GT_EXPR)
3463 tree one = build_int_cst (TREE_TYPE (op0), 1);
3464 min = fold_build2 (PLUS_EXPR, TREE_TYPE (op0), min, one);
3465 /* Signal to compare_values_warnv this expr doesn't overflow. */
3466 if (EXPR_P (min))
3467 TREE_NO_WARNING (min) = 1;
3471 /* Now refine the minimum and maximum values using any
3472 value range information we have for op0. */
3473 if (min && max)
3475 if (compare_values (vr->min (), min) == 1)
3476 min = vr->min ();
3477 if (compare_values (vr->max (), max) == -1)
3478 max = vr->max ();
3480 /* If the new min/max values have converged to a single value,
3481 then there is only one value which can satisfy the condition,
3482 return that value. */
3483 if (operand_equal_p (min, max, 0) && is_gimple_min_invariant (min))
3484 return min;
3486 return NULL;
3489 /* Return whether the value range *VR fits in an integer type specified
3490 by PRECISION and UNSIGNED_P. */
3492 static bool
3493 range_fits_type_p (const value_range *vr,
3494 unsigned dest_precision, signop dest_sgn)
3496 tree src_type;
3497 unsigned src_precision;
3498 widest_int tem;
3499 signop src_sgn;
3501 /* We can only handle integral and pointer types. */
3502 src_type = vr->type ();
3503 if (!INTEGRAL_TYPE_P (src_type)
3504 && !POINTER_TYPE_P (src_type))
3505 return false;
3507 /* An extension is fine unless VR is SIGNED and dest_sgn is UNSIGNED,
3508 and so is an identity transform. */
3509 src_precision = TYPE_PRECISION (vr->type ());
3510 src_sgn = TYPE_SIGN (src_type);
3511 if ((src_precision < dest_precision
3512 && !(dest_sgn == UNSIGNED && src_sgn == SIGNED))
3513 || (src_precision == dest_precision && src_sgn == dest_sgn))
3514 return true;
3516 /* Now we can only handle ranges with constant bounds. */
3517 if (!range_int_cst_p (vr))
3518 return false;
3520 /* For sign changes, the MSB of the wide_int has to be clear.
3521 An unsigned value with its MSB set cannot be represented by
3522 a signed wide_int, while a negative value cannot be represented
3523 by an unsigned wide_int. */
3524 if (src_sgn != dest_sgn
3525 && (wi::lts_p (wi::to_wide (vr->min ()), 0)
3526 || wi::lts_p (wi::to_wide (vr->max ()), 0)))
3527 return false;
3529 /* Then we can perform the conversion on both ends and compare
3530 the result for equality. */
3531 tem = wi::ext (wi::to_widest (vr->min ()), dest_precision, dest_sgn);
3532 if (tem != wi::to_widest (vr->min ()))
3533 return false;
3534 tem = wi::ext (wi::to_widest (vr->max ()), dest_precision, dest_sgn);
3535 if (tem != wi::to_widest (vr->max ()))
3536 return false;
3538 return true;
3541 /* Simplify a conditional using a relational operator to an equality
3542 test if the range information indicates only one value can satisfy
3543 the original conditional. */
3545 bool
3546 vr_values::simplify_cond_using_ranges_1 (gcond *stmt)
3548 tree op0 = gimple_cond_lhs (stmt);
3549 tree op1 = gimple_cond_rhs (stmt);
3550 enum tree_code cond_code = gimple_cond_code (stmt);
3552 if (cond_code != NE_EXPR
3553 && cond_code != EQ_EXPR
3554 && TREE_CODE (op0) == SSA_NAME
3555 && INTEGRAL_TYPE_P (TREE_TYPE (op0))
3556 && is_gimple_min_invariant (op1))
3558 const value_range *vr = get_value_range (op0);
3560 /* If we have range information for OP0, then we might be
3561 able to simplify this conditional. */
3562 if (vr->kind () == VR_RANGE)
3564 tree new_tree = test_for_singularity (cond_code, op0, op1, vr);
3565 if (new_tree)
3567 if (dump_file)
3569 fprintf (dump_file, "Simplified relational ");
3570 print_gimple_stmt (dump_file, stmt, 0);
3571 fprintf (dump_file, " into ");
3574 gimple_cond_set_code (stmt, EQ_EXPR);
3575 gimple_cond_set_lhs (stmt, op0);
3576 gimple_cond_set_rhs (stmt, new_tree);
3578 update_stmt (stmt);
3580 if (dump_file)
3582 print_gimple_stmt (dump_file, stmt, 0);
3583 fprintf (dump_file, "\n");
3586 return true;
3589 /* Try again after inverting the condition. We only deal
3590 with integral types here, so no need to worry about
3591 issues with inverting FP comparisons. */
3592 new_tree = test_for_singularity
3593 (invert_tree_comparison (cond_code, false),
3594 op0, op1, vr);
3595 if (new_tree)
3597 if (dump_file)
3599 fprintf (dump_file, "Simplified relational ");
3600 print_gimple_stmt (dump_file, stmt, 0);
3601 fprintf (dump_file, " into ");
3604 gimple_cond_set_code (stmt, NE_EXPR);
3605 gimple_cond_set_lhs (stmt, op0);
3606 gimple_cond_set_rhs (stmt, new_tree);
3608 update_stmt (stmt);
3610 if (dump_file)
3612 print_gimple_stmt (dump_file, stmt, 0);
3613 fprintf (dump_file, "\n");
3616 return true;
3620 return false;
3623 /* STMT is a conditional at the end of a basic block.
3625 If the conditional is of the form SSA_NAME op constant and the SSA_NAME
3626 was set via a type conversion, try to replace the SSA_NAME with the RHS
3627 of the type conversion. Doing so makes the conversion dead which helps
3628 subsequent passes. */
3630 void
3631 vr_values::simplify_cond_using_ranges_2 (gcond *stmt)
3633 tree op0 = gimple_cond_lhs (stmt);
3634 tree op1 = gimple_cond_rhs (stmt);
3636 /* If we have a comparison of an SSA_NAME (OP0) against a constant,
3637 see if OP0 was set by a type conversion where the source of
3638 the conversion is another SSA_NAME with a range that fits
3639 into the range of OP0's type.
3641 If so, the conversion is redundant as the earlier SSA_NAME can be
3642 used for the comparison directly if we just massage the constant in the
3643 comparison. */
3644 if (TREE_CODE (op0) == SSA_NAME
3645 && TREE_CODE (op1) == INTEGER_CST)
3647 gimple *def_stmt = SSA_NAME_DEF_STMT (op0);
3648 tree innerop;
3650 if (!is_gimple_assign (def_stmt)
3651 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)))
3652 return;
3654 innerop = gimple_assign_rhs1 (def_stmt);
3656 if (TREE_CODE (innerop) == SSA_NAME
3657 && !POINTER_TYPE_P (TREE_TYPE (innerop))
3658 && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (innerop)
3659 && desired_pro_or_demotion_p (TREE_TYPE (innerop), TREE_TYPE (op0)))
3661 const value_range *vr = get_value_range (innerop);
3663 if (range_int_cst_p (vr)
3664 && range_fits_type_p (vr,
3665 TYPE_PRECISION (TREE_TYPE (op0)),
3666 TYPE_SIGN (TREE_TYPE (op0)))
3667 && int_fits_type_p (op1, TREE_TYPE (innerop)))
3669 tree newconst = fold_convert (TREE_TYPE (innerop), op1);
3670 gimple_cond_set_lhs (stmt, innerop);
3671 gimple_cond_set_rhs (stmt, newconst);
3672 update_stmt (stmt);
3673 if (dump_file && (dump_flags & TDF_DETAILS))
3675 fprintf (dump_file, "Folded into: ");
3676 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
3677 fprintf (dump_file, "\n");
3684 /* Simplify a switch statement using the value range of the switch
3685 argument. */
3687 bool
3688 vr_values::simplify_switch_using_ranges (gswitch *stmt)
3690 tree op = gimple_switch_index (stmt);
3691 const value_range *vr = NULL;
3692 bool take_default;
3693 edge e;
3694 edge_iterator ei;
3695 size_t i = 0, j = 0, n, n2;
3696 tree vec2;
3697 switch_update su;
3698 size_t k = 1, l = 0;
3700 if (TREE_CODE (op) == SSA_NAME)
3702 vr = get_value_range (op);
3704 /* We can only handle integer ranges. */
3705 if (vr->varying_p ()
3706 || vr->undefined_p ()
3707 || vr->symbolic_p ())
3708 return false;
3710 /* Find case label for min/max of the value range. */
3711 take_default = !find_case_label_ranges (stmt, vr, &i, &j, &k, &l);
3713 else if (TREE_CODE (op) == INTEGER_CST)
3715 take_default = !find_case_label_index (stmt, 1, op, &i);
3716 if (take_default)
3718 i = 1;
3719 j = 0;
3721 else
3723 j = i;
3726 else
3727 return false;
3729 n = gimple_switch_num_labels (stmt);
3731 /* We can truncate the case label ranges that partially overlap with OP's
3732 value range. */
3733 size_t min_idx = 1, max_idx = 0;
3734 if (vr != NULL)
3735 find_case_label_range (stmt, vr->min (), vr->max (), &min_idx, &max_idx);
3736 if (min_idx <= max_idx)
3738 tree min_label = gimple_switch_label (stmt, min_idx);
3739 tree max_label = gimple_switch_label (stmt, max_idx);
3741 /* Avoid changing the type of the case labels when truncating. */
3742 tree case_label_type = TREE_TYPE (CASE_LOW (min_label));
3743 tree vr_min = fold_convert (case_label_type, vr->min ());
3744 tree vr_max = fold_convert (case_label_type, vr->max ());
3746 if (vr->kind () == VR_RANGE)
3748 /* If OP's value range is [2,8] and the low label range is
3749 0 ... 3, truncate the label's range to 2 .. 3. */
3750 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
3751 && CASE_HIGH (min_label) != NULL_TREE
3752 && tree_int_cst_compare (CASE_HIGH (min_label), vr_min) >= 0)
3753 CASE_LOW (min_label) = vr_min;
3755 /* If OP's value range is [2,8] and the high label range is
3756 7 ... 10, truncate the label's range to 7 .. 8. */
3757 if (tree_int_cst_compare (CASE_LOW (max_label), vr_max) <= 0
3758 && CASE_HIGH (max_label) != NULL_TREE
3759 && tree_int_cst_compare (CASE_HIGH (max_label), vr_max) > 0)
3760 CASE_HIGH (max_label) = vr_max;
3762 else if (vr->kind () == VR_ANTI_RANGE)
3764 tree one_cst = build_one_cst (case_label_type);
3766 if (min_label == max_label)
3768 /* If OP's value range is ~[7,8] and the label's range is
3769 7 ... 10, truncate the label's range to 9 ... 10. */
3770 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) == 0
3771 && CASE_HIGH (min_label) != NULL_TREE
3772 && tree_int_cst_compare (CASE_HIGH (min_label), vr_max) > 0)
3773 CASE_LOW (min_label)
3774 = int_const_binop (PLUS_EXPR, vr_max, one_cst);
3776 /* If OP's value range is ~[7,8] and the label's range is
3777 5 ... 8, truncate the label's range to 5 ... 6. */
3778 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
3779 && CASE_HIGH (min_label) != NULL_TREE
3780 && tree_int_cst_compare (CASE_HIGH (min_label), vr_max) == 0)
3781 CASE_HIGH (min_label)
3782 = int_const_binop (MINUS_EXPR, vr_min, one_cst);
3784 else
3786 /* If OP's value range is ~[2,8] and the low label range is
3787 0 ... 3, truncate the label's range to 0 ... 1. */
3788 if (tree_int_cst_compare (CASE_LOW (min_label), vr_min) < 0
3789 && CASE_HIGH (min_label) != NULL_TREE
3790 && tree_int_cst_compare (CASE_HIGH (min_label), vr_min) >= 0)
3791 CASE_HIGH (min_label)
3792 = int_const_binop (MINUS_EXPR, vr_min, one_cst);
3794 /* If OP's value range is ~[2,8] and the high label range is
3795 7 ... 10, truncate the label's range to 9 ... 10. */
3796 if (tree_int_cst_compare (CASE_LOW (max_label), vr_max) <= 0
3797 && CASE_HIGH (max_label) != NULL_TREE
3798 && tree_int_cst_compare (CASE_HIGH (max_label), vr_max) > 0)
3799 CASE_LOW (max_label)
3800 = int_const_binop (PLUS_EXPR, vr_max, one_cst);
3804 /* Canonicalize singleton case ranges. */
3805 if (tree_int_cst_equal (CASE_LOW (min_label), CASE_HIGH (min_label)))
3806 CASE_HIGH (min_label) = NULL_TREE;
3807 if (tree_int_cst_equal (CASE_LOW (max_label), CASE_HIGH (max_label)))
3808 CASE_HIGH (max_label) = NULL_TREE;
3811 /* We can also eliminate case labels that lie completely outside OP's value
3812 range. */
3814 /* Bail out if this is just all edges taken. */
3815 if (i == 1
3816 && j == n - 1
3817 && take_default)
3818 return false;
3820 /* Build a new vector of taken case labels. */
3821 vec2 = make_tree_vec (j - i + 1 + l - k + 1 + (int)take_default);
3822 n2 = 0;
3824 /* Add the default edge, if necessary. */
3825 if (take_default)
3826 TREE_VEC_ELT (vec2, n2++) = gimple_switch_default_label (stmt);
3828 for (; i <= j; ++i, ++n2)
3829 TREE_VEC_ELT (vec2, n2) = gimple_switch_label (stmt, i);
3831 for (; k <= l; ++k, ++n2)
3832 TREE_VEC_ELT (vec2, n2) = gimple_switch_label (stmt, k);
3834 /* Mark needed edges. */
3835 for (i = 0; i < n2; ++i)
3837 e = find_edge (gimple_bb (stmt),
3838 label_to_block (cfun,
3839 CASE_LABEL (TREE_VEC_ELT (vec2, i))));
3840 e->aux = (void *)-1;
3843 /* Queue not needed edges for later removal. */
3844 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
3846 if (e->aux == (void *)-1)
3848 e->aux = NULL;
3849 continue;
3852 if (dump_file && (dump_flags & TDF_DETAILS))
3854 fprintf (dump_file, "removing unreachable case label\n");
3856 to_remove_edges.safe_push (e);
3857 e->flags &= ~EDGE_EXECUTABLE;
3858 e->flags |= EDGE_IGNORE;
3861 /* And queue an update for the stmt. */
3862 su.stmt = stmt;
3863 su.vec = vec2;
3864 to_update_switch_stmts.safe_push (su);
3865 return false;
3868 void
3869 vr_values::cleanup_edges_and_switches (void)
3871 int i;
3872 edge e;
3873 switch_update *su;
3875 /* Remove dead edges from SWITCH_EXPR optimization. This leaves the
3876 CFG in a broken state and requires a cfg_cleanup run. */
3877 FOR_EACH_VEC_ELT (to_remove_edges, i, e)
3878 remove_edge (e);
3880 /* Update SWITCH_EXPR case label vector. */
3881 FOR_EACH_VEC_ELT (to_update_switch_stmts, i, su)
3883 size_t j;
3884 size_t n = TREE_VEC_LENGTH (su->vec);
3885 tree label;
3886 gimple_switch_set_num_labels (su->stmt, n);
3887 for (j = 0; j < n; j++)
3888 gimple_switch_set_label (su->stmt, j, TREE_VEC_ELT (su->vec, j));
3889 /* As we may have replaced the default label with a regular one
3890 make sure to make it a real default label again. This ensures
3891 optimal expansion. */
3892 label = gimple_switch_label (su->stmt, 0);
3893 CASE_LOW (label) = NULL_TREE;
3894 CASE_HIGH (label) = NULL_TREE;
3897 if (!to_remove_edges.is_empty ())
3899 free_dominance_info (CDI_DOMINATORS);
3900 loops_state_set (LOOPS_NEED_FIXUP);
3903 to_remove_edges.release ();
3904 to_update_switch_stmts.release ();
3907 /* Simplify an integral conversion from an SSA name in STMT. */
3909 static bool
3910 simplify_conversion_using_ranges (gimple_stmt_iterator *gsi, gimple *stmt)
3912 tree innerop, middleop, finaltype;
3913 gimple *def_stmt;
3914 signop inner_sgn, middle_sgn, final_sgn;
3915 unsigned inner_prec, middle_prec, final_prec;
3916 widest_int innermin, innermed, innermax, middlemin, middlemed, middlemax;
3918 finaltype = TREE_TYPE (gimple_assign_lhs (stmt));
3919 if (!INTEGRAL_TYPE_P (finaltype))
3920 return false;
3921 middleop = gimple_assign_rhs1 (stmt);
3922 def_stmt = SSA_NAME_DEF_STMT (middleop);
3923 if (!is_gimple_assign (def_stmt)
3924 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)))
3925 return false;
3926 innerop = gimple_assign_rhs1 (def_stmt);
3927 if (TREE_CODE (innerop) != SSA_NAME
3928 || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (innerop))
3929 return false;
3931 /* Get the value-range of the inner operand. Use get_range_info in
3932 case innerop was created during substitute-and-fold. */
3933 wide_int imin, imax;
3934 if (!INTEGRAL_TYPE_P (TREE_TYPE (innerop))
3935 || get_range_info (innerop, &imin, &imax) != VR_RANGE)
3936 return false;
3937 innermin = widest_int::from (imin, TYPE_SIGN (TREE_TYPE (innerop)));
3938 innermax = widest_int::from (imax, TYPE_SIGN (TREE_TYPE (innerop)));
3940 /* Simulate the conversion chain to check if the result is equal if
3941 the middle conversion is removed. */
3942 inner_prec = TYPE_PRECISION (TREE_TYPE (innerop));
3943 middle_prec = TYPE_PRECISION (TREE_TYPE (middleop));
3944 final_prec = TYPE_PRECISION (finaltype);
3946 /* If the first conversion is not injective, the second must not
3947 be widening. */
3948 if (wi::gtu_p (innermax - innermin,
3949 wi::mask <widest_int> (middle_prec, false))
3950 && middle_prec < final_prec)
3951 return false;
3952 /* We also want a medium value so that we can track the effect that
3953 narrowing conversions with sign change have. */
3954 inner_sgn = TYPE_SIGN (TREE_TYPE (innerop));
3955 if (inner_sgn == UNSIGNED)
3956 innermed = wi::shifted_mask <widest_int> (1, inner_prec - 1, false);
3957 else
3958 innermed = 0;
3959 if (wi::cmp (innermin, innermed, inner_sgn) >= 0
3960 || wi::cmp (innermed, innermax, inner_sgn) >= 0)
3961 innermed = innermin;
3963 middle_sgn = TYPE_SIGN (TREE_TYPE (middleop));
3964 middlemin = wi::ext (innermin, middle_prec, middle_sgn);
3965 middlemed = wi::ext (innermed, middle_prec, middle_sgn);
3966 middlemax = wi::ext (innermax, middle_prec, middle_sgn);
3968 /* Require that the final conversion applied to both the original
3969 and the intermediate range produces the same result. */
3970 final_sgn = TYPE_SIGN (finaltype);
3971 if (wi::ext (middlemin, final_prec, final_sgn)
3972 != wi::ext (innermin, final_prec, final_sgn)
3973 || wi::ext (middlemed, final_prec, final_sgn)
3974 != wi::ext (innermed, final_prec, final_sgn)
3975 || wi::ext (middlemax, final_prec, final_sgn)
3976 != wi::ext (innermax, final_prec, final_sgn))
3977 return false;
3979 gimple_assign_set_rhs1 (stmt, innerop);
3980 fold_stmt (gsi, follow_single_use_edges);
3981 return true;
3984 /* Simplify a conversion from integral SSA name to float in STMT. */
3986 bool
3987 vr_values::simplify_float_conversion_using_ranges (gimple_stmt_iterator *gsi,
3988 gimple *stmt)
3990 tree rhs1 = gimple_assign_rhs1 (stmt);
3991 const value_range *vr = get_value_range (rhs1);
3992 scalar_float_mode fltmode
3993 = SCALAR_FLOAT_TYPE_MODE (TREE_TYPE (gimple_assign_lhs (stmt)));
3994 scalar_int_mode mode;
3995 tree tem;
3996 gassign *conv;
3998 /* We can only handle constant ranges. */
3999 if (!range_int_cst_p (vr))
4000 return false;
4002 /* First check if we can use a signed type in place of an unsigned. */
4003 scalar_int_mode rhs_mode = SCALAR_INT_TYPE_MODE (TREE_TYPE (rhs1));
4004 if (TYPE_UNSIGNED (TREE_TYPE (rhs1))
4005 && can_float_p (fltmode, rhs_mode, 0) != CODE_FOR_nothing
4006 && range_fits_type_p (vr, TYPE_PRECISION (TREE_TYPE (rhs1)), SIGNED))
4007 mode = rhs_mode;
4008 /* If we can do the conversion in the current input mode do nothing. */
4009 else if (can_float_p (fltmode, rhs_mode,
4010 TYPE_UNSIGNED (TREE_TYPE (rhs1))) != CODE_FOR_nothing)
4011 return false;
4012 /* Otherwise search for a mode we can use, starting from the narrowest
4013 integer mode available. */
4014 else
4016 mode = NARROWEST_INT_MODE;
4017 for (;;)
4019 /* If we cannot do a signed conversion to float from mode
4020 or if the value-range does not fit in the signed type
4021 try with a wider mode. */
4022 if (can_float_p (fltmode, mode, 0) != CODE_FOR_nothing
4023 && range_fits_type_p (vr, GET_MODE_PRECISION (mode), SIGNED))
4024 break;
4026 /* But do not widen the input. Instead leave that to the
4027 optabs expansion code. */
4028 if (!GET_MODE_WIDER_MODE (mode).exists (&mode)
4029 || GET_MODE_PRECISION (mode) > TYPE_PRECISION (TREE_TYPE (rhs1)))
4030 return false;
4034 /* It works, insert a truncation or sign-change before the
4035 float conversion. */
4036 tem = make_ssa_name (build_nonstandard_integer_type
4037 (GET_MODE_PRECISION (mode), 0));
4038 conv = gimple_build_assign (tem, NOP_EXPR, rhs1);
4039 gsi_insert_before (gsi, conv, GSI_SAME_STMT);
4040 gimple_assign_set_rhs1 (stmt, tem);
4041 fold_stmt (gsi, follow_single_use_edges);
4043 return true;
4046 /* Simplify an internal fn call using ranges if possible. */
4048 bool
4049 vr_values::simplify_internal_call_using_ranges (gimple_stmt_iterator *gsi,
4050 gimple *stmt)
4052 enum tree_code subcode;
4053 bool is_ubsan = false;
4054 bool ovf = false;
4055 switch (gimple_call_internal_fn (stmt))
4057 case IFN_UBSAN_CHECK_ADD:
4058 subcode = PLUS_EXPR;
4059 is_ubsan = true;
4060 break;
4061 case IFN_UBSAN_CHECK_SUB:
4062 subcode = MINUS_EXPR;
4063 is_ubsan = true;
4064 break;
4065 case IFN_UBSAN_CHECK_MUL:
4066 subcode = MULT_EXPR;
4067 is_ubsan = true;
4068 break;
4069 case IFN_ADD_OVERFLOW:
4070 subcode = PLUS_EXPR;
4071 break;
4072 case IFN_SUB_OVERFLOW:
4073 subcode = MINUS_EXPR;
4074 break;
4075 case IFN_MUL_OVERFLOW:
4076 subcode = MULT_EXPR;
4077 break;
4078 default:
4079 return false;
4082 tree op0 = gimple_call_arg (stmt, 0);
4083 tree op1 = gimple_call_arg (stmt, 1);
4084 tree type;
4085 if (is_ubsan)
4087 type = TREE_TYPE (op0);
4088 if (VECTOR_TYPE_P (type))
4089 return false;
4091 else if (gimple_call_lhs (stmt) == NULL_TREE)
4092 return false;
4093 else
4094 type = TREE_TYPE (TREE_TYPE (gimple_call_lhs (stmt)));
4095 if (!check_for_binary_op_overflow (subcode, type, op0, op1, &ovf)
4096 || (is_ubsan && ovf))
4097 return false;
4099 gimple *g;
4100 location_t loc = gimple_location (stmt);
4101 if (is_ubsan)
4102 g = gimple_build_assign (gimple_call_lhs (stmt), subcode, op0, op1);
4103 else
4105 int prec = TYPE_PRECISION (type);
4106 tree utype = type;
4107 if (ovf
4108 || !useless_type_conversion_p (type, TREE_TYPE (op0))
4109 || !useless_type_conversion_p (type, TREE_TYPE (op1)))
4110 utype = build_nonstandard_integer_type (prec, 1);
4111 if (TREE_CODE (op0) == INTEGER_CST)
4112 op0 = fold_convert (utype, op0);
4113 else if (!useless_type_conversion_p (utype, TREE_TYPE (op0)))
4115 g = gimple_build_assign (make_ssa_name (utype), NOP_EXPR, op0);
4116 gimple_set_location (g, loc);
4117 gsi_insert_before (gsi, g, GSI_SAME_STMT);
4118 op0 = gimple_assign_lhs (g);
4120 if (TREE_CODE (op1) == INTEGER_CST)
4121 op1 = fold_convert (utype, op1);
4122 else if (!useless_type_conversion_p (utype, TREE_TYPE (op1)))
4124 g = gimple_build_assign (make_ssa_name (utype), NOP_EXPR, op1);
4125 gimple_set_location (g, loc);
4126 gsi_insert_before (gsi, g, GSI_SAME_STMT);
4127 op1 = gimple_assign_lhs (g);
4129 g = gimple_build_assign (make_ssa_name (utype), subcode, op0, op1);
4130 gimple_set_location (g, loc);
4131 gsi_insert_before (gsi, g, GSI_SAME_STMT);
4132 if (utype != type)
4134 g = gimple_build_assign (make_ssa_name (type), NOP_EXPR,
4135 gimple_assign_lhs (g));
4136 gimple_set_location (g, loc);
4137 gsi_insert_before (gsi, g, GSI_SAME_STMT);
4139 g = gimple_build_assign (gimple_call_lhs (stmt), COMPLEX_EXPR,
4140 gimple_assign_lhs (g),
4141 build_int_cst (type, ovf));
4143 gimple_set_location (g, loc);
4144 gsi_replace (gsi, g, false);
4145 return true;
4148 /* Return true if VAR is a two-valued variable. Set a and b with the
4149 two-values when it is true. Return false otherwise. */
4151 bool
4152 vr_values::two_valued_val_range_p (tree var, tree *a, tree *b)
4154 const value_range *vr = get_value_range (var);
4155 if (vr->varying_p ()
4156 || vr->undefined_p ()
4157 || TREE_CODE (vr->min ()) != INTEGER_CST
4158 || TREE_CODE (vr->max ()) != INTEGER_CST)
4159 return false;
4161 if (vr->kind () == VR_RANGE
4162 && wi::to_wide (vr->max ()) - wi::to_wide (vr->min ()) == 1)
4164 *a = vr->min ();
4165 *b = vr->max ();
4166 return true;
4169 /* ~[TYPE_MIN + 1, TYPE_MAX - 1] */
4170 if (vr->kind () == VR_ANTI_RANGE
4171 && (wi::to_wide (vr->min ())
4172 - wi::to_wide (vrp_val_min (TREE_TYPE (var)))) == 1
4173 && (wi::to_wide (vrp_val_max (TREE_TYPE (var)))
4174 - wi::to_wide (vr->max ())) == 1)
4176 *a = vrp_val_min (TREE_TYPE (var));
4177 *b = vrp_val_max (TREE_TYPE (var));
4178 return true;
4181 return false;
4184 /* Simplify STMT using ranges if possible. */
4186 bool
4187 vr_values::simplify_stmt_using_ranges (gimple_stmt_iterator *gsi)
4189 gimple *stmt = gsi_stmt (*gsi);
4190 if (is_gimple_assign (stmt))
4192 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
4193 tree rhs1 = gimple_assign_rhs1 (stmt);
4194 tree rhs2 = gimple_assign_rhs2 (stmt);
4195 tree lhs = gimple_assign_lhs (stmt);
4196 tree val1 = NULL_TREE, val2 = NULL_TREE;
4197 use_operand_p use_p;
4198 gimple *use_stmt;
4200 /* Convert:
4201 LHS = CST BINOP VAR
4202 Where VAR is two-valued and LHS is used in GIMPLE_COND only
4204 LHS = VAR == VAL1 ? (CST BINOP VAL1) : (CST BINOP VAL2)
4206 Also handles:
4207 LHS = VAR BINOP CST
4208 Where VAR is two-valued and LHS is used in GIMPLE_COND only
4210 LHS = VAR == VAL1 ? (VAL1 BINOP CST) : (VAL2 BINOP CST) */
4212 if (TREE_CODE_CLASS (rhs_code) == tcc_binary
4213 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1))
4214 && ((TREE_CODE (rhs1) == INTEGER_CST
4215 && TREE_CODE (rhs2) == SSA_NAME)
4216 || (TREE_CODE (rhs2) == INTEGER_CST
4217 && TREE_CODE (rhs1) == SSA_NAME))
4218 && single_imm_use (lhs, &use_p, &use_stmt)
4219 && gimple_code (use_stmt) == GIMPLE_COND)
4222 tree new_rhs1 = NULL_TREE;
4223 tree new_rhs2 = NULL_TREE;
4224 tree cmp_var = NULL_TREE;
4226 if (TREE_CODE (rhs2) == SSA_NAME
4227 && two_valued_val_range_p (rhs2, &val1, &val2))
4229 /* Optimize RHS1 OP [VAL1, VAL2]. */
4230 new_rhs1 = int_const_binop (rhs_code, rhs1, val1);
4231 new_rhs2 = int_const_binop (rhs_code, rhs1, val2);
4232 cmp_var = rhs2;
4234 else if (TREE_CODE (rhs1) == SSA_NAME
4235 && two_valued_val_range_p (rhs1, &val1, &val2))
4237 /* Optimize [VAL1, VAL2] OP RHS2. */
4238 new_rhs1 = int_const_binop (rhs_code, val1, rhs2);
4239 new_rhs2 = int_const_binop (rhs_code, val2, rhs2);
4240 cmp_var = rhs1;
4243 /* If we could not find two-vals or the optimzation is invalid as
4244 in divide by zero, new_rhs1 / new_rhs will be NULL_TREE. */
4245 if (new_rhs1 && new_rhs2)
4247 tree cond = build2 (EQ_EXPR, boolean_type_node, cmp_var, val1);
4248 gimple_assign_set_rhs_with_ops (gsi,
4249 COND_EXPR, cond,
4250 new_rhs1,
4251 new_rhs2);
4252 update_stmt (gsi_stmt (*gsi));
4253 fold_stmt (gsi, follow_single_use_edges);
4254 return true;
4258 switch (rhs_code)
4260 case EQ_EXPR:
4261 case NE_EXPR:
4262 /* Transform EQ_EXPR, NE_EXPR into BIT_XOR_EXPR or identity
4263 if the RHS is zero or one, and the LHS are known to be boolean
4264 values. */
4265 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
4266 return simplify_truth_ops_using_ranges (gsi, stmt);
4267 break;
4269 /* Transform TRUNC_DIV_EXPR and TRUNC_MOD_EXPR into RSHIFT_EXPR
4270 and BIT_AND_EXPR respectively if the first operand is greater
4271 than zero and the second operand is an exact power of two.
4272 Also optimize TRUNC_MOD_EXPR away if the second operand is
4273 constant and the first operand already has the right value
4274 range. */
4275 case TRUNC_DIV_EXPR:
4276 case TRUNC_MOD_EXPR:
4277 if ((TREE_CODE (rhs1) == SSA_NAME
4278 || TREE_CODE (rhs1) == INTEGER_CST)
4279 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
4280 return simplify_div_or_mod_using_ranges (gsi, stmt);
4281 break;
4283 /* Transform ABS (X) into X or -X as appropriate. */
4284 case ABS_EXPR:
4285 if (TREE_CODE (rhs1) == SSA_NAME
4286 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
4287 return simplify_abs_using_ranges (gsi, stmt);
4288 break;
4290 case BIT_AND_EXPR:
4291 case BIT_IOR_EXPR:
4292 /* Optimize away BIT_AND_EXPR and BIT_IOR_EXPR
4293 if all the bits being cleared are already cleared or
4294 all the bits being set are already set. */
4295 if (INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
4296 return simplify_bit_ops_using_ranges (gsi, stmt);
4297 break;
4299 CASE_CONVERT:
4300 if (TREE_CODE (rhs1) == SSA_NAME
4301 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
4302 return simplify_conversion_using_ranges (gsi, stmt);
4303 break;
4305 case FLOAT_EXPR:
4306 if (TREE_CODE (rhs1) == SSA_NAME
4307 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
4308 return simplify_float_conversion_using_ranges (gsi, stmt);
4309 break;
4311 case MIN_EXPR:
4312 case MAX_EXPR:
4313 return simplify_min_or_max_using_ranges (gsi, stmt);
4315 default:
4316 break;
4319 else if (gimple_code (stmt) == GIMPLE_COND)
4320 return simplify_cond_using_ranges_1 (as_a <gcond *> (stmt));
4321 else if (gimple_code (stmt) == GIMPLE_SWITCH)
4322 return simplify_switch_using_ranges (as_a <gswitch *> (stmt));
4323 else if (is_gimple_call (stmt)
4324 && gimple_call_internal_p (stmt))
4325 return simplify_internal_call_using_ranges (gsi, stmt);
4327 return false;
4330 /* Set the lattice entry for VAR to VR. */
4332 void
4333 vr_values::set_vr_value (tree var, value_range *vr)
4335 if (SSA_NAME_VERSION (var) >= num_vr_values)
4336 return;
4337 vr_value[SSA_NAME_VERSION (var)] = vr;
4340 /* Swap the lattice entry for VAR with VR and return the old entry. */
4342 value_range *
4343 vr_values::swap_vr_value (tree var, value_range *vr)
4345 if (SSA_NAME_VERSION (var) >= num_vr_values)
4346 return NULL;
4347 std::swap (vr_value[SSA_NAME_VERSION (var)], vr);
4348 return vr;