1 /* Scalar evolution detector.
2 Copyright (C) 2003-2019 Free Software Foundation, Inc.
3 Contributed by Sebastian Pop <s.pop@laposte.net>
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
24 This pass analyzes the evolution of scalar variables in loop
25 structures. The algorithm is based on the SSA representation,
26 and on the loop hierarchy tree. This algorithm is not based on
27 the notion of versions of a variable, as it was the case for the
28 previous implementations of the scalar evolution algorithm, but
29 it assumes that each defined name is unique.
31 The notation used in this file is called "chains of recurrences",
32 and has been proposed by Eugene Zima, Robert Van Engelen, and
33 others for describing induction variables in programs. For example
34 "b -> {0, +, 2}_1" means that the scalar variable "b" is equal to 0
35 when entering in the loop_1 and has a step 2 in this loop, in other
36 words "for (b = 0; b < N; b+=2);". Note that the coefficients of
37 this chain of recurrence (or chrec [shrek]) can contain the name of
38 other variables, in which case they are called parametric chrecs.
39 For example, "b -> {a, +, 2}_1" means that the initial value of "b"
40 is the value of "a". In most of the cases these parametric chrecs
41 are fully instantiated before their use because symbolic names can
42 hide some difficult cases such as self-references described later
43 (see the Fibonacci example).
45 A short sketch of the algorithm is:
47 Given a scalar variable to be analyzed, follow the SSA edge to
50 - When the definition is a GIMPLE_ASSIGN: if the right hand side
51 (RHS) of the definition cannot be statically analyzed, the answer
52 of the analyzer is: "don't know".
53 Otherwise, for all the variables that are not yet analyzed in the
54 RHS, try to determine their evolution, and finally try to
55 evaluate the operation of the RHS that gives the evolution
56 function of the analyzed variable.
58 - When the definition is a condition-phi-node: determine the
59 evolution function for all the branches of the phi node, and
60 finally merge these evolutions (see chrec_merge).
62 - When the definition is a loop-phi-node: determine its initial
63 condition, that is the SSA edge defined in an outer loop, and
64 keep it symbolic. Then determine the SSA edges that are defined
65 in the body of the loop. Follow the inner edges until ending on
66 another loop-phi-node of the same analyzed loop. If the reached
67 loop-phi-node is not the starting loop-phi-node, then we keep
68 this definition under a symbolic form. If the reached
69 loop-phi-node is the same as the starting one, then we compute a
70 symbolic stride on the return path. The result is then the
71 symbolic chrec {initial_condition, +, symbolic_stride}_loop.
75 Example 1: Illustration of the basic algorithm.
81 | if (c > 10) exit_loop
84 Suppose that we want to know the number of iterations of the
85 loop_1. The exit_loop is controlled by a COND_EXPR (c > 10). We
86 ask the scalar evolution analyzer two questions: what's the
87 scalar evolution (scev) of "c", and what's the scev of "10". For
88 "10" the answer is "10" since it is a scalar constant. For the
89 scalar variable "c", it follows the SSA edge to its definition,
90 "c = b + 1", and then asks again what's the scev of "b".
91 Following the SSA edge, we end on a loop-phi-node "b = phi (a,
92 c)", where the initial condition is "a", and the inner loop edge
93 is "c". The initial condition is kept under a symbolic form (it
94 may be the case that the copy constant propagation has done its
95 work and we end with the constant "3" as one of the edges of the
96 loop-phi-node). The update edge is followed to the end of the
97 loop, and until reaching again the starting loop-phi-node: b -> c
98 -> b. At this point we have drawn a path from "b" to "b" from
99 which we compute the stride in the loop: in this example it is
100 "+1". The resulting scev for "b" is "b -> {a, +, 1}_1". Now
101 that the scev for "b" is known, it is possible to compute the
102 scev for "c", that is "c -> {a + 1, +, 1}_1". In order to
103 determine the number of iterations in the loop_1, we have to
104 instantiate_parameters (loop_1, {a + 1, +, 1}_1), that gives after some
105 more analysis the scev {4, +, 1}_1, or in other words, this is
106 the function "f (x) = x + 4", where x is the iteration count of
107 the loop_1. Now we have to solve the inequality "x + 4 > 10",
108 and take the smallest iteration number for which the loop is
109 exited: x = 7. This loop runs from x = 0 to x = 7, and in total
110 there are 8 iterations. In terms of loop normalization, we have
111 created a variable that is implicitly defined, "x" or just "_1",
112 and all the other analyzed scalars of the loop are defined in
113 function of this variable:
119 or in terms of a C program:
122 | for (x = 0; x <= 7; x++)
128 Example 2a: Illustration of the algorithm on nested loops.
139 For analyzing the scalar evolution of "a", the algorithm follows
140 the SSA edge into the loop's body: "a -> b". "b" is an inner
141 loop-phi-node, and its analysis as in Example 1, gives:
146 Following the SSA edge for the initial condition, we end on "c = a
147 + 2", and then on the starting loop-phi-node "a". From this point,
148 the loop stride is computed: back on "c = a + 2" we get a "+2" in
149 the loop_1, then on the loop-phi-node "b" we compute the overall
150 effect of the inner loop that is "b = c + 30", and we get a "+30"
151 in the loop_1. That means that the overall stride in loop_1 is
152 equal to "+32", and the result is:
157 Example 2b: Multivariate chains of recurrences.
170 Analyzing the access function of array A with
171 instantiate_parameters (loop_1, "j + k"), we obtain the
172 instantiation and the analysis of the scalar variables "j" and "k"
173 in loop_1. This leads to the scalar evolution {4, +, 1}_1: the end
174 value of loop_2 for "j" is 4, and the evolution of "k" in loop_1 is
175 {0, +, 1}_1. To obtain the evolution function in loop_3 and
176 instantiate the scalar variables up to loop_1, one has to use:
177 instantiate_scev (block_before_loop (loop_1), loop_3, "j + k").
178 The result of this call is {{0, +, 1}_1, +, 1}_2.
180 Example 3: Higher degree polynomials.
194 instantiate_parameters (loop_1, {5, +, a}_1) -> {5, +, 2, +, 1}_1
195 instantiate_parameters (loop_1, {5 + a, +, a}_1) -> {7, +, 3, +, 1}_1
197 Example 4: Lucas, Fibonacci, or mixers in general.
209 The syntax "(1, c)_1" stands for a PEELED_CHREC that has the
210 following semantics: during the first iteration of the loop_1, the
211 variable contains the value 1, and then it contains the value "c".
212 Note that this syntax is close to the syntax of the loop-phi-node:
213 "a -> (1, c)_1" vs. "a = phi (1, c)".
215 The symbolic chrec representation contains all the semantics of the
216 original code. What is more difficult is to use this information.
218 Example 5: Flip-flops, or exchangers.
230 Based on these symbolic chrecs, it is possible to refine this
231 information into the more precise PERIODIC_CHRECs:
236 This transformation is not yet implemented.
240 You can find a more detailed description of the algorithm in:
241 http://icps.u-strasbg.fr/~pop/DEA_03_Pop.pdf
242 http://icps.u-strasbg.fr/~pop/DEA_03_Pop.ps.gz. But note that
243 this is a preliminary report and some of the details of the
244 algorithm have changed. I'm working on a research report that
245 updates the description of the algorithms to reflect the design
246 choices used in this implementation.
248 A set of slides show a high level overview of the algorithm and run
249 an example through the scalar evolution analyzer:
250 http://cri.ensmp.fr/~pop/gcc/mar04/slides.pdf
252 The slides that I have presented at the GCC Summit'04 are available
253 at: http://cri.ensmp.fr/~pop/gcc/20040604/gccsummit-lno-spop.pdf
258 #include "coretypes.h"
262 #include "optabs-query.h"
266 #include "gimple-pretty-print.h"
267 #include "fold-const.h"
268 #include "gimplify.h"
269 #include "gimple-iterator.h"
270 #include "gimplify-me.h"
271 #include "tree-cfg.h"
272 #include "tree-ssa-loop-ivopts.h"
273 #include "tree-ssa-loop-manip.h"
274 #include "tree-ssa-loop-niter.h"
275 #include "tree-ssa-loop.h"
276 #include "tree-ssa.h"
278 #include "tree-chrec.h"
279 #include "tree-affine.h"
280 #include "tree-scalar-evolution.h"
281 #include "dumpfile.h"
283 #include "tree-ssa-propagate.h"
284 #include "gimple-fold.h"
285 #include "tree-into-ssa.h"
286 #include "builtins.h"
287 #include "case-cfn-macros.h"
289 static tree
analyze_scalar_evolution_1 (struct loop
*, tree
);
290 static tree
analyze_scalar_evolution_for_address_of (struct loop
*loop
,
293 /* The cached information about an SSA name with version NAME_VERSION,
294 claiming that below basic block with index INSTANTIATED_BELOW, the
295 value of the SSA name can be expressed as CHREC. */
297 struct GTY((for_user
)) scev_info_str
{
298 unsigned int name_version
;
299 int instantiated_below
;
303 /* Counters for the scev database. */
304 static unsigned nb_set_scev
= 0;
305 static unsigned nb_get_scev
= 0;
307 struct scev_info_hasher
: ggc_ptr_hash
<scev_info_str
>
309 static hashval_t
hash (scev_info_str
*i
);
310 static bool equal (const scev_info_str
*a
, const scev_info_str
*b
);
313 static GTY (()) hash_table
<scev_info_hasher
> *scalar_evolution_info
;
316 /* Constructs a new SCEV_INFO_STR structure for VAR and INSTANTIATED_BELOW. */
318 static inline struct scev_info_str
*
319 new_scev_info_str (basic_block instantiated_below
, tree var
)
321 struct scev_info_str
*res
;
323 res
= ggc_alloc
<scev_info_str
> ();
324 res
->name_version
= SSA_NAME_VERSION (var
);
325 res
->chrec
= chrec_not_analyzed_yet
;
326 res
->instantiated_below
= instantiated_below
->index
;
331 /* Computes a hash function for database element ELT. */
334 scev_info_hasher::hash (scev_info_str
*elt
)
336 return elt
->name_version
^ elt
->instantiated_below
;
339 /* Compares database elements E1 and E2. */
342 scev_info_hasher::equal (const scev_info_str
*elt1
, const scev_info_str
*elt2
)
344 return (elt1
->name_version
== elt2
->name_version
345 && elt1
->instantiated_below
== elt2
->instantiated_below
);
348 /* Get the scalar evolution of VAR for INSTANTIATED_BELOW basic block.
349 A first query on VAR returns chrec_not_analyzed_yet. */
352 find_var_scev_info (basic_block instantiated_below
, tree var
)
354 struct scev_info_str
*res
;
355 struct scev_info_str tmp
;
357 tmp
.name_version
= SSA_NAME_VERSION (var
);
358 tmp
.instantiated_below
= instantiated_below
->index
;
359 scev_info_str
**slot
= scalar_evolution_info
->find_slot (&tmp
, INSERT
);
362 *slot
= new_scev_info_str (instantiated_below
, var
);
369 /* Hashtable helpers for a temporary hash-table used when
370 analyzing a scalar evolution, instantiating a CHREC or
373 struct instantiate_cache_type
376 vec
<scev_info_str
> entries
;
378 instantiate_cache_type () : map (NULL
), entries (vNULL
) {}
379 ~instantiate_cache_type ();
380 tree
get (unsigned slot
) { return entries
[slot
].chrec
; }
381 void set (unsigned slot
, tree chrec
) { entries
[slot
].chrec
= chrec
; }
384 instantiate_cache_type::~instantiate_cache_type ()
393 /* Cache to avoid infinite recursion when instantiating an SSA name.
394 Live during the outermost analyze_scalar_evolution, instantiate_scev
395 or resolve_mixers call. */
396 static instantiate_cache_type
*global_cache
;
399 /* Return true when PHI is a loop-phi-node. */
402 loop_phi_node_p (gimple
*phi
)
404 /* The implementation of this function is based on the following
405 property: "all the loop-phi-nodes of a loop are contained in the
406 loop's header basic block". */
408 return loop_containing_stmt (phi
)->header
== gimple_bb (phi
);
411 /* Compute the scalar evolution for EVOLUTION_FN after crossing LOOP.
412 In general, in the case of multivariate evolutions we want to get
413 the evolution in different loops. LOOP specifies the level for
414 which to get the evolution.
418 | for (j = 0; j < 100; j++)
420 | for (k = 0; k < 100; k++)
422 | i = k + j; - Here the value of i is a function of j, k.
424 | ... = i - Here the value of i is a function of j.
426 | ... = i - Here the value of i is a scalar.
432 | i_1 = phi (i_0, i_2)
436 This loop has the same effect as:
437 LOOP_1 has the same effect as:
441 The overall effect of the loop, "i_0 + 20" in the previous example,
442 is obtained by passing in the parameters: LOOP = 1,
443 EVOLUTION_FN = {i_0, +, 2}_1.
447 compute_overall_effect_of_inner_loop (struct loop
*loop
, tree evolution_fn
)
451 if (evolution_fn
== chrec_dont_know
)
452 return chrec_dont_know
;
454 else if (TREE_CODE (evolution_fn
) == POLYNOMIAL_CHREC
)
456 struct loop
*inner_loop
= get_chrec_loop (evolution_fn
);
458 if (inner_loop
== loop
459 || flow_loop_nested_p (loop
, inner_loop
))
461 tree nb_iter
= number_of_latch_executions (inner_loop
);
463 if (nb_iter
== chrec_dont_know
)
464 return chrec_dont_know
;
469 /* evolution_fn is the evolution function in LOOP. Get
470 its value in the nb_iter-th iteration. */
471 res
= chrec_apply (inner_loop
->num
, evolution_fn
, nb_iter
);
473 if (chrec_contains_symbols_defined_in_loop (res
, loop
->num
))
474 res
= instantiate_parameters (loop
, res
);
476 /* Continue the computation until ending on a parent of LOOP. */
477 return compute_overall_effect_of_inner_loop (loop
, res
);
484 /* If the evolution function is an invariant, there is nothing to do. */
485 else if (no_evolution_in_loop_p (evolution_fn
, loop
->num
, &val
) && val
)
489 return chrec_dont_know
;
492 /* Associate CHREC to SCALAR. */
495 set_scalar_evolution (basic_block instantiated_below
, tree scalar
, tree chrec
)
499 if (TREE_CODE (scalar
) != SSA_NAME
)
502 scalar_info
= find_var_scev_info (instantiated_below
, scalar
);
506 if (dump_flags
& TDF_SCEV
)
508 fprintf (dump_file
, "(set_scalar_evolution \n");
509 fprintf (dump_file
, " instantiated_below = %d \n",
510 instantiated_below
->index
);
511 fprintf (dump_file
, " (scalar = ");
512 print_generic_expr (dump_file
, scalar
);
513 fprintf (dump_file
, ")\n (scalar_evolution = ");
514 print_generic_expr (dump_file
, chrec
);
515 fprintf (dump_file
, "))\n");
517 if (dump_flags
& TDF_STATS
)
521 *scalar_info
= chrec
;
524 /* Retrieve the chrec associated to SCALAR instantiated below
525 INSTANTIATED_BELOW block. */
528 get_scalar_evolution (basic_block instantiated_below
, tree scalar
)
534 if (dump_flags
& TDF_SCEV
)
536 fprintf (dump_file
, "(get_scalar_evolution \n");
537 fprintf (dump_file
, " (scalar = ");
538 print_generic_expr (dump_file
, scalar
);
539 fprintf (dump_file
, ")\n");
541 if (dump_flags
& TDF_STATS
)
545 if (VECTOR_TYPE_P (TREE_TYPE (scalar
))
546 || TREE_CODE (TREE_TYPE (scalar
)) == COMPLEX_TYPE
)
547 /* For chrec_dont_know we keep the symbolic form. */
550 switch (TREE_CODE (scalar
))
553 if (SSA_NAME_IS_DEFAULT_DEF (scalar
))
556 res
= *find_var_scev_info (instantiated_below
, scalar
);
566 res
= chrec_not_analyzed_yet
;
570 if (dump_file
&& (dump_flags
& TDF_SCEV
))
572 fprintf (dump_file
, " (scalar_evolution = ");
573 print_generic_expr (dump_file
, res
);
574 fprintf (dump_file
, "))\n");
580 /* Helper function for add_to_evolution. Returns the evolution
581 function for an assignment of the form "a = b + c", where "a" and
582 "b" are on the strongly connected component. CHREC_BEFORE is the
583 information that we already have collected up to this point.
584 TO_ADD is the evolution of "c".
586 When CHREC_BEFORE has an evolution part in LOOP_NB, add to this
587 evolution the expression TO_ADD, otherwise construct an evolution
588 part for this loop. */
591 add_to_evolution_1 (unsigned loop_nb
, tree chrec_before
, tree to_add
,
594 tree type
, left
, right
;
595 struct loop
*loop
= get_loop (cfun
, loop_nb
), *chloop
;
597 switch (TREE_CODE (chrec_before
))
599 case POLYNOMIAL_CHREC
:
600 chloop
= get_chrec_loop (chrec_before
);
602 || flow_loop_nested_p (chloop
, loop
))
606 type
= chrec_type (chrec_before
);
608 /* When there is no evolution part in this loop, build it. */
613 right
= SCALAR_FLOAT_TYPE_P (type
)
614 ? build_real (type
, dconst0
)
615 : build_int_cst (type
, 0);
619 var
= CHREC_VARIABLE (chrec_before
);
620 left
= CHREC_LEFT (chrec_before
);
621 right
= CHREC_RIGHT (chrec_before
);
624 to_add
= chrec_convert (type
, to_add
, at_stmt
);
625 right
= chrec_convert_rhs (type
, right
, at_stmt
);
626 right
= chrec_fold_plus (chrec_type (right
), right
, to_add
);
627 return build_polynomial_chrec (var
, left
, right
);
631 gcc_assert (flow_loop_nested_p (loop
, chloop
));
633 /* Search the evolution in LOOP_NB. */
634 left
= add_to_evolution_1 (loop_nb
, CHREC_LEFT (chrec_before
),
636 right
= CHREC_RIGHT (chrec_before
);
637 right
= chrec_convert_rhs (chrec_type (left
), right
, at_stmt
);
638 return build_polynomial_chrec (CHREC_VARIABLE (chrec_before
),
643 /* These nodes do not depend on a loop. */
644 if (chrec_before
== chrec_dont_know
)
645 return chrec_dont_know
;
648 right
= chrec_convert_rhs (chrec_type (left
), to_add
, at_stmt
);
649 return build_polynomial_chrec (loop_nb
, left
, right
);
653 /* Add TO_ADD to the evolution part of CHREC_BEFORE in the dimension
656 Description (provided for completeness, for those who read code in
657 a plane, and for my poor 62 bytes brain that would have forgotten
658 all this in the next two or three months):
660 The algorithm of translation of programs from the SSA representation
661 into the chrecs syntax is based on a pattern matching. After having
662 reconstructed the overall tree expression for a loop, there are only
663 two cases that can arise:
665 1. a = loop-phi (init, a + expr)
666 2. a = loop-phi (init, expr)
668 where EXPR is either a scalar constant with respect to the analyzed
669 loop (this is a degree 0 polynomial), or an expression containing
670 other loop-phi definitions (these are higher degree polynomials).
677 | a = phi (init, a + 5)
684 | a = phi (inita, 2 * b + 3)
685 | b = phi (initb, b + 1)
688 For the first case, the semantics of the SSA representation is:
690 | a (x) = init + \sum_{j = 0}^{x - 1} expr (j)
692 that is, there is a loop index "x" that determines the scalar value
693 of the variable during the loop execution. During the first
694 iteration, the value is that of the initial condition INIT, while
695 during the subsequent iterations, it is the sum of the initial
696 condition with the sum of all the values of EXPR from the initial
697 iteration to the before last considered iteration.
699 For the second case, the semantics of the SSA program is:
701 | a (x) = init, if x = 0;
702 | expr (x - 1), otherwise.
704 The second case corresponds to the PEELED_CHREC, whose syntax is
705 close to the syntax of a loop-phi-node:
707 | phi (init, expr) vs. (init, expr)_x
709 The proof of the translation algorithm for the first case is a
710 proof by structural induction based on the degree of EXPR.
713 When EXPR is a constant with respect to the analyzed loop, or in
714 other words when EXPR is a polynomial of degree 0, the evolution of
715 the variable A in the loop is an affine function with an initial
716 condition INIT, and a step EXPR. In order to show this, we start
717 from the semantics of the SSA representation:
719 f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
721 and since "expr (j)" is a constant with respect to "j",
723 f (x) = init + x * expr
725 Finally, based on the semantics of the pure sum chrecs, by
726 identification we get the corresponding chrecs syntax:
728 f (x) = init * \binom{x}{0} + expr * \binom{x}{1}
729 f (x) -> {init, +, expr}_x
732 Suppose that EXPR is a polynomial of degree N with respect to the
733 analyzed loop_x for which we have already determined that it is
734 written under the chrecs syntax:
736 | expr (x) -> {b_0, +, b_1, +, ..., +, b_{n-1}} (x)
738 We start from the semantics of the SSA program:
740 | f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
742 | f (x) = init + \sum_{j = 0}^{x - 1}
743 | (b_0 * \binom{j}{0} + ... + b_{n-1} * \binom{j}{n-1})
745 | f (x) = init + \sum_{j = 0}^{x - 1}
746 | \sum_{k = 0}^{n - 1} (b_k * \binom{j}{k})
748 | f (x) = init + \sum_{k = 0}^{n - 1}
749 | (b_k * \sum_{j = 0}^{x - 1} \binom{j}{k})
751 | f (x) = init + \sum_{k = 0}^{n - 1}
752 | (b_k * \binom{x}{k + 1})
754 | f (x) = init + b_0 * \binom{x}{1} + ...
755 | + b_{n-1} * \binom{x}{n}
757 | f (x) = init * \binom{x}{0} + b_0 * \binom{x}{1} + ...
758 | + b_{n-1} * \binom{x}{n}
761 And finally from the definition of the chrecs syntax, we identify:
762 | f (x) -> {init, +, b_0, +, ..., +, b_{n-1}}_x
764 This shows the mechanism that stands behind the add_to_evolution
765 function. An important point is that the use of symbolic
766 parameters avoids the need of an analysis schedule.
773 | a = phi (inita, a + 2 + b)
774 | b = phi (initb, b + 1)
777 When analyzing "a", the algorithm keeps "b" symbolically:
779 | a -> {inita, +, 2 + b}_1
781 Then, after instantiation, the analyzer ends on the evolution:
783 | a -> {inita, +, 2 + initb, +, 1}_1
788 add_to_evolution (unsigned loop_nb
, tree chrec_before
, enum tree_code code
,
789 tree to_add
, gimple
*at_stmt
)
791 tree type
= chrec_type (to_add
);
792 tree res
= NULL_TREE
;
794 if (to_add
== NULL_TREE
)
797 /* TO_ADD is either a scalar, or a parameter. TO_ADD is not
798 instantiated at this point. */
799 if (TREE_CODE (to_add
) == POLYNOMIAL_CHREC
)
800 /* This should not happen. */
801 return chrec_dont_know
;
803 if (dump_file
&& (dump_flags
& TDF_SCEV
))
805 fprintf (dump_file
, "(add_to_evolution \n");
806 fprintf (dump_file
, " (loop_nb = %d)\n", loop_nb
);
807 fprintf (dump_file
, " (chrec_before = ");
808 print_generic_expr (dump_file
, chrec_before
);
809 fprintf (dump_file
, ")\n (to_add = ");
810 print_generic_expr (dump_file
, to_add
);
811 fprintf (dump_file
, ")\n");
814 if (code
== MINUS_EXPR
)
815 to_add
= chrec_fold_multiply (type
, to_add
, SCALAR_FLOAT_TYPE_P (type
)
816 ? build_real (type
, dconstm1
)
817 : build_int_cst_type (type
, -1));
819 res
= add_to_evolution_1 (loop_nb
, chrec_before
, to_add
, at_stmt
);
821 if (dump_file
&& (dump_flags
& TDF_SCEV
))
823 fprintf (dump_file
, " (res = ");
824 print_generic_expr (dump_file
, res
);
825 fprintf (dump_file
, "))\n");
833 /* This section selects the loops that will be good candidates for the
834 scalar evolution analysis. For the moment, greedily select all the
835 loop nests we could analyze. */
837 /* For a loop with a single exit edge, return the COND_EXPR that
838 guards the exit edge. If the expression is too difficult to
839 analyze, then give up. */
842 get_loop_exit_condition (const struct loop
*loop
)
845 edge exit_edge
= single_exit (loop
);
847 if (dump_file
&& (dump_flags
& TDF_SCEV
))
848 fprintf (dump_file
, "(get_loop_exit_condition \n ");
854 stmt
= last_stmt (exit_edge
->src
);
855 if (gcond
*cond_stmt
= safe_dyn_cast
<gcond
*> (stmt
))
859 if (dump_file
&& (dump_flags
& TDF_SCEV
))
861 print_gimple_stmt (dump_file
, res
, 0);
862 fprintf (dump_file
, ")\n");
869 /* Depth first search algorithm. */
878 static t_bool
follow_ssa_edge (struct loop
*loop
, gimple
*, gphi
*,
881 /* Follow the ssa edge into the binary expression RHS0 CODE RHS1.
882 Return true if the strongly connected component has been found. */
885 follow_ssa_edge_binary (struct loop
*loop
, gimple
*at_stmt
,
886 tree type
, tree rhs0
, enum tree_code code
, tree rhs1
,
887 gphi
*halting_phi
, tree
*evolution_of_loop
,
890 t_bool res
= t_false
;
895 case POINTER_PLUS_EXPR
:
897 if (TREE_CODE (rhs0
) == SSA_NAME
)
899 if (TREE_CODE (rhs1
) == SSA_NAME
)
901 /* Match an assignment under the form:
904 /* We want only assignments of form "name + name" contribute to
905 LIMIT, as the other cases do not necessarily contribute to
906 the complexity of the expression. */
909 evol
= *evolution_of_loop
;
910 evol
= add_to_evolution
912 chrec_convert (type
, evol
, at_stmt
),
913 code
, rhs1
, at_stmt
);
914 res
= follow_ssa_edge
915 (loop
, SSA_NAME_DEF_STMT (rhs0
), halting_phi
, &evol
, limit
);
917 *evolution_of_loop
= evol
;
918 else if (res
== t_false
)
920 *evolution_of_loop
= add_to_evolution
922 chrec_convert (type
, *evolution_of_loop
, at_stmt
),
923 code
, rhs0
, at_stmt
);
924 res
= follow_ssa_edge
925 (loop
, SSA_NAME_DEF_STMT (rhs1
), halting_phi
,
926 evolution_of_loop
, limit
);
929 else if (res
== t_dont_know
)
930 *evolution_of_loop
= chrec_dont_know
;
933 else if (res
== t_dont_know
)
934 *evolution_of_loop
= chrec_dont_know
;
939 /* Match an assignment under the form:
941 *evolution_of_loop
= add_to_evolution
942 (loop
->num
, chrec_convert (type
, *evolution_of_loop
,
944 code
, rhs1
, at_stmt
);
945 res
= follow_ssa_edge
946 (loop
, SSA_NAME_DEF_STMT (rhs0
), halting_phi
,
947 evolution_of_loop
, limit
);
950 else if (res
== t_dont_know
)
951 *evolution_of_loop
= chrec_dont_know
;
955 else if (TREE_CODE (rhs1
) == SSA_NAME
)
957 /* Match an assignment under the form:
959 *evolution_of_loop
= add_to_evolution
960 (loop
->num
, chrec_convert (type
, *evolution_of_loop
,
962 code
, rhs0
, at_stmt
);
963 res
= follow_ssa_edge
964 (loop
, SSA_NAME_DEF_STMT (rhs1
), halting_phi
,
965 evolution_of_loop
, limit
);
968 else if (res
== t_dont_know
)
969 *evolution_of_loop
= chrec_dont_know
;
973 /* Otherwise, match an assignment under the form:
975 /* And there is nothing to do. */
980 /* This case is under the form "opnd0 = rhs0 - rhs1". */
981 if (TREE_CODE (rhs0
) == SSA_NAME
)
983 /* Match an assignment under the form:
986 /* We want only assignments of form "name - name" contribute to
987 LIMIT, as the other cases do not necessarily contribute to
988 the complexity of the expression. */
989 if (TREE_CODE (rhs1
) == SSA_NAME
)
992 *evolution_of_loop
= add_to_evolution
993 (loop
->num
, chrec_convert (type
, *evolution_of_loop
, at_stmt
),
994 MINUS_EXPR
, rhs1
, at_stmt
);
995 res
= follow_ssa_edge (loop
, SSA_NAME_DEF_STMT (rhs0
), halting_phi
,
996 evolution_of_loop
, limit
);
999 else if (res
== t_dont_know
)
1000 *evolution_of_loop
= chrec_dont_know
;
1003 /* Otherwise, match an assignment under the form:
1005 /* And there is nothing to do. */
1016 /* Follow the ssa edge into the expression EXPR.
1017 Return true if the strongly connected component has been found. */
1020 follow_ssa_edge_expr (struct loop
*loop
, gimple
*at_stmt
, tree expr
,
1021 gphi
*halting_phi
, tree
*evolution_of_loop
,
1024 enum tree_code code
= TREE_CODE (expr
);
1025 tree type
= TREE_TYPE (expr
), rhs0
, rhs1
;
1028 /* The EXPR is one of the following cases:
1032 - a POINTER_PLUS_EXPR,
1035 - other cases are not yet handled. */
1040 /* This assignment is under the form "a_1 = (cast) rhs. */
1041 res
= follow_ssa_edge_expr (loop
, at_stmt
, TREE_OPERAND (expr
, 0),
1042 halting_phi
, evolution_of_loop
, limit
);
1043 *evolution_of_loop
= chrec_convert (type
, *evolution_of_loop
, at_stmt
);
1047 /* This assignment is under the form "a_1 = 7". */
1052 /* This assignment is under the form: "a_1 = b_2". */
1053 res
= follow_ssa_edge
1054 (loop
, SSA_NAME_DEF_STMT (expr
), halting_phi
, evolution_of_loop
, limit
);
1057 case POINTER_PLUS_EXPR
:
1060 /* This case is under the form "rhs0 +- rhs1". */
1061 rhs0
= TREE_OPERAND (expr
, 0);
1062 rhs1
= TREE_OPERAND (expr
, 1);
1063 type
= TREE_TYPE (rhs0
);
1064 STRIP_USELESS_TYPE_CONVERSION (rhs0
);
1065 STRIP_USELESS_TYPE_CONVERSION (rhs1
);
1066 res
= follow_ssa_edge_binary (loop
, at_stmt
, type
, rhs0
, code
, rhs1
,
1067 halting_phi
, evolution_of_loop
, limit
);
1071 /* Handle &MEM[ptr + CST] which is equivalent to POINTER_PLUS_EXPR. */
1072 if (TREE_CODE (TREE_OPERAND (expr
, 0)) == MEM_REF
)
1074 expr
= TREE_OPERAND (expr
, 0);
1075 rhs0
= TREE_OPERAND (expr
, 0);
1076 rhs1
= TREE_OPERAND (expr
, 1);
1077 type
= TREE_TYPE (rhs0
);
1078 STRIP_USELESS_TYPE_CONVERSION (rhs0
);
1079 STRIP_USELESS_TYPE_CONVERSION (rhs1
);
1080 res
= follow_ssa_edge_binary (loop
, at_stmt
, type
,
1081 rhs0
, POINTER_PLUS_EXPR
, rhs1
,
1082 halting_phi
, evolution_of_loop
, limit
);
1089 /* This assignment is of the form: "a_1 = ASSERT_EXPR <a_2, ...>"
1090 It must be handled as a copy assignment of the form a_1 = a_2. */
1091 rhs0
= ASSERT_EXPR_VAR (expr
);
1092 if (TREE_CODE (rhs0
) == SSA_NAME
)
1093 res
= follow_ssa_edge (loop
, SSA_NAME_DEF_STMT (rhs0
),
1094 halting_phi
, evolution_of_loop
, limit
);
1107 /* Follow the ssa edge into the right hand side of an assignment STMT.
1108 Return true if the strongly connected component has been found. */
1111 follow_ssa_edge_in_rhs (struct loop
*loop
, gimple
*stmt
,
1112 gphi
*halting_phi
, tree
*evolution_of_loop
,
1115 enum tree_code code
= gimple_assign_rhs_code (stmt
);
1116 tree type
= gimple_expr_type (stmt
), rhs1
, rhs2
;
1122 /* This assignment is under the form "a_1 = (cast) rhs. */
1123 res
= follow_ssa_edge_expr (loop
, stmt
, gimple_assign_rhs1 (stmt
),
1124 halting_phi
, evolution_of_loop
, limit
);
1125 *evolution_of_loop
= chrec_convert (type
, *evolution_of_loop
, stmt
);
1128 case POINTER_PLUS_EXPR
:
1131 rhs1
= gimple_assign_rhs1 (stmt
);
1132 rhs2
= gimple_assign_rhs2 (stmt
);
1133 type
= TREE_TYPE (rhs1
);
1134 res
= follow_ssa_edge_binary (loop
, stmt
, type
, rhs1
, code
, rhs2
,
1135 halting_phi
, evolution_of_loop
, limit
);
1139 if (get_gimple_rhs_class (code
) == GIMPLE_SINGLE_RHS
)
1140 res
= follow_ssa_edge_expr (loop
, stmt
, gimple_assign_rhs1 (stmt
),
1141 halting_phi
, evolution_of_loop
, limit
);
1150 /* Checks whether the I-th argument of a PHI comes from a backedge. */
1153 backedge_phi_arg_p (gphi
*phi
, int i
)
1155 const_edge e
= gimple_phi_arg_edge (phi
, i
);
1157 /* We would in fact like to test EDGE_DFS_BACK here, but we do not care
1158 about updating it anywhere, and this should work as well most of the
1160 if (e
->flags
& EDGE_IRREDUCIBLE_LOOP
)
1166 /* Helper function for one branch of the condition-phi-node. Return
1167 true if the strongly connected component has been found following
1170 static inline t_bool
1171 follow_ssa_edge_in_condition_phi_branch (int i
,
1173 gphi
*condition_phi
,
1175 tree
*evolution_of_branch
,
1176 tree init_cond
, int limit
)
1178 tree branch
= PHI_ARG_DEF (condition_phi
, i
);
1179 *evolution_of_branch
= chrec_dont_know
;
1181 /* Do not follow back edges (they must belong to an irreducible loop, which
1182 we really do not want to worry about). */
1183 if (backedge_phi_arg_p (condition_phi
, i
))
1186 if (TREE_CODE (branch
) == SSA_NAME
)
1188 *evolution_of_branch
= init_cond
;
1189 return follow_ssa_edge (loop
, SSA_NAME_DEF_STMT (branch
), halting_phi
,
1190 evolution_of_branch
, limit
);
1193 /* This case occurs when one of the condition branches sets
1194 the variable to a constant: i.e. a phi-node like
1195 "a_2 = PHI <a_7(5), 2(6)>;".
1197 FIXME: This case have to be refined correctly:
1198 in some cases it is possible to say something better than
1199 chrec_dont_know, for example using a wrap-around notation. */
1203 /* This function merges the branches of a condition-phi-node in a
1207 follow_ssa_edge_in_condition_phi (struct loop
*loop
,
1208 gphi
*condition_phi
,
1210 tree
*evolution_of_loop
, int limit
)
1213 tree init
= *evolution_of_loop
;
1214 tree evolution_of_branch
;
1215 t_bool res
= follow_ssa_edge_in_condition_phi_branch (0, loop
, condition_phi
,
1217 &evolution_of_branch
,
1219 if (res
== t_false
|| res
== t_dont_know
)
1222 *evolution_of_loop
= evolution_of_branch
;
1224 n
= gimple_phi_num_args (condition_phi
);
1225 for (i
= 1; i
< n
; i
++)
1227 /* Quickly give up when the evolution of one of the branches is
1229 if (*evolution_of_loop
== chrec_dont_know
)
1232 /* Increase the limit by the PHI argument number to avoid exponential
1233 time and memory complexity. */
1234 res
= follow_ssa_edge_in_condition_phi_branch (i
, loop
, condition_phi
,
1236 &evolution_of_branch
,
1238 if (res
== t_false
|| res
== t_dont_know
)
1241 *evolution_of_loop
= chrec_merge (*evolution_of_loop
,
1242 evolution_of_branch
);
1248 /* Follow an SSA edge in an inner loop. It computes the overall
1249 effect of the loop, and following the symbolic initial conditions,
1250 it follows the edges in the parent loop. The inner loop is
1251 considered as a single statement. */
1254 follow_ssa_edge_inner_loop_phi (struct loop
*outer_loop
,
1255 gphi
*loop_phi_node
,
1257 tree
*evolution_of_loop
, int limit
)
1259 struct loop
*loop
= loop_containing_stmt (loop_phi_node
);
1260 tree ev
= analyze_scalar_evolution (loop
, PHI_RESULT (loop_phi_node
));
1262 /* Sometimes, the inner loop is too difficult to analyze, and the
1263 result of the analysis is a symbolic parameter. */
1264 if (ev
== PHI_RESULT (loop_phi_node
))
1266 t_bool res
= t_false
;
1267 int i
, n
= gimple_phi_num_args (loop_phi_node
);
1269 for (i
= 0; i
< n
; i
++)
1271 tree arg
= PHI_ARG_DEF (loop_phi_node
, i
);
1274 /* Follow the edges that exit the inner loop. */
1275 bb
= gimple_phi_arg_edge (loop_phi_node
, i
)->src
;
1276 if (!flow_bb_inside_loop_p (loop
, bb
))
1277 res
= follow_ssa_edge_expr (outer_loop
, loop_phi_node
,
1279 evolution_of_loop
, limit
);
1284 /* If the path crosses this loop-phi, give up. */
1286 *evolution_of_loop
= chrec_dont_know
;
1291 /* Otherwise, compute the overall effect of the inner loop. */
1292 ev
= compute_overall_effect_of_inner_loop (loop
, ev
);
1293 return follow_ssa_edge_expr (outer_loop
, loop_phi_node
, ev
, halting_phi
,
1294 evolution_of_loop
, limit
);
1297 /* Follow an SSA edge from a loop-phi-node to itself, constructing a
1298 path that is analyzed on the return walk. */
1301 follow_ssa_edge (struct loop
*loop
, gimple
*def
, gphi
*halting_phi
,
1302 tree
*evolution_of_loop
, int limit
)
1304 struct loop
*def_loop
;
1306 if (gimple_nop_p (def
))
1309 /* Give up if the path is longer than the MAX that we allow. */
1310 if (limit
> PARAM_VALUE (PARAM_SCEV_MAX_EXPR_COMPLEXITY
))
1313 def_loop
= loop_containing_stmt (def
);
1315 switch (gimple_code (def
))
1318 if (!loop_phi_node_p (def
))
1319 /* DEF is a condition-phi-node. Follow the branches, and
1320 record their evolutions. Finally, merge the collected
1321 information and set the approximation to the main
1323 return follow_ssa_edge_in_condition_phi
1324 (loop
, as_a
<gphi
*> (def
), halting_phi
, evolution_of_loop
,
1327 /* When the analyzed phi is the halting_phi, the
1328 depth-first search is over: we have found a path from
1329 the halting_phi to itself in the loop. */
1330 if (def
== halting_phi
)
1333 /* Otherwise, the evolution of the HALTING_PHI depends
1334 on the evolution of another loop-phi-node, i.e. the
1335 evolution function is a higher degree polynomial. */
1336 if (def_loop
== loop
)
1340 if (flow_loop_nested_p (loop
, def_loop
))
1341 return follow_ssa_edge_inner_loop_phi
1342 (loop
, as_a
<gphi
*> (def
), halting_phi
, evolution_of_loop
,
1349 return follow_ssa_edge_in_rhs (loop
, def
, halting_phi
,
1350 evolution_of_loop
, limit
);
1353 /* At this level of abstraction, the program is just a set
1354 of GIMPLE_ASSIGNs and PHI_NODEs. In principle there is no
1355 other node to be handled. */
1361 /* Simplify PEELED_CHREC represented by (init_cond, arg) in LOOP.
1362 Handle below case and return the corresponding POLYNOMIAL_CHREC:
1364 # i_17 = PHI <i_13(5), 0(3)>
1365 # _20 = PHI <_5(5), start_4(D)(3)>
1368 _5 = start_4(D) + i_13;
1370 Though variable _20 appears as a PEELED_CHREC in the form of
1371 (start_4, _5)_LOOP, it's a POLYNOMIAL_CHREC like {start_4, 1}_LOOP.
1376 simplify_peeled_chrec (struct loop
*loop
, tree arg
, tree init_cond
)
1378 aff_tree aff1
, aff2
;
1379 tree ev
, left
, right
, type
, step_val
;
1380 hash_map
<tree
, name_expansion
*> *peeled_chrec_map
= NULL
;
1382 ev
= instantiate_parameters (loop
, analyze_scalar_evolution (loop
, arg
));
1383 if (ev
== NULL_TREE
|| TREE_CODE (ev
) != POLYNOMIAL_CHREC
)
1384 return chrec_dont_know
;
1386 left
= CHREC_LEFT (ev
);
1387 right
= CHREC_RIGHT (ev
);
1388 type
= TREE_TYPE (left
);
1389 step_val
= chrec_fold_plus (type
, init_cond
, right
);
1391 /* Transform (init, {left, right}_LOOP)_LOOP to {init, right}_LOOP
1392 if "left" equals to "init + right". */
1393 if (operand_equal_p (left
, step_val
, 0))
1395 if (dump_file
&& (dump_flags
& TDF_SCEV
))
1396 fprintf (dump_file
, "Simplify PEELED_CHREC into POLYNOMIAL_CHREC.\n");
1398 return build_polynomial_chrec (loop
->num
, init_cond
, right
);
1401 /* The affine code only deals with pointer and integer types. */
1402 if (!POINTER_TYPE_P (type
)
1403 && !INTEGRAL_TYPE_P (type
))
1404 return chrec_dont_know
;
1406 /* Try harder to check if they are equal. */
1407 tree_to_aff_combination_expand (left
, type
, &aff1
, &peeled_chrec_map
);
1408 tree_to_aff_combination_expand (step_val
, type
, &aff2
, &peeled_chrec_map
);
1409 free_affine_expand_cache (&peeled_chrec_map
);
1410 aff_combination_scale (&aff2
, -1);
1411 aff_combination_add (&aff1
, &aff2
);
1413 /* Transform (init, {left, right}_LOOP)_LOOP to {init, right}_LOOP
1414 if "left" equals to "init + right". */
1415 if (aff_combination_zero_p (&aff1
))
1417 if (dump_file
&& (dump_flags
& TDF_SCEV
))
1418 fprintf (dump_file
, "Simplify PEELED_CHREC into POLYNOMIAL_CHREC.\n");
1420 return build_polynomial_chrec (loop
->num
, init_cond
, right
);
1422 return chrec_dont_know
;
1425 /* Given a LOOP_PHI_NODE, this function determines the evolution
1426 function from LOOP_PHI_NODE to LOOP_PHI_NODE in the loop. */
1429 analyze_evolution_in_loop (gphi
*loop_phi_node
,
1432 int i
, n
= gimple_phi_num_args (loop_phi_node
);
1433 tree evolution_function
= chrec_not_analyzed_yet
;
1434 struct loop
*loop
= loop_containing_stmt (loop_phi_node
);
1436 static bool simplify_peeled_chrec_p
= true;
1438 if (dump_file
&& (dump_flags
& TDF_SCEV
))
1440 fprintf (dump_file
, "(analyze_evolution_in_loop \n");
1441 fprintf (dump_file
, " (loop_phi_node = ");
1442 print_gimple_stmt (dump_file
, loop_phi_node
, 0);
1443 fprintf (dump_file
, ")\n");
1446 for (i
= 0; i
< n
; i
++)
1448 tree arg
= PHI_ARG_DEF (loop_phi_node
, i
);
1453 /* Select the edges that enter the loop body. */
1454 bb
= gimple_phi_arg_edge (loop_phi_node
, i
)->src
;
1455 if (!flow_bb_inside_loop_p (loop
, bb
))
1458 if (TREE_CODE (arg
) == SSA_NAME
)
1462 ssa_chain
= SSA_NAME_DEF_STMT (arg
);
1464 /* Pass in the initial condition to the follow edge function. */
1466 res
= follow_ssa_edge (loop
, ssa_chain
, loop_phi_node
, &ev_fn
, 0);
1468 /* If ev_fn has no evolution in the inner loop, and the
1469 init_cond is not equal to ev_fn, then we have an
1470 ambiguity between two possible values, as we cannot know
1471 the number of iterations at this point. */
1472 if (TREE_CODE (ev_fn
) != POLYNOMIAL_CHREC
1473 && no_evolution_in_loop_p (ev_fn
, loop
->num
, &val
) && val
1474 && !operand_equal_p (init_cond
, ev_fn
, 0))
1475 ev_fn
= chrec_dont_know
;
1480 /* When it is impossible to go back on the same
1481 loop_phi_node by following the ssa edges, the
1482 evolution is represented by a peeled chrec, i.e. the
1483 first iteration, EV_FN has the value INIT_COND, then
1484 all the other iterations it has the value of ARG.
1485 For the moment, PEELED_CHREC nodes are not built. */
1488 ev_fn
= chrec_dont_know
;
1489 /* Try to recognize POLYNOMIAL_CHREC which appears in
1490 the form of PEELED_CHREC, but guard the process with
1491 a bool variable to keep the analyzer from infinite
1492 recurrence for real PEELED_RECs. */
1493 if (simplify_peeled_chrec_p
&& TREE_CODE (arg
) == SSA_NAME
)
1495 simplify_peeled_chrec_p
= false;
1496 ev_fn
= simplify_peeled_chrec (loop
, arg
, init_cond
);
1497 simplify_peeled_chrec_p
= true;
1501 /* When there are multiple back edges of the loop (which in fact never
1502 happens currently, but nevertheless), merge their evolutions. */
1503 evolution_function
= chrec_merge (evolution_function
, ev_fn
);
1505 if (evolution_function
== chrec_dont_know
)
1509 if (dump_file
&& (dump_flags
& TDF_SCEV
))
1511 fprintf (dump_file
, " (evolution_function = ");
1512 print_generic_expr (dump_file
, evolution_function
);
1513 fprintf (dump_file
, "))\n");
1516 return evolution_function
;
1519 /* Looks to see if VAR is a copy of a constant (via straightforward assignments
1520 or degenerate phi's). If so, returns the constant; else, returns VAR. */
1523 follow_copies_to_constant (tree var
)
1526 while (TREE_CODE (res
) == SSA_NAME
1527 /* We face not updated SSA form in multiple places and this walk
1528 may end up in sibling loops so we have to guard it. */
1529 && !name_registered_for_update_p (res
))
1531 gimple
*def
= SSA_NAME_DEF_STMT (res
);
1532 if (gphi
*phi
= dyn_cast
<gphi
*> (def
))
1534 if (tree rhs
= degenerate_phi_result (phi
))
1539 else if (gimple_assign_single_p (def
))
1540 /* Will exit loop if not an SSA_NAME. */
1541 res
= gimple_assign_rhs1 (def
);
1545 if (CONSTANT_CLASS_P (res
))
1550 /* Given a loop-phi-node, return the initial conditions of the
1551 variable on entry of the loop. When the CCP has propagated
1552 constants into the loop-phi-node, the initial condition is
1553 instantiated, otherwise the initial condition is kept symbolic.
1554 This analyzer does not analyze the evolution outside the current
1555 loop, and leaves this task to the on-demand tree reconstructor. */
1558 analyze_initial_condition (gphi
*loop_phi_node
)
1561 tree init_cond
= chrec_not_analyzed_yet
;
1562 struct loop
*loop
= loop_containing_stmt (loop_phi_node
);
1564 if (dump_file
&& (dump_flags
& TDF_SCEV
))
1566 fprintf (dump_file
, "(analyze_initial_condition \n");
1567 fprintf (dump_file
, " (loop_phi_node = \n");
1568 print_gimple_stmt (dump_file
, loop_phi_node
, 0);
1569 fprintf (dump_file
, ")\n");
1572 n
= gimple_phi_num_args (loop_phi_node
);
1573 for (i
= 0; i
< n
; i
++)
1575 tree branch
= PHI_ARG_DEF (loop_phi_node
, i
);
1576 basic_block bb
= gimple_phi_arg_edge (loop_phi_node
, i
)->src
;
1578 /* When the branch is oriented to the loop's body, it does
1579 not contribute to the initial condition. */
1580 if (flow_bb_inside_loop_p (loop
, bb
))
1583 if (init_cond
== chrec_not_analyzed_yet
)
1589 if (TREE_CODE (branch
) == SSA_NAME
)
1591 init_cond
= chrec_dont_know
;
1595 init_cond
= chrec_merge (init_cond
, branch
);
1598 /* Ooops -- a loop without an entry??? */
1599 if (init_cond
== chrec_not_analyzed_yet
)
1600 init_cond
= chrec_dont_know
;
1602 /* We may not have fully constant propagated IL. Handle degenerate PHIs here
1603 to not miss important early loop unrollings. */
1604 init_cond
= follow_copies_to_constant (init_cond
);
1606 if (dump_file
&& (dump_flags
& TDF_SCEV
))
1608 fprintf (dump_file
, " (init_cond = ");
1609 print_generic_expr (dump_file
, init_cond
);
1610 fprintf (dump_file
, "))\n");
1616 /* Analyze the scalar evolution for LOOP_PHI_NODE. */
1619 interpret_loop_phi (struct loop
*loop
, gphi
*loop_phi_node
)
1622 struct loop
*phi_loop
= loop_containing_stmt (loop_phi_node
);
1625 gcc_assert (phi_loop
== loop
);
1627 /* Otherwise really interpret the loop phi. */
1628 init_cond
= analyze_initial_condition (loop_phi_node
);
1629 res
= analyze_evolution_in_loop (loop_phi_node
, init_cond
);
1631 /* Verify we maintained the correct initial condition throughout
1632 possible conversions in the SSA chain. */
1633 if (res
!= chrec_dont_know
)
1635 tree new_init
= res
;
1636 if (CONVERT_EXPR_P (res
)
1637 && TREE_CODE (TREE_OPERAND (res
, 0)) == POLYNOMIAL_CHREC
)
1638 new_init
= fold_convert (TREE_TYPE (res
),
1639 CHREC_LEFT (TREE_OPERAND (res
, 0)));
1640 else if (TREE_CODE (res
) == POLYNOMIAL_CHREC
)
1641 new_init
= CHREC_LEFT (res
);
1642 STRIP_USELESS_TYPE_CONVERSION (new_init
);
1643 if (TREE_CODE (new_init
) == POLYNOMIAL_CHREC
1644 || !operand_equal_p (init_cond
, new_init
, 0))
1645 return chrec_dont_know
;
1651 /* This function merges the branches of a condition-phi-node,
1652 contained in the outermost loop, and whose arguments are already
1656 interpret_condition_phi (struct loop
*loop
, gphi
*condition_phi
)
1658 int i
, n
= gimple_phi_num_args (condition_phi
);
1659 tree res
= chrec_not_analyzed_yet
;
1661 for (i
= 0; i
< n
; i
++)
1665 if (backedge_phi_arg_p (condition_phi
, i
))
1667 res
= chrec_dont_know
;
1671 branch_chrec
= analyze_scalar_evolution
1672 (loop
, PHI_ARG_DEF (condition_phi
, i
));
1674 res
= chrec_merge (res
, branch_chrec
);
1675 if (res
== chrec_dont_know
)
1682 /* Interpret the operation RHS1 OP RHS2. If we didn't
1683 analyze this node before, follow the definitions until ending
1684 either on an analyzed GIMPLE_ASSIGN, or on a loop-phi-node. On the
1685 return path, this function propagates evolutions (ala constant copy
1686 propagation). OPND1 is not a GIMPLE expression because we could
1687 analyze the effect of an inner loop: see interpret_loop_phi. */
1690 interpret_rhs_expr (struct loop
*loop
, gimple
*at_stmt
,
1691 tree type
, tree rhs1
, enum tree_code code
, tree rhs2
)
1693 tree res
, chrec1
, chrec2
, ctype
;
1696 if (get_gimple_rhs_class (code
) == GIMPLE_SINGLE_RHS
)
1698 if (is_gimple_min_invariant (rhs1
))
1699 return chrec_convert (type
, rhs1
, at_stmt
);
1701 if (code
== SSA_NAME
)
1702 return chrec_convert (type
, analyze_scalar_evolution (loop
, rhs1
),
1705 if (code
== ASSERT_EXPR
)
1707 rhs1
= ASSERT_EXPR_VAR (rhs1
);
1708 return chrec_convert (type
, analyze_scalar_evolution (loop
, rhs1
),
1716 if (TREE_CODE (TREE_OPERAND (rhs1
, 0)) == MEM_REF
1717 || handled_component_p (TREE_OPERAND (rhs1
, 0)))
1720 poly_int64 bitsize
, bitpos
;
1721 int unsignedp
, reversep
;
1727 base
= get_inner_reference (TREE_OPERAND (rhs1
, 0),
1728 &bitsize
, &bitpos
, &offset
, &mode
,
1729 &unsignedp
, &reversep
, &volatilep
);
1731 if (TREE_CODE (base
) == MEM_REF
)
1733 rhs2
= TREE_OPERAND (base
, 1);
1734 rhs1
= TREE_OPERAND (base
, 0);
1736 chrec1
= analyze_scalar_evolution (loop
, rhs1
);
1737 chrec2
= analyze_scalar_evolution (loop
, rhs2
);
1738 chrec1
= chrec_convert (type
, chrec1
, at_stmt
);
1739 chrec2
= chrec_convert (TREE_TYPE (rhs2
), chrec2
, at_stmt
);
1740 chrec1
= instantiate_parameters (loop
, chrec1
);
1741 chrec2
= instantiate_parameters (loop
, chrec2
);
1742 res
= chrec_fold_plus (type
, chrec1
, chrec2
);
1746 chrec1
= analyze_scalar_evolution_for_address_of (loop
, base
);
1747 chrec1
= chrec_convert (type
, chrec1
, at_stmt
);
1751 if (offset
!= NULL_TREE
)
1753 chrec2
= analyze_scalar_evolution (loop
, offset
);
1754 chrec2
= chrec_convert (TREE_TYPE (offset
), chrec2
, at_stmt
);
1755 chrec2
= instantiate_parameters (loop
, chrec2
);
1756 res
= chrec_fold_plus (type
, res
, chrec2
);
1759 if (maybe_ne (bitpos
, 0))
1761 unitpos
= size_int (exact_div (bitpos
, BITS_PER_UNIT
));
1762 chrec3
= analyze_scalar_evolution (loop
, unitpos
);
1763 chrec3
= chrec_convert (TREE_TYPE (unitpos
), chrec3
, at_stmt
);
1764 chrec3
= instantiate_parameters (loop
, chrec3
);
1765 res
= chrec_fold_plus (type
, res
, chrec3
);
1769 res
= chrec_dont_know
;
1772 case POINTER_PLUS_EXPR
:
1773 chrec1
= analyze_scalar_evolution (loop
, rhs1
);
1774 chrec2
= analyze_scalar_evolution (loop
, rhs2
);
1775 chrec1
= chrec_convert (type
, chrec1
, at_stmt
);
1776 chrec2
= chrec_convert (TREE_TYPE (rhs2
), chrec2
, at_stmt
);
1777 chrec1
= instantiate_parameters (loop
, chrec1
);
1778 chrec2
= instantiate_parameters (loop
, chrec2
);
1779 res
= chrec_fold_plus (type
, chrec1
, chrec2
);
1783 chrec1
= analyze_scalar_evolution (loop
, rhs1
);
1784 chrec2
= analyze_scalar_evolution (loop
, rhs2
);
1786 /* When the stmt is conditionally executed re-write the CHREC
1787 into a form that has well-defined behavior on overflow. */
1789 && INTEGRAL_TYPE_P (type
)
1790 && ! TYPE_OVERFLOW_WRAPS (type
)
1791 && ! dominated_by_p (CDI_DOMINATORS
, loop
->latch
,
1792 gimple_bb (at_stmt
)))
1793 ctype
= unsigned_type_for (type
);
1794 chrec1
= chrec_convert (ctype
, chrec1
, at_stmt
);
1795 chrec2
= chrec_convert (ctype
, chrec2
, at_stmt
);
1796 chrec1
= instantiate_parameters (loop
, chrec1
);
1797 chrec2
= instantiate_parameters (loop
, chrec2
);
1798 res
= chrec_fold_plus (ctype
, chrec1
, chrec2
);
1800 res
= chrec_convert (type
, res
, at_stmt
);
1804 chrec1
= analyze_scalar_evolution (loop
, rhs1
);
1805 chrec2
= analyze_scalar_evolution (loop
, rhs2
);
1807 /* When the stmt is conditionally executed re-write the CHREC
1808 into a form that has well-defined behavior on overflow. */
1810 && INTEGRAL_TYPE_P (type
)
1811 && ! TYPE_OVERFLOW_WRAPS (type
)
1812 && ! dominated_by_p (CDI_DOMINATORS
,
1813 loop
->latch
, gimple_bb (at_stmt
)))
1814 ctype
= unsigned_type_for (type
);
1815 chrec1
= chrec_convert (ctype
, chrec1
, at_stmt
);
1816 chrec2
= chrec_convert (ctype
, chrec2
, at_stmt
);
1817 chrec1
= instantiate_parameters (loop
, chrec1
);
1818 chrec2
= instantiate_parameters (loop
, chrec2
);
1819 res
= chrec_fold_minus (ctype
, chrec1
, chrec2
);
1821 res
= chrec_convert (type
, res
, at_stmt
);
1825 chrec1
= analyze_scalar_evolution (loop
, rhs1
);
1827 /* When the stmt is conditionally executed re-write the CHREC
1828 into a form that has well-defined behavior on overflow. */
1830 && INTEGRAL_TYPE_P (type
)
1831 && ! TYPE_OVERFLOW_WRAPS (type
)
1832 && ! dominated_by_p (CDI_DOMINATORS
,
1833 loop
->latch
, gimple_bb (at_stmt
)))
1834 ctype
= unsigned_type_for (type
);
1835 chrec1
= chrec_convert (ctype
, chrec1
, at_stmt
);
1836 /* TYPE may be integer, real or complex, so use fold_convert. */
1837 chrec1
= instantiate_parameters (loop
, chrec1
);
1838 res
= chrec_fold_multiply (ctype
, chrec1
,
1839 fold_convert (ctype
, integer_minus_one_node
));
1841 res
= chrec_convert (type
, res
, at_stmt
);
1845 /* Handle ~X as -1 - X. */
1846 chrec1
= analyze_scalar_evolution (loop
, rhs1
);
1847 chrec1
= chrec_convert (type
, chrec1
, at_stmt
);
1848 chrec1
= instantiate_parameters (loop
, chrec1
);
1849 res
= chrec_fold_minus (type
,
1850 fold_convert (type
, integer_minus_one_node
),
1855 chrec1
= analyze_scalar_evolution (loop
, rhs1
);
1856 chrec2
= analyze_scalar_evolution (loop
, rhs2
);
1858 /* When the stmt is conditionally executed re-write the CHREC
1859 into a form that has well-defined behavior on overflow. */
1861 && INTEGRAL_TYPE_P (type
)
1862 && ! TYPE_OVERFLOW_WRAPS (type
)
1863 && ! dominated_by_p (CDI_DOMINATORS
,
1864 loop
->latch
, gimple_bb (at_stmt
)))
1865 ctype
= unsigned_type_for (type
);
1866 chrec1
= chrec_convert (ctype
, chrec1
, at_stmt
);
1867 chrec2
= chrec_convert (ctype
, chrec2
, at_stmt
);
1868 chrec1
= instantiate_parameters (loop
, chrec1
);
1869 chrec2
= instantiate_parameters (loop
, chrec2
);
1870 res
= chrec_fold_multiply (ctype
, chrec1
, chrec2
);
1872 res
= chrec_convert (type
, res
, at_stmt
);
1877 /* Handle A<<B as A * (1<<B). */
1878 tree uns
= unsigned_type_for (type
);
1879 chrec1
= analyze_scalar_evolution (loop
, rhs1
);
1880 chrec2
= analyze_scalar_evolution (loop
, rhs2
);
1881 chrec1
= chrec_convert (uns
, chrec1
, at_stmt
);
1882 chrec1
= instantiate_parameters (loop
, chrec1
);
1883 chrec2
= instantiate_parameters (loop
, chrec2
);
1885 tree one
= build_int_cst (uns
, 1);
1886 chrec2
= fold_build2 (LSHIFT_EXPR
, uns
, one
, chrec2
);
1887 res
= chrec_fold_multiply (uns
, chrec1
, chrec2
);
1888 res
= chrec_convert (type
, res
, at_stmt
);
1893 /* In case we have a truncation of a widened operation that in
1894 the truncated type has undefined overflow behavior analyze
1895 the operation done in an unsigned type of the same precision
1896 as the final truncation. We cannot derive a scalar evolution
1897 for the widened operation but for the truncated result. */
1898 if (TREE_CODE (type
) == INTEGER_TYPE
1899 && TREE_CODE (TREE_TYPE (rhs1
)) == INTEGER_TYPE
1900 && TYPE_PRECISION (type
) < TYPE_PRECISION (TREE_TYPE (rhs1
))
1901 && TYPE_OVERFLOW_UNDEFINED (type
)
1902 && TREE_CODE (rhs1
) == SSA_NAME
1903 && (def
= SSA_NAME_DEF_STMT (rhs1
))
1904 && is_gimple_assign (def
)
1905 && TREE_CODE_CLASS (gimple_assign_rhs_code (def
)) == tcc_binary
1906 && TREE_CODE (gimple_assign_rhs2 (def
)) == INTEGER_CST
)
1908 tree utype
= unsigned_type_for (type
);
1909 chrec1
= interpret_rhs_expr (loop
, at_stmt
, utype
,
1910 gimple_assign_rhs1 (def
),
1911 gimple_assign_rhs_code (def
),
1912 gimple_assign_rhs2 (def
));
1915 chrec1
= analyze_scalar_evolution (loop
, rhs1
);
1916 res
= chrec_convert (type
, chrec1
, at_stmt
, true, rhs1
);
1920 /* Given int variable A, handle A&0xffff as (int)(unsigned short)A.
1921 If A is SCEV and its value is in the range of representable set
1922 of type unsigned short, the result expression is a (no-overflow)
1924 res
= chrec_dont_know
;
1925 if (tree_fits_uhwi_p (rhs2
))
1928 unsigned HOST_WIDE_INT val
= tree_to_uhwi (rhs2
);
1931 /* Skip if value of rhs2 wraps in unsigned HOST_WIDE_INT or
1932 it's not the maximum value of a smaller type than rhs1. */
1934 && (precision
= exact_log2 (val
)) > 0
1935 && (unsigned) precision
< TYPE_PRECISION (TREE_TYPE (rhs1
)))
1937 tree utype
= build_nonstandard_integer_type (precision
, 1);
1939 if (TYPE_PRECISION (utype
) < TYPE_PRECISION (TREE_TYPE (rhs1
)))
1941 chrec1
= analyze_scalar_evolution (loop
, rhs1
);
1942 chrec1
= chrec_convert (utype
, chrec1
, at_stmt
);
1943 res
= chrec_convert (TREE_TYPE (rhs1
), chrec1
, at_stmt
);
1950 res
= chrec_dont_know
;
1957 /* Interpret the expression EXPR. */
1960 interpret_expr (struct loop
*loop
, gimple
*at_stmt
, tree expr
)
1962 enum tree_code code
;
1963 tree type
= TREE_TYPE (expr
), op0
, op1
;
1965 if (automatically_generated_chrec_p (expr
))
1968 if (TREE_CODE (expr
) == POLYNOMIAL_CHREC
1969 || TREE_CODE (expr
) == CALL_EXPR
1970 || get_gimple_rhs_class (TREE_CODE (expr
)) == GIMPLE_TERNARY_RHS
)
1971 return chrec_dont_know
;
1973 extract_ops_from_tree (expr
, &code
, &op0
, &op1
);
1975 return interpret_rhs_expr (loop
, at_stmt
, type
,
1979 /* Interpret the rhs of the assignment STMT. */
1982 interpret_gimple_assign (struct loop
*loop
, gimple
*stmt
)
1984 tree type
= TREE_TYPE (gimple_assign_lhs (stmt
));
1985 enum tree_code code
= gimple_assign_rhs_code (stmt
);
1987 return interpret_rhs_expr (loop
, stmt
, type
,
1988 gimple_assign_rhs1 (stmt
), code
,
1989 gimple_assign_rhs2 (stmt
));
1994 /* This section contains all the entry points:
1995 - number_of_iterations_in_loop,
1996 - analyze_scalar_evolution,
1997 - instantiate_parameters.
2000 /* Helper recursive function. */
2003 analyze_scalar_evolution_1 (struct loop
*loop
, tree var
)
2007 struct loop
*def_loop
;
2010 if (TREE_CODE (var
) != SSA_NAME
)
2011 return interpret_expr (loop
, NULL
, var
);
2013 def
= SSA_NAME_DEF_STMT (var
);
2014 bb
= gimple_bb (def
);
2015 def_loop
= bb
->loop_father
;
2017 if (!flow_bb_inside_loop_p (loop
, bb
))
2019 /* Keep symbolic form, but look through obvious copies for constants. */
2020 res
= follow_copies_to_constant (var
);
2024 if (loop
!= def_loop
)
2026 res
= analyze_scalar_evolution_1 (def_loop
, var
);
2027 struct loop
*loop_to_skip
= superloop_at_depth (def_loop
,
2028 loop_depth (loop
) + 1);
2029 res
= compute_overall_effect_of_inner_loop (loop_to_skip
, res
);
2030 if (chrec_contains_symbols_defined_in_loop (res
, loop
->num
))
2031 res
= analyze_scalar_evolution_1 (loop
, res
);
2035 switch (gimple_code (def
))
2038 res
= interpret_gimple_assign (loop
, def
);
2042 if (loop_phi_node_p (def
))
2043 res
= interpret_loop_phi (loop
, as_a
<gphi
*> (def
));
2045 res
= interpret_condition_phi (loop
, as_a
<gphi
*> (def
));
2049 res
= chrec_dont_know
;
2055 /* Keep the symbolic form. */
2056 if (res
== chrec_dont_know
)
2059 if (loop
== def_loop
)
2060 set_scalar_evolution (block_before_loop (loop
), var
, res
);
2065 /* Analyzes and returns the scalar evolution of the ssa_name VAR in
2066 LOOP. LOOP is the loop in which the variable is used.
2068 Example of use: having a pointer VAR to a SSA_NAME node, STMT a
2069 pointer to the statement that uses this variable, in order to
2070 determine the evolution function of the variable, use the following
2073 loop_p loop = loop_containing_stmt (stmt);
2074 tree chrec_with_symbols = analyze_scalar_evolution (loop, var);
2075 tree chrec_instantiated = instantiate_parameters (loop, chrec_with_symbols);
2079 analyze_scalar_evolution (struct loop
*loop
, tree var
)
2083 /* ??? Fix callers. */
2087 if (dump_file
&& (dump_flags
& TDF_SCEV
))
2089 fprintf (dump_file
, "(analyze_scalar_evolution \n");
2090 fprintf (dump_file
, " (loop_nb = %d)\n", loop
->num
);
2091 fprintf (dump_file
, " (scalar = ");
2092 print_generic_expr (dump_file
, var
);
2093 fprintf (dump_file
, ")\n");
2096 res
= get_scalar_evolution (block_before_loop (loop
), var
);
2097 if (res
== chrec_not_analyzed_yet
)
2099 /* We'll recurse into instantiate_scev, avoid tearing down the
2100 instantiate cache repeatedly and keep it live from here. */
2104 global_cache
= new instantiate_cache_type
;
2107 res
= analyze_scalar_evolution_1 (loop
, var
);
2110 delete global_cache
;
2111 global_cache
= NULL
;
2115 if (dump_file
&& (dump_flags
& TDF_SCEV
))
2116 fprintf (dump_file
, ")\n");
2121 /* Analyzes and returns the scalar evolution of VAR address in LOOP. */
2124 analyze_scalar_evolution_for_address_of (struct loop
*loop
, tree var
)
2126 return analyze_scalar_evolution (loop
, build_fold_addr_expr (var
));
2129 /* Analyze scalar evolution of use of VERSION in USE_LOOP with respect to
2130 WRTO_LOOP (which should be a superloop of USE_LOOP)
2132 FOLDED_CASTS is set to true if resolve_mixers used
2133 chrec_convert_aggressive (TODO -- not really, we are way too conservative
2134 at the moment in order to keep things simple).
2136 To illustrate the meaning of USE_LOOP and WRTO_LOOP, consider the following
2139 for (i = 0; i < 100; i++) -- loop 1
2141 for (j = 0; j < 100; j++) -- loop 2
2148 for (t = 0; t < 100; t++) -- loop 3
2155 Both k1 and k2 are invariants in loop3, thus
2156 analyze_scalar_evolution_in_loop (loop3, loop3, k1) = k1
2157 analyze_scalar_evolution_in_loop (loop3, loop3, k2) = k2
2159 As they are invariant, it does not matter whether we consider their
2160 usage in loop 3 or loop 2, hence
2161 analyze_scalar_evolution_in_loop (loop2, loop3, k1) =
2162 analyze_scalar_evolution_in_loop (loop2, loop2, k1) = i
2163 analyze_scalar_evolution_in_loop (loop2, loop3, k2) =
2164 analyze_scalar_evolution_in_loop (loop2, loop2, k2) = [0,+,1]_2
2166 Similarly for their evolutions with respect to loop 1. The values of K2
2167 in the use in loop 2 vary independently on loop 1, thus we cannot express
2168 the evolution with respect to loop 1:
2169 analyze_scalar_evolution_in_loop (loop1, loop3, k1) =
2170 analyze_scalar_evolution_in_loop (loop1, loop2, k1) = [0,+,1]_1
2171 analyze_scalar_evolution_in_loop (loop1, loop3, k2) =
2172 analyze_scalar_evolution_in_loop (loop1, loop2, k2) = dont_know
2174 The value of k2 in the use in loop 1 is known, though:
2175 analyze_scalar_evolution_in_loop (loop1, loop1, k1) = [0,+,1]_1
2176 analyze_scalar_evolution_in_loop (loop1, loop1, k2) = 100
2180 analyze_scalar_evolution_in_loop (struct loop
*wrto_loop
, struct loop
*use_loop
,
2181 tree version
, bool *folded_casts
)
2184 tree ev
= version
, tmp
;
2186 /* We cannot just do
2188 tmp = analyze_scalar_evolution (use_loop, version);
2189 ev = resolve_mixers (wrto_loop, tmp, folded_casts);
2191 as resolve_mixers would query the scalar evolution with respect to
2192 wrto_loop. For example, in the situation described in the function
2193 comment, suppose that wrto_loop = loop1, use_loop = loop3 and
2196 analyze_scalar_evolution (use_loop, version) = k2
2198 and resolve_mixers (loop1, k2, folded_casts) finds that the value of
2199 k2 in loop 1 is 100, which is a wrong result, since we are interested
2200 in the value in loop 3.
2202 Instead, we need to proceed from use_loop to wrto_loop loop by loop,
2203 each time checking that there is no evolution in the inner loop. */
2206 *folded_casts
= false;
2209 tmp
= analyze_scalar_evolution (use_loop
, ev
);
2210 ev
= resolve_mixers (use_loop
, tmp
, folded_casts
);
2212 if (use_loop
== wrto_loop
)
2215 /* If the value of the use changes in the inner loop, we cannot express
2216 its value in the outer loop (we might try to return interval chrec,
2217 but we do not have a user for it anyway) */
2218 if (!no_evolution_in_loop_p (ev
, use_loop
->num
, &val
)
2220 return chrec_dont_know
;
2222 use_loop
= loop_outer (use_loop
);
2227 /* Computes a hash function for database element ELT. */
2229 static inline hashval_t
2230 hash_idx_scev_info (const void *elt_
)
2232 unsigned idx
= ((size_t) elt_
) - 2;
2233 return scev_info_hasher::hash (&global_cache
->entries
[idx
]);
2236 /* Compares database elements E1 and E2. */
2239 eq_idx_scev_info (const void *e1
, const void *e2
)
2241 unsigned idx1
= ((size_t) e1
) - 2;
2242 return scev_info_hasher::equal (&global_cache
->entries
[idx1
],
2243 (const scev_info_str
*) e2
);
2246 /* Returns from CACHE the slot number of the cached chrec for NAME. */
2249 get_instantiated_value_entry (instantiate_cache_type
&cache
,
2250 tree name
, edge instantiate_below
)
2254 cache
.map
= htab_create (10, hash_idx_scev_info
, eq_idx_scev_info
, NULL
);
2255 cache
.entries
.create (10);
2259 e
.name_version
= SSA_NAME_VERSION (name
);
2260 e
.instantiated_below
= instantiate_below
->dest
->index
;
2261 void **slot
= htab_find_slot_with_hash (cache
.map
, &e
,
2262 scev_info_hasher::hash (&e
), INSERT
);
2265 e
.chrec
= chrec_not_analyzed_yet
;
2266 *slot
= (void *)(size_t)(cache
.entries
.length () + 2);
2267 cache
.entries
.safe_push (e
);
2270 return ((size_t)*slot
) - 2;
2274 /* Return the closed_loop_phi node for VAR. If there is none, return
2278 loop_closed_phi_def (tree var
)
2285 if (var
== NULL_TREE
2286 || TREE_CODE (var
) != SSA_NAME
)
2289 loop
= loop_containing_stmt (SSA_NAME_DEF_STMT (var
));
2290 exit
= single_exit (loop
);
2294 for (psi
= gsi_start_phis (exit
->dest
); !gsi_end_p (psi
); gsi_next (&psi
))
2297 if (PHI_ARG_DEF_FROM_EDGE (phi
, exit
) == var
)
2298 return PHI_RESULT (phi
);
2304 static tree
instantiate_scev_r (edge
, struct loop
*, struct loop
*,
2307 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2308 and EVOLUTION_LOOP, that were left under a symbolic form.
2310 CHREC is an SSA_NAME to be instantiated.
2312 CACHE is the cache of already instantiated values.
2314 Variable pointed by FOLD_CONVERSIONS is set to TRUE when the
2315 conversions that may wrap in signed/pointer type are folded, as long
2316 as the value of the chrec is preserved. If FOLD_CONVERSIONS is NULL
2317 then we don't do such fold.
2319 SIZE_EXPR is used for computing the size of the expression to be
2320 instantiated, and to stop if it exceeds some limit. */
2323 instantiate_scev_name (edge instantiate_below
,
2324 struct loop
*evolution_loop
, struct loop
*inner_loop
,
2326 bool *fold_conversions
,
2330 struct loop
*def_loop
;
2331 basic_block def_bb
= gimple_bb (SSA_NAME_DEF_STMT (chrec
));
2333 /* A parameter, nothing to do. */
2335 || !dominated_by_p (CDI_DOMINATORS
, def_bb
, instantiate_below
->dest
))
2338 /* We cache the value of instantiated variable to avoid exponential
2339 time complexity due to reevaluations. We also store the convenient
2340 value in the cache in order to prevent infinite recursion -- we do
2341 not want to instantiate the SSA_NAME if it is in a mixer
2342 structure. This is used for avoiding the instantiation of
2343 recursively defined functions, such as:
2345 | a_2 -> {0, +, 1, +, a_2}_1 */
2347 unsigned si
= get_instantiated_value_entry (*global_cache
,
2348 chrec
, instantiate_below
);
2349 if (global_cache
->get (si
) != chrec_not_analyzed_yet
)
2350 return global_cache
->get (si
);
2352 /* On recursion return chrec_dont_know. */
2353 global_cache
->set (si
, chrec_dont_know
);
2355 def_loop
= find_common_loop (evolution_loop
, def_bb
->loop_father
);
2357 if (! dominated_by_p (CDI_DOMINATORS
,
2358 def_loop
->header
, instantiate_below
->dest
))
2360 gimple
*def
= SSA_NAME_DEF_STMT (chrec
);
2361 if (gassign
*ass
= dyn_cast
<gassign
*> (def
))
2363 switch (gimple_assign_rhs_class (ass
))
2365 case GIMPLE_UNARY_RHS
:
2367 tree op0
= instantiate_scev_r (instantiate_below
, evolution_loop
,
2368 inner_loop
, gimple_assign_rhs1 (ass
),
2369 fold_conversions
, size_expr
);
2370 if (op0
== chrec_dont_know
)
2371 return chrec_dont_know
;
2372 res
= fold_build1 (gimple_assign_rhs_code (ass
),
2373 TREE_TYPE (chrec
), op0
);
2376 case GIMPLE_BINARY_RHS
:
2378 tree op0
= instantiate_scev_r (instantiate_below
, evolution_loop
,
2379 inner_loop
, gimple_assign_rhs1 (ass
),
2380 fold_conversions
, size_expr
);
2381 if (op0
== chrec_dont_know
)
2382 return chrec_dont_know
;
2383 tree op1
= instantiate_scev_r (instantiate_below
, evolution_loop
,
2384 inner_loop
, gimple_assign_rhs2 (ass
),
2385 fold_conversions
, size_expr
);
2386 if (op1
== chrec_dont_know
)
2387 return chrec_dont_know
;
2388 res
= fold_build2 (gimple_assign_rhs_code (ass
),
2389 TREE_TYPE (chrec
), op0
, op1
);
2393 res
= chrec_dont_know
;
2397 res
= chrec_dont_know
;
2398 global_cache
->set (si
, res
);
2402 /* If the analysis yields a parametric chrec, instantiate the
2404 res
= analyze_scalar_evolution (def_loop
, chrec
);
2406 /* Don't instantiate default definitions. */
2407 if (TREE_CODE (res
) == SSA_NAME
2408 && SSA_NAME_IS_DEFAULT_DEF (res
))
2411 /* Don't instantiate loop-closed-ssa phi nodes. */
2412 else if (TREE_CODE (res
) == SSA_NAME
2413 && loop_depth (loop_containing_stmt (SSA_NAME_DEF_STMT (res
)))
2414 > loop_depth (def_loop
))
2417 res
= loop_closed_phi_def (chrec
);
2421 /* When there is no loop_closed_phi_def, it means that the
2422 variable is not used after the loop: try to still compute the
2423 value of the variable when exiting the loop. */
2424 if (res
== NULL_TREE
)
2426 loop_p loop
= loop_containing_stmt (SSA_NAME_DEF_STMT (chrec
));
2427 res
= analyze_scalar_evolution (loop
, chrec
);
2428 res
= compute_overall_effect_of_inner_loop (loop
, res
);
2429 res
= instantiate_scev_r (instantiate_below
, evolution_loop
,
2431 fold_conversions
, size_expr
);
2433 else if (dominated_by_p (CDI_DOMINATORS
,
2434 gimple_bb (SSA_NAME_DEF_STMT (res
)),
2435 instantiate_below
->dest
))
2436 res
= chrec_dont_know
;
2439 else if (res
!= chrec_dont_know
)
2442 && def_bb
->loop_father
!= inner_loop
2443 && !flow_loop_nested_p (def_bb
->loop_father
, inner_loop
))
2444 /* ??? We could try to compute the overall effect of the loop here. */
2445 res
= chrec_dont_know
;
2447 res
= instantiate_scev_r (instantiate_below
, evolution_loop
,
2449 fold_conversions
, size_expr
);
2452 /* Store the correct value to the cache. */
2453 global_cache
->set (si
, res
);
2457 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2458 and EVOLUTION_LOOP, that were left under a symbolic form.
2460 CHREC is a polynomial chain of recurrence to be instantiated.
2462 CACHE is the cache of already instantiated values.
2464 Variable pointed by FOLD_CONVERSIONS is set to TRUE when the
2465 conversions that may wrap in signed/pointer type are folded, as long
2466 as the value of the chrec is preserved. If FOLD_CONVERSIONS is NULL
2467 then we don't do such fold.
2469 SIZE_EXPR is used for computing the size of the expression to be
2470 instantiated, and to stop if it exceeds some limit. */
2473 instantiate_scev_poly (edge instantiate_below
,
2474 struct loop
*evolution_loop
, struct loop
*,
2475 tree chrec
, bool *fold_conversions
, int size_expr
)
2478 tree op0
= instantiate_scev_r (instantiate_below
, evolution_loop
,
2479 get_chrec_loop (chrec
),
2480 CHREC_LEFT (chrec
), fold_conversions
,
2482 if (op0
== chrec_dont_know
)
2483 return chrec_dont_know
;
2485 op1
= instantiate_scev_r (instantiate_below
, evolution_loop
,
2486 get_chrec_loop (chrec
),
2487 CHREC_RIGHT (chrec
), fold_conversions
,
2489 if (op1
== chrec_dont_know
)
2490 return chrec_dont_know
;
2492 if (CHREC_LEFT (chrec
) != op0
2493 || CHREC_RIGHT (chrec
) != op1
)
2495 op1
= chrec_convert_rhs (chrec_type (op0
), op1
, NULL
);
2496 chrec
= build_polynomial_chrec (CHREC_VARIABLE (chrec
), op0
, op1
);
2502 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2503 and EVOLUTION_LOOP, that were left under a symbolic form.
2505 "C0 CODE C1" is a binary expression of type TYPE to be instantiated.
2507 CACHE is the cache of already instantiated values.
2509 Variable pointed by FOLD_CONVERSIONS is set to TRUE when the
2510 conversions that may wrap in signed/pointer type are folded, as long
2511 as the value of the chrec is preserved. If FOLD_CONVERSIONS is NULL
2512 then we don't do such fold.
2514 SIZE_EXPR is used for computing the size of the expression to be
2515 instantiated, and to stop if it exceeds some limit. */
2518 instantiate_scev_binary (edge instantiate_below
,
2519 struct loop
*evolution_loop
, struct loop
*inner_loop
,
2520 tree chrec
, enum tree_code code
,
2521 tree type
, tree c0
, tree c1
,
2522 bool *fold_conversions
, int size_expr
)
2525 tree op0
= instantiate_scev_r (instantiate_below
, evolution_loop
, inner_loop
,
2526 c0
, fold_conversions
, size_expr
);
2527 if (op0
== chrec_dont_know
)
2528 return chrec_dont_know
;
2530 /* While we eventually compute the same op1 if c0 == c1 the process
2531 of doing this is expensive so the following short-cut prevents
2532 exponential compile-time behavior. */
2535 op1
= instantiate_scev_r (instantiate_below
, evolution_loop
, inner_loop
,
2536 c1
, fold_conversions
, size_expr
);
2537 if (op1
== chrec_dont_know
)
2538 return chrec_dont_know
;
2546 op0
= chrec_convert (type
, op0
, NULL
);
2547 op1
= chrec_convert_rhs (type
, op1
, NULL
);
2551 case POINTER_PLUS_EXPR
:
2553 return chrec_fold_plus (type
, op0
, op1
);
2556 return chrec_fold_minus (type
, op0
, op1
);
2559 return chrec_fold_multiply (type
, op0
, op1
);
2566 return chrec
? chrec
: fold_build2 (code
, type
, c0
, c1
);
2569 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2570 and EVOLUTION_LOOP, that were left under a symbolic form.
2572 "CHREC" that stands for a convert expression "(TYPE) OP" is to be
2575 CACHE is the cache of already instantiated values.
2577 Variable pointed by FOLD_CONVERSIONS is set to TRUE when the
2578 conversions that may wrap in signed/pointer type are folded, as long
2579 as the value of the chrec is preserved. If FOLD_CONVERSIONS is NULL
2580 then we don't do such fold.
2582 SIZE_EXPR is used for computing the size of the expression to be
2583 instantiated, and to stop if it exceeds some limit. */
2586 instantiate_scev_convert (edge instantiate_below
,
2587 struct loop
*evolution_loop
, struct loop
*inner_loop
,
2588 tree chrec
, tree type
, tree op
,
2589 bool *fold_conversions
, int size_expr
)
2591 tree op0
= instantiate_scev_r (instantiate_below
, evolution_loop
,
2593 fold_conversions
, size_expr
);
2595 if (op0
== chrec_dont_know
)
2596 return chrec_dont_know
;
2598 if (fold_conversions
)
2600 tree tmp
= chrec_convert_aggressive (type
, op0
, fold_conversions
);
2604 /* If we used chrec_convert_aggressive, we can no longer assume that
2605 signed chrecs do not overflow, as chrec_convert does, so avoid
2606 calling it in that case. */
2607 if (*fold_conversions
)
2609 if (chrec
&& op0
== op
)
2612 return fold_convert (type
, op0
);
2616 return chrec_convert (type
, op0
, NULL
);
2619 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2620 and EVOLUTION_LOOP, that were left under a symbolic form.
2622 CHREC is a BIT_NOT_EXPR or a NEGATE_EXPR expression to be instantiated.
2623 Handle ~X as -1 - X.
2624 Handle -X as -1 * X.
2626 CACHE is the cache of already instantiated values.
2628 Variable pointed by FOLD_CONVERSIONS is set to TRUE when the
2629 conversions that may wrap in signed/pointer type are folded, as long
2630 as the value of the chrec is preserved. If FOLD_CONVERSIONS is NULL
2631 then we don't do such fold.
2633 SIZE_EXPR is used for computing the size of the expression to be
2634 instantiated, and to stop if it exceeds some limit. */
2637 instantiate_scev_not (edge instantiate_below
,
2638 struct loop
*evolution_loop
, struct loop
*inner_loop
,
2640 enum tree_code code
, tree type
, tree op
,
2641 bool *fold_conversions
, int size_expr
)
2643 tree op0
= instantiate_scev_r (instantiate_below
, evolution_loop
,
2645 fold_conversions
, size_expr
);
2647 if (op0
== chrec_dont_know
)
2648 return chrec_dont_know
;
2652 op0
= chrec_convert (type
, op0
, NULL
);
2657 return chrec_fold_minus
2658 (type
, fold_convert (type
, integer_minus_one_node
), op0
);
2661 return chrec_fold_multiply
2662 (type
, fold_convert (type
, integer_minus_one_node
), op0
);
2669 return chrec
? chrec
: fold_build1 (code
, type
, op0
);
2672 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2673 and EVOLUTION_LOOP, that were left under a symbolic form.
2675 CHREC is the scalar evolution to instantiate.
2677 CACHE is the cache of already instantiated values.
2679 Variable pointed by FOLD_CONVERSIONS is set to TRUE when the
2680 conversions that may wrap in signed/pointer type are folded, as long
2681 as the value of the chrec is preserved. If FOLD_CONVERSIONS is NULL
2682 then we don't do such fold.
2684 SIZE_EXPR is used for computing the size of the expression to be
2685 instantiated, and to stop if it exceeds some limit. */
2688 instantiate_scev_r (edge instantiate_below
,
2689 struct loop
*evolution_loop
, struct loop
*inner_loop
,
2691 bool *fold_conversions
, int size_expr
)
2693 /* Give up if the expression is larger than the MAX that we allow. */
2694 if (size_expr
++ > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_SIZE
))
2695 return chrec_dont_know
;
2697 if (chrec
== NULL_TREE
2698 || automatically_generated_chrec_p (chrec
)
2699 || is_gimple_min_invariant (chrec
))
2702 switch (TREE_CODE (chrec
))
2705 return instantiate_scev_name (instantiate_below
, evolution_loop
,
2707 fold_conversions
, size_expr
);
2709 case POLYNOMIAL_CHREC
:
2710 return instantiate_scev_poly (instantiate_below
, evolution_loop
,
2712 fold_conversions
, size_expr
);
2714 case POINTER_PLUS_EXPR
:
2718 return instantiate_scev_binary (instantiate_below
, evolution_loop
,
2720 TREE_CODE (chrec
), chrec_type (chrec
),
2721 TREE_OPERAND (chrec
, 0),
2722 TREE_OPERAND (chrec
, 1),
2723 fold_conversions
, size_expr
);
2726 return instantiate_scev_convert (instantiate_below
, evolution_loop
,
2728 TREE_TYPE (chrec
), TREE_OPERAND (chrec
, 0),
2729 fold_conversions
, size_expr
);
2733 return instantiate_scev_not (instantiate_below
, evolution_loop
,
2735 TREE_CODE (chrec
), TREE_TYPE (chrec
),
2736 TREE_OPERAND (chrec
, 0),
2737 fold_conversions
, size_expr
);
2740 if (is_gimple_min_invariant (chrec
))
2743 case SCEV_NOT_KNOWN
:
2744 return chrec_dont_know
;
2750 if (CONSTANT_CLASS_P (chrec
))
2752 return chrec_dont_know
;
2756 /* Analyze all the parameters of the chrec that were left under a
2757 symbolic form. INSTANTIATE_BELOW is the basic block that stops the
2758 recursive instantiation of parameters: a parameter is a variable
2759 that is defined in a basic block that dominates INSTANTIATE_BELOW or
2760 a function parameter. */
2763 instantiate_scev (edge instantiate_below
, struct loop
*evolution_loop
,
2768 if (dump_file
&& (dump_flags
& TDF_SCEV
))
2770 fprintf (dump_file
, "(instantiate_scev \n");
2771 fprintf (dump_file
, " (instantiate_below = %d -> %d)\n",
2772 instantiate_below
->src
->index
, instantiate_below
->dest
->index
);
2774 fprintf (dump_file
, " (evolution_loop = %d)\n", evolution_loop
->num
);
2775 fprintf (dump_file
, " (chrec = ");
2776 print_generic_expr (dump_file
, chrec
);
2777 fprintf (dump_file
, ")\n");
2783 global_cache
= new instantiate_cache_type
;
2787 res
= instantiate_scev_r (instantiate_below
, evolution_loop
,
2788 NULL
, chrec
, NULL
, 0);
2792 delete global_cache
;
2793 global_cache
= NULL
;
2796 if (dump_file
&& (dump_flags
& TDF_SCEV
))
2798 fprintf (dump_file
, " (res = ");
2799 print_generic_expr (dump_file
, res
);
2800 fprintf (dump_file
, "))\n");
2806 /* Similar to instantiate_parameters, but does not introduce the
2807 evolutions in outer loops for LOOP invariants in CHREC, and does not
2808 care about causing overflows, as long as they do not affect value
2809 of an expression. */
2812 resolve_mixers (struct loop
*loop
, tree chrec
, bool *folded_casts
)
2815 bool fold_conversions
= false;
2818 global_cache
= new instantiate_cache_type
;
2822 tree ret
= instantiate_scev_r (loop_preheader_edge (loop
), loop
, NULL
,
2823 chrec
, &fold_conversions
, 0);
2825 if (folded_casts
&& !*folded_casts
)
2826 *folded_casts
= fold_conversions
;
2830 delete global_cache
;
2831 global_cache
= NULL
;
2837 /* Entry point for the analysis of the number of iterations pass.
2838 This function tries to safely approximate the number of iterations
2839 the loop will run. When this property is not decidable at compile
2840 time, the result is chrec_dont_know. Otherwise the result is a
2841 scalar or a symbolic parameter. When the number of iterations may
2842 be equal to zero and the property cannot be determined at compile
2843 time, the result is a COND_EXPR that represents in a symbolic form
2844 the conditions under which the number of iterations is not zero.
2846 Example of analysis: suppose that the loop has an exit condition:
2848 "if (b > 49) goto end_loop;"
2850 and that in a previous analysis we have determined that the
2851 variable 'b' has an evolution function:
2853 "EF = {23, +, 5}_2".
2855 When we evaluate the function at the point 5, i.e. the value of the
2856 variable 'b' after 5 iterations in the loop, we have EF (5) = 48,
2857 and EF (6) = 53. In this case the value of 'b' on exit is '53' and
2858 the loop body has been executed 6 times. */
2861 number_of_latch_executions (struct loop
*loop
)
2864 struct tree_niter_desc niter_desc
;
2868 /* Determine whether the number of iterations in loop has already
2870 res
= loop
->nb_iterations
;
2874 may_be_zero
= NULL_TREE
;
2876 if (dump_file
&& (dump_flags
& TDF_SCEV
))
2877 fprintf (dump_file
, "(number_of_iterations_in_loop = \n");
2879 res
= chrec_dont_know
;
2880 exit
= single_exit (loop
);
2882 if (exit
&& number_of_iterations_exit (loop
, exit
, &niter_desc
, false))
2884 may_be_zero
= niter_desc
.may_be_zero
;
2885 res
= niter_desc
.niter
;
2888 if (res
== chrec_dont_know
2890 || integer_zerop (may_be_zero
))
2892 else if (integer_nonzerop (may_be_zero
))
2893 res
= build_int_cst (TREE_TYPE (res
), 0);
2895 else if (COMPARISON_CLASS_P (may_be_zero
))
2896 res
= fold_build3 (COND_EXPR
, TREE_TYPE (res
), may_be_zero
,
2897 build_int_cst (TREE_TYPE (res
), 0), res
);
2899 res
= chrec_dont_know
;
2901 if (dump_file
&& (dump_flags
& TDF_SCEV
))
2903 fprintf (dump_file
, " (set_nb_iterations_in_loop = ");
2904 print_generic_expr (dump_file
, res
);
2905 fprintf (dump_file
, "))\n");
2908 loop
->nb_iterations
= res
;
2913 /* Counters for the stats. */
2919 unsigned nb_affine_multivar
;
2920 unsigned nb_higher_poly
;
2921 unsigned nb_chrec_dont_know
;
2922 unsigned nb_undetermined
;
2925 /* Reset the counters. */
2928 reset_chrecs_counters (struct chrec_stats
*stats
)
2930 stats
->nb_chrecs
= 0;
2931 stats
->nb_affine
= 0;
2932 stats
->nb_affine_multivar
= 0;
2933 stats
->nb_higher_poly
= 0;
2934 stats
->nb_chrec_dont_know
= 0;
2935 stats
->nb_undetermined
= 0;
2938 /* Dump the contents of a CHREC_STATS structure. */
2941 dump_chrecs_stats (FILE *file
, struct chrec_stats
*stats
)
2943 fprintf (file
, "\n(\n");
2944 fprintf (file
, "-----------------------------------------\n");
2945 fprintf (file
, "%d\taffine univariate chrecs\n", stats
->nb_affine
);
2946 fprintf (file
, "%d\taffine multivariate chrecs\n", stats
->nb_affine_multivar
);
2947 fprintf (file
, "%d\tdegree greater than 2 polynomials\n",
2948 stats
->nb_higher_poly
);
2949 fprintf (file
, "%d\tchrec_dont_know chrecs\n", stats
->nb_chrec_dont_know
);
2950 fprintf (file
, "-----------------------------------------\n");
2951 fprintf (file
, "%d\ttotal chrecs\n", stats
->nb_chrecs
);
2952 fprintf (file
, "%d\twith undetermined coefficients\n",
2953 stats
->nb_undetermined
);
2954 fprintf (file
, "-----------------------------------------\n");
2955 fprintf (file
, "%d\tchrecs in the scev database\n",
2956 (int) scalar_evolution_info
->elements ());
2957 fprintf (file
, "%d\tsets in the scev database\n", nb_set_scev
);
2958 fprintf (file
, "%d\tgets in the scev database\n", nb_get_scev
);
2959 fprintf (file
, "-----------------------------------------\n");
2960 fprintf (file
, ")\n\n");
2963 /* Gather statistics about CHREC. */
2966 gather_chrec_stats (tree chrec
, struct chrec_stats
*stats
)
2968 if (dump_file
&& (dump_flags
& TDF_STATS
))
2970 fprintf (dump_file
, "(classify_chrec ");
2971 print_generic_expr (dump_file
, chrec
);
2972 fprintf (dump_file
, "\n");
2977 if (chrec
== NULL_TREE
)
2979 stats
->nb_undetermined
++;
2983 switch (TREE_CODE (chrec
))
2985 case POLYNOMIAL_CHREC
:
2986 if (evolution_function_is_affine_p (chrec
))
2988 if (dump_file
&& (dump_flags
& TDF_STATS
))
2989 fprintf (dump_file
, " affine_univariate\n");
2992 else if (evolution_function_is_affine_multivariate_p (chrec
, 0))
2994 if (dump_file
&& (dump_flags
& TDF_STATS
))
2995 fprintf (dump_file
, " affine_multivariate\n");
2996 stats
->nb_affine_multivar
++;
3000 if (dump_file
&& (dump_flags
& TDF_STATS
))
3001 fprintf (dump_file
, " higher_degree_polynomial\n");
3002 stats
->nb_higher_poly
++;
3011 if (chrec_contains_undetermined (chrec
))
3013 if (dump_file
&& (dump_flags
& TDF_STATS
))
3014 fprintf (dump_file
, " undetermined\n");
3015 stats
->nb_undetermined
++;
3018 if (dump_file
&& (dump_flags
& TDF_STATS
))
3019 fprintf (dump_file
, ")\n");
3022 /* Classify the chrecs of the whole database. */
3025 gather_stats_on_scev_database (void)
3027 struct chrec_stats stats
;
3032 reset_chrecs_counters (&stats
);
3034 hash_table
<scev_info_hasher
>::iterator iter
;
3036 FOR_EACH_HASH_TABLE_ELEMENT (*scalar_evolution_info
, elt
, scev_info_str
*,
3038 gather_chrec_stats (elt
->chrec
, &stats
);
3040 dump_chrecs_stats (dump_file
, &stats
);
3044 /* Initialize the analysis of scalar evolutions for LOOPS. */
3047 scev_initialize (void)
3051 gcc_assert (! scev_initialized_p ());
3053 scalar_evolution_info
= hash_table
<scev_info_hasher
>::create_ggc (100);
3055 FOR_EACH_LOOP (loop
, 0)
3057 loop
->nb_iterations
= NULL_TREE
;
3061 /* Return true if SCEV is initialized. */
3064 scev_initialized_p (void)
3066 return scalar_evolution_info
!= NULL
;
3069 /* Cleans up the information cached by the scalar evolutions analysis
3070 in the hash table. */
3073 scev_reset_htab (void)
3075 if (!scalar_evolution_info
)
3078 scalar_evolution_info
->empty ();
3081 /* Cleans up the information cached by the scalar evolutions analysis
3082 in the hash table and in the loop->nb_iterations. */
3091 FOR_EACH_LOOP (loop
, 0)
3093 loop
->nb_iterations
= NULL_TREE
;
3097 /* Return true if the IV calculation in TYPE can overflow based on the knowledge
3098 of the upper bound on the number of iterations of LOOP, the BASE and STEP
3101 We do not use information whether TYPE can overflow so it is safe to
3102 use this test even for derived IVs not computed every iteration or
3103 hypotetical IVs to be inserted into code. */
3106 iv_can_overflow_p (struct loop
*loop
, tree type
, tree base
, tree step
)
3109 wide_int base_min
, base_max
, step_min
, step_max
, type_min
, type_max
;
3110 signop sgn
= TYPE_SIGN (type
);
3112 if (integer_zerop (step
))
3115 if (TREE_CODE (base
) == INTEGER_CST
)
3116 base_min
= base_max
= wi::to_wide (base
);
3117 else if (TREE_CODE (base
) == SSA_NAME
3118 && INTEGRAL_TYPE_P (TREE_TYPE (base
))
3119 && get_range_info (base
, &base_min
, &base_max
) == VR_RANGE
)
3124 if (TREE_CODE (step
) == INTEGER_CST
)
3125 step_min
= step_max
= wi::to_wide (step
);
3126 else if (TREE_CODE (step
) == SSA_NAME
3127 && INTEGRAL_TYPE_P (TREE_TYPE (step
))
3128 && get_range_info (step
, &step_min
, &step_max
) == VR_RANGE
)
3133 if (!get_max_loop_iterations (loop
, &nit
))
3136 type_min
= wi::min_value (type
);
3137 type_max
= wi::max_value (type
);
3139 /* Just sanity check that we don't see values out of the range of the type.
3140 In this case the arithmetics bellow would overflow. */
3141 gcc_checking_assert (wi::ge_p (base_min
, type_min
, sgn
)
3142 && wi::le_p (base_max
, type_max
, sgn
));
3144 /* Account the possible increment in the last ieration. */
3145 wi::overflow_type overflow
= wi::OVF_NONE
;
3146 nit
= wi::add (nit
, 1, SIGNED
, &overflow
);
3150 /* NIT is typeless and can exceed the precision of the type. In this case
3151 overflow is always possible, because we know STEP is non-zero. */
3152 if (wi::min_precision (nit
, UNSIGNED
) > TYPE_PRECISION (type
))
3154 wide_int nit2
= wide_int::from (nit
, TYPE_PRECISION (type
), UNSIGNED
);
3156 /* If step can be positive, check that nit*step <= type_max-base.
3157 This can be done by unsigned arithmetic and we only need to watch overflow
3158 in the multiplication. The right hand side can always be represented in
3160 if (sgn
== UNSIGNED
|| !wi::neg_p (step_max
))
3162 wi::overflow_type overflow
= wi::OVF_NONE
;
3163 if (wi::gtu_p (wi::mul (step_max
, nit2
, UNSIGNED
, &overflow
),
3164 type_max
- base_max
)
3168 /* If step can be negative, check that nit*(-step) <= base_min-type_min. */
3169 if (sgn
== SIGNED
&& wi::neg_p (step_min
))
3171 wi::overflow_type overflow
, overflow2
;
3172 overflow
= overflow2
= wi::OVF_NONE
;
3173 if (wi::gtu_p (wi::mul (wi::neg (step_min
, &overflow2
),
3174 nit2
, UNSIGNED
, &overflow
),
3175 base_min
- type_min
)
3176 || overflow
|| overflow2
)
3183 /* Given EV with form of "(type) {inner_base, inner_step}_loop", this
3184 function tries to derive condition under which it can be simplified
3185 into "{(type)inner_base, (type)inner_step}_loop". The condition is
3186 the maximum number that inner iv can iterate. */
3189 derive_simple_iv_with_niters (tree ev
, tree
*niters
)
3191 if (!CONVERT_EXPR_P (ev
))
3194 tree inner_ev
= TREE_OPERAND (ev
, 0);
3195 if (TREE_CODE (inner_ev
) != POLYNOMIAL_CHREC
)
3198 tree init
= CHREC_LEFT (inner_ev
);
3199 tree step
= CHREC_RIGHT (inner_ev
);
3200 if (TREE_CODE (init
) != INTEGER_CST
3201 || TREE_CODE (step
) != INTEGER_CST
|| integer_zerop (step
))
3204 tree type
= TREE_TYPE (ev
);
3205 tree inner_type
= TREE_TYPE (inner_ev
);
3206 if (TYPE_PRECISION (inner_type
) >= TYPE_PRECISION (type
))
3209 /* Type conversion in "(type) {inner_base, inner_step}_loop" can be
3210 folded only if inner iv won't overflow. We compute the maximum
3211 number the inner iv can iterate before overflowing and return the
3212 simplified affine iv. */
3214 init
= fold_convert (type
, init
);
3215 step
= fold_convert (type
, step
);
3216 ev
= build_polynomial_chrec (CHREC_VARIABLE (inner_ev
), init
, step
);
3217 if (tree_int_cst_sign_bit (step
))
3219 tree bound
= lower_bound_in_type (inner_type
, inner_type
);
3220 delta
= fold_build2 (MINUS_EXPR
, type
, init
, fold_convert (type
, bound
));
3221 step
= fold_build1 (NEGATE_EXPR
, type
, step
);
3225 tree bound
= upper_bound_in_type (inner_type
, inner_type
);
3226 delta
= fold_build2 (MINUS_EXPR
, type
, fold_convert (type
, bound
), init
);
3228 *niters
= fold_build2 (FLOOR_DIV_EXPR
, type
, delta
, step
);
3232 /* Checks whether use of OP in USE_LOOP behaves as a simple affine iv with
3233 respect to WRTO_LOOP and returns its base and step in IV if possible
3234 (see analyze_scalar_evolution_in_loop for more details on USE_LOOP
3235 and WRTO_LOOP). If ALLOW_NONCONSTANT_STEP is true, we want step to be
3236 invariant in LOOP. Otherwise we require it to be an integer constant.
3238 IV->no_overflow is set to true if we are sure the iv cannot overflow (e.g.
3239 because it is computed in signed arithmetics). Consequently, adding an
3242 for (i = IV->base; ; i += IV->step)
3244 is only safe if IV->no_overflow is false, or TYPE_OVERFLOW_UNDEFINED is
3245 false for the type of the induction variable, or you can prove that i does
3246 not wrap by some other argument. Otherwise, this might introduce undefined
3250 for (; ; i = (type) ((unsigned type) i + (unsigned type) iv->step))
3252 must be used instead.
3254 When IV_NITERS is not NULL, this function also checks case in which OP
3255 is a conversion of an inner simple iv of below form:
3257 (outer_type){inner_base, inner_step}_loop.
3259 If type of inner iv has smaller precision than outer_type, it can't be
3260 folded into {(outer_type)inner_base, (outer_type)inner_step}_loop because
3261 the inner iv could overflow/wrap. In this case, we derive a condition
3262 under which the inner iv won't overflow/wrap and do the simplification.
3263 The derived condition normally is the maximum number the inner iv can
3264 iterate, and will be stored in IV_NITERS. This is useful in loop niter
3265 analysis, to derive break conditions when a loop must terminate, when is
3269 simple_iv_with_niters (struct loop
*wrto_loop
, struct loop
*use_loop
,
3270 tree op
, affine_iv
*iv
, tree
*iv_niters
,
3271 bool allow_nonconstant_step
)
3273 enum tree_code code
;
3274 tree type
, ev
, base
, e
;
3278 iv
->base
= NULL_TREE
;
3279 iv
->step
= NULL_TREE
;
3280 iv
->no_overflow
= false;
3282 type
= TREE_TYPE (op
);
3283 if (!POINTER_TYPE_P (type
)
3284 && !INTEGRAL_TYPE_P (type
))
3287 ev
= analyze_scalar_evolution_in_loop (wrto_loop
, use_loop
, op
,
3289 if (chrec_contains_undetermined (ev
)
3290 || chrec_contains_symbols_defined_in_loop (ev
, wrto_loop
->num
))
3293 if (tree_does_not_contain_chrecs (ev
))
3296 iv
->step
= build_int_cst (TREE_TYPE (ev
), 0);
3297 iv
->no_overflow
= true;
3301 /* If we can derive valid scalar evolution with assumptions. */
3302 if (iv_niters
&& TREE_CODE (ev
) != POLYNOMIAL_CHREC
)
3303 ev
= derive_simple_iv_with_niters (ev
, iv_niters
);
3305 if (TREE_CODE (ev
) != POLYNOMIAL_CHREC
)
3308 if (CHREC_VARIABLE (ev
) != (unsigned) wrto_loop
->num
)
3311 iv
->step
= CHREC_RIGHT (ev
);
3312 if ((!allow_nonconstant_step
&& TREE_CODE (iv
->step
) != INTEGER_CST
)
3313 || tree_contains_chrecs (iv
->step
, NULL
))
3316 iv
->base
= CHREC_LEFT (ev
);
3317 if (tree_contains_chrecs (iv
->base
, NULL
))
3320 iv
->no_overflow
= !folded_casts
&& nowrap_type_p (type
);
3322 if (!iv
->no_overflow
3323 && !iv_can_overflow_p (wrto_loop
, type
, iv
->base
, iv
->step
))
3324 iv
->no_overflow
= true;
3326 /* Try to simplify iv base:
3328 (signed T) ((unsigned T)base + step) ;; TREE_TYPE (base) == signed T
3329 == (signed T)(unsigned T)base + step
3332 If we can prove operation (base + step) doesn't overflow or underflow.
3333 Specifically, we try to prove below conditions are satisfied:
3335 base <= UPPER_BOUND (type) - step ;;step > 0
3336 base >= LOWER_BOUND (type) - step ;;step < 0
3338 This is done by proving the reverse conditions are false using loop's
3341 The is necessary to make loop niter, or iv overflow analysis easier
3344 int foo (int *a, signed char s, signed char l)
3347 for (i = s; i < l; i++)
3352 Note variable I is firstly converted to type unsigned char, incremented,
3353 then converted back to type signed char. */
3355 if (wrto_loop
->num
!= use_loop
->num
)
3358 if (!CONVERT_EXPR_P (iv
->base
) || TREE_CODE (iv
->step
) != INTEGER_CST
)
3361 type
= TREE_TYPE (iv
->base
);
3362 e
= TREE_OPERAND (iv
->base
, 0);
3363 if (TREE_CODE (e
) != PLUS_EXPR
3364 || TREE_CODE (TREE_OPERAND (e
, 1)) != INTEGER_CST
3365 || !tree_int_cst_equal (iv
->step
,
3366 fold_convert (type
, TREE_OPERAND (e
, 1))))
3368 e
= TREE_OPERAND (e
, 0);
3369 if (!CONVERT_EXPR_P (e
))
3371 base
= TREE_OPERAND (e
, 0);
3372 if (!useless_type_conversion_p (type
, TREE_TYPE (base
)))
3375 if (tree_int_cst_sign_bit (iv
->step
))
3378 extreme
= wi::min_value (type
);
3383 extreme
= wi::max_value (type
);
3385 wi::overflow_type overflow
= wi::OVF_NONE
;
3386 extreme
= wi::sub (extreme
, wi::to_wide (iv
->step
),
3387 TYPE_SIGN (type
), &overflow
);
3390 e
= fold_build2 (code
, boolean_type_node
, base
,
3391 wide_int_to_tree (type
, extreme
));
3392 e
= simplify_using_initial_conditions (use_loop
, e
);
3393 if (!integer_zerop (e
))
3396 if (POINTER_TYPE_P (TREE_TYPE (base
)))
3397 code
= POINTER_PLUS_EXPR
;
3401 iv
->base
= fold_build2 (code
, TREE_TYPE (base
), base
, iv
->step
);
3405 /* Like simple_iv_with_niters, but return TRUE when OP behaves as a simple
3406 affine iv unconditionally. */
3409 simple_iv (struct loop
*wrto_loop
, struct loop
*use_loop
, tree op
,
3410 affine_iv
*iv
, bool allow_nonconstant_step
)
3412 return simple_iv_with_niters (wrto_loop
, use_loop
, op
, iv
,
3413 NULL
, allow_nonconstant_step
);
3416 /* Finalize the scalar evolution analysis. */
3419 scev_finalize (void)
3421 if (!scalar_evolution_info
)
3423 scalar_evolution_info
->empty ();
3424 scalar_evolution_info
= NULL
;
3425 free_numbers_of_iterations_estimates (cfun
);
3428 /* Returns true if the expression EXPR is considered to be too expensive
3429 for scev_const_prop. */
3432 expression_expensive_p (tree expr
, hash_map
<tree
, uint64_t> &cache
,
3435 enum tree_code code
;
3437 if (is_gimple_val (expr
))
3440 code
= TREE_CODE (expr
);
3441 if (code
== TRUNC_DIV_EXPR
3442 || code
== CEIL_DIV_EXPR
3443 || code
== FLOOR_DIV_EXPR
3444 || code
== ROUND_DIV_EXPR
3445 || code
== TRUNC_MOD_EXPR
3446 || code
== CEIL_MOD_EXPR
3447 || code
== FLOOR_MOD_EXPR
3448 || code
== ROUND_MOD_EXPR
3449 || code
== EXACT_DIV_EXPR
)
3451 /* Division by power of two is usually cheap, so we allow it.
3452 Forbid anything else. */
3453 if (!integer_pow2p (TREE_OPERAND (expr
, 1)))
3458 uint64_t &local_cost
= cache
.get_or_insert (expr
, &visited_p
);
3461 uint64_t tem
= cost
+ local_cost
;
3469 uint64_t op_cost
= 0;
3470 if (code
== CALL_EXPR
)
3473 call_expr_arg_iterator iter
;
3474 /* Even though is_inexpensive_builtin might say true, we will get a
3475 library call for popcount when backend does not have an instruction
3476 to do so. We consider this to be expenseive and generate
3477 __builtin_popcount only when backend defines it. */
3478 combined_fn cfn
= get_call_combined_fn (expr
);
3482 /* Check if opcode for popcount is available in the mode required. */
3483 if (optab_handler (popcount_optab
,
3484 TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (expr
, 0))))
3485 == CODE_FOR_nothing
)
3488 mode
= TYPE_MODE (TREE_TYPE (CALL_EXPR_ARG (expr
, 0)));
3489 scalar_int_mode int_mode
;
3491 /* If the mode is of 2 * UNITS_PER_WORD size, we can handle
3492 double-word popcount by emitting two single-word popcount
3494 if (is_a
<scalar_int_mode
> (mode
, &int_mode
)
3495 && GET_MODE_SIZE (int_mode
) == 2 * UNITS_PER_WORD
3496 && (optab_handler (popcount_optab
, word_mode
)
3497 != CODE_FOR_nothing
))
3505 if (!is_inexpensive_builtin (get_callee_fndecl (expr
)))
3507 FOR_EACH_CALL_EXPR_ARG (arg
, iter
, expr
)
3508 if (expression_expensive_p (arg
, cache
, op_cost
))
3510 *cache
.get (expr
) += op_cost
;
3511 cost
+= op_cost
+ 1;
3515 if (code
== COND_EXPR
)
3517 if (expression_expensive_p (TREE_OPERAND (expr
, 0), cache
, op_cost
)
3518 || (EXPR_P (TREE_OPERAND (expr
, 1))
3519 && EXPR_P (TREE_OPERAND (expr
, 2)))
3520 /* If either branch has side effects or could trap. */
3521 || TREE_SIDE_EFFECTS (TREE_OPERAND (expr
, 1))
3522 || generic_expr_could_trap_p (TREE_OPERAND (expr
, 1))
3523 || TREE_SIDE_EFFECTS (TREE_OPERAND (expr
, 0))
3524 || generic_expr_could_trap_p (TREE_OPERAND (expr
, 0))
3525 || expression_expensive_p (TREE_OPERAND (expr
, 1),
3527 || expression_expensive_p (TREE_OPERAND (expr
, 2),
3530 *cache
.get (expr
) += op_cost
;
3531 cost
+= op_cost
+ 1;
3535 switch (TREE_CODE_CLASS (code
))
3538 case tcc_comparison
:
3539 if (expression_expensive_p (TREE_OPERAND (expr
, 1), cache
, op_cost
))
3544 if (expression_expensive_p (TREE_OPERAND (expr
, 0), cache
, op_cost
))
3546 *cache
.get (expr
) += op_cost
;
3547 cost
+= op_cost
+ 1;
3556 expression_expensive_p (tree expr
)
3558 hash_map
<tree
, uint64_t> cache
;
3559 uint64_t expanded_size
= 0;
3560 return (expression_expensive_p (expr
, cache
, expanded_size
)
3561 || expanded_size
> cache
.elements ());
3564 /* Do final value replacement for LOOP, return true if we did anything. */
3567 final_value_replacement_loop (struct loop
*loop
)
3569 /* If we do not know exact number of iterations of the loop, we cannot
3570 replace the final value. */
3571 edge exit
= single_exit (loop
);
3575 tree niter
= number_of_latch_executions (loop
);
3576 if (niter
== chrec_dont_know
)
3579 /* Ensure that it is possible to insert new statements somewhere. */
3580 if (!single_pred_p (exit
->dest
))
3581 split_loop_exit_edge (exit
);
3583 /* Set stmt insertion pointer. All stmts are inserted before this point. */
3584 gimple_stmt_iterator gsi
= gsi_after_labels (exit
->dest
);
3586 struct loop
*ex_loop
3587 = superloop_at_depth (loop
,
3588 loop_depth (exit
->dest
->loop_father
) + 1);
3592 for (psi
= gsi_start_phis (exit
->dest
); !gsi_end_p (psi
); )
3594 gphi
*phi
= psi
.phi ();
3595 tree rslt
= PHI_RESULT (phi
);
3596 tree def
= PHI_ARG_DEF_FROM_EDGE (phi
, exit
);
3597 if (virtual_operand_p (def
))
3603 if (!POINTER_TYPE_P (TREE_TYPE (def
))
3604 && !INTEGRAL_TYPE_P (TREE_TYPE (def
)))
3611 def
= analyze_scalar_evolution_in_loop (ex_loop
, loop
, def
,
3613 def
= compute_overall_effect_of_inner_loop (ex_loop
, def
);
3614 if (!tree_does_not_contain_chrecs (def
)
3615 || chrec_contains_symbols_defined_in_loop (def
, ex_loop
->num
)
3616 /* Moving the computation from the loop may prolong life range
3617 of some ssa names, which may cause problems if they appear
3618 on abnormal edges. */
3619 || contains_abnormal_ssa_name_p (def
)
3620 /* Do not emit expensive expressions. The rationale is that
3621 when someone writes a code like
3623 while (n > 45) n -= 45;
3625 he probably knows that n is not large, and does not want it
3626 to be turned into n %= 45. */
3627 || expression_expensive_p (def
))
3629 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3631 fprintf (dump_file
, "not replacing:\n ");
3632 print_gimple_stmt (dump_file
, phi
, 0);
3633 fprintf (dump_file
, "\n");
3639 /* Eliminate the PHI node and replace it by a computation outside
3643 fprintf (dump_file
, "\nfinal value replacement:\n ");
3644 print_gimple_stmt (dump_file
, phi
, 0);
3645 fprintf (dump_file
, " with expr: ");
3646 print_generic_expr (dump_file
, def
);
3649 def
= unshare_expr (def
);
3650 remove_phi_node (&psi
, false);
3652 /* If def's type has undefined overflow and there were folded
3653 casts, rewrite all stmts added for def into arithmetics
3654 with defined overflow behavior. */
3655 if (folded_casts
&& ANY_INTEGRAL_TYPE_P (TREE_TYPE (def
))
3656 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (def
)))
3659 gimple_stmt_iterator gsi2
;
3660 def
= force_gimple_operand (def
, &stmts
, true, NULL_TREE
);
3661 gsi2
= gsi_start (stmts
);
3662 while (!gsi_end_p (gsi2
))
3664 gimple
*stmt
= gsi_stmt (gsi2
);
3665 gimple_stmt_iterator gsi3
= gsi2
;
3667 gsi_remove (&gsi3
, false);
3668 if (is_gimple_assign (stmt
)
3669 && arith_code_with_undefined_signed_overflow
3670 (gimple_assign_rhs_code (stmt
)))
3671 gsi_insert_seq_before (&gsi
,
3672 rewrite_to_defined_overflow (stmt
),
3675 gsi_insert_before (&gsi
, stmt
, GSI_SAME_STMT
);
3679 def
= force_gimple_operand_gsi (&gsi
, def
, false, NULL_TREE
,
3680 true, GSI_SAME_STMT
);
3682 gassign
*ass
= gimple_build_assign (rslt
, def
);
3683 gsi_insert_before (&gsi
, ass
, GSI_SAME_STMT
);
3686 fprintf (dump_file
, "\n final stmt:\n ");
3687 print_gimple_stmt (dump_file
, ass
, 0);
3688 fprintf (dump_file
, "\n");
3695 #include "gt-tree-scalar-evolution.h"