Daily bump.
[official-gcc.git] / gcc / tree-scalar-evolution.c
blobada942df389b8d5855b5b2658dc297ba8fe8e219
1 /* Scalar evolution detector.
2 Copyright (C) 2003-2013 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
10 version.
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
15 for more details.
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/>. */
22 Description:
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
48 its definition:
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.
73 Examples:
75 Example 1: Illustration of the basic algorithm.
77 | a = 3
78 | loop_1
79 | b = phi (a, c)
80 | c = b + 1
81 | if (c > 10) exit_loop
82 | endloop
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:
115 a -> 3
116 b -> {3, +, 1}_1
117 c -> {4, +, 1}_1
119 or in terms of a C program:
121 | a = 3
122 | for (x = 0; x <= 7; x++)
124 | b = x + 3
125 | c = x + 4
128 Example 2a: Illustration of the algorithm on nested loops.
130 | loop_1
131 | a = phi (1, b)
132 | c = a + 2
133 | loop_2 10 times
134 | b = phi (c, d)
135 | d = b + 3
136 | endloop
137 | endloop
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:
143 b -> {c, +, 3}_2
144 d -> {c + 3, +, 3}_2
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:
154 a -> {1, +, 32}_1
155 c -> {3, +, 32}_1
157 Example 2b: Multivariate chains of recurrences.
159 | loop_1
160 | k = phi (0, k + 1)
161 | loop_2 4 times
162 | j = phi (0, j + 1)
163 | loop_3 4 times
164 | i = phi (0, i + 1)
165 | A[j + k] = ...
166 | endloop
167 | endloop
168 | endloop
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.
182 | loop_1
183 | a = phi (2, b)
184 | c = phi (5, d)
185 | b = a + 1
186 | d = c + a
187 | endloop
189 a -> {2, +, 1}_1
190 b -> {3, +, 1}_1
191 c -> {5, +, a}_1
192 d -> {5 + a, +, a}_1
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.
199 | loop_1
200 | a = phi (1, b)
201 | c = phi (3, d)
202 | b = c
203 | d = c + a
204 | endloop
206 a -> (1, c)_1
207 c -> {3, +, a}_1
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.
220 | loop_1
221 | a = phi (1, b)
222 | c = phi (3, d)
223 | b = c
224 | d = a
225 | endloop
227 a -> (1, c)_1
228 c -> (3, a)_1
230 Based on these symbolic chrecs, it is possible to refine this
231 information into the more precise PERIODIC_CHRECs:
233 a -> |1, 3|_1
234 c -> |3, 1|_1
236 This transformation is not yet implemented.
238 Further readings:
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
256 #include "config.h"
257 #include "system.h"
258 #include "coretypes.h"
259 #include "tree.h"
260 #include "expr.h"
261 #include "gimple-pretty-print.h"
262 #include "basic-block.h"
263 #include "tree-ssa-alias.h"
264 #include "internal-fn.h"
265 #include "gimple-expr.h"
266 #include "is-a.h"
267 #include "gimple.h"
268 #include "gimplify.h"
269 #include "gimple-iterator.h"
270 #include "gimplify-me.h"
271 #include "gimple-ssa.h"
272 #include "tree-cfg.h"
273 #include "tree-phinodes.h"
274 #include "stringpool.h"
275 #include "tree-ssanames.h"
276 #include "tree-ssa-loop-ivopts.h"
277 #include "tree-ssa-loop-manip.h"
278 #include "tree-ssa-loop-niter.h"
279 #include "tree-ssa-loop.h"
280 #include "tree-ssa.h"
281 #include "cfgloop.h"
282 #include "tree-chrec.h"
283 #include "tree-scalar-evolution.h"
284 #include "dumpfile.h"
285 #include "params.h"
286 #include "tree-ssa-propagate.h"
288 static tree analyze_scalar_evolution_1 (struct loop *, tree, tree);
289 static tree analyze_scalar_evolution_for_address_of (struct loop *loop,
290 tree var);
292 /* The cached information about an SSA name with version NAME_VERSION,
293 claiming that below basic block with index INSTANTIATED_BELOW, the
294 value of the SSA name can be expressed as CHREC. */
296 struct GTY(()) scev_info_str {
297 unsigned int name_version;
298 int instantiated_below;
299 tree chrec;
302 /* Counters for the scev database. */
303 static unsigned nb_set_scev = 0;
304 static unsigned nb_get_scev = 0;
306 /* The following trees are unique elements. Thus the comparison of
307 another element to these elements should be done on the pointer to
308 these trees, and not on their value. */
310 /* The SSA_NAMEs that are not yet analyzed are qualified with NULL_TREE. */
311 tree chrec_not_analyzed_yet;
313 /* Reserved to the cases where the analyzer has detected an
314 undecidable property at compile time. */
315 tree chrec_dont_know;
317 /* When the analyzer has detected that a property will never
318 happen, then it qualifies it with chrec_known. */
319 tree chrec_known;
321 static GTY ((param_is (struct scev_info_str))) htab_t scalar_evolution_info;
324 /* Constructs a new SCEV_INFO_STR structure for VAR and INSTANTIATED_BELOW. */
326 static inline struct scev_info_str *
327 new_scev_info_str (basic_block instantiated_below, tree var)
329 struct scev_info_str *res;
331 res = ggc_alloc_scev_info_str ();
332 res->name_version = SSA_NAME_VERSION (var);
333 res->chrec = chrec_not_analyzed_yet;
334 res->instantiated_below = instantiated_below->index;
336 return res;
339 /* Computes a hash function for database element ELT. */
341 static inline hashval_t
342 hash_scev_info (const void *elt_)
344 const struct scev_info_str *elt = (const struct scev_info_str *) elt_;
345 return elt->name_version ^ elt->instantiated_below;
348 /* Compares database elements E1 and E2. */
350 static inline int
351 eq_scev_info (const void *e1, const void *e2)
353 const struct scev_info_str *elt1 = (const struct scev_info_str *) e1;
354 const struct scev_info_str *elt2 = (const struct scev_info_str *) e2;
356 return (elt1->name_version == elt2->name_version
357 && elt1->instantiated_below == elt2->instantiated_below);
360 /* Deletes database element E. */
362 static void
363 del_scev_info (void *e)
365 ggc_free (e);
369 /* Get the scalar evolution of VAR for INSTANTIATED_BELOW basic block.
370 A first query on VAR returns chrec_not_analyzed_yet. */
372 static tree *
373 find_var_scev_info (basic_block instantiated_below, tree var)
375 struct scev_info_str *res;
376 struct scev_info_str tmp;
377 PTR *slot;
379 tmp.name_version = SSA_NAME_VERSION (var);
380 tmp.instantiated_below = instantiated_below->index;
381 slot = htab_find_slot (scalar_evolution_info, &tmp, INSERT);
383 if (!*slot)
384 *slot = new_scev_info_str (instantiated_below, var);
385 res = (struct scev_info_str *) *slot;
387 return &res->chrec;
390 /* Return true when CHREC contains symbolic names defined in
391 LOOP_NB. */
393 bool
394 chrec_contains_symbols_defined_in_loop (const_tree chrec, unsigned loop_nb)
396 int i, n;
398 if (chrec == NULL_TREE)
399 return false;
401 if (is_gimple_min_invariant (chrec))
402 return false;
404 if (TREE_CODE (chrec) == SSA_NAME)
406 gimple def;
407 loop_p def_loop, loop;
409 if (SSA_NAME_IS_DEFAULT_DEF (chrec))
410 return false;
412 def = SSA_NAME_DEF_STMT (chrec);
413 def_loop = loop_containing_stmt (def);
414 loop = get_loop (cfun, loop_nb);
416 if (def_loop == NULL)
417 return false;
419 if (loop == def_loop || flow_loop_nested_p (loop, def_loop))
420 return true;
422 return false;
425 n = TREE_OPERAND_LENGTH (chrec);
426 for (i = 0; i < n; i++)
427 if (chrec_contains_symbols_defined_in_loop (TREE_OPERAND (chrec, i),
428 loop_nb))
429 return true;
430 return false;
433 /* Return true when PHI is a loop-phi-node. */
435 static bool
436 loop_phi_node_p (gimple phi)
438 /* The implementation of this function is based on the following
439 property: "all the loop-phi-nodes of a loop are contained in the
440 loop's header basic block". */
442 return loop_containing_stmt (phi)->header == gimple_bb (phi);
445 /* Compute the scalar evolution for EVOLUTION_FN after crossing LOOP.
446 In general, in the case of multivariate evolutions we want to get
447 the evolution in different loops. LOOP specifies the level for
448 which to get the evolution.
450 Example:
452 | for (j = 0; j < 100; j++)
454 | for (k = 0; k < 100; k++)
456 | i = k + j; - Here the value of i is a function of j, k.
458 | ... = i - Here the value of i is a function of j.
460 | ... = i - Here the value of i is a scalar.
462 Example:
464 | i_0 = ...
465 | loop_1 10 times
466 | i_1 = phi (i_0, i_2)
467 | i_2 = i_1 + 2
468 | endloop
470 This loop has the same effect as:
471 LOOP_1 has the same effect as:
473 | i_1 = i_0 + 20
475 The overall effect of the loop, "i_0 + 20" in the previous example,
476 is obtained by passing in the parameters: LOOP = 1,
477 EVOLUTION_FN = {i_0, +, 2}_1.
480 tree
481 compute_overall_effect_of_inner_loop (struct loop *loop, tree evolution_fn)
483 bool val = false;
485 if (evolution_fn == chrec_dont_know)
486 return chrec_dont_know;
488 else if (TREE_CODE (evolution_fn) == POLYNOMIAL_CHREC)
490 struct loop *inner_loop = get_chrec_loop (evolution_fn);
492 if (inner_loop == loop
493 || flow_loop_nested_p (loop, inner_loop))
495 tree nb_iter = number_of_latch_executions (inner_loop);
497 if (nb_iter == chrec_dont_know)
498 return chrec_dont_know;
499 else
501 tree res;
503 /* evolution_fn is the evolution function in LOOP. Get
504 its value in the nb_iter-th iteration. */
505 res = chrec_apply (inner_loop->num, evolution_fn, nb_iter);
507 if (chrec_contains_symbols_defined_in_loop (res, loop->num))
508 res = instantiate_parameters (loop, res);
510 /* Continue the computation until ending on a parent of LOOP. */
511 return compute_overall_effect_of_inner_loop (loop, res);
514 else
515 return evolution_fn;
518 /* If the evolution function is an invariant, there is nothing to do. */
519 else if (no_evolution_in_loop_p (evolution_fn, loop->num, &val) && val)
520 return evolution_fn;
522 else
523 return chrec_dont_know;
526 /* Associate CHREC to SCALAR. */
528 static void
529 set_scalar_evolution (basic_block instantiated_below, tree scalar, tree chrec)
531 tree *scalar_info;
533 if (TREE_CODE (scalar) != SSA_NAME)
534 return;
536 scalar_info = find_var_scev_info (instantiated_below, scalar);
538 if (dump_file)
540 if (dump_flags & TDF_SCEV)
542 fprintf (dump_file, "(set_scalar_evolution \n");
543 fprintf (dump_file, " instantiated_below = %d \n",
544 instantiated_below->index);
545 fprintf (dump_file, " (scalar = ");
546 print_generic_expr (dump_file, scalar, 0);
547 fprintf (dump_file, ")\n (scalar_evolution = ");
548 print_generic_expr (dump_file, chrec, 0);
549 fprintf (dump_file, "))\n");
551 if (dump_flags & TDF_STATS)
552 nb_set_scev++;
555 *scalar_info = chrec;
558 /* Retrieve the chrec associated to SCALAR instantiated below
559 INSTANTIATED_BELOW block. */
561 static tree
562 get_scalar_evolution (basic_block instantiated_below, tree scalar)
564 tree res;
566 if (dump_file)
568 if (dump_flags & TDF_SCEV)
570 fprintf (dump_file, "(get_scalar_evolution \n");
571 fprintf (dump_file, " (scalar = ");
572 print_generic_expr (dump_file, scalar, 0);
573 fprintf (dump_file, ")\n");
575 if (dump_flags & TDF_STATS)
576 nb_get_scev++;
579 switch (TREE_CODE (scalar))
581 case SSA_NAME:
582 res = *find_var_scev_info (instantiated_below, scalar);
583 break;
585 case REAL_CST:
586 case FIXED_CST:
587 case INTEGER_CST:
588 res = scalar;
589 break;
591 default:
592 res = chrec_not_analyzed_yet;
593 break;
596 if (dump_file && (dump_flags & TDF_SCEV))
598 fprintf (dump_file, " (scalar_evolution = ");
599 print_generic_expr (dump_file, res, 0);
600 fprintf (dump_file, "))\n");
603 return res;
606 /* Helper function for add_to_evolution. Returns the evolution
607 function for an assignment of the form "a = b + c", where "a" and
608 "b" are on the strongly connected component. CHREC_BEFORE is the
609 information that we already have collected up to this point.
610 TO_ADD is the evolution of "c".
612 When CHREC_BEFORE has an evolution part in LOOP_NB, add to this
613 evolution the expression TO_ADD, otherwise construct an evolution
614 part for this loop. */
616 static tree
617 add_to_evolution_1 (unsigned loop_nb, tree chrec_before, tree to_add,
618 gimple at_stmt)
620 tree type, left, right;
621 struct loop *loop = get_loop (cfun, loop_nb), *chloop;
623 switch (TREE_CODE (chrec_before))
625 case POLYNOMIAL_CHREC:
626 chloop = get_chrec_loop (chrec_before);
627 if (chloop == loop
628 || flow_loop_nested_p (chloop, loop))
630 unsigned var;
632 type = chrec_type (chrec_before);
634 /* When there is no evolution part in this loop, build it. */
635 if (chloop != loop)
637 var = loop_nb;
638 left = chrec_before;
639 right = SCALAR_FLOAT_TYPE_P (type)
640 ? build_real (type, dconst0)
641 : build_int_cst (type, 0);
643 else
645 var = CHREC_VARIABLE (chrec_before);
646 left = CHREC_LEFT (chrec_before);
647 right = CHREC_RIGHT (chrec_before);
650 to_add = chrec_convert (type, to_add, at_stmt);
651 right = chrec_convert_rhs (type, right, at_stmt);
652 right = chrec_fold_plus (chrec_type (right), right, to_add);
653 return build_polynomial_chrec (var, left, right);
655 else
657 gcc_assert (flow_loop_nested_p (loop, chloop));
659 /* Search the evolution in LOOP_NB. */
660 left = add_to_evolution_1 (loop_nb, CHREC_LEFT (chrec_before),
661 to_add, at_stmt);
662 right = CHREC_RIGHT (chrec_before);
663 right = chrec_convert_rhs (chrec_type (left), right, at_stmt);
664 return build_polynomial_chrec (CHREC_VARIABLE (chrec_before),
665 left, right);
668 default:
669 /* These nodes do not depend on a loop. */
670 if (chrec_before == chrec_dont_know)
671 return chrec_dont_know;
673 left = chrec_before;
674 right = chrec_convert_rhs (chrec_type (left), to_add, at_stmt);
675 return build_polynomial_chrec (loop_nb, left, right);
679 /* Add TO_ADD to the evolution part of CHREC_BEFORE in the dimension
680 of LOOP_NB.
682 Description (provided for completeness, for those who read code in
683 a plane, and for my poor 62 bytes brain that would have forgotten
684 all this in the next two or three months):
686 The algorithm of translation of programs from the SSA representation
687 into the chrecs syntax is based on a pattern matching. After having
688 reconstructed the overall tree expression for a loop, there are only
689 two cases that can arise:
691 1. a = loop-phi (init, a + expr)
692 2. a = loop-phi (init, expr)
694 where EXPR is either a scalar constant with respect to the analyzed
695 loop (this is a degree 0 polynomial), or an expression containing
696 other loop-phi definitions (these are higher degree polynomials).
698 Examples:
701 | init = ...
702 | loop_1
703 | a = phi (init, a + 5)
704 | endloop
707 | inita = ...
708 | initb = ...
709 | loop_1
710 | a = phi (inita, 2 * b + 3)
711 | b = phi (initb, b + 1)
712 | endloop
714 For the first case, the semantics of the SSA representation is:
716 | a (x) = init + \sum_{j = 0}^{x - 1} expr (j)
718 that is, there is a loop index "x" that determines the scalar value
719 of the variable during the loop execution. During the first
720 iteration, the value is that of the initial condition INIT, while
721 during the subsequent iterations, it is the sum of the initial
722 condition with the sum of all the values of EXPR from the initial
723 iteration to the before last considered iteration.
725 For the second case, the semantics of the SSA program is:
727 | a (x) = init, if x = 0;
728 | expr (x - 1), otherwise.
730 The second case corresponds to the PEELED_CHREC, whose syntax is
731 close to the syntax of a loop-phi-node:
733 | phi (init, expr) vs. (init, expr)_x
735 The proof of the translation algorithm for the first case is a
736 proof by structural induction based on the degree of EXPR.
738 Degree 0:
739 When EXPR is a constant with respect to the analyzed loop, or in
740 other words when EXPR is a polynomial of degree 0, the evolution of
741 the variable A in the loop is an affine function with an initial
742 condition INIT, and a step EXPR. In order to show this, we start
743 from the semantics of the SSA representation:
745 f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
747 and since "expr (j)" is a constant with respect to "j",
749 f (x) = init + x * expr
751 Finally, based on the semantics of the pure sum chrecs, by
752 identification we get the corresponding chrecs syntax:
754 f (x) = init * \binom{x}{0} + expr * \binom{x}{1}
755 f (x) -> {init, +, expr}_x
757 Higher degree:
758 Suppose that EXPR is a polynomial of degree N with respect to the
759 analyzed loop_x for which we have already determined that it is
760 written under the chrecs syntax:
762 | expr (x) -> {b_0, +, b_1, +, ..., +, b_{n-1}} (x)
764 We start from the semantics of the SSA program:
766 | f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
768 | f (x) = init + \sum_{j = 0}^{x - 1}
769 | (b_0 * \binom{j}{0} + ... + b_{n-1} * \binom{j}{n-1})
771 | f (x) = init + \sum_{j = 0}^{x - 1}
772 | \sum_{k = 0}^{n - 1} (b_k * \binom{j}{k})
774 | f (x) = init + \sum_{k = 0}^{n - 1}
775 | (b_k * \sum_{j = 0}^{x - 1} \binom{j}{k})
777 | f (x) = init + \sum_{k = 0}^{n - 1}
778 | (b_k * \binom{x}{k + 1})
780 | f (x) = init + b_0 * \binom{x}{1} + ...
781 | + b_{n-1} * \binom{x}{n}
783 | f (x) = init * \binom{x}{0} + b_0 * \binom{x}{1} + ...
784 | + b_{n-1} * \binom{x}{n}
787 And finally from the definition of the chrecs syntax, we identify:
788 | f (x) -> {init, +, b_0, +, ..., +, b_{n-1}}_x
790 This shows the mechanism that stands behind the add_to_evolution
791 function. An important point is that the use of symbolic
792 parameters avoids the need of an analysis schedule.
794 Example:
796 | inita = ...
797 | initb = ...
798 | loop_1
799 | a = phi (inita, a + 2 + b)
800 | b = phi (initb, b + 1)
801 | endloop
803 When analyzing "a", the algorithm keeps "b" symbolically:
805 | a -> {inita, +, 2 + b}_1
807 Then, after instantiation, the analyzer ends on the evolution:
809 | a -> {inita, +, 2 + initb, +, 1}_1
813 static tree
814 add_to_evolution (unsigned loop_nb, tree chrec_before, enum tree_code code,
815 tree to_add, gimple at_stmt)
817 tree type = chrec_type (to_add);
818 tree res = NULL_TREE;
820 if (to_add == NULL_TREE)
821 return chrec_before;
823 /* TO_ADD is either a scalar, or a parameter. TO_ADD is not
824 instantiated at this point. */
825 if (TREE_CODE (to_add) == POLYNOMIAL_CHREC)
826 /* This should not happen. */
827 return chrec_dont_know;
829 if (dump_file && (dump_flags & TDF_SCEV))
831 fprintf (dump_file, "(add_to_evolution \n");
832 fprintf (dump_file, " (loop_nb = %d)\n", loop_nb);
833 fprintf (dump_file, " (chrec_before = ");
834 print_generic_expr (dump_file, chrec_before, 0);
835 fprintf (dump_file, ")\n (to_add = ");
836 print_generic_expr (dump_file, to_add, 0);
837 fprintf (dump_file, ")\n");
840 if (code == MINUS_EXPR)
841 to_add = chrec_fold_multiply (type, to_add, SCALAR_FLOAT_TYPE_P (type)
842 ? build_real (type, dconstm1)
843 : build_int_cst_type (type, -1));
845 res = add_to_evolution_1 (loop_nb, chrec_before, to_add, at_stmt);
847 if (dump_file && (dump_flags & TDF_SCEV))
849 fprintf (dump_file, " (res = ");
850 print_generic_expr (dump_file, res, 0);
851 fprintf (dump_file, "))\n");
854 return res;
859 /* This section selects the loops that will be good candidates for the
860 scalar evolution analysis. For the moment, greedily select all the
861 loop nests we could analyze. */
863 /* For a loop with a single exit edge, return the COND_EXPR that
864 guards the exit edge. If the expression is too difficult to
865 analyze, then give up. */
867 gimple
868 get_loop_exit_condition (const struct loop *loop)
870 gimple res = NULL;
871 edge exit_edge = single_exit (loop);
873 if (dump_file && (dump_flags & TDF_SCEV))
874 fprintf (dump_file, "(get_loop_exit_condition \n ");
876 if (exit_edge)
878 gimple stmt;
880 stmt = last_stmt (exit_edge->src);
881 if (gimple_code (stmt) == GIMPLE_COND)
882 res = stmt;
885 if (dump_file && (dump_flags & TDF_SCEV))
887 print_gimple_stmt (dump_file, res, 0, 0);
888 fprintf (dump_file, ")\n");
891 return res;
895 /* Depth first search algorithm. */
897 typedef enum t_bool {
898 t_false,
899 t_true,
900 t_dont_know
901 } t_bool;
904 static t_bool follow_ssa_edge (struct loop *loop, gimple, gimple, tree *, int);
906 /* Follow the ssa edge into the binary expression RHS0 CODE RHS1.
907 Return true if the strongly connected component has been found. */
909 static t_bool
910 follow_ssa_edge_binary (struct loop *loop, gimple at_stmt,
911 tree type, tree rhs0, enum tree_code code, tree rhs1,
912 gimple halting_phi, tree *evolution_of_loop, int limit)
914 t_bool res = t_false;
915 tree evol;
917 switch (code)
919 case POINTER_PLUS_EXPR:
920 case PLUS_EXPR:
921 if (TREE_CODE (rhs0) == SSA_NAME)
923 if (TREE_CODE (rhs1) == SSA_NAME)
925 /* Match an assignment under the form:
926 "a = b + c". */
928 /* We want only assignments of form "name + name" contribute to
929 LIMIT, as the other cases do not necessarily contribute to
930 the complexity of the expression. */
931 limit++;
933 evol = *evolution_of_loop;
934 res = follow_ssa_edge
935 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi, &evol, limit);
937 if (res == t_true)
938 *evolution_of_loop = add_to_evolution
939 (loop->num,
940 chrec_convert (type, evol, at_stmt),
941 code, rhs1, at_stmt);
943 else if (res == t_false)
945 res = follow_ssa_edge
946 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
947 evolution_of_loop, limit);
949 if (res == t_true)
950 *evolution_of_loop = add_to_evolution
951 (loop->num,
952 chrec_convert (type, *evolution_of_loop, at_stmt),
953 code, rhs0, at_stmt);
955 else if (res == t_dont_know)
956 *evolution_of_loop = chrec_dont_know;
959 else if (res == t_dont_know)
960 *evolution_of_loop = chrec_dont_know;
963 else
965 /* Match an assignment under the form:
966 "a = b + ...". */
967 res = follow_ssa_edge
968 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
969 evolution_of_loop, limit);
970 if (res == t_true)
971 *evolution_of_loop = add_to_evolution
972 (loop->num, chrec_convert (type, *evolution_of_loop,
973 at_stmt),
974 code, rhs1, at_stmt);
976 else if (res == t_dont_know)
977 *evolution_of_loop = chrec_dont_know;
981 else if (TREE_CODE (rhs1) == SSA_NAME)
983 /* Match an assignment under the form:
984 "a = ... + c". */
985 res = follow_ssa_edge
986 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
987 evolution_of_loop, limit);
988 if (res == t_true)
989 *evolution_of_loop = add_to_evolution
990 (loop->num, chrec_convert (type, *evolution_of_loop,
991 at_stmt),
992 code, rhs0, at_stmt);
994 else if (res == t_dont_know)
995 *evolution_of_loop = chrec_dont_know;
998 else
999 /* Otherwise, match an assignment under the form:
1000 "a = ... + ...". */
1001 /* And there is nothing to do. */
1002 res = t_false;
1003 break;
1005 case MINUS_EXPR:
1006 /* This case is under the form "opnd0 = rhs0 - rhs1". */
1007 if (TREE_CODE (rhs0) == SSA_NAME)
1009 /* Match an assignment under the form:
1010 "a = b - ...". */
1012 /* We want only assignments of form "name - name" contribute to
1013 LIMIT, as the other cases do not necessarily contribute to
1014 the complexity of the expression. */
1015 if (TREE_CODE (rhs1) == SSA_NAME)
1016 limit++;
1018 res = follow_ssa_edge (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
1019 evolution_of_loop, limit);
1020 if (res == t_true)
1021 *evolution_of_loop = add_to_evolution
1022 (loop->num, chrec_convert (type, *evolution_of_loop, at_stmt),
1023 MINUS_EXPR, rhs1, at_stmt);
1025 else if (res == t_dont_know)
1026 *evolution_of_loop = chrec_dont_know;
1028 else
1029 /* Otherwise, match an assignment under the form:
1030 "a = ... - ...". */
1031 /* And there is nothing to do. */
1032 res = t_false;
1033 break;
1035 default:
1036 res = t_false;
1039 return res;
1042 /* Follow the ssa edge into the expression EXPR.
1043 Return true if the strongly connected component has been found. */
1045 static t_bool
1046 follow_ssa_edge_expr (struct loop *loop, gimple at_stmt, tree expr,
1047 gimple halting_phi, tree *evolution_of_loop, int limit)
1049 enum tree_code code = TREE_CODE (expr);
1050 tree type = TREE_TYPE (expr), rhs0, rhs1;
1051 t_bool res;
1053 /* The EXPR is one of the following cases:
1054 - an SSA_NAME,
1055 - an INTEGER_CST,
1056 - a PLUS_EXPR,
1057 - a POINTER_PLUS_EXPR,
1058 - a MINUS_EXPR,
1059 - an ASSERT_EXPR,
1060 - other cases are not yet handled. */
1062 switch (code)
1064 CASE_CONVERT:
1065 /* This assignment is under the form "a_1 = (cast) rhs. */
1066 res = follow_ssa_edge_expr (loop, at_stmt, TREE_OPERAND (expr, 0),
1067 halting_phi, evolution_of_loop, limit);
1068 *evolution_of_loop = chrec_convert (type, *evolution_of_loop, at_stmt);
1069 break;
1071 case INTEGER_CST:
1072 /* This assignment is under the form "a_1 = 7". */
1073 res = t_false;
1074 break;
1076 case SSA_NAME:
1077 /* This assignment is under the form: "a_1 = b_2". */
1078 res = follow_ssa_edge
1079 (loop, SSA_NAME_DEF_STMT (expr), halting_phi, evolution_of_loop, limit);
1080 break;
1082 case POINTER_PLUS_EXPR:
1083 case PLUS_EXPR:
1084 case MINUS_EXPR:
1085 /* This case is under the form "rhs0 +- rhs1". */
1086 rhs0 = TREE_OPERAND (expr, 0);
1087 rhs1 = TREE_OPERAND (expr, 1);
1088 type = TREE_TYPE (rhs0);
1089 STRIP_USELESS_TYPE_CONVERSION (rhs0);
1090 STRIP_USELESS_TYPE_CONVERSION (rhs1);
1091 res = follow_ssa_edge_binary (loop, at_stmt, type, rhs0, code, rhs1,
1092 halting_phi, evolution_of_loop, limit);
1093 break;
1095 case ADDR_EXPR:
1096 /* Handle &MEM[ptr + CST] which is equivalent to POINTER_PLUS_EXPR. */
1097 if (TREE_CODE (TREE_OPERAND (expr, 0)) == MEM_REF)
1099 expr = TREE_OPERAND (expr, 0);
1100 rhs0 = TREE_OPERAND (expr, 0);
1101 rhs1 = TREE_OPERAND (expr, 1);
1102 type = TREE_TYPE (rhs0);
1103 STRIP_USELESS_TYPE_CONVERSION (rhs0);
1104 STRIP_USELESS_TYPE_CONVERSION (rhs1);
1105 res = follow_ssa_edge_binary (loop, at_stmt, type,
1106 rhs0, POINTER_PLUS_EXPR, rhs1,
1107 halting_phi, evolution_of_loop, limit);
1109 else
1110 res = t_false;
1111 break;
1113 case ASSERT_EXPR:
1114 /* This assignment is of the form: "a_1 = ASSERT_EXPR <a_2, ...>"
1115 It must be handled as a copy assignment of the form a_1 = a_2. */
1116 rhs0 = ASSERT_EXPR_VAR (expr);
1117 if (TREE_CODE (rhs0) == SSA_NAME)
1118 res = follow_ssa_edge (loop, SSA_NAME_DEF_STMT (rhs0),
1119 halting_phi, evolution_of_loop, limit);
1120 else
1121 res = t_false;
1122 break;
1124 default:
1125 res = t_false;
1126 break;
1129 return res;
1132 /* Follow the ssa edge into the right hand side of an assignment STMT.
1133 Return true if the strongly connected component has been found. */
1135 static t_bool
1136 follow_ssa_edge_in_rhs (struct loop *loop, gimple stmt,
1137 gimple halting_phi, tree *evolution_of_loop, int limit)
1139 enum tree_code code = gimple_assign_rhs_code (stmt);
1140 tree type = gimple_expr_type (stmt), rhs1, rhs2;
1141 t_bool res;
1143 switch (code)
1145 CASE_CONVERT:
1146 /* This assignment is under the form "a_1 = (cast) rhs. */
1147 res = follow_ssa_edge_expr (loop, stmt, gimple_assign_rhs1 (stmt),
1148 halting_phi, evolution_of_loop, limit);
1149 *evolution_of_loop = chrec_convert (type, *evolution_of_loop, stmt);
1150 break;
1152 case POINTER_PLUS_EXPR:
1153 case PLUS_EXPR:
1154 case MINUS_EXPR:
1155 rhs1 = gimple_assign_rhs1 (stmt);
1156 rhs2 = gimple_assign_rhs2 (stmt);
1157 type = TREE_TYPE (rhs1);
1158 res = follow_ssa_edge_binary (loop, stmt, type, rhs1, code, rhs2,
1159 halting_phi, evolution_of_loop, limit);
1160 break;
1162 default:
1163 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1164 res = follow_ssa_edge_expr (loop, stmt, gimple_assign_rhs1 (stmt),
1165 halting_phi, evolution_of_loop, limit);
1166 else
1167 res = t_false;
1168 break;
1171 return res;
1174 /* Checks whether the I-th argument of a PHI comes from a backedge. */
1176 static bool
1177 backedge_phi_arg_p (gimple phi, int i)
1179 const_edge e = gimple_phi_arg_edge (phi, i);
1181 /* We would in fact like to test EDGE_DFS_BACK here, but we do not care
1182 about updating it anywhere, and this should work as well most of the
1183 time. */
1184 if (e->flags & EDGE_IRREDUCIBLE_LOOP)
1185 return true;
1187 return false;
1190 /* Helper function for one branch of the condition-phi-node. Return
1191 true if the strongly connected component has been found following
1192 this path. */
1194 static inline t_bool
1195 follow_ssa_edge_in_condition_phi_branch (int i,
1196 struct loop *loop,
1197 gimple condition_phi,
1198 gimple halting_phi,
1199 tree *evolution_of_branch,
1200 tree init_cond, int limit)
1202 tree branch = PHI_ARG_DEF (condition_phi, i);
1203 *evolution_of_branch = chrec_dont_know;
1205 /* Do not follow back edges (they must belong to an irreducible loop, which
1206 we really do not want to worry about). */
1207 if (backedge_phi_arg_p (condition_phi, i))
1208 return t_false;
1210 if (TREE_CODE (branch) == SSA_NAME)
1212 *evolution_of_branch = init_cond;
1213 return follow_ssa_edge (loop, SSA_NAME_DEF_STMT (branch), halting_phi,
1214 evolution_of_branch, limit);
1217 /* This case occurs when one of the condition branches sets
1218 the variable to a constant: i.e. a phi-node like
1219 "a_2 = PHI <a_7(5), 2(6)>;".
1221 FIXME: This case have to be refined correctly:
1222 in some cases it is possible to say something better than
1223 chrec_dont_know, for example using a wrap-around notation. */
1224 return t_false;
1227 /* This function merges the branches of a condition-phi-node in a
1228 loop. */
1230 static t_bool
1231 follow_ssa_edge_in_condition_phi (struct loop *loop,
1232 gimple condition_phi,
1233 gimple halting_phi,
1234 tree *evolution_of_loop, int limit)
1236 int i, n;
1237 tree init = *evolution_of_loop;
1238 tree evolution_of_branch;
1239 t_bool res = follow_ssa_edge_in_condition_phi_branch (0, loop, condition_phi,
1240 halting_phi,
1241 &evolution_of_branch,
1242 init, limit);
1243 if (res == t_false || res == t_dont_know)
1244 return res;
1246 *evolution_of_loop = evolution_of_branch;
1248 n = gimple_phi_num_args (condition_phi);
1249 for (i = 1; i < n; i++)
1251 /* Quickly give up when the evolution of one of the branches is
1252 not known. */
1253 if (*evolution_of_loop == chrec_dont_know)
1254 return t_true;
1256 /* Increase the limit by the PHI argument number to avoid exponential
1257 time and memory complexity. */
1258 res = follow_ssa_edge_in_condition_phi_branch (i, loop, condition_phi,
1259 halting_phi,
1260 &evolution_of_branch,
1261 init, limit + i);
1262 if (res == t_false || res == t_dont_know)
1263 return res;
1265 *evolution_of_loop = chrec_merge (*evolution_of_loop,
1266 evolution_of_branch);
1269 return t_true;
1272 /* Follow an SSA edge in an inner loop. It computes the overall
1273 effect of the loop, and following the symbolic initial conditions,
1274 it follows the edges in the parent loop. The inner loop is
1275 considered as a single statement. */
1277 static t_bool
1278 follow_ssa_edge_inner_loop_phi (struct loop *outer_loop,
1279 gimple loop_phi_node,
1280 gimple halting_phi,
1281 tree *evolution_of_loop, int limit)
1283 struct loop *loop = loop_containing_stmt (loop_phi_node);
1284 tree ev = analyze_scalar_evolution (loop, PHI_RESULT (loop_phi_node));
1286 /* Sometimes, the inner loop is too difficult to analyze, and the
1287 result of the analysis is a symbolic parameter. */
1288 if (ev == PHI_RESULT (loop_phi_node))
1290 t_bool res = t_false;
1291 int i, n = gimple_phi_num_args (loop_phi_node);
1293 for (i = 0; i < n; i++)
1295 tree arg = PHI_ARG_DEF (loop_phi_node, i);
1296 basic_block bb;
1298 /* Follow the edges that exit the inner loop. */
1299 bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1300 if (!flow_bb_inside_loop_p (loop, bb))
1301 res = follow_ssa_edge_expr (outer_loop, loop_phi_node,
1302 arg, halting_phi,
1303 evolution_of_loop, limit);
1304 if (res == t_true)
1305 break;
1308 /* If the path crosses this loop-phi, give up. */
1309 if (res == t_true)
1310 *evolution_of_loop = chrec_dont_know;
1312 return res;
1315 /* Otherwise, compute the overall effect of the inner loop. */
1316 ev = compute_overall_effect_of_inner_loop (loop, ev);
1317 return follow_ssa_edge_expr (outer_loop, loop_phi_node, ev, halting_phi,
1318 evolution_of_loop, limit);
1321 /* Follow an SSA edge from a loop-phi-node to itself, constructing a
1322 path that is analyzed on the return walk. */
1324 static t_bool
1325 follow_ssa_edge (struct loop *loop, gimple def, gimple halting_phi,
1326 tree *evolution_of_loop, int limit)
1328 struct loop *def_loop;
1330 if (gimple_nop_p (def))
1331 return t_false;
1333 /* Give up if the path is longer than the MAX that we allow. */
1334 if (limit > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_COMPLEXITY))
1335 return t_dont_know;
1337 def_loop = loop_containing_stmt (def);
1339 switch (gimple_code (def))
1341 case GIMPLE_PHI:
1342 if (!loop_phi_node_p (def))
1343 /* DEF is a condition-phi-node. Follow the branches, and
1344 record their evolutions. Finally, merge the collected
1345 information and set the approximation to the main
1346 variable. */
1347 return follow_ssa_edge_in_condition_phi
1348 (loop, def, halting_phi, evolution_of_loop, limit);
1350 /* When the analyzed phi is the halting_phi, the
1351 depth-first search is over: we have found a path from
1352 the halting_phi to itself in the loop. */
1353 if (def == halting_phi)
1354 return t_true;
1356 /* Otherwise, the evolution of the HALTING_PHI depends
1357 on the evolution of another loop-phi-node, i.e. the
1358 evolution function is a higher degree polynomial. */
1359 if (def_loop == loop)
1360 return t_false;
1362 /* Inner loop. */
1363 if (flow_loop_nested_p (loop, def_loop))
1364 return follow_ssa_edge_inner_loop_phi
1365 (loop, def, halting_phi, evolution_of_loop, limit + 1);
1367 /* Outer loop. */
1368 return t_false;
1370 case GIMPLE_ASSIGN:
1371 return follow_ssa_edge_in_rhs (loop, def, halting_phi,
1372 evolution_of_loop, limit);
1374 default:
1375 /* At this level of abstraction, the program is just a set
1376 of GIMPLE_ASSIGNs and PHI_NODEs. In principle there is no
1377 other node to be handled. */
1378 return t_false;
1384 /* Given a LOOP_PHI_NODE, this function determines the evolution
1385 function from LOOP_PHI_NODE to LOOP_PHI_NODE in the loop. */
1387 static tree
1388 analyze_evolution_in_loop (gimple loop_phi_node,
1389 tree init_cond)
1391 int i, n = gimple_phi_num_args (loop_phi_node);
1392 tree evolution_function = chrec_not_analyzed_yet;
1393 struct loop *loop = loop_containing_stmt (loop_phi_node);
1394 basic_block bb;
1396 if (dump_file && (dump_flags & TDF_SCEV))
1398 fprintf (dump_file, "(analyze_evolution_in_loop \n");
1399 fprintf (dump_file, " (loop_phi_node = ");
1400 print_gimple_stmt (dump_file, loop_phi_node, 0, 0);
1401 fprintf (dump_file, ")\n");
1404 for (i = 0; i < n; i++)
1406 tree arg = PHI_ARG_DEF (loop_phi_node, i);
1407 gimple ssa_chain;
1408 tree ev_fn;
1409 t_bool res;
1411 /* Select the edges that enter the loop body. */
1412 bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1413 if (!flow_bb_inside_loop_p (loop, bb))
1414 continue;
1416 if (TREE_CODE (arg) == SSA_NAME)
1418 bool val = false;
1420 ssa_chain = SSA_NAME_DEF_STMT (arg);
1422 /* Pass in the initial condition to the follow edge function. */
1423 ev_fn = init_cond;
1424 res = follow_ssa_edge (loop, ssa_chain, loop_phi_node, &ev_fn, 0);
1426 /* If ev_fn has no evolution in the inner loop, and the
1427 init_cond is not equal to ev_fn, then we have an
1428 ambiguity between two possible values, as we cannot know
1429 the number of iterations at this point. */
1430 if (TREE_CODE (ev_fn) != POLYNOMIAL_CHREC
1431 && no_evolution_in_loop_p (ev_fn, loop->num, &val) && val
1432 && !operand_equal_p (init_cond, ev_fn, 0))
1433 ev_fn = chrec_dont_know;
1435 else
1436 res = t_false;
1438 /* When it is impossible to go back on the same
1439 loop_phi_node by following the ssa edges, the
1440 evolution is represented by a peeled chrec, i.e. the
1441 first iteration, EV_FN has the value INIT_COND, then
1442 all the other iterations it has the value of ARG.
1443 For the moment, PEELED_CHREC nodes are not built. */
1444 if (res != t_true)
1445 ev_fn = chrec_dont_know;
1447 /* When there are multiple back edges of the loop (which in fact never
1448 happens currently, but nevertheless), merge their evolutions. */
1449 evolution_function = chrec_merge (evolution_function, ev_fn);
1452 if (dump_file && (dump_flags & TDF_SCEV))
1454 fprintf (dump_file, " (evolution_function = ");
1455 print_generic_expr (dump_file, evolution_function, 0);
1456 fprintf (dump_file, "))\n");
1459 return evolution_function;
1462 /* Given a loop-phi-node, return the initial conditions of the
1463 variable on entry of the loop. When the CCP has propagated
1464 constants into the loop-phi-node, the initial condition is
1465 instantiated, otherwise the initial condition is kept symbolic.
1466 This analyzer does not analyze the evolution outside the current
1467 loop, and leaves this task to the on-demand tree reconstructor. */
1469 static tree
1470 analyze_initial_condition (gimple loop_phi_node)
1472 int i, n;
1473 tree init_cond = chrec_not_analyzed_yet;
1474 struct loop *loop = loop_containing_stmt (loop_phi_node);
1476 if (dump_file && (dump_flags & TDF_SCEV))
1478 fprintf (dump_file, "(analyze_initial_condition \n");
1479 fprintf (dump_file, " (loop_phi_node = \n");
1480 print_gimple_stmt (dump_file, loop_phi_node, 0, 0);
1481 fprintf (dump_file, ")\n");
1484 n = gimple_phi_num_args (loop_phi_node);
1485 for (i = 0; i < n; i++)
1487 tree branch = PHI_ARG_DEF (loop_phi_node, i);
1488 basic_block bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1490 /* When the branch is oriented to the loop's body, it does
1491 not contribute to the initial condition. */
1492 if (flow_bb_inside_loop_p (loop, bb))
1493 continue;
1495 if (init_cond == chrec_not_analyzed_yet)
1497 init_cond = branch;
1498 continue;
1501 if (TREE_CODE (branch) == SSA_NAME)
1503 init_cond = chrec_dont_know;
1504 break;
1507 init_cond = chrec_merge (init_cond, branch);
1510 /* Ooops -- a loop without an entry??? */
1511 if (init_cond == chrec_not_analyzed_yet)
1512 init_cond = chrec_dont_know;
1514 /* During early loop unrolling we do not have fully constant propagated IL.
1515 Handle degenerate PHIs here to not miss important unrollings. */
1516 if (TREE_CODE (init_cond) == SSA_NAME)
1518 gimple def = SSA_NAME_DEF_STMT (init_cond);
1519 tree res;
1520 if (gimple_code (def) == GIMPLE_PHI
1521 && (res = degenerate_phi_result (def)) != NULL_TREE
1522 /* Only allow invariants here, otherwise we may break
1523 loop-closed SSA form. */
1524 && is_gimple_min_invariant (res))
1525 init_cond = res;
1528 if (dump_file && (dump_flags & TDF_SCEV))
1530 fprintf (dump_file, " (init_cond = ");
1531 print_generic_expr (dump_file, init_cond, 0);
1532 fprintf (dump_file, "))\n");
1535 return init_cond;
1538 /* Analyze the scalar evolution for LOOP_PHI_NODE. */
1540 static tree
1541 interpret_loop_phi (struct loop *loop, gimple loop_phi_node)
1543 tree res;
1544 struct loop *phi_loop = loop_containing_stmt (loop_phi_node);
1545 tree init_cond;
1547 if (phi_loop != loop)
1549 struct loop *subloop;
1550 tree evolution_fn = analyze_scalar_evolution
1551 (phi_loop, PHI_RESULT (loop_phi_node));
1553 /* Dive one level deeper. */
1554 subloop = superloop_at_depth (phi_loop, loop_depth (loop) + 1);
1556 /* Interpret the subloop. */
1557 res = compute_overall_effect_of_inner_loop (subloop, evolution_fn);
1558 return res;
1561 /* Otherwise really interpret the loop phi. */
1562 init_cond = analyze_initial_condition (loop_phi_node);
1563 res = analyze_evolution_in_loop (loop_phi_node, init_cond);
1565 /* Verify we maintained the correct initial condition throughout
1566 possible conversions in the SSA chain. */
1567 if (res != chrec_dont_know)
1569 tree new_init = res;
1570 if (CONVERT_EXPR_P (res)
1571 && TREE_CODE (TREE_OPERAND (res, 0)) == POLYNOMIAL_CHREC)
1572 new_init = fold_convert (TREE_TYPE (res),
1573 CHREC_LEFT (TREE_OPERAND (res, 0)));
1574 else if (TREE_CODE (res) == POLYNOMIAL_CHREC)
1575 new_init = CHREC_LEFT (res);
1576 STRIP_USELESS_TYPE_CONVERSION (new_init);
1577 if (TREE_CODE (new_init) == POLYNOMIAL_CHREC
1578 || !operand_equal_p (init_cond, new_init, 0))
1579 return chrec_dont_know;
1582 return res;
1585 /* This function merges the branches of a condition-phi-node,
1586 contained in the outermost loop, and whose arguments are already
1587 analyzed. */
1589 static tree
1590 interpret_condition_phi (struct loop *loop, gimple condition_phi)
1592 int i, n = gimple_phi_num_args (condition_phi);
1593 tree res = chrec_not_analyzed_yet;
1595 for (i = 0; i < n; i++)
1597 tree branch_chrec;
1599 if (backedge_phi_arg_p (condition_phi, i))
1601 res = chrec_dont_know;
1602 break;
1605 branch_chrec = analyze_scalar_evolution
1606 (loop, PHI_ARG_DEF (condition_phi, i));
1608 res = chrec_merge (res, branch_chrec);
1611 return res;
1614 /* Interpret the operation RHS1 OP RHS2. If we didn't
1615 analyze this node before, follow the definitions until ending
1616 either on an analyzed GIMPLE_ASSIGN, or on a loop-phi-node. On the
1617 return path, this function propagates evolutions (ala constant copy
1618 propagation). OPND1 is not a GIMPLE expression because we could
1619 analyze the effect of an inner loop: see interpret_loop_phi. */
1621 static tree
1622 interpret_rhs_expr (struct loop *loop, gimple at_stmt,
1623 tree type, tree rhs1, enum tree_code code, tree rhs2)
1625 tree res, chrec1, chrec2;
1626 gimple def;
1628 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1630 if (is_gimple_min_invariant (rhs1))
1631 return chrec_convert (type, rhs1, at_stmt);
1633 if (code == SSA_NAME)
1634 return chrec_convert (type, analyze_scalar_evolution (loop, rhs1),
1635 at_stmt);
1637 if (code == ASSERT_EXPR)
1639 rhs1 = ASSERT_EXPR_VAR (rhs1);
1640 return chrec_convert (type, analyze_scalar_evolution (loop, rhs1),
1641 at_stmt);
1645 switch (code)
1647 case ADDR_EXPR:
1648 if (TREE_CODE (TREE_OPERAND (rhs1, 0)) == MEM_REF
1649 || handled_component_p (TREE_OPERAND (rhs1, 0)))
1651 enum machine_mode mode;
1652 HOST_WIDE_INT bitsize, bitpos;
1653 int unsignedp;
1654 int volatilep = 0;
1655 tree base, offset;
1656 tree chrec3;
1657 tree unitpos;
1659 base = get_inner_reference (TREE_OPERAND (rhs1, 0),
1660 &bitsize, &bitpos, &offset,
1661 &mode, &unsignedp, &volatilep, false);
1663 if (TREE_CODE (base) == MEM_REF)
1665 rhs2 = TREE_OPERAND (base, 1);
1666 rhs1 = TREE_OPERAND (base, 0);
1668 chrec1 = analyze_scalar_evolution (loop, rhs1);
1669 chrec2 = analyze_scalar_evolution (loop, rhs2);
1670 chrec1 = chrec_convert (type, chrec1, at_stmt);
1671 chrec2 = chrec_convert (TREE_TYPE (rhs2), chrec2, at_stmt);
1672 chrec1 = instantiate_parameters (loop, chrec1);
1673 chrec2 = instantiate_parameters (loop, chrec2);
1674 res = chrec_fold_plus (type, chrec1, chrec2);
1676 else
1678 chrec1 = analyze_scalar_evolution_for_address_of (loop, base);
1679 chrec1 = chrec_convert (type, chrec1, at_stmt);
1680 res = chrec1;
1683 if (offset != NULL_TREE)
1685 chrec2 = analyze_scalar_evolution (loop, offset);
1686 chrec2 = chrec_convert (TREE_TYPE (offset), chrec2, at_stmt);
1687 chrec2 = instantiate_parameters (loop, chrec2);
1688 res = chrec_fold_plus (type, res, chrec2);
1691 if (bitpos != 0)
1693 gcc_assert ((bitpos % BITS_PER_UNIT) == 0);
1695 unitpos = size_int (bitpos / BITS_PER_UNIT);
1696 chrec3 = analyze_scalar_evolution (loop, unitpos);
1697 chrec3 = chrec_convert (TREE_TYPE (unitpos), chrec3, at_stmt);
1698 chrec3 = instantiate_parameters (loop, chrec3);
1699 res = chrec_fold_plus (type, res, chrec3);
1702 else
1703 res = chrec_dont_know;
1704 break;
1706 case POINTER_PLUS_EXPR:
1707 chrec1 = analyze_scalar_evolution (loop, rhs1);
1708 chrec2 = analyze_scalar_evolution (loop, rhs2);
1709 chrec1 = chrec_convert (type, chrec1, at_stmt);
1710 chrec2 = chrec_convert (TREE_TYPE (rhs2), chrec2, at_stmt);
1711 chrec1 = instantiate_parameters (loop, chrec1);
1712 chrec2 = instantiate_parameters (loop, chrec2);
1713 res = chrec_fold_plus (type, chrec1, chrec2);
1714 break;
1716 case PLUS_EXPR:
1717 chrec1 = analyze_scalar_evolution (loop, rhs1);
1718 chrec2 = analyze_scalar_evolution (loop, rhs2);
1719 chrec1 = chrec_convert (type, chrec1, at_stmt);
1720 chrec2 = chrec_convert (type, chrec2, at_stmt);
1721 chrec1 = instantiate_parameters (loop, chrec1);
1722 chrec2 = instantiate_parameters (loop, chrec2);
1723 res = chrec_fold_plus (type, chrec1, chrec2);
1724 break;
1726 case MINUS_EXPR:
1727 chrec1 = analyze_scalar_evolution (loop, rhs1);
1728 chrec2 = analyze_scalar_evolution (loop, rhs2);
1729 chrec1 = chrec_convert (type, chrec1, at_stmt);
1730 chrec2 = chrec_convert (type, chrec2, at_stmt);
1731 chrec1 = instantiate_parameters (loop, chrec1);
1732 chrec2 = instantiate_parameters (loop, chrec2);
1733 res = chrec_fold_minus (type, chrec1, chrec2);
1734 break;
1736 case NEGATE_EXPR:
1737 chrec1 = analyze_scalar_evolution (loop, rhs1);
1738 chrec1 = chrec_convert (type, chrec1, at_stmt);
1739 /* TYPE may be integer, real or complex, so use fold_convert. */
1740 chrec1 = instantiate_parameters (loop, chrec1);
1741 res = chrec_fold_multiply (type, chrec1,
1742 fold_convert (type, integer_minus_one_node));
1743 break;
1745 case BIT_NOT_EXPR:
1746 /* Handle ~X as -1 - X. */
1747 chrec1 = analyze_scalar_evolution (loop, rhs1);
1748 chrec1 = chrec_convert (type, chrec1, at_stmt);
1749 chrec1 = instantiate_parameters (loop, chrec1);
1750 res = chrec_fold_minus (type,
1751 fold_convert (type, integer_minus_one_node),
1752 chrec1);
1753 break;
1755 case MULT_EXPR:
1756 chrec1 = analyze_scalar_evolution (loop, rhs1);
1757 chrec2 = analyze_scalar_evolution (loop, rhs2);
1758 chrec1 = chrec_convert (type, chrec1, at_stmt);
1759 chrec2 = chrec_convert (type, chrec2, at_stmt);
1760 chrec1 = instantiate_parameters (loop, chrec1);
1761 chrec2 = instantiate_parameters (loop, chrec2);
1762 res = chrec_fold_multiply (type, chrec1, chrec2);
1763 break;
1765 CASE_CONVERT:
1766 /* In case we have a truncation of a widened operation that in
1767 the truncated type has undefined overflow behavior analyze
1768 the operation done in an unsigned type of the same precision
1769 as the final truncation. We cannot derive a scalar evolution
1770 for the widened operation but for the truncated result. */
1771 if (TREE_CODE (type) == INTEGER_TYPE
1772 && TREE_CODE (TREE_TYPE (rhs1)) == INTEGER_TYPE
1773 && TYPE_PRECISION (type) < TYPE_PRECISION (TREE_TYPE (rhs1))
1774 && TYPE_OVERFLOW_UNDEFINED (type)
1775 && TREE_CODE (rhs1) == SSA_NAME
1776 && (def = SSA_NAME_DEF_STMT (rhs1))
1777 && is_gimple_assign (def)
1778 && TREE_CODE_CLASS (gimple_assign_rhs_code (def)) == tcc_binary
1779 && TREE_CODE (gimple_assign_rhs2 (def)) == INTEGER_CST)
1781 tree utype = unsigned_type_for (type);
1782 chrec1 = interpret_rhs_expr (loop, at_stmt, utype,
1783 gimple_assign_rhs1 (def),
1784 gimple_assign_rhs_code (def),
1785 gimple_assign_rhs2 (def));
1787 else
1788 chrec1 = analyze_scalar_evolution (loop, rhs1);
1789 res = chrec_convert (type, chrec1, at_stmt);
1790 break;
1792 default:
1793 res = chrec_dont_know;
1794 break;
1797 return res;
1800 /* Interpret the expression EXPR. */
1802 static tree
1803 interpret_expr (struct loop *loop, gimple at_stmt, tree expr)
1805 enum tree_code code;
1806 tree type = TREE_TYPE (expr), op0, op1;
1808 if (automatically_generated_chrec_p (expr))
1809 return expr;
1811 if (TREE_CODE (expr) == POLYNOMIAL_CHREC
1812 || get_gimple_rhs_class (TREE_CODE (expr)) == GIMPLE_TERNARY_RHS)
1813 return chrec_dont_know;
1815 extract_ops_from_tree (expr, &code, &op0, &op1);
1817 return interpret_rhs_expr (loop, at_stmt, type,
1818 op0, code, op1);
1821 /* Interpret the rhs of the assignment STMT. */
1823 static tree
1824 interpret_gimple_assign (struct loop *loop, gimple stmt)
1826 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
1827 enum tree_code code = gimple_assign_rhs_code (stmt);
1829 return interpret_rhs_expr (loop, stmt, type,
1830 gimple_assign_rhs1 (stmt), code,
1831 gimple_assign_rhs2 (stmt));
1836 /* This section contains all the entry points:
1837 - number_of_iterations_in_loop,
1838 - analyze_scalar_evolution,
1839 - instantiate_parameters.
1842 /* Compute and return the evolution function in WRTO_LOOP, the nearest
1843 common ancestor of DEF_LOOP and USE_LOOP. */
1845 static tree
1846 compute_scalar_evolution_in_loop (struct loop *wrto_loop,
1847 struct loop *def_loop,
1848 tree ev)
1850 bool val;
1851 tree res;
1853 if (def_loop == wrto_loop)
1854 return ev;
1856 def_loop = superloop_at_depth (def_loop, loop_depth (wrto_loop) + 1);
1857 res = compute_overall_effect_of_inner_loop (def_loop, ev);
1859 if (no_evolution_in_loop_p (res, wrto_loop->num, &val) && val)
1860 return res;
1862 return analyze_scalar_evolution_1 (wrto_loop, res, chrec_not_analyzed_yet);
1865 /* Helper recursive function. */
1867 static tree
1868 analyze_scalar_evolution_1 (struct loop *loop, tree var, tree res)
1870 tree type = TREE_TYPE (var);
1871 gimple def;
1872 basic_block bb;
1873 struct loop *def_loop;
1875 if (loop == NULL || TREE_CODE (type) == VECTOR_TYPE)
1876 return chrec_dont_know;
1878 if (TREE_CODE (var) != SSA_NAME)
1879 return interpret_expr (loop, NULL, var);
1881 def = SSA_NAME_DEF_STMT (var);
1882 bb = gimple_bb (def);
1883 def_loop = bb ? bb->loop_father : NULL;
1885 if (bb == NULL
1886 || !flow_bb_inside_loop_p (loop, bb))
1888 /* Keep the symbolic form. */
1889 res = var;
1890 goto set_and_end;
1893 if (res != chrec_not_analyzed_yet)
1895 if (loop != bb->loop_father)
1896 res = compute_scalar_evolution_in_loop
1897 (find_common_loop (loop, bb->loop_father), bb->loop_father, res);
1899 goto set_and_end;
1902 if (loop != def_loop)
1904 res = analyze_scalar_evolution_1 (def_loop, var, chrec_not_analyzed_yet);
1905 res = compute_scalar_evolution_in_loop (loop, def_loop, res);
1907 goto set_and_end;
1910 switch (gimple_code (def))
1912 case GIMPLE_ASSIGN:
1913 res = interpret_gimple_assign (loop, def);
1914 break;
1916 case GIMPLE_PHI:
1917 if (loop_phi_node_p (def))
1918 res = interpret_loop_phi (loop, def);
1919 else
1920 res = interpret_condition_phi (loop, def);
1921 break;
1923 default:
1924 res = chrec_dont_know;
1925 break;
1928 set_and_end:
1930 /* Keep the symbolic form. */
1931 if (res == chrec_dont_know)
1932 res = var;
1934 if (loop == def_loop)
1935 set_scalar_evolution (block_before_loop (loop), var, res);
1937 return res;
1940 /* Analyzes and returns the scalar evolution of the ssa_name VAR in
1941 LOOP. LOOP is the loop in which the variable is used.
1943 Example of use: having a pointer VAR to a SSA_NAME node, STMT a
1944 pointer to the statement that uses this variable, in order to
1945 determine the evolution function of the variable, use the following
1946 calls:
1948 loop_p loop = loop_containing_stmt (stmt);
1949 tree chrec_with_symbols = analyze_scalar_evolution (loop, var);
1950 tree chrec_instantiated = instantiate_parameters (loop, chrec_with_symbols);
1953 tree
1954 analyze_scalar_evolution (struct loop *loop, tree var)
1956 tree res;
1958 if (dump_file && (dump_flags & TDF_SCEV))
1960 fprintf (dump_file, "(analyze_scalar_evolution \n");
1961 fprintf (dump_file, " (loop_nb = %d)\n", loop->num);
1962 fprintf (dump_file, " (scalar = ");
1963 print_generic_expr (dump_file, var, 0);
1964 fprintf (dump_file, ")\n");
1967 res = get_scalar_evolution (block_before_loop (loop), var);
1968 res = analyze_scalar_evolution_1 (loop, var, res);
1970 if (dump_file && (dump_flags & TDF_SCEV))
1971 fprintf (dump_file, ")\n");
1973 return res;
1976 /* Analyzes and returns the scalar evolution of VAR address in LOOP. */
1978 static tree
1979 analyze_scalar_evolution_for_address_of (struct loop *loop, tree var)
1981 return analyze_scalar_evolution (loop, build_fold_addr_expr (var));
1984 /* Analyze scalar evolution of use of VERSION in USE_LOOP with respect to
1985 WRTO_LOOP (which should be a superloop of USE_LOOP)
1987 FOLDED_CASTS is set to true if resolve_mixers used
1988 chrec_convert_aggressive (TODO -- not really, we are way too conservative
1989 at the moment in order to keep things simple).
1991 To illustrate the meaning of USE_LOOP and WRTO_LOOP, consider the following
1992 example:
1994 for (i = 0; i < 100; i++) -- loop 1
1996 for (j = 0; j < 100; j++) -- loop 2
1998 k1 = i;
1999 k2 = j;
2001 use2 (k1, k2);
2003 for (t = 0; t < 100; t++) -- loop 3
2004 use3 (k1, k2);
2007 use1 (k1, k2);
2010 Both k1 and k2 are invariants in loop3, thus
2011 analyze_scalar_evolution_in_loop (loop3, loop3, k1) = k1
2012 analyze_scalar_evolution_in_loop (loop3, loop3, k2) = k2
2014 As they are invariant, it does not matter whether we consider their
2015 usage in loop 3 or loop 2, hence
2016 analyze_scalar_evolution_in_loop (loop2, loop3, k1) =
2017 analyze_scalar_evolution_in_loop (loop2, loop2, k1) = i
2018 analyze_scalar_evolution_in_loop (loop2, loop3, k2) =
2019 analyze_scalar_evolution_in_loop (loop2, loop2, k2) = [0,+,1]_2
2021 Similarly for their evolutions with respect to loop 1. The values of K2
2022 in the use in loop 2 vary independently on loop 1, thus we cannot express
2023 the evolution with respect to loop 1:
2024 analyze_scalar_evolution_in_loop (loop1, loop3, k1) =
2025 analyze_scalar_evolution_in_loop (loop1, loop2, k1) = [0,+,1]_1
2026 analyze_scalar_evolution_in_loop (loop1, loop3, k2) =
2027 analyze_scalar_evolution_in_loop (loop1, loop2, k2) = dont_know
2029 The value of k2 in the use in loop 1 is known, though:
2030 analyze_scalar_evolution_in_loop (loop1, loop1, k1) = [0,+,1]_1
2031 analyze_scalar_evolution_in_loop (loop1, loop1, k2) = 100
2034 static tree
2035 analyze_scalar_evolution_in_loop (struct loop *wrto_loop, struct loop *use_loop,
2036 tree version, bool *folded_casts)
2038 bool val = false;
2039 tree ev = version, tmp;
2041 /* We cannot just do
2043 tmp = analyze_scalar_evolution (use_loop, version);
2044 ev = resolve_mixers (wrto_loop, tmp);
2046 as resolve_mixers would query the scalar evolution with respect to
2047 wrto_loop. For example, in the situation described in the function
2048 comment, suppose that wrto_loop = loop1, use_loop = loop3 and
2049 version = k2. Then
2051 analyze_scalar_evolution (use_loop, version) = k2
2053 and resolve_mixers (loop1, k2) finds that the value of k2 in loop 1
2054 is 100, which is a wrong result, since we are interested in the
2055 value in loop 3.
2057 Instead, we need to proceed from use_loop to wrto_loop loop by loop,
2058 each time checking that there is no evolution in the inner loop. */
2060 if (folded_casts)
2061 *folded_casts = false;
2062 while (1)
2064 tmp = analyze_scalar_evolution (use_loop, ev);
2065 ev = resolve_mixers (use_loop, tmp);
2067 if (folded_casts && tmp != ev)
2068 *folded_casts = true;
2070 if (use_loop == wrto_loop)
2071 return ev;
2073 /* If the value of the use changes in the inner loop, we cannot express
2074 its value in the outer loop (we might try to return interval chrec,
2075 but we do not have a user for it anyway) */
2076 if (!no_evolution_in_loop_p (ev, use_loop->num, &val)
2077 || !val)
2078 return chrec_dont_know;
2080 use_loop = loop_outer (use_loop);
2085 /* Hashtable helpers for a temporary hash-table used when
2086 instantiating a CHREC or resolving mixers. For this use
2087 instantiated_below is always the same. */
2089 struct instantiate_cache_type
2091 htab_t map;
2092 vec<scev_info_str> entries;
2094 instantiate_cache_type () : map (NULL), entries (vNULL) {}
2095 ~instantiate_cache_type ();
2096 tree get (unsigned slot) { return entries[slot].chrec; }
2097 void set (unsigned slot, tree chrec) { entries[slot].chrec = chrec; }
2100 instantiate_cache_type::~instantiate_cache_type ()
2102 if (map != NULL)
2104 htab_delete (map);
2105 entries.release ();
2109 /* Cache to avoid infinite recursion when instantiating an SSA name.
2110 Live during the outermost instantiate_scev or resolve_mixers call. */
2111 static instantiate_cache_type *global_cache;
2113 /* Computes a hash function for database element ELT. */
2115 static inline hashval_t
2116 hash_idx_scev_info (const void *elt_)
2118 unsigned idx = ((size_t) elt_) - 2;
2119 return hash_scev_info (&global_cache->entries[idx]);
2122 /* Compares database elements E1 and E2. */
2124 static inline int
2125 eq_idx_scev_info (const void *e1, const void *e2)
2127 unsigned idx1 = ((size_t) e1) - 2;
2128 return eq_scev_info (&global_cache->entries[idx1], e2);
2131 /* Returns from CACHE the slot number of the cached chrec for NAME. */
2133 static unsigned
2134 get_instantiated_value_entry (instantiate_cache_type &cache,
2135 tree name, basic_block instantiate_below)
2137 if (!cache.map)
2139 cache.map = htab_create (10, hash_idx_scev_info, eq_idx_scev_info, NULL);
2140 cache.entries.create (10);
2143 scev_info_str e;
2144 e.name_version = SSA_NAME_VERSION (name);
2145 e.instantiated_below = instantiate_below->index;
2146 void **slot = htab_find_slot_with_hash (cache.map, &e,
2147 hash_scev_info (&e), INSERT);
2148 if (!*slot)
2150 e.chrec = chrec_not_analyzed_yet;
2151 *slot = (void *)(size_t)(cache.entries.length () + 2);
2152 cache.entries.safe_push (e);
2155 return ((size_t)*slot) - 2;
2159 /* Return the closed_loop_phi node for VAR. If there is none, return
2160 NULL_TREE. */
2162 static tree
2163 loop_closed_phi_def (tree var)
2165 struct loop *loop;
2166 edge exit;
2167 gimple phi;
2168 gimple_stmt_iterator psi;
2170 if (var == NULL_TREE
2171 || TREE_CODE (var) != SSA_NAME)
2172 return NULL_TREE;
2174 loop = loop_containing_stmt (SSA_NAME_DEF_STMT (var));
2175 exit = single_exit (loop);
2176 if (!exit)
2177 return NULL_TREE;
2179 for (psi = gsi_start_phis (exit->dest); !gsi_end_p (psi); gsi_next (&psi))
2181 phi = gsi_stmt (psi);
2182 if (PHI_ARG_DEF_FROM_EDGE (phi, exit) == var)
2183 return PHI_RESULT (phi);
2186 return NULL_TREE;
2189 static tree instantiate_scev_r (basic_block, struct loop *, struct loop *,
2190 tree, bool, int);
2192 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2193 and EVOLUTION_LOOP, that were left under a symbolic form.
2195 CHREC is an SSA_NAME to be instantiated.
2197 CACHE is the cache of already instantiated values.
2199 FOLD_CONVERSIONS should be set to true when the conversions that
2200 may wrap in signed/pointer type are folded, as long as the value of
2201 the chrec is preserved.
2203 SIZE_EXPR is used for computing the size of the expression to be
2204 instantiated, and to stop if it exceeds some limit. */
2206 static tree
2207 instantiate_scev_name (basic_block instantiate_below,
2208 struct loop *evolution_loop, struct loop *inner_loop,
2209 tree chrec,
2210 bool fold_conversions,
2211 int size_expr)
2213 tree res;
2214 struct loop *def_loop;
2215 basic_block def_bb = gimple_bb (SSA_NAME_DEF_STMT (chrec));
2217 /* A parameter (or loop invariant and we do not want to include
2218 evolutions in outer loops), nothing to do. */
2219 if (!def_bb
2220 || loop_depth (def_bb->loop_father) == 0
2221 || dominated_by_p (CDI_DOMINATORS, instantiate_below, def_bb))
2222 return chrec;
2224 /* We cache the value of instantiated variable to avoid exponential
2225 time complexity due to reevaluations. We also store the convenient
2226 value in the cache in order to prevent infinite recursion -- we do
2227 not want to instantiate the SSA_NAME if it is in a mixer
2228 structure. This is used for avoiding the instantiation of
2229 recursively defined functions, such as:
2231 | a_2 -> {0, +, 1, +, a_2}_1 */
2233 unsigned si = get_instantiated_value_entry (*global_cache,
2234 chrec, instantiate_below);
2235 if (global_cache->get (si) != chrec_not_analyzed_yet)
2236 return global_cache->get (si);
2238 /* On recursion return chrec_dont_know. */
2239 global_cache->set (si, chrec_dont_know);
2241 def_loop = find_common_loop (evolution_loop, def_bb->loop_father);
2243 /* If the analysis yields a parametric chrec, instantiate the
2244 result again. */
2245 res = analyze_scalar_evolution (def_loop, chrec);
2247 /* Don't instantiate default definitions. */
2248 if (TREE_CODE (res) == SSA_NAME
2249 && SSA_NAME_IS_DEFAULT_DEF (res))
2252 /* Don't instantiate loop-closed-ssa phi nodes. */
2253 else if (TREE_CODE (res) == SSA_NAME
2254 && loop_depth (loop_containing_stmt (SSA_NAME_DEF_STMT (res)))
2255 > loop_depth (def_loop))
2257 if (res == chrec)
2258 res = loop_closed_phi_def (chrec);
2259 else
2260 res = chrec;
2262 /* When there is no loop_closed_phi_def, it means that the
2263 variable is not used after the loop: try to still compute the
2264 value of the variable when exiting the loop. */
2265 if (res == NULL_TREE)
2267 loop_p loop = loop_containing_stmt (SSA_NAME_DEF_STMT (chrec));
2268 res = analyze_scalar_evolution (loop, chrec);
2269 res = compute_overall_effect_of_inner_loop (loop, res);
2270 res = instantiate_scev_r (instantiate_below, evolution_loop,
2271 inner_loop, res,
2272 fold_conversions, size_expr);
2274 else if (!dominated_by_p (CDI_DOMINATORS, instantiate_below,
2275 gimple_bb (SSA_NAME_DEF_STMT (res))))
2276 res = chrec_dont_know;
2279 else if (res != chrec_dont_know)
2281 if (inner_loop
2282 && def_bb->loop_father != inner_loop
2283 && !flow_loop_nested_p (def_bb->loop_father, inner_loop))
2284 /* ??? We could try to compute the overall effect of the loop here. */
2285 res = chrec_dont_know;
2286 else
2287 res = instantiate_scev_r (instantiate_below, evolution_loop,
2288 inner_loop, res,
2289 fold_conversions, size_expr);
2292 /* Store the correct value to the cache. */
2293 global_cache->set (si, res);
2294 return res;
2297 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2298 and EVOLUTION_LOOP, that were left under a symbolic form.
2300 CHREC is a polynomial chain of recurrence to be instantiated.
2302 CACHE is the cache of already instantiated values.
2304 FOLD_CONVERSIONS should be set to true when the conversions that
2305 may wrap in signed/pointer type are folded, as long as the value of
2306 the chrec is preserved.
2308 SIZE_EXPR is used for computing the size of the expression to be
2309 instantiated, and to stop if it exceeds some limit. */
2311 static tree
2312 instantiate_scev_poly (basic_block instantiate_below,
2313 struct loop *evolution_loop, struct loop *,
2314 tree chrec, bool fold_conversions, int size_expr)
2316 tree op1;
2317 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2318 get_chrec_loop (chrec),
2319 CHREC_LEFT (chrec), fold_conversions,
2320 size_expr);
2321 if (op0 == chrec_dont_know)
2322 return chrec_dont_know;
2324 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2325 get_chrec_loop (chrec),
2326 CHREC_RIGHT (chrec), fold_conversions,
2327 size_expr);
2328 if (op1 == chrec_dont_know)
2329 return chrec_dont_know;
2331 if (CHREC_LEFT (chrec) != op0
2332 || CHREC_RIGHT (chrec) != op1)
2334 op1 = chrec_convert_rhs (chrec_type (op0), op1, NULL);
2335 chrec = build_polynomial_chrec (CHREC_VARIABLE (chrec), op0, op1);
2338 return chrec;
2341 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2342 and EVOLUTION_LOOP, that were left under a symbolic form.
2344 "C0 CODE C1" is a binary expression of type TYPE to be instantiated.
2346 CACHE is the cache of already instantiated values.
2348 FOLD_CONVERSIONS should be set to true when the conversions that
2349 may wrap in signed/pointer type are folded, as long as the value of
2350 the chrec is preserved.
2352 SIZE_EXPR is used for computing the size of the expression to be
2353 instantiated, and to stop if it exceeds some limit. */
2355 static tree
2356 instantiate_scev_binary (basic_block instantiate_below,
2357 struct loop *evolution_loop, struct loop *inner_loop,
2358 tree chrec, enum tree_code code,
2359 tree type, tree c0, tree c1,
2360 bool fold_conversions, int size_expr)
2362 tree op1;
2363 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop, inner_loop,
2364 c0, fold_conversions, size_expr);
2365 if (op0 == chrec_dont_know)
2366 return chrec_dont_know;
2368 op1 = instantiate_scev_r (instantiate_below, evolution_loop, inner_loop,
2369 c1, fold_conversions, size_expr);
2370 if (op1 == chrec_dont_know)
2371 return chrec_dont_know;
2373 if (c0 != op0
2374 || c1 != op1)
2376 op0 = chrec_convert (type, op0, NULL);
2377 op1 = chrec_convert_rhs (type, op1, NULL);
2379 switch (code)
2381 case POINTER_PLUS_EXPR:
2382 case PLUS_EXPR:
2383 return chrec_fold_plus (type, op0, op1);
2385 case MINUS_EXPR:
2386 return chrec_fold_minus (type, op0, op1);
2388 case MULT_EXPR:
2389 return chrec_fold_multiply (type, op0, op1);
2391 default:
2392 gcc_unreachable ();
2396 return chrec ? chrec : fold_build2 (code, type, c0, c1);
2399 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2400 and EVOLUTION_LOOP, that were left under a symbolic form.
2402 "CHREC" is an array reference to be instantiated.
2404 CACHE is the cache of already instantiated values.
2406 FOLD_CONVERSIONS should be set to true when the conversions that
2407 may wrap in signed/pointer type are folded, as long as the value of
2408 the chrec is preserved.
2410 SIZE_EXPR is used for computing the size of the expression to be
2411 instantiated, and to stop if it exceeds some limit. */
2413 static tree
2414 instantiate_array_ref (basic_block instantiate_below,
2415 struct loop *evolution_loop, struct loop *inner_loop,
2416 tree chrec, bool fold_conversions, int size_expr)
2418 tree res;
2419 tree index = TREE_OPERAND (chrec, 1);
2420 tree op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2421 inner_loop, index,
2422 fold_conversions, size_expr);
2424 if (op1 == chrec_dont_know)
2425 return chrec_dont_know;
2427 if (chrec && op1 == index)
2428 return chrec;
2430 res = unshare_expr (chrec);
2431 TREE_OPERAND (res, 1) = op1;
2432 return res;
2435 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2436 and EVOLUTION_LOOP, that were left under a symbolic form.
2438 "CHREC" that stands for a convert expression "(TYPE) OP" is to be
2439 instantiated.
2441 CACHE is the cache of already instantiated values.
2443 FOLD_CONVERSIONS should be set to true when the conversions that
2444 may wrap in signed/pointer type are folded, as long as the value of
2445 the chrec is preserved.
2447 SIZE_EXPR is used for computing the size of the expression to be
2448 instantiated, and to stop if it exceeds some limit. */
2450 static tree
2451 instantiate_scev_convert (basic_block instantiate_below,
2452 struct loop *evolution_loop, struct loop *inner_loop,
2453 tree chrec, tree type, tree op,
2454 bool fold_conversions, int size_expr)
2456 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2457 inner_loop, op,
2458 fold_conversions, size_expr);
2460 if (op0 == chrec_dont_know)
2461 return chrec_dont_know;
2463 if (fold_conversions)
2465 tree tmp = chrec_convert_aggressive (type, op0);
2466 if (tmp)
2467 return tmp;
2470 if (chrec && op0 == op)
2471 return chrec;
2473 /* If we used chrec_convert_aggressive, we can no longer assume that
2474 signed chrecs do not overflow, as chrec_convert does, so avoid
2475 calling it in that case. */
2476 if (fold_conversions)
2477 return fold_convert (type, op0);
2479 return chrec_convert (type, op0, NULL);
2482 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2483 and EVOLUTION_LOOP, that were left under a symbolic form.
2485 CHREC is a BIT_NOT_EXPR or a NEGATE_EXPR expression to be instantiated.
2486 Handle ~X as -1 - X.
2487 Handle -X as -1 * X.
2489 CACHE is the cache of already instantiated values.
2491 FOLD_CONVERSIONS should be set to true when the conversions that
2492 may wrap in signed/pointer type are folded, as long as the value of
2493 the chrec is preserved.
2495 SIZE_EXPR is used for computing the size of the expression to be
2496 instantiated, and to stop if it exceeds some limit. */
2498 static tree
2499 instantiate_scev_not (basic_block instantiate_below,
2500 struct loop *evolution_loop, struct loop *inner_loop,
2501 tree chrec,
2502 enum tree_code code, tree type, tree op,
2503 bool fold_conversions, int size_expr)
2505 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2506 inner_loop, op,
2507 fold_conversions, size_expr);
2509 if (op0 == chrec_dont_know)
2510 return chrec_dont_know;
2512 if (op != op0)
2514 op0 = chrec_convert (type, op0, NULL);
2516 switch (code)
2518 case BIT_NOT_EXPR:
2519 return chrec_fold_minus
2520 (type, fold_convert (type, integer_minus_one_node), op0);
2522 case NEGATE_EXPR:
2523 return chrec_fold_multiply
2524 (type, fold_convert (type, integer_minus_one_node), op0);
2526 default:
2527 gcc_unreachable ();
2531 return chrec ? chrec : fold_build1 (code, type, op0);
2534 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2535 and EVOLUTION_LOOP, that were left under a symbolic form.
2537 CHREC is an expression with 3 operands to be instantiated.
2539 CACHE is the cache of already instantiated values.
2541 FOLD_CONVERSIONS should be set to true when the conversions that
2542 may wrap in signed/pointer type are folded, as long as the value of
2543 the chrec is preserved.
2545 SIZE_EXPR is used for computing the size of the expression to be
2546 instantiated, and to stop if it exceeds some limit. */
2548 static tree
2549 instantiate_scev_3 (basic_block instantiate_below,
2550 struct loop *evolution_loop, struct loop *inner_loop,
2551 tree chrec,
2552 bool fold_conversions, int size_expr)
2554 tree op1, op2;
2555 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2556 inner_loop, TREE_OPERAND (chrec, 0),
2557 fold_conversions, size_expr);
2558 if (op0 == chrec_dont_know)
2559 return chrec_dont_know;
2561 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2562 inner_loop, TREE_OPERAND (chrec, 1),
2563 fold_conversions, size_expr);
2564 if (op1 == chrec_dont_know)
2565 return chrec_dont_know;
2567 op2 = instantiate_scev_r (instantiate_below, evolution_loop,
2568 inner_loop, TREE_OPERAND (chrec, 2),
2569 fold_conversions, size_expr);
2570 if (op2 == chrec_dont_know)
2571 return chrec_dont_know;
2573 if (op0 == TREE_OPERAND (chrec, 0)
2574 && op1 == TREE_OPERAND (chrec, 1)
2575 && op2 == TREE_OPERAND (chrec, 2))
2576 return chrec;
2578 return fold_build3 (TREE_CODE (chrec),
2579 TREE_TYPE (chrec), op0, op1, op2);
2582 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2583 and EVOLUTION_LOOP, that were left under a symbolic form.
2585 CHREC is an expression with 2 operands to be instantiated.
2587 CACHE is the cache of already instantiated values.
2589 FOLD_CONVERSIONS should be set to true when the conversions that
2590 may wrap in signed/pointer type are folded, as long as the value of
2591 the chrec is preserved.
2593 SIZE_EXPR is used for computing the size of the expression to be
2594 instantiated, and to stop if it exceeds some limit. */
2596 static tree
2597 instantiate_scev_2 (basic_block instantiate_below,
2598 struct loop *evolution_loop, struct loop *inner_loop,
2599 tree chrec,
2600 bool fold_conversions, int size_expr)
2602 tree op1;
2603 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2604 inner_loop, TREE_OPERAND (chrec, 0),
2605 fold_conversions, size_expr);
2606 if (op0 == chrec_dont_know)
2607 return chrec_dont_know;
2609 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2610 inner_loop, TREE_OPERAND (chrec, 1),
2611 fold_conversions, size_expr);
2612 if (op1 == chrec_dont_know)
2613 return chrec_dont_know;
2615 if (op0 == TREE_OPERAND (chrec, 0)
2616 && op1 == TREE_OPERAND (chrec, 1))
2617 return chrec;
2619 return fold_build2 (TREE_CODE (chrec), TREE_TYPE (chrec), op0, op1);
2622 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2623 and EVOLUTION_LOOP, that were left under a symbolic form.
2625 CHREC is an expression with 2 operands to be instantiated.
2627 CACHE is the cache of already instantiated values.
2629 FOLD_CONVERSIONS should be set to true when the conversions that
2630 may wrap in signed/pointer type are folded, as long as the value of
2631 the chrec is preserved.
2633 SIZE_EXPR is used for computing the size of the expression to be
2634 instantiated, and to stop if it exceeds some limit. */
2636 static tree
2637 instantiate_scev_1 (basic_block instantiate_below,
2638 struct loop *evolution_loop, struct loop *inner_loop,
2639 tree chrec,
2640 bool fold_conversions, int size_expr)
2642 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2643 inner_loop, TREE_OPERAND (chrec, 0),
2644 fold_conversions, size_expr);
2646 if (op0 == chrec_dont_know)
2647 return chrec_dont_know;
2649 if (op0 == TREE_OPERAND (chrec, 0))
2650 return chrec;
2652 return fold_build1 (TREE_CODE (chrec), TREE_TYPE (chrec), op0);
2655 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2656 and EVOLUTION_LOOP, that were left under a symbolic form.
2658 CHREC is the scalar evolution to instantiate.
2660 CACHE is the cache of already instantiated values.
2662 FOLD_CONVERSIONS should be set to true when the conversions that
2663 may wrap in signed/pointer type are folded, as long as the value of
2664 the chrec is preserved.
2666 SIZE_EXPR is used for computing the size of the expression to be
2667 instantiated, and to stop if it exceeds some limit. */
2669 static tree
2670 instantiate_scev_r (basic_block instantiate_below,
2671 struct loop *evolution_loop, struct loop *inner_loop,
2672 tree chrec,
2673 bool fold_conversions, int size_expr)
2675 /* Give up if the expression is larger than the MAX that we allow. */
2676 if (size_expr++ > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_SIZE))
2677 return chrec_dont_know;
2679 if (chrec == NULL_TREE
2680 || automatically_generated_chrec_p (chrec)
2681 || is_gimple_min_invariant (chrec))
2682 return chrec;
2684 switch (TREE_CODE (chrec))
2686 case SSA_NAME:
2687 return instantiate_scev_name (instantiate_below, evolution_loop,
2688 inner_loop, chrec,
2689 fold_conversions, size_expr);
2691 case POLYNOMIAL_CHREC:
2692 return instantiate_scev_poly (instantiate_below, evolution_loop,
2693 inner_loop, chrec,
2694 fold_conversions, size_expr);
2696 case POINTER_PLUS_EXPR:
2697 case PLUS_EXPR:
2698 case MINUS_EXPR:
2699 case MULT_EXPR:
2700 return instantiate_scev_binary (instantiate_below, evolution_loop,
2701 inner_loop, chrec,
2702 TREE_CODE (chrec), chrec_type (chrec),
2703 TREE_OPERAND (chrec, 0),
2704 TREE_OPERAND (chrec, 1),
2705 fold_conversions, size_expr);
2707 CASE_CONVERT:
2708 return instantiate_scev_convert (instantiate_below, evolution_loop,
2709 inner_loop, chrec,
2710 TREE_TYPE (chrec), TREE_OPERAND (chrec, 0),
2711 fold_conversions, size_expr);
2713 case NEGATE_EXPR:
2714 case BIT_NOT_EXPR:
2715 return instantiate_scev_not (instantiate_below, evolution_loop,
2716 inner_loop, chrec,
2717 TREE_CODE (chrec), TREE_TYPE (chrec),
2718 TREE_OPERAND (chrec, 0),
2719 fold_conversions, size_expr);
2721 case ADDR_EXPR:
2722 case SCEV_NOT_KNOWN:
2723 return chrec_dont_know;
2725 case SCEV_KNOWN:
2726 return chrec_known;
2728 case ARRAY_REF:
2729 return instantiate_array_ref (instantiate_below, evolution_loop,
2730 inner_loop, chrec,
2731 fold_conversions, size_expr);
2733 default:
2734 break;
2737 if (VL_EXP_CLASS_P (chrec))
2738 return chrec_dont_know;
2740 switch (TREE_CODE_LENGTH (TREE_CODE (chrec)))
2742 case 3:
2743 return instantiate_scev_3 (instantiate_below, evolution_loop,
2744 inner_loop, chrec,
2745 fold_conversions, size_expr);
2747 case 2:
2748 return instantiate_scev_2 (instantiate_below, evolution_loop,
2749 inner_loop, chrec,
2750 fold_conversions, size_expr);
2752 case 1:
2753 return instantiate_scev_1 (instantiate_below, evolution_loop,
2754 inner_loop, chrec,
2755 fold_conversions, size_expr);
2757 case 0:
2758 return chrec;
2760 default:
2761 break;
2764 /* Too complicated to handle. */
2765 return chrec_dont_know;
2768 /* Analyze all the parameters of the chrec that were left under a
2769 symbolic form. INSTANTIATE_BELOW is the basic block that stops the
2770 recursive instantiation of parameters: a parameter is a variable
2771 that is defined in a basic block that dominates INSTANTIATE_BELOW or
2772 a function parameter. */
2774 tree
2775 instantiate_scev (basic_block instantiate_below, struct loop *evolution_loop,
2776 tree chrec)
2778 tree res;
2780 if (dump_file && (dump_flags & TDF_SCEV))
2782 fprintf (dump_file, "(instantiate_scev \n");
2783 fprintf (dump_file, " (instantiate_below = %d)\n", instantiate_below->index);
2784 fprintf (dump_file, " (evolution_loop = %d)\n", evolution_loop->num);
2785 fprintf (dump_file, " (chrec = ");
2786 print_generic_expr (dump_file, chrec, 0);
2787 fprintf (dump_file, ")\n");
2790 bool destr = false;
2791 if (!global_cache)
2793 global_cache = new instantiate_cache_type;
2794 destr = true;
2797 res = instantiate_scev_r (instantiate_below, evolution_loop,
2798 NULL, chrec, false, 0);
2800 if (destr)
2802 delete global_cache;
2803 global_cache = NULL;
2806 if (dump_file && (dump_flags & TDF_SCEV))
2808 fprintf (dump_file, " (res = ");
2809 print_generic_expr (dump_file, res, 0);
2810 fprintf (dump_file, "))\n");
2813 return res;
2816 /* Similar to instantiate_parameters, but does not introduce the
2817 evolutions in outer loops for LOOP invariants in CHREC, and does not
2818 care about causing overflows, as long as they do not affect value
2819 of an expression. */
2821 tree
2822 resolve_mixers (struct loop *loop, tree chrec)
2824 bool destr = false;
2825 if (!global_cache)
2827 global_cache = new instantiate_cache_type;
2828 destr = true;
2831 tree ret = instantiate_scev_r (block_before_loop (loop), loop, NULL,
2832 chrec, true, 0);
2834 if (destr)
2836 delete global_cache;
2837 global_cache = NULL;
2840 return ret;
2843 /* Entry point for the analysis of the number of iterations pass.
2844 This function tries to safely approximate the number of iterations
2845 the loop will run. When this property is not decidable at compile
2846 time, the result is chrec_dont_know. Otherwise the result is a
2847 scalar or a symbolic parameter. When the number of iterations may
2848 be equal to zero and the property cannot be determined at compile
2849 time, the result is a COND_EXPR that represents in a symbolic form
2850 the conditions under which the number of iterations is not zero.
2852 Example of analysis: suppose that the loop has an exit condition:
2854 "if (b > 49) goto end_loop;"
2856 and that in a previous analysis we have determined that the
2857 variable 'b' has an evolution function:
2859 "EF = {23, +, 5}_2".
2861 When we evaluate the function at the point 5, i.e. the value of the
2862 variable 'b' after 5 iterations in the loop, we have EF (5) = 48,
2863 and EF (6) = 53. In this case the value of 'b' on exit is '53' and
2864 the loop body has been executed 6 times. */
2866 tree
2867 number_of_latch_executions (struct loop *loop)
2869 edge exit;
2870 struct tree_niter_desc niter_desc;
2871 tree may_be_zero;
2872 tree res;
2874 /* Determine whether the number of iterations in loop has already
2875 been computed. */
2876 res = loop->nb_iterations;
2877 if (res)
2878 return res;
2880 may_be_zero = NULL_TREE;
2882 if (dump_file && (dump_flags & TDF_SCEV))
2883 fprintf (dump_file, "(number_of_iterations_in_loop = \n");
2885 res = chrec_dont_know;
2886 exit = single_exit (loop);
2888 if (exit && number_of_iterations_exit (loop, exit, &niter_desc, false))
2890 may_be_zero = niter_desc.may_be_zero;
2891 res = niter_desc.niter;
2894 if (res == chrec_dont_know
2895 || !may_be_zero
2896 || integer_zerop (may_be_zero))
2898 else if (integer_nonzerop (may_be_zero))
2899 res = build_int_cst (TREE_TYPE (res), 0);
2901 else if (COMPARISON_CLASS_P (may_be_zero))
2902 res = fold_build3 (COND_EXPR, TREE_TYPE (res), may_be_zero,
2903 build_int_cst (TREE_TYPE (res), 0), res);
2904 else
2905 res = chrec_dont_know;
2907 if (dump_file && (dump_flags & TDF_SCEV))
2909 fprintf (dump_file, " (set_nb_iterations_in_loop = ");
2910 print_generic_expr (dump_file, res, 0);
2911 fprintf (dump_file, "))\n");
2914 loop->nb_iterations = res;
2915 return res;
2919 /* Counters for the stats. */
2921 struct chrec_stats
2923 unsigned nb_chrecs;
2924 unsigned nb_affine;
2925 unsigned nb_affine_multivar;
2926 unsigned nb_higher_poly;
2927 unsigned nb_chrec_dont_know;
2928 unsigned nb_undetermined;
2931 /* Reset the counters. */
2933 static inline void
2934 reset_chrecs_counters (struct chrec_stats *stats)
2936 stats->nb_chrecs = 0;
2937 stats->nb_affine = 0;
2938 stats->nb_affine_multivar = 0;
2939 stats->nb_higher_poly = 0;
2940 stats->nb_chrec_dont_know = 0;
2941 stats->nb_undetermined = 0;
2944 /* Dump the contents of a CHREC_STATS structure. */
2946 static void
2947 dump_chrecs_stats (FILE *file, struct chrec_stats *stats)
2949 fprintf (file, "\n(\n");
2950 fprintf (file, "-----------------------------------------\n");
2951 fprintf (file, "%d\taffine univariate chrecs\n", stats->nb_affine);
2952 fprintf (file, "%d\taffine multivariate chrecs\n", stats->nb_affine_multivar);
2953 fprintf (file, "%d\tdegree greater than 2 polynomials\n",
2954 stats->nb_higher_poly);
2955 fprintf (file, "%d\tchrec_dont_know chrecs\n", stats->nb_chrec_dont_know);
2956 fprintf (file, "-----------------------------------------\n");
2957 fprintf (file, "%d\ttotal chrecs\n", stats->nb_chrecs);
2958 fprintf (file, "%d\twith undetermined coefficients\n",
2959 stats->nb_undetermined);
2960 fprintf (file, "-----------------------------------------\n");
2961 fprintf (file, "%d\tchrecs in the scev database\n",
2962 (int) htab_elements (scalar_evolution_info));
2963 fprintf (file, "%d\tsets in the scev database\n", nb_set_scev);
2964 fprintf (file, "%d\tgets in the scev database\n", nb_get_scev);
2965 fprintf (file, "-----------------------------------------\n");
2966 fprintf (file, ")\n\n");
2969 /* Gather statistics about CHREC. */
2971 static void
2972 gather_chrec_stats (tree chrec, struct chrec_stats *stats)
2974 if (dump_file && (dump_flags & TDF_STATS))
2976 fprintf (dump_file, "(classify_chrec ");
2977 print_generic_expr (dump_file, chrec, 0);
2978 fprintf (dump_file, "\n");
2981 stats->nb_chrecs++;
2983 if (chrec == NULL_TREE)
2985 stats->nb_undetermined++;
2986 return;
2989 switch (TREE_CODE (chrec))
2991 case POLYNOMIAL_CHREC:
2992 if (evolution_function_is_affine_p (chrec))
2994 if (dump_file && (dump_flags & TDF_STATS))
2995 fprintf (dump_file, " affine_univariate\n");
2996 stats->nb_affine++;
2998 else if (evolution_function_is_affine_multivariate_p (chrec, 0))
3000 if (dump_file && (dump_flags & TDF_STATS))
3001 fprintf (dump_file, " affine_multivariate\n");
3002 stats->nb_affine_multivar++;
3004 else
3006 if (dump_file && (dump_flags & TDF_STATS))
3007 fprintf (dump_file, " higher_degree_polynomial\n");
3008 stats->nb_higher_poly++;
3011 break;
3013 default:
3014 break;
3017 if (chrec_contains_undetermined (chrec))
3019 if (dump_file && (dump_flags & TDF_STATS))
3020 fprintf (dump_file, " undetermined\n");
3021 stats->nb_undetermined++;
3024 if (dump_file && (dump_flags & TDF_STATS))
3025 fprintf (dump_file, ")\n");
3028 /* Callback for htab_traverse, gathers information on chrecs in the
3029 hashtable. */
3031 static int
3032 gather_stats_on_scev_database_1 (void **slot, void *stats)
3034 struct scev_info_str *entry = (struct scev_info_str *) *slot;
3036 gather_chrec_stats (entry->chrec, (struct chrec_stats *) stats);
3038 return 1;
3041 /* Classify the chrecs of the whole database. */
3043 void
3044 gather_stats_on_scev_database (void)
3046 struct chrec_stats stats;
3048 if (!dump_file)
3049 return;
3051 reset_chrecs_counters (&stats);
3053 htab_traverse (scalar_evolution_info, gather_stats_on_scev_database_1,
3054 &stats);
3056 dump_chrecs_stats (dump_file, &stats);
3061 /* Initializer. */
3063 static void
3064 initialize_scalar_evolutions_analyzer (void)
3066 /* The elements below are unique. */
3067 if (chrec_dont_know == NULL_TREE)
3069 chrec_not_analyzed_yet = NULL_TREE;
3070 chrec_dont_know = make_node (SCEV_NOT_KNOWN);
3071 chrec_known = make_node (SCEV_KNOWN);
3072 TREE_TYPE (chrec_dont_know) = void_type_node;
3073 TREE_TYPE (chrec_known) = void_type_node;
3077 /* Initialize the analysis of scalar evolutions for LOOPS. */
3079 void
3080 scev_initialize (void)
3082 struct loop *loop;
3084 scalar_evolution_info = htab_create_ggc (100, hash_scev_info, eq_scev_info,
3085 del_scev_info);
3087 initialize_scalar_evolutions_analyzer ();
3089 FOR_EACH_LOOP (loop, 0)
3091 loop->nb_iterations = NULL_TREE;
3095 /* Return true if SCEV is initialized. */
3097 bool
3098 scev_initialized_p (void)
3100 return scalar_evolution_info != NULL;
3103 /* Cleans up the information cached by the scalar evolutions analysis
3104 in the hash table. */
3106 void
3107 scev_reset_htab (void)
3109 if (!scalar_evolution_info)
3110 return;
3112 htab_empty (scalar_evolution_info);
3115 /* Cleans up the information cached by the scalar evolutions analysis
3116 in the hash table and in the loop->nb_iterations. */
3118 void
3119 scev_reset (void)
3121 struct loop *loop;
3123 scev_reset_htab ();
3125 if (!current_loops)
3126 return;
3128 FOR_EACH_LOOP (loop, 0)
3130 loop->nb_iterations = NULL_TREE;
3134 /* Checks whether use of OP in USE_LOOP behaves as a simple affine iv with
3135 respect to WRTO_LOOP and returns its base and step in IV if possible
3136 (see analyze_scalar_evolution_in_loop for more details on USE_LOOP
3137 and WRTO_LOOP). If ALLOW_NONCONSTANT_STEP is true, we want step to be
3138 invariant in LOOP. Otherwise we require it to be an integer constant.
3140 IV->no_overflow is set to true if we are sure the iv cannot overflow (e.g.
3141 because it is computed in signed arithmetics). Consequently, adding an
3142 induction variable
3144 for (i = IV->base; ; i += IV->step)
3146 is only safe if IV->no_overflow is false, or TYPE_OVERFLOW_UNDEFINED is
3147 false for the type of the induction variable, or you can prove that i does
3148 not wrap by some other argument. Otherwise, this might introduce undefined
3149 behavior, and
3151 for (i = iv->base; ; i = (type) ((unsigned type) i + (unsigned type) iv->step))
3153 must be used instead. */
3155 bool
3156 simple_iv (struct loop *wrto_loop, struct loop *use_loop, tree op,
3157 affine_iv *iv, bool allow_nonconstant_step)
3159 tree type, ev;
3160 bool folded_casts;
3162 iv->base = NULL_TREE;
3163 iv->step = NULL_TREE;
3164 iv->no_overflow = false;
3166 type = TREE_TYPE (op);
3167 if (!POINTER_TYPE_P (type)
3168 && !INTEGRAL_TYPE_P (type))
3169 return false;
3171 ev = analyze_scalar_evolution_in_loop (wrto_loop, use_loop, op,
3172 &folded_casts);
3173 if (chrec_contains_undetermined (ev)
3174 || chrec_contains_symbols_defined_in_loop (ev, wrto_loop->num))
3175 return false;
3177 if (tree_does_not_contain_chrecs (ev))
3179 iv->base = ev;
3180 iv->step = build_int_cst (TREE_TYPE (ev), 0);
3181 iv->no_overflow = true;
3182 return true;
3185 if (TREE_CODE (ev) != POLYNOMIAL_CHREC
3186 || CHREC_VARIABLE (ev) != (unsigned) wrto_loop->num)
3187 return false;
3189 iv->step = CHREC_RIGHT (ev);
3190 if ((!allow_nonconstant_step && TREE_CODE (iv->step) != INTEGER_CST)
3191 || tree_contains_chrecs (iv->step, NULL))
3192 return false;
3194 iv->base = CHREC_LEFT (ev);
3195 if (tree_contains_chrecs (iv->base, NULL))
3196 return false;
3198 iv->no_overflow = !folded_casts && TYPE_OVERFLOW_UNDEFINED (type);
3200 return true;
3203 /* Finalize the scalar evolution analysis. */
3205 void
3206 scev_finalize (void)
3208 if (!scalar_evolution_info)
3209 return;
3210 htab_delete (scalar_evolution_info);
3211 scalar_evolution_info = NULL;
3214 /* Returns true if the expression EXPR is considered to be too expensive
3215 for scev_const_prop. */
3217 bool
3218 expression_expensive_p (tree expr)
3220 enum tree_code code;
3222 if (is_gimple_val (expr))
3223 return false;
3225 code = TREE_CODE (expr);
3226 if (code == TRUNC_DIV_EXPR
3227 || code == CEIL_DIV_EXPR
3228 || code == FLOOR_DIV_EXPR
3229 || code == ROUND_DIV_EXPR
3230 || code == TRUNC_MOD_EXPR
3231 || code == CEIL_MOD_EXPR
3232 || code == FLOOR_MOD_EXPR
3233 || code == ROUND_MOD_EXPR
3234 || code == EXACT_DIV_EXPR)
3236 /* Division by power of two is usually cheap, so we allow it.
3237 Forbid anything else. */
3238 if (!integer_pow2p (TREE_OPERAND (expr, 1)))
3239 return true;
3242 switch (TREE_CODE_CLASS (code))
3244 case tcc_binary:
3245 case tcc_comparison:
3246 if (expression_expensive_p (TREE_OPERAND (expr, 1)))
3247 return true;
3249 /* Fallthru. */
3250 case tcc_unary:
3251 return expression_expensive_p (TREE_OPERAND (expr, 0));
3253 default:
3254 return true;
3258 /* Replace ssa names for that scev can prove they are constant by the
3259 appropriate constants. Also perform final value replacement in loops,
3260 in case the replacement expressions are cheap.
3262 We only consider SSA names defined by phi nodes; rest is left to the
3263 ordinary constant propagation pass. */
3265 unsigned int
3266 scev_const_prop (void)
3268 basic_block bb;
3269 tree name, type, ev;
3270 gimple phi, ass;
3271 struct loop *loop, *ex_loop;
3272 bitmap ssa_names_to_remove = NULL;
3273 unsigned i;
3274 gimple_stmt_iterator psi;
3276 if (number_of_loops (cfun) <= 1)
3277 return 0;
3279 FOR_EACH_BB (bb)
3281 loop = bb->loop_father;
3283 for (psi = gsi_start_phis (bb); !gsi_end_p (psi); gsi_next (&psi))
3285 phi = gsi_stmt (psi);
3286 name = PHI_RESULT (phi);
3288 if (virtual_operand_p (name))
3289 continue;
3291 type = TREE_TYPE (name);
3293 if (!POINTER_TYPE_P (type)
3294 && !INTEGRAL_TYPE_P (type))
3295 continue;
3297 ev = resolve_mixers (loop, analyze_scalar_evolution (loop, name));
3298 if (!is_gimple_min_invariant (ev)
3299 || !may_propagate_copy (name, ev))
3300 continue;
3302 /* Replace the uses of the name. */
3303 if (name != ev)
3304 replace_uses_by (name, ev);
3306 if (!ssa_names_to_remove)
3307 ssa_names_to_remove = BITMAP_ALLOC (NULL);
3308 bitmap_set_bit (ssa_names_to_remove, SSA_NAME_VERSION (name));
3312 /* Remove the ssa names that were replaced by constants. We do not
3313 remove them directly in the previous cycle, since this
3314 invalidates scev cache. */
3315 if (ssa_names_to_remove)
3317 bitmap_iterator bi;
3319 EXECUTE_IF_SET_IN_BITMAP (ssa_names_to_remove, 0, i, bi)
3321 gimple_stmt_iterator psi;
3322 name = ssa_name (i);
3323 phi = SSA_NAME_DEF_STMT (name);
3325 gcc_assert (gimple_code (phi) == GIMPLE_PHI);
3326 psi = gsi_for_stmt (phi);
3327 remove_phi_node (&psi, true);
3330 BITMAP_FREE (ssa_names_to_remove);
3331 scev_reset ();
3334 /* Now the regular final value replacement. */
3335 FOR_EACH_LOOP (loop, LI_FROM_INNERMOST)
3337 edge exit;
3338 tree def, rslt, niter;
3339 gimple_stmt_iterator bsi;
3341 /* If we do not know exact number of iterations of the loop, we cannot
3342 replace the final value. */
3343 exit = single_exit (loop);
3344 if (!exit)
3345 continue;
3347 niter = number_of_latch_executions (loop);
3348 if (niter == chrec_dont_know)
3349 continue;
3351 /* Ensure that it is possible to insert new statements somewhere. */
3352 if (!single_pred_p (exit->dest))
3353 split_loop_exit_edge (exit);
3354 bsi = gsi_after_labels (exit->dest);
3356 ex_loop = superloop_at_depth (loop,
3357 loop_depth (exit->dest->loop_father) + 1);
3359 for (psi = gsi_start_phis (exit->dest); !gsi_end_p (psi); )
3361 phi = gsi_stmt (psi);
3362 rslt = PHI_RESULT (phi);
3363 def = PHI_ARG_DEF_FROM_EDGE (phi, exit);
3364 if (virtual_operand_p (def))
3366 gsi_next (&psi);
3367 continue;
3370 if (!POINTER_TYPE_P (TREE_TYPE (def))
3371 && !INTEGRAL_TYPE_P (TREE_TYPE (def)))
3373 gsi_next (&psi);
3374 continue;
3377 def = analyze_scalar_evolution_in_loop (ex_loop, loop, def, NULL);
3378 def = compute_overall_effect_of_inner_loop (ex_loop, def);
3379 if (!tree_does_not_contain_chrecs (def)
3380 || chrec_contains_symbols_defined_in_loop (def, ex_loop->num)
3381 /* Moving the computation from the loop may prolong life range
3382 of some ssa names, which may cause problems if they appear
3383 on abnormal edges. */
3384 || contains_abnormal_ssa_name_p (def)
3385 /* Do not emit expensive expressions. The rationale is that
3386 when someone writes a code like
3388 while (n > 45) n -= 45;
3390 he probably knows that n is not large, and does not want it
3391 to be turned into n %= 45. */
3392 || expression_expensive_p (def))
3394 if (dump_file && (dump_flags & TDF_DETAILS))
3396 fprintf (dump_file, "not replacing:\n ");
3397 print_gimple_stmt (dump_file, phi, 0, 0);
3398 fprintf (dump_file, "\n");
3400 gsi_next (&psi);
3401 continue;
3404 /* Eliminate the PHI node and replace it by a computation outside
3405 the loop. */
3406 if (dump_file)
3408 fprintf (dump_file, "\nfinal value replacement:\n ");
3409 print_gimple_stmt (dump_file, phi, 0, 0);
3410 fprintf (dump_file, " with\n ");
3412 def = unshare_expr (def);
3413 remove_phi_node (&psi, false);
3415 def = force_gimple_operand_gsi (&bsi, def, false, NULL_TREE,
3416 true, GSI_SAME_STMT);
3417 ass = gimple_build_assign (rslt, def);
3418 gsi_insert_before (&bsi, ass, GSI_SAME_STMT);
3419 if (dump_file)
3421 print_gimple_stmt (dump_file, ass, 0, 0);
3422 fprintf (dump_file, "\n");
3426 return 0;
3429 #include "gt-tree-scalar-evolution.h"