2008-06-04 Xinliang David Li <davidxl@google.com>
[official-gcc.git] / gcc / tree-scalar-evolution.c
blob2cc008020e22fd4fc95bc79fb3d00b16073c7613
1 /* Scalar evolution detector.
2 Copyright (C) 2003, 2004, 2005, 2006, 2007 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/>. */
21 /*
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_MODIFY_STMT: 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 (loop_1, loop_3, "j + k"). The result of this
178 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 "tm.h"
260 #include "ggc.h"
261 #include "tree.h"
262 #include "real.h"
264 /* These RTL headers are needed for basic-block.h. */
265 #include "rtl.h"
266 #include "basic-block.h"
267 #include "diagnostic.h"
268 #include "tree-flow.h"
269 #include "tree-dump.h"
270 #include "timevar.h"
271 #include "cfgloop.h"
272 #include "tree-chrec.h"
273 #include "tree-scalar-evolution.h"
274 #include "tree-pass.h"
275 #include "flags.h"
276 #include "params.h"
278 static tree analyze_scalar_evolution_1 (struct loop *, tree, tree);
280 /* The cached information about a ssa name VAR, claiming that inside LOOP,
281 the value of VAR can be expressed as CHREC. */
283 struct scev_info_str GTY(())
285 tree var;
286 tree chrec;
289 /* Counters for the scev database. */
290 static unsigned nb_set_scev = 0;
291 static unsigned nb_get_scev = 0;
293 /* The following trees are unique elements. Thus the comparison of
294 another element to these elements should be done on the pointer to
295 these trees, and not on their value. */
297 /* The SSA_NAMEs that are not yet analyzed are qualified with NULL_TREE. */
298 tree chrec_not_analyzed_yet;
300 /* Reserved to the cases where the analyzer has detected an
301 undecidable property at compile time. */
302 tree chrec_dont_know;
304 /* When the analyzer has detected that a property will never
305 happen, then it qualifies it with chrec_known. */
306 tree chrec_known;
308 static bitmap already_instantiated;
310 static GTY ((param_is (struct scev_info_str))) htab_t scalar_evolution_info;
313 /* Constructs a new SCEV_INFO_STR structure. */
315 static inline struct scev_info_str *
316 new_scev_info_str (tree var)
318 struct scev_info_str *res;
320 res = GGC_NEW (struct scev_info_str);
321 res->var = var;
322 res->chrec = chrec_not_analyzed_yet;
324 return res;
327 /* Computes a hash function for database element ELT. */
329 static hashval_t
330 hash_scev_info (const void *elt)
332 return SSA_NAME_VERSION (((const struct scev_info_str *) elt)->var);
335 /* Compares database elements E1 and E2. */
337 static int
338 eq_scev_info (const void *e1, const void *e2)
340 const struct scev_info_str *elt1 = (const struct scev_info_str *) e1;
341 const struct scev_info_str *elt2 = (const struct scev_info_str *) e2;
343 return elt1->var == elt2->var;
346 /* Deletes database element E. */
348 static void
349 del_scev_info (void *e)
351 ggc_free (e);
354 /* Get the index corresponding to VAR in the current LOOP. If
355 it's the first time we ask for this VAR, then we return
356 chrec_not_analyzed_yet for this VAR and return its index. */
358 static tree *
359 find_var_scev_info (tree var)
361 struct scev_info_str *res;
362 struct scev_info_str tmp;
363 PTR *slot;
365 tmp.var = var;
366 slot = htab_find_slot (scalar_evolution_info, &tmp, INSERT);
368 if (!*slot)
369 *slot = new_scev_info_str (var);
370 res = (struct scev_info_str *) *slot;
372 return &res->chrec;
375 /* Return true when CHREC contains symbolic names defined in
376 LOOP_NB. */
378 bool
379 chrec_contains_symbols_defined_in_loop (const_tree chrec, unsigned loop_nb)
381 int i, n;
383 if (chrec == NULL_TREE)
384 return false;
386 if (is_gimple_min_invariant (chrec))
387 return false;
389 if (TREE_CODE (chrec) == VAR_DECL
390 || TREE_CODE (chrec) == PARM_DECL
391 || TREE_CODE (chrec) == FUNCTION_DECL
392 || TREE_CODE (chrec) == LABEL_DECL
393 || TREE_CODE (chrec) == RESULT_DECL
394 || TREE_CODE (chrec) == FIELD_DECL)
395 return true;
397 if (TREE_CODE (chrec) == SSA_NAME)
399 tree def = SSA_NAME_DEF_STMT (chrec);
400 struct loop *def_loop = loop_containing_stmt (def);
401 struct loop *loop = get_loop (loop_nb);
403 if (def_loop == NULL)
404 return false;
406 if (loop == def_loop || flow_loop_nested_p (loop, def_loop))
407 return true;
409 return false;
412 n = TREE_OPERAND_LENGTH (chrec);
413 for (i = 0; i < n; i++)
414 if (chrec_contains_symbols_defined_in_loop (TREE_OPERAND (chrec, i),
415 loop_nb))
416 return true;
417 return false;
420 /* Return true when PHI is a loop-phi-node. */
422 static bool
423 loop_phi_node_p (tree phi)
425 /* The implementation of this function is based on the following
426 property: "all the loop-phi-nodes of a loop are contained in the
427 loop's header basic block". */
429 return loop_containing_stmt (phi)->header == bb_for_stmt (phi);
432 /* Compute the scalar evolution for EVOLUTION_FN after crossing LOOP.
433 In general, in the case of multivariate evolutions we want to get
434 the evolution in different loops. LOOP specifies the level for
435 which to get the evolution.
437 Example:
439 | for (j = 0; j < 100; j++)
441 | for (k = 0; k < 100; k++)
443 | i = k + j; - Here the value of i is a function of j, k.
445 | ... = i - Here the value of i is a function of j.
447 | ... = i - Here the value of i is a scalar.
449 Example:
451 | i_0 = ...
452 | loop_1 10 times
453 | i_1 = phi (i_0, i_2)
454 | i_2 = i_1 + 2
455 | endloop
457 This loop has the same effect as:
458 LOOP_1 has the same effect as:
460 | i_1 = i_0 + 20
462 The overall effect of the loop, "i_0 + 20" in the previous example,
463 is obtained by passing in the parameters: LOOP = 1,
464 EVOLUTION_FN = {i_0, +, 2}_1.
467 static tree
468 compute_overall_effect_of_inner_loop (struct loop *loop, tree evolution_fn)
470 bool val = false;
472 if (evolution_fn == chrec_dont_know)
473 return chrec_dont_know;
475 else if (TREE_CODE (evolution_fn) == POLYNOMIAL_CHREC)
477 struct loop *inner_loop = get_chrec_loop (evolution_fn);
479 if (inner_loop == loop
480 || flow_loop_nested_p (loop, inner_loop))
482 tree nb_iter = number_of_latch_executions (inner_loop);
484 if (nb_iter == chrec_dont_know)
485 return chrec_dont_know;
486 else
488 tree res;
490 /* evolution_fn is the evolution function in LOOP. Get
491 its value in the nb_iter-th iteration. */
492 res = chrec_apply (inner_loop->num, evolution_fn, nb_iter);
494 /* Continue the computation until ending on a parent of LOOP. */
495 return compute_overall_effect_of_inner_loop (loop, res);
498 else
499 return evolution_fn;
502 /* If the evolution function is an invariant, there is nothing to do. */
503 else if (no_evolution_in_loop_p (evolution_fn, loop->num, &val) && val)
504 return evolution_fn;
506 else
507 return chrec_dont_know;
510 /* Determine whether the CHREC is always positive/negative. If the expression
511 cannot be statically analyzed, return false, otherwise set the answer into
512 VALUE. */
514 bool
515 chrec_is_positive (tree chrec, bool *value)
517 bool value0, value1, value2;
518 tree end_value, nb_iter;
520 switch (TREE_CODE (chrec))
522 case POLYNOMIAL_CHREC:
523 if (!chrec_is_positive (CHREC_LEFT (chrec), &value0)
524 || !chrec_is_positive (CHREC_RIGHT (chrec), &value1))
525 return false;
527 /* FIXME -- overflows. */
528 if (value0 == value1)
530 *value = value0;
531 return true;
534 /* Otherwise the chrec is under the form: "{-197, +, 2}_1",
535 and the proof consists in showing that the sign never
536 changes during the execution of the loop, from 0 to
537 loop->nb_iterations. */
538 if (!evolution_function_is_affine_p (chrec))
539 return false;
541 nb_iter = number_of_latch_executions (get_chrec_loop (chrec));
542 if (chrec_contains_undetermined (nb_iter))
543 return false;
545 #if 0
546 /* TODO -- If the test is after the exit, we may decrease the number of
547 iterations by one. */
548 if (after_exit)
549 nb_iter = chrec_fold_minus (type, nb_iter, build_int_cst (type, 1));
550 #endif
552 end_value = chrec_apply (CHREC_VARIABLE (chrec), chrec, nb_iter);
554 if (!chrec_is_positive (end_value, &value2))
555 return false;
557 *value = value0;
558 return value0 == value1;
560 case INTEGER_CST:
561 *value = (tree_int_cst_sgn (chrec) == 1);
562 return true;
564 default:
565 return false;
569 /* Associate CHREC to SCALAR. */
571 static void
572 set_scalar_evolution (tree scalar, tree chrec)
574 tree *scalar_info;
576 if (TREE_CODE (scalar) != SSA_NAME)
577 return;
579 scalar_info = find_var_scev_info (scalar);
581 if (dump_file)
583 if (dump_flags & TDF_DETAILS)
585 fprintf (dump_file, "(set_scalar_evolution \n");
586 fprintf (dump_file, " (scalar = ");
587 print_generic_expr (dump_file, scalar, 0);
588 fprintf (dump_file, ")\n (scalar_evolution = ");
589 print_generic_expr (dump_file, chrec, 0);
590 fprintf (dump_file, "))\n");
592 if (dump_flags & TDF_STATS)
593 nb_set_scev++;
596 *scalar_info = chrec;
599 /* Retrieve the chrec associated to SCALAR in the LOOP. */
601 static tree
602 get_scalar_evolution (tree scalar)
604 tree res;
606 if (dump_file)
608 if (dump_flags & TDF_DETAILS)
610 fprintf (dump_file, "(get_scalar_evolution \n");
611 fprintf (dump_file, " (scalar = ");
612 print_generic_expr (dump_file, scalar, 0);
613 fprintf (dump_file, ")\n");
615 if (dump_flags & TDF_STATS)
616 nb_get_scev++;
619 switch (TREE_CODE (scalar))
621 case SSA_NAME:
622 res = *find_var_scev_info (scalar);
623 break;
625 case REAL_CST:
626 case FIXED_CST:
627 case INTEGER_CST:
628 res = scalar;
629 break;
631 default:
632 res = chrec_not_analyzed_yet;
633 break;
636 if (dump_file && (dump_flags & TDF_DETAILS))
638 fprintf (dump_file, " (scalar_evolution = ");
639 print_generic_expr (dump_file, res, 0);
640 fprintf (dump_file, "))\n");
643 return res;
646 /* Helper function for add_to_evolution. Returns the evolution
647 function for an assignment of the form "a = b + c", where "a" and
648 "b" are on the strongly connected component. CHREC_BEFORE is the
649 information that we already have collected up to this point.
650 TO_ADD is the evolution of "c".
652 When CHREC_BEFORE has an evolution part in LOOP_NB, add to this
653 evolution the expression TO_ADD, otherwise construct an evolution
654 part for this loop. */
656 static tree
657 add_to_evolution_1 (unsigned loop_nb, tree chrec_before, tree to_add,
658 tree at_stmt)
660 tree type, left, right;
661 struct loop *loop = get_loop (loop_nb), *chloop;
663 switch (TREE_CODE (chrec_before))
665 case POLYNOMIAL_CHREC:
666 chloop = get_chrec_loop (chrec_before);
667 if (chloop == loop
668 || flow_loop_nested_p (chloop, loop))
670 unsigned var;
672 type = chrec_type (chrec_before);
674 /* When there is no evolution part in this loop, build it. */
675 if (chloop != loop)
677 var = loop_nb;
678 left = chrec_before;
679 right = SCALAR_FLOAT_TYPE_P (type)
680 ? build_real (type, dconst0)
681 : build_int_cst (type, 0);
683 else
685 var = CHREC_VARIABLE (chrec_before);
686 left = CHREC_LEFT (chrec_before);
687 right = CHREC_RIGHT (chrec_before);
690 to_add = chrec_convert (type, to_add, at_stmt);
691 right = chrec_convert_rhs (type, right, at_stmt);
692 right = chrec_fold_plus (chrec_type (right), right, to_add);
693 return build_polynomial_chrec (var, left, right);
695 else
697 gcc_assert (flow_loop_nested_p (loop, chloop));
699 /* Search the evolution in LOOP_NB. */
700 left = add_to_evolution_1 (loop_nb, CHREC_LEFT (chrec_before),
701 to_add, at_stmt);
702 right = CHREC_RIGHT (chrec_before);
703 right = chrec_convert_rhs (chrec_type (left), right, at_stmt);
704 return build_polynomial_chrec (CHREC_VARIABLE (chrec_before),
705 left, right);
708 default:
709 /* These nodes do not depend on a loop. */
710 if (chrec_before == chrec_dont_know)
711 return chrec_dont_know;
713 left = chrec_before;
714 right = chrec_convert_rhs (chrec_type (left), to_add, at_stmt);
715 return build_polynomial_chrec (loop_nb, left, right);
719 /* Add TO_ADD to the evolution part of CHREC_BEFORE in the dimension
720 of LOOP_NB.
722 Description (provided for completeness, for those who read code in
723 a plane, and for my poor 62 bytes brain that would have forgotten
724 all this in the next two or three months):
726 The algorithm of translation of programs from the SSA representation
727 into the chrecs syntax is based on a pattern matching. After having
728 reconstructed the overall tree expression for a loop, there are only
729 two cases that can arise:
731 1. a = loop-phi (init, a + expr)
732 2. a = loop-phi (init, expr)
734 where EXPR is either a scalar constant with respect to the analyzed
735 loop (this is a degree 0 polynomial), or an expression containing
736 other loop-phi definitions (these are higher degree polynomials).
738 Examples:
741 | init = ...
742 | loop_1
743 | a = phi (init, a + 5)
744 | endloop
747 | inita = ...
748 | initb = ...
749 | loop_1
750 | a = phi (inita, 2 * b + 3)
751 | b = phi (initb, b + 1)
752 | endloop
754 For the first case, the semantics of the SSA representation is:
756 | a (x) = init + \sum_{j = 0}^{x - 1} expr (j)
758 that is, there is a loop index "x" that determines the scalar value
759 of the variable during the loop execution. During the first
760 iteration, the value is that of the initial condition INIT, while
761 during the subsequent iterations, it is the sum of the initial
762 condition with the sum of all the values of EXPR from the initial
763 iteration to the before last considered iteration.
765 For the second case, the semantics of the SSA program is:
767 | a (x) = init, if x = 0;
768 | expr (x - 1), otherwise.
770 The second case corresponds to the PEELED_CHREC, whose syntax is
771 close to the syntax of a loop-phi-node:
773 | phi (init, expr) vs. (init, expr)_x
775 The proof of the translation algorithm for the first case is a
776 proof by structural induction based on the degree of EXPR.
778 Degree 0:
779 When EXPR is a constant with respect to the analyzed loop, or in
780 other words when EXPR is a polynomial of degree 0, the evolution of
781 the variable A in the loop is an affine function with an initial
782 condition INIT, and a step EXPR. In order to show this, we start
783 from the semantics of the SSA representation:
785 f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
787 and since "expr (j)" is a constant with respect to "j",
789 f (x) = init + x * expr
791 Finally, based on the semantics of the pure sum chrecs, by
792 identification we get the corresponding chrecs syntax:
794 f (x) = init * \binom{x}{0} + expr * \binom{x}{1}
795 f (x) -> {init, +, expr}_x
797 Higher degree:
798 Suppose that EXPR is a polynomial of degree N with respect to the
799 analyzed loop_x for which we have already determined that it is
800 written under the chrecs syntax:
802 | expr (x) -> {b_0, +, b_1, +, ..., +, b_{n-1}} (x)
804 We start from the semantics of the SSA program:
806 | f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
808 | f (x) = init + \sum_{j = 0}^{x - 1}
809 | (b_0 * \binom{j}{0} + ... + b_{n-1} * \binom{j}{n-1})
811 | f (x) = init + \sum_{j = 0}^{x - 1}
812 | \sum_{k = 0}^{n - 1} (b_k * \binom{j}{k})
814 | f (x) = init + \sum_{k = 0}^{n - 1}
815 | (b_k * \sum_{j = 0}^{x - 1} \binom{j}{k})
817 | f (x) = init + \sum_{k = 0}^{n - 1}
818 | (b_k * \binom{x}{k + 1})
820 | f (x) = init + b_0 * \binom{x}{1} + ...
821 | + b_{n-1} * \binom{x}{n}
823 | f (x) = init * \binom{x}{0} + b_0 * \binom{x}{1} + ...
824 | + b_{n-1} * \binom{x}{n}
827 And finally from the definition of the chrecs syntax, we identify:
828 | f (x) -> {init, +, b_0, +, ..., +, b_{n-1}}_x
830 This shows the mechanism that stands behind the add_to_evolution
831 function. An important point is that the use of symbolic
832 parameters avoids the need of an analysis schedule.
834 Example:
836 | inita = ...
837 | initb = ...
838 | loop_1
839 | a = phi (inita, a + 2 + b)
840 | b = phi (initb, b + 1)
841 | endloop
843 When analyzing "a", the algorithm keeps "b" symbolically:
845 | a -> {inita, +, 2 + b}_1
847 Then, after instantiation, the analyzer ends on the evolution:
849 | a -> {inita, +, 2 + initb, +, 1}_1
853 static tree
854 add_to_evolution (unsigned loop_nb, tree chrec_before, enum tree_code code,
855 tree to_add, tree at_stmt)
857 tree type = chrec_type (to_add);
858 tree res = NULL_TREE;
860 if (to_add == NULL_TREE)
861 return chrec_before;
863 /* TO_ADD is either a scalar, or a parameter. TO_ADD is not
864 instantiated at this point. */
865 if (TREE_CODE (to_add) == POLYNOMIAL_CHREC)
866 /* This should not happen. */
867 return chrec_dont_know;
869 if (dump_file && (dump_flags & TDF_DETAILS))
871 fprintf (dump_file, "(add_to_evolution \n");
872 fprintf (dump_file, " (loop_nb = %d)\n", loop_nb);
873 fprintf (dump_file, " (chrec_before = ");
874 print_generic_expr (dump_file, chrec_before, 0);
875 fprintf (dump_file, ")\n (to_add = ");
876 print_generic_expr (dump_file, to_add, 0);
877 fprintf (dump_file, ")\n");
880 if (code == MINUS_EXPR)
881 to_add = chrec_fold_multiply (type, to_add, SCALAR_FLOAT_TYPE_P (type)
882 ? build_real (type, dconstm1)
883 : build_int_cst_type (type, -1));
885 res = add_to_evolution_1 (loop_nb, chrec_before, to_add, at_stmt);
887 if (dump_file && (dump_flags & TDF_DETAILS))
889 fprintf (dump_file, " (res = ");
890 print_generic_expr (dump_file, res, 0);
891 fprintf (dump_file, "))\n");
894 return res;
897 /* Helper function. */
899 static inline tree
900 set_nb_iterations_in_loop (struct loop *loop,
901 tree res)
903 if (dump_file && (dump_flags & TDF_DETAILS))
905 fprintf (dump_file, " (set_nb_iterations_in_loop = ");
906 print_generic_expr (dump_file, res, 0);
907 fprintf (dump_file, "))\n");
910 loop->nb_iterations = res;
911 return res;
916 /* This section selects the loops that will be good candidates for the
917 scalar evolution analysis. For the moment, greedily select all the
918 loop nests we could analyze. */
920 /* Return true when it is possible to analyze the condition expression
921 EXPR. */
923 static bool
924 analyzable_condition (const_tree expr)
926 tree condition;
928 if (TREE_CODE (expr) != COND_EXPR)
929 return false;
931 condition = TREE_OPERAND (expr, 0);
933 switch (TREE_CODE (condition))
935 case SSA_NAME:
936 return true;
938 case LT_EXPR:
939 case LE_EXPR:
940 case GT_EXPR:
941 case GE_EXPR:
942 case EQ_EXPR:
943 case NE_EXPR:
944 return true;
946 default:
947 return false;
950 return false;
953 /* For a loop with a single exit edge, return the COND_EXPR that
954 guards the exit edge. If the expression is too difficult to
955 analyze, then give up. */
957 tree
958 get_loop_exit_condition (const struct loop *loop)
960 tree res = NULL_TREE;
961 edge exit_edge = single_exit (loop);
963 if (dump_file && (dump_flags & TDF_DETAILS))
964 fprintf (dump_file, "(get_loop_exit_condition \n ");
966 if (exit_edge)
968 tree expr;
970 expr = last_stmt (exit_edge->src);
971 if (analyzable_condition (expr))
972 res = expr;
975 if (dump_file && (dump_flags & TDF_DETAILS))
977 print_generic_expr (dump_file, res, 0);
978 fprintf (dump_file, ")\n");
981 return res;
984 /* Recursively determine and enqueue the exit conditions for a loop. */
986 static void
987 get_exit_conditions_rec (struct loop *loop,
988 VEC(tree,heap) **exit_conditions)
990 if (!loop)
991 return;
993 /* Recurse on the inner loops, then on the next (sibling) loops. */
994 get_exit_conditions_rec (loop->inner, exit_conditions);
995 get_exit_conditions_rec (loop->next, exit_conditions);
997 if (single_exit (loop))
999 tree loop_condition = get_loop_exit_condition (loop);
1001 if (loop_condition)
1002 VEC_safe_push (tree, heap, *exit_conditions, loop_condition);
1006 /* Select the candidate loop nests for the analysis. This function
1007 initializes the EXIT_CONDITIONS array. */
1009 static void
1010 select_loops_exit_conditions (VEC(tree,heap) **exit_conditions)
1012 struct loop *function_body = current_loops->tree_root;
1014 get_exit_conditions_rec (function_body->inner, exit_conditions);
1018 /* Depth first search algorithm. */
1020 typedef enum t_bool {
1021 t_false,
1022 t_true,
1023 t_dont_know
1024 } t_bool;
1027 static t_bool follow_ssa_edge (struct loop *loop, tree, tree, tree *, int);
1029 /* Follow the ssa edge into the right hand side RHS of an assignment.
1030 Return true if the strongly connected component has been found. */
1032 static t_bool
1033 follow_ssa_edge_in_rhs (struct loop *loop, tree at_stmt, tree rhs,
1034 tree halting_phi, tree *evolution_of_loop, int limit)
1036 t_bool res = t_false;
1037 tree rhs0, rhs1;
1038 tree type_rhs = TREE_TYPE (rhs);
1039 tree evol;
1040 enum tree_code code;
1042 /* The RHS is one of the following cases:
1043 - an SSA_NAME,
1044 - an INTEGER_CST,
1045 - a PLUS_EXPR,
1046 - a POINTER_PLUS_EXPR,
1047 - a MINUS_EXPR,
1048 - an ASSERT_EXPR,
1049 - other cases are not yet handled. */
1050 code = TREE_CODE (rhs);
1051 switch (code)
1053 case NOP_EXPR:
1054 /* This assignment is under the form "a_1 = (cast) rhs. */
1055 res = follow_ssa_edge_in_rhs (loop, at_stmt, TREE_OPERAND (rhs, 0),
1056 halting_phi, evolution_of_loop, limit);
1057 *evolution_of_loop = chrec_convert (TREE_TYPE (rhs),
1058 *evolution_of_loop, at_stmt);
1059 break;
1061 case INTEGER_CST:
1062 /* This assignment is under the form "a_1 = 7". */
1063 res = t_false;
1064 break;
1066 case SSA_NAME:
1067 /* This assignment is under the form: "a_1 = b_2". */
1068 res = follow_ssa_edge
1069 (loop, SSA_NAME_DEF_STMT (rhs), halting_phi, evolution_of_loop, limit);
1070 break;
1072 case POINTER_PLUS_EXPR:
1073 case PLUS_EXPR:
1074 /* This case is under the form "rhs0 + rhs1". */
1075 rhs0 = TREE_OPERAND (rhs, 0);
1076 rhs1 = TREE_OPERAND (rhs, 1);
1077 STRIP_TYPE_NOPS (rhs0);
1078 STRIP_TYPE_NOPS (rhs1);
1080 if (TREE_CODE (rhs0) == SSA_NAME)
1082 if (TREE_CODE (rhs1) == SSA_NAME)
1084 /* Match an assignment under the form:
1085 "a = b + c". */
1087 /* We want only assignments of form "name + name" contribute to
1088 LIMIT, as the other cases do not necessarily contribute to
1089 the complexity of the expression. */
1090 limit++;
1092 evol = *evolution_of_loop;
1093 res = follow_ssa_edge
1094 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
1095 &evol, limit);
1097 if (res == t_true)
1098 *evolution_of_loop = add_to_evolution
1099 (loop->num,
1100 chrec_convert (type_rhs, evol, at_stmt),
1101 code, rhs1, at_stmt);
1103 else if (res == t_false)
1105 res = follow_ssa_edge
1106 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
1107 evolution_of_loop, limit);
1109 if (res == t_true)
1110 *evolution_of_loop = add_to_evolution
1111 (loop->num,
1112 chrec_convert (type_rhs, *evolution_of_loop, at_stmt),
1113 code, rhs0, at_stmt);
1115 else if (res == t_dont_know)
1116 *evolution_of_loop = chrec_dont_know;
1119 else if (res == t_dont_know)
1120 *evolution_of_loop = chrec_dont_know;
1123 else
1125 /* Match an assignment under the form:
1126 "a = b + ...". */
1127 res = follow_ssa_edge
1128 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
1129 evolution_of_loop, limit);
1130 if (res == t_true)
1131 *evolution_of_loop = add_to_evolution
1132 (loop->num, chrec_convert (type_rhs, *evolution_of_loop,
1133 at_stmt),
1134 code, rhs1, at_stmt);
1136 else if (res == t_dont_know)
1137 *evolution_of_loop = chrec_dont_know;
1141 else if (TREE_CODE (rhs1) == SSA_NAME)
1143 /* Match an assignment under the form:
1144 "a = ... + c". */
1145 res = follow_ssa_edge
1146 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
1147 evolution_of_loop, limit);
1148 if (res == t_true)
1149 *evolution_of_loop = add_to_evolution
1150 (loop->num, chrec_convert (type_rhs, *evolution_of_loop,
1151 at_stmt),
1152 code, rhs0, at_stmt);
1154 else if (res == t_dont_know)
1155 *evolution_of_loop = chrec_dont_know;
1158 else
1159 /* Otherwise, match an assignment under the form:
1160 "a = ... + ...". */
1161 /* And there is nothing to do. */
1162 res = t_false;
1164 break;
1166 case MINUS_EXPR:
1167 /* This case is under the form "opnd0 = rhs0 - rhs1". */
1168 rhs0 = TREE_OPERAND (rhs, 0);
1169 rhs1 = TREE_OPERAND (rhs, 1);
1170 STRIP_TYPE_NOPS (rhs0);
1171 STRIP_TYPE_NOPS (rhs1);
1173 if (TREE_CODE (rhs0) == SSA_NAME)
1175 /* Match an assignment under the form:
1176 "a = b - ...". */
1178 /* We want only assignments of form "name - name" contribute to
1179 LIMIT, as the other cases do not necessarily contribute to
1180 the complexity of the expression. */
1181 if (TREE_CODE (rhs1) == SSA_NAME)
1182 limit++;
1184 res = follow_ssa_edge (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
1185 evolution_of_loop, limit);
1186 if (res == t_true)
1187 *evolution_of_loop = add_to_evolution
1188 (loop->num, chrec_convert (type_rhs, *evolution_of_loop, at_stmt),
1189 MINUS_EXPR, rhs1, at_stmt);
1191 else if (res == t_dont_know)
1192 *evolution_of_loop = chrec_dont_know;
1194 else
1195 /* Otherwise, match an assignment under the form:
1196 "a = ... - ...". */
1197 /* And there is nothing to do. */
1198 res = t_false;
1200 break;
1202 case ASSERT_EXPR:
1204 /* This assignment is of the form: "a_1 = ASSERT_EXPR <a_2, ...>"
1205 It must be handled as a copy assignment of the form a_1 = a_2. */
1206 tree op0 = ASSERT_EXPR_VAR (rhs);
1207 if (TREE_CODE (op0) == SSA_NAME)
1208 res = follow_ssa_edge (loop, SSA_NAME_DEF_STMT (op0),
1209 halting_phi, evolution_of_loop, limit);
1210 else
1211 res = t_false;
1212 break;
1216 default:
1217 res = t_false;
1218 break;
1221 return res;
1224 /* Checks whether the I-th argument of a PHI comes from a backedge. */
1226 static bool
1227 backedge_phi_arg_p (const_tree phi, int i)
1229 const_edge e = PHI_ARG_EDGE (phi, i);
1231 /* We would in fact like to test EDGE_DFS_BACK here, but we do not care
1232 about updating it anywhere, and this should work as well most of the
1233 time. */
1234 if (e->flags & EDGE_IRREDUCIBLE_LOOP)
1235 return true;
1237 return false;
1240 /* Helper function for one branch of the condition-phi-node. Return
1241 true if the strongly connected component has been found following
1242 this path. */
1244 static inline t_bool
1245 follow_ssa_edge_in_condition_phi_branch (int i,
1246 struct loop *loop,
1247 tree condition_phi,
1248 tree halting_phi,
1249 tree *evolution_of_branch,
1250 tree init_cond, int limit)
1252 tree branch = PHI_ARG_DEF (condition_phi, i);
1253 *evolution_of_branch = chrec_dont_know;
1255 /* Do not follow back edges (they must belong to an irreducible loop, which
1256 we really do not want to worry about). */
1257 if (backedge_phi_arg_p (condition_phi, i))
1258 return t_false;
1260 if (TREE_CODE (branch) == SSA_NAME)
1262 *evolution_of_branch = init_cond;
1263 return follow_ssa_edge (loop, SSA_NAME_DEF_STMT (branch), halting_phi,
1264 evolution_of_branch, limit);
1267 /* This case occurs when one of the condition branches sets
1268 the variable to a constant: i.e. a phi-node like
1269 "a_2 = PHI <a_7(5), 2(6)>;".
1271 FIXME: This case have to be refined correctly:
1272 in some cases it is possible to say something better than
1273 chrec_dont_know, for example using a wrap-around notation. */
1274 return t_false;
1277 /* This function merges the branches of a condition-phi-node in a
1278 loop. */
1280 static t_bool
1281 follow_ssa_edge_in_condition_phi (struct loop *loop,
1282 tree condition_phi,
1283 tree halting_phi,
1284 tree *evolution_of_loop, int limit)
1286 int i;
1287 tree init = *evolution_of_loop;
1288 tree evolution_of_branch;
1289 t_bool res = follow_ssa_edge_in_condition_phi_branch (0, loop, condition_phi,
1290 halting_phi,
1291 &evolution_of_branch,
1292 init, limit);
1293 if (res == t_false || res == t_dont_know)
1294 return res;
1296 *evolution_of_loop = evolution_of_branch;
1298 /* If the phi node is just a copy, do not increase the limit. */
1299 if (PHI_NUM_ARGS (condition_phi) > 1)
1300 limit++;
1302 for (i = 1; i < PHI_NUM_ARGS (condition_phi); i++)
1304 /* Quickly give up when the evolution of one of the branches is
1305 not known. */
1306 if (*evolution_of_loop == chrec_dont_know)
1307 return t_true;
1309 res = follow_ssa_edge_in_condition_phi_branch (i, loop, condition_phi,
1310 halting_phi,
1311 &evolution_of_branch,
1312 init, limit);
1313 if (res == t_false || res == t_dont_know)
1314 return res;
1316 *evolution_of_loop = chrec_merge (*evolution_of_loop,
1317 evolution_of_branch);
1320 return t_true;
1323 /* Follow an SSA edge in an inner loop. It computes the overall
1324 effect of the loop, and following the symbolic initial conditions,
1325 it follows the edges in the parent loop. The inner loop is
1326 considered as a single statement. */
1328 static t_bool
1329 follow_ssa_edge_inner_loop_phi (struct loop *outer_loop,
1330 tree loop_phi_node,
1331 tree halting_phi,
1332 tree *evolution_of_loop, int limit)
1334 struct loop *loop = loop_containing_stmt (loop_phi_node);
1335 tree ev = analyze_scalar_evolution (loop, PHI_RESULT (loop_phi_node));
1337 /* Sometimes, the inner loop is too difficult to analyze, and the
1338 result of the analysis is a symbolic parameter. */
1339 if (ev == PHI_RESULT (loop_phi_node))
1341 t_bool res = t_false;
1342 int i;
1344 for (i = 0; i < PHI_NUM_ARGS (loop_phi_node); i++)
1346 tree arg = PHI_ARG_DEF (loop_phi_node, i);
1347 basic_block bb;
1349 /* Follow the edges that exit the inner loop. */
1350 bb = PHI_ARG_EDGE (loop_phi_node, i)->src;
1351 if (!flow_bb_inside_loop_p (loop, bb))
1352 res = follow_ssa_edge_in_rhs (outer_loop, loop_phi_node,
1353 arg, halting_phi,
1354 evolution_of_loop, limit);
1355 if (res == t_true)
1356 break;
1359 /* If the path crosses this loop-phi, give up. */
1360 if (res == t_true)
1361 *evolution_of_loop = chrec_dont_know;
1363 return res;
1366 /* Otherwise, compute the overall effect of the inner loop. */
1367 ev = compute_overall_effect_of_inner_loop (loop, ev);
1368 return follow_ssa_edge_in_rhs (outer_loop, loop_phi_node, ev, halting_phi,
1369 evolution_of_loop, limit);
1372 /* Follow an SSA edge from a loop-phi-node to itself, constructing a
1373 path that is analyzed on the return walk. */
1375 static t_bool
1376 follow_ssa_edge (struct loop *loop, tree def, tree halting_phi,
1377 tree *evolution_of_loop, int limit)
1379 struct loop *def_loop;
1381 if (TREE_CODE (def) == NOP_EXPR)
1382 return t_false;
1384 /* Give up if the path is longer than the MAX that we allow. */
1385 if (limit > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_SIZE))
1386 return t_dont_know;
1388 def_loop = loop_containing_stmt (def);
1390 switch (TREE_CODE (def))
1392 case PHI_NODE:
1393 if (!loop_phi_node_p (def))
1394 /* DEF is a condition-phi-node. Follow the branches, and
1395 record their evolutions. Finally, merge the collected
1396 information and set the approximation to the main
1397 variable. */
1398 return follow_ssa_edge_in_condition_phi
1399 (loop, def, halting_phi, evolution_of_loop, limit);
1401 /* When the analyzed phi is the halting_phi, the
1402 depth-first search is over: we have found a path from
1403 the halting_phi to itself in the loop. */
1404 if (def == halting_phi)
1405 return t_true;
1407 /* Otherwise, the evolution of the HALTING_PHI depends
1408 on the evolution of another loop-phi-node, i.e. the
1409 evolution function is a higher degree polynomial. */
1410 if (def_loop == loop)
1411 return t_false;
1413 /* Inner loop. */
1414 if (flow_loop_nested_p (loop, def_loop))
1415 return follow_ssa_edge_inner_loop_phi
1416 (loop, def, halting_phi, evolution_of_loop, limit + 1);
1418 /* Outer loop. */
1419 return t_false;
1421 case GIMPLE_MODIFY_STMT:
1422 return follow_ssa_edge_in_rhs (loop, def,
1423 GIMPLE_STMT_OPERAND (def, 1),
1424 halting_phi,
1425 evolution_of_loop, limit);
1427 default:
1428 /* At this level of abstraction, the program is just a set
1429 of GIMPLE_MODIFY_STMTs and PHI_NODEs. In principle there is no
1430 other node to be handled. */
1431 return t_false;
1437 /* Given a LOOP_PHI_NODE, this function determines the evolution
1438 function from LOOP_PHI_NODE to LOOP_PHI_NODE in the loop. */
1440 static tree
1441 analyze_evolution_in_loop (tree loop_phi_node,
1442 tree init_cond)
1444 int i;
1445 tree evolution_function = chrec_not_analyzed_yet;
1446 struct loop *loop = loop_containing_stmt (loop_phi_node);
1447 basic_block bb;
1449 if (dump_file && (dump_flags & TDF_DETAILS))
1451 fprintf (dump_file, "(analyze_evolution_in_loop \n");
1452 fprintf (dump_file, " (loop_phi_node = ");
1453 print_generic_expr (dump_file, loop_phi_node, 0);
1454 fprintf (dump_file, ")\n");
1457 for (i = 0; i < PHI_NUM_ARGS (loop_phi_node); i++)
1459 tree arg = PHI_ARG_DEF (loop_phi_node, i);
1460 tree ssa_chain, ev_fn;
1461 t_bool res;
1463 /* Select the edges that enter the loop body. */
1464 bb = PHI_ARG_EDGE (loop_phi_node, i)->src;
1465 if (!flow_bb_inside_loop_p (loop, bb))
1466 continue;
1468 if (TREE_CODE (arg) == SSA_NAME)
1470 ssa_chain = SSA_NAME_DEF_STMT (arg);
1472 /* Pass in the initial condition to the follow edge function. */
1473 ev_fn = init_cond;
1474 res = follow_ssa_edge (loop, ssa_chain, loop_phi_node, &ev_fn, 0);
1476 else
1477 res = t_false;
1479 /* When it is impossible to go back on the same
1480 loop_phi_node by following the ssa edges, the
1481 evolution is represented by a peeled chrec, i.e. the
1482 first iteration, EV_FN has the value INIT_COND, then
1483 all the other iterations it has the value of ARG.
1484 For the moment, PEELED_CHREC nodes are not built. */
1485 if (res != t_true)
1486 ev_fn = chrec_dont_know;
1488 /* When there are multiple back edges of the loop (which in fact never
1489 happens currently, but nevertheless), merge their evolutions. */
1490 evolution_function = chrec_merge (evolution_function, ev_fn);
1493 if (dump_file && (dump_flags & TDF_DETAILS))
1495 fprintf (dump_file, " (evolution_function = ");
1496 print_generic_expr (dump_file, evolution_function, 0);
1497 fprintf (dump_file, "))\n");
1500 return evolution_function;
1503 /* Given a loop-phi-node, return the initial conditions of the
1504 variable on entry of the loop. When the CCP has propagated
1505 constants into the loop-phi-node, the initial condition is
1506 instantiated, otherwise the initial condition is kept symbolic.
1507 This analyzer does not analyze the evolution outside the current
1508 loop, and leaves this task to the on-demand tree reconstructor. */
1510 static tree
1511 analyze_initial_condition (tree loop_phi_node)
1513 int i;
1514 tree init_cond = chrec_not_analyzed_yet;
1515 struct loop *loop = bb_for_stmt (loop_phi_node)->loop_father;
1517 if (dump_file && (dump_flags & TDF_DETAILS))
1519 fprintf (dump_file, "(analyze_initial_condition \n");
1520 fprintf (dump_file, " (loop_phi_node = \n");
1521 print_generic_expr (dump_file, loop_phi_node, 0);
1522 fprintf (dump_file, ")\n");
1525 for (i = 0; i < PHI_NUM_ARGS (loop_phi_node); i++)
1527 tree branch = PHI_ARG_DEF (loop_phi_node, i);
1528 basic_block bb = PHI_ARG_EDGE (loop_phi_node, i)->src;
1530 /* When the branch is oriented to the loop's body, it does
1531 not contribute to the initial condition. */
1532 if (flow_bb_inside_loop_p (loop, bb))
1533 continue;
1535 if (init_cond == chrec_not_analyzed_yet)
1537 init_cond = branch;
1538 continue;
1541 if (TREE_CODE (branch) == SSA_NAME)
1543 init_cond = chrec_dont_know;
1544 break;
1547 init_cond = chrec_merge (init_cond, branch);
1550 /* Ooops -- a loop without an entry??? */
1551 if (init_cond == chrec_not_analyzed_yet)
1552 init_cond = chrec_dont_know;
1554 if (dump_file && (dump_flags & TDF_DETAILS))
1556 fprintf (dump_file, " (init_cond = ");
1557 print_generic_expr (dump_file, init_cond, 0);
1558 fprintf (dump_file, "))\n");
1561 return init_cond;
1564 /* Analyze the scalar evolution for LOOP_PHI_NODE. */
1566 static tree
1567 interpret_loop_phi (struct loop *loop, tree loop_phi_node)
1569 tree res;
1570 struct loop *phi_loop = loop_containing_stmt (loop_phi_node);
1571 tree init_cond;
1573 if (phi_loop != loop)
1575 struct loop *subloop;
1576 tree evolution_fn = analyze_scalar_evolution
1577 (phi_loop, PHI_RESULT (loop_phi_node));
1579 /* Dive one level deeper. */
1580 subloop = superloop_at_depth (phi_loop, loop_depth (loop) + 1);
1582 /* Interpret the subloop. */
1583 res = compute_overall_effect_of_inner_loop (subloop, evolution_fn);
1584 return res;
1587 /* Otherwise really interpret the loop phi. */
1588 init_cond = analyze_initial_condition (loop_phi_node);
1589 res = analyze_evolution_in_loop (loop_phi_node, init_cond);
1591 return res;
1594 /* This function merges the branches of a condition-phi-node,
1595 contained in the outermost loop, and whose arguments are already
1596 analyzed. */
1598 static tree
1599 interpret_condition_phi (struct loop *loop, tree condition_phi)
1601 int i;
1602 tree res = chrec_not_analyzed_yet;
1604 for (i = 0; i < PHI_NUM_ARGS (condition_phi); i++)
1606 tree branch_chrec;
1608 if (backedge_phi_arg_p (condition_phi, i))
1610 res = chrec_dont_know;
1611 break;
1614 branch_chrec = analyze_scalar_evolution
1615 (loop, PHI_ARG_DEF (condition_phi, i));
1617 res = chrec_merge (res, branch_chrec);
1620 return res;
1623 /* Interpret the right hand side of a GIMPLE_MODIFY_STMT OPND1. If we didn't
1624 analyze this node before, follow the definitions until ending
1625 either on an analyzed GIMPLE_MODIFY_STMT, or on a loop-phi-node. On the
1626 return path, this function propagates evolutions (ala constant copy
1627 propagation). OPND1 is not a GIMPLE expression because we could
1628 analyze the effect of an inner loop: see interpret_loop_phi. */
1630 static tree
1631 interpret_rhs_modify_stmt (struct loop *loop, tree at_stmt,
1632 tree opnd1, tree type)
1634 tree res, opnd10, opnd11, chrec10, chrec11;
1636 if (is_gimple_min_invariant (opnd1))
1637 return chrec_convert (type, opnd1, at_stmt);
1639 switch (TREE_CODE (opnd1))
1641 case POINTER_PLUS_EXPR:
1642 opnd10 = TREE_OPERAND (opnd1, 0);
1643 opnd11 = TREE_OPERAND (opnd1, 1);
1644 chrec10 = analyze_scalar_evolution (loop, opnd10);
1645 chrec11 = analyze_scalar_evolution (loop, opnd11);
1646 chrec10 = chrec_convert (type, chrec10, at_stmt);
1647 chrec11 = chrec_convert (sizetype, chrec11, at_stmt);
1648 res = chrec_fold_plus (type, chrec10, chrec11);
1649 break;
1651 case PLUS_EXPR:
1652 opnd10 = TREE_OPERAND (opnd1, 0);
1653 opnd11 = TREE_OPERAND (opnd1, 1);
1654 chrec10 = analyze_scalar_evolution (loop, opnd10);
1655 chrec11 = analyze_scalar_evolution (loop, opnd11);
1656 chrec10 = chrec_convert (type, chrec10, at_stmt);
1657 chrec11 = chrec_convert (type, chrec11, at_stmt);
1658 res = chrec_fold_plus (type, chrec10, chrec11);
1659 break;
1661 case MINUS_EXPR:
1662 opnd10 = TREE_OPERAND (opnd1, 0);
1663 opnd11 = TREE_OPERAND (opnd1, 1);
1664 chrec10 = analyze_scalar_evolution (loop, opnd10);
1665 chrec11 = analyze_scalar_evolution (loop, opnd11);
1666 chrec10 = chrec_convert (type, chrec10, at_stmt);
1667 chrec11 = chrec_convert (type, chrec11, at_stmt);
1668 res = chrec_fold_minus (type, chrec10, chrec11);
1669 break;
1671 case NEGATE_EXPR:
1672 opnd10 = TREE_OPERAND (opnd1, 0);
1673 chrec10 = analyze_scalar_evolution (loop, opnd10);
1674 chrec10 = chrec_convert (type, chrec10, at_stmt);
1675 /* TYPE may be integer, real or complex, so use fold_convert. */
1676 res = chrec_fold_multiply (type, chrec10,
1677 fold_convert (type, integer_minus_one_node));
1678 break;
1680 case MULT_EXPR:
1681 opnd10 = TREE_OPERAND (opnd1, 0);
1682 opnd11 = TREE_OPERAND (opnd1, 1);
1683 chrec10 = analyze_scalar_evolution (loop, opnd10);
1684 chrec11 = analyze_scalar_evolution (loop, opnd11);
1685 chrec10 = chrec_convert (type, chrec10, at_stmt);
1686 chrec11 = chrec_convert (type, chrec11, at_stmt);
1687 res = chrec_fold_multiply (type, chrec10, chrec11);
1688 break;
1690 case SSA_NAME:
1691 res = chrec_convert (type, analyze_scalar_evolution (loop, opnd1),
1692 at_stmt);
1693 break;
1695 case ASSERT_EXPR:
1696 opnd10 = ASSERT_EXPR_VAR (opnd1);
1697 res = chrec_convert (type, analyze_scalar_evolution (loop, opnd10),
1698 at_stmt);
1699 break;
1701 CASE_CONVERT:
1702 opnd10 = TREE_OPERAND (opnd1, 0);
1703 chrec10 = analyze_scalar_evolution (loop, opnd10);
1704 res = chrec_convert (type, chrec10, at_stmt);
1705 break;
1707 default:
1708 res = chrec_dont_know;
1709 break;
1712 return res;
1717 /* This section contains all the entry points:
1718 - number_of_iterations_in_loop,
1719 - analyze_scalar_evolution,
1720 - instantiate_parameters.
1723 /* Compute and return the evolution function in WRTO_LOOP, the nearest
1724 common ancestor of DEF_LOOP and USE_LOOP. */
1726 static tree
1727 compute_scalar_evolution_in_loop (struct loop *wrto_loop,
1728 struct loop *def_loop,
1729 tree ev)
1731 tree res;
1732 if (def_loop == wrto_loop)
1733 return ev;
1735 def_loop = superloop_at_depth (def_loop, loop_depth (wrto_loop) + 1);
1736 res = compute_overall_effect_of_inner_loop (def_loop, ev);
1738 return analyze_scalar_evolution_1 (wrto_loop, res, chrec_not_analyzed_yet);
1741 /* Helper recursive function. */
1743 static tree
1744 analyze_scalar_evolution_1 (struct loop *loop, tree var, tree res)
1746 tree def, type = TREE_TYPE (var);
1747 basic_block bb;
1748 struct loop *def_loop;
1750 if (loop == NULL || TREE_CODE (type) == VECTOR_TYPE)
1751 return chrec_dont_know;
1753 if (TREE_CODE (var) != SSA_NAME)
1754 return interpret_rhs_modify_stmt (loop, NULL_TREE, var, type);
1756 def = SSA_NAME_DEF_STMT (var);
1757 bb = bb_for_stmt (def);
1758 def_loop = bb ? bb->loop_father : NULL;
1760 if (bb == NULL
1761 || !flow_bb_inside_loop_p (loop, bb))
1763 /* Keep the symbolic form. */
1764 res = var;
1765 goto set_and_end;
1768 if (res != chrec_not_analyzed_yet)
1770 if (loop != bb->loop_father)
1771 res = compute_scalar_evolution_in_loop
1772 (find_common_loop (loop, bb->loop_father), bb->loop_father, res);
1774 goto set_and_end;
1777 if (loop != def_loop)
1779 res = analyze_scalar_evolution_1 (def_loop, var, chrec_not_analyzed_yet);
1780 res = compute_scalar_evolution_in_loop (loop, def_loop, res);
1782 goto set_and_end;
1785 switch (TREE_CODE (def))
1787 case GIMPLE_MODIFY_STMT:
1788 res = interpret_rhs_modify_stmt (loop, def,
1789 GIMPLE_STMT_OPERAND (def, 1), type);
1790 break;
1792 case PHI_NODE:
1793 if (loop_phi_node_p (def))
1794 res = interpret_loop_phi (loop, def);
1795 else
1796 res = interpret_condition_phi (loop, def);
1797 break;
1799 default:
1800 res = chrec_dont_know;
1801 break;
1804 set_and_end:
1806 /* Keep the symbolic form. */
1807 if (res == chrec_dont_know)
1808 res = var;
1810 if (loop == def_loop)
1811 set_scalar_evolution (var, res);
1813 return res;
1816 /* Entry point for the scalar evolution analyzer.
1817 Analyzes and returns the scalar evolution of the ssa_name VAR.
1818 LOOP_NB is the identifier number of the loop in which the variable
1819 is used.
1821 Example of use: having a pointer VAR to a SSA_NAME node, STMT a
1822 pointer to the statement that uses this variable, in order to
1823 determine the evolution function of the variable, use the following
1824 calls:
1826 unsigned loop_nb = loop_containing_stmt (stmt)->num;
1827 tree chrec_with_symbols = analyze_scalar_evolution (loop_nb, var);
1828 tree chrec_instantiated = instantiate_parameters (loop, chrec_with_symbols);
1831 tree
1832 analyze_scalar_evolution (struct loop *loop, tree var)
1834 tree res;
1836 if (dump_file && (dump_flags & TDF_DETAILS))
1838 fprintf (dump_file, "(analyze_scalar_evolution \n");
1839 fprintf (dump_file, " (loop_nb = %d)\n", loop->num);
1840 fprintf (dump_file, " (scalar = ");
1841 print_generic_expr (dump_file, var, 0);
1842 fprintf (dump_file, ")\n");
1845 res = analyze_scalar_evolution_1 (loop, var, get_scalar_evolution (var));
1847 if (TREE_CODE (var) == SSA_NAME && res == chrec_dont_know)
1848 res = var;
1850 if (dump_file && (dump_flags & TDF_DETAILS))
1851 fprintf (dump_file, ")\n");
1853 return res;
1856 /* Analyze scalar evolution of use of VERSION in USE_LOOP with respect to
1857 WRTO_LOOP (which should be a superloop of both USE_LOOP and definition
1858 of VERSION).
1860 FOLDED_CASTS is set to true if resolve_mixers used
1861 chrec_convert_aggressive (TODO -- not really, we are way too conservative
1862 at the moment in order to keep things simple). */
1864 static tree
1865 analyze_scalar_evolution_in_loop (struct loop *wrto_loop, struct loop *use_loop,
1866 tree version, bool *folded_casts)
1868 bool val = false;
1869 tree ev = version, tmp;
1871 if (folded_casts)
1872 *folded_casts = false;
1873 while (1)
1875 tmp = analyze_scalar_evolution (use_loop, ev);
1876 ev = resolve_mixers (use_loop, tmp);
1878 if (folded_casts && tmp != ev)
1879 *folded_casts = true;
1881 if (use_loop == wrto_loop)
1882 return ev;
1884 /* If the value of the use changes in the inner loop, we cannot express
1885 its value in the outer loop (we might try to return interval chrec,
1886 but we do not have a user for it anyway) */
1887 if (!no_evolution_in_loop_p (ev, use_loop->num, &val)
1888 || !val)
1889 return chrec_dont_know;
1891 use_loop = loop_outer (use_loop);
1895 /* Returns instantiated value for VERSION in CACHE. */
1897 static tree
1898 get_instantiated_value (htab_t cache, tree version)
1900 struct scev_info_str *info, pattern;
1902 pattern.var = version;
1903 info = (struct scev_info_str *) htab_find (cache, &pattern);
1905 if (info)
1906 return info->chrec;
1907 else
1908 return NULL_TREE;
1911 /* Sets instantiated value for VERSION to VAL in CACHE. */
1913 static void
1914 set_instantiated_value (htab_t cache, tree version, tree val)
1916 struct scev_info_str *info, pattern;
1917 PTR *slot;
1919 pattern.var = version;
1920 slot = htab_find_slot (cache, &pattern, INSERT);
1922 if (!*slot)
1923 *slot = new_scev_info_str (version);
1924 info = (struct scev_info_str *) *slot;
1925 info->chrec = val;
1928 /* Return the closed_loop_phi node for VAR. If there is none, return
1929 NULL_TREE. */
1931 static tree
1932 loop_closed_phi_def (tree var)
1934 struct loop *loop;
1935 edge exit;
1936 tree phi;
1938 if (var == NULL_TREE
1939 || TREE_CODE (var) != SSA_NAME)
1940 return NULL_TREE;
1942 loop = loop_containing_stmt (SSA_NAME_DEF_STMT (var));
1943 exit = single_exit (loop);
1944 if (!exit)
1945 return NULL_TREE;
1947 for (phi = phi_nodes (exit->dest); phi; phi = PHI_CHAIN (phi))
1948 if (PHI_ARG_DEF_FROM_EDGE (phi, exit) == var)
1949 return PHI_RESULT (phi);
1951 return NULL_TREE;
1954 /* Analyze all the parameters of the chrec, between INSTANTIATION_LOOP
1955 and EVOLUTION_LOOP, that were left under a symbolic form.
1957 CHREC is the scalar evolution to instantiate.
1959 CACHE is the cache of already instantiated values.
1961 FOLD_CONVERSIONS should be set to true when the conversions that
1962 may wrap in signed/pointer type are folded, as long as the value of
1963 the chrec is preserved.
1965 SIZE_EXPR is used for computing the size of the expression to be
1966 instantiated, and to stop if it exceeds some limit. */
1968 static tree
1969 instantiate_scev_1 (struct loop *instantiation_loop,
1970 struct loop *evolution_loop, tree chrec,
1971 bool fold_conversions, htab_t cache, int size_expr)
1973 tree res, op0, op1, op2;
1974 basic_block def_bb;
1975 struct loop *def_loop;
1976 tree type = chrec_type (chrec);
1978 /* Give up if the expression is larger than the MAX that we allow. */
1979 if (size_expr++ > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_SIZE))
1980 return chrec_dont_know;
1982 if (automatically_generated_chrec_p (chrec)
1983 || is_gimple_min_invariant (chrec))
1984 return chrec;
1986 switch (TREE_CODE (chrec))
1988 case SSA_NAME:
1989 def_bb = bb_for_stmt (SSA_NAME_DEF_STMT (chrec));
1991 /* A parameter (or loop invariant and we do not want to include
1992 evolutions in outer loops), nothing to do. */
1993 if (!def_bb
1994 || loop_depth (def_bb->loop_father) == 0
1995 || !flow_bb_inside_loop_p (instantiation_loop, def_bb))
1996 return chrec;
1998 /* We cache the value of instantiated variable to avoid exponential
1999 time complexity due to reevaluations. We also store the convenient
2000 value in the cache in order to prevent infinite recursion -- we do
2001 not want to instantiate the SSA_NAME if it is in a mixer
2002 structure. This is used for avoiding the instantiation of
2003 recursively defined functions, such as:
2005 | a_2 -> {0, +, 1, +, a_2}_1 */
2007 res = get_instantiated_value (cache, chrec);
2008 if (res)
2009 return res;
2011 /* Store the convenient value for chrec in the structure. If it
2012 is defined outside of the loop, we may just leave it in symbolic
2013 form, otherwise we need to admit that we do not know its behavior
2014 inside the loop. */
2015 res = !flow_bb_inside_loop_p (instantiation_loop, def_bb)
2016 ? chrec : chrec_dont_know;
2017 set_instantiated_value (cache, chrec, res);
2019 /* To make things even more complicated, instantiate_scev_1
2020 calls analyze_scalar_evolution that may call # of iterations
2021 analysis that may in turn call instantiate_scev_1 again.
2022 To prevent the infinite recursion, keep also the bitmap of
2023 ssa names that are being instantiated globally. */
2024 if (bitmap_bit_p (already_instantiated, SSA_NAME_VERSION (chrec)))
2025 return res;
2027 def_loop = find_common_loop (evolution_loop, def_bb->loop_father);
2029 /* If the analysis yields a parametric chrec, instantiate the
2030 result again. */
2031 bitmap_set_bit (already_instantiated, SSA_NAME_VERSION (chrec));
2032 res = analyze_scalar_evolution (def_loop, chrec);
2034 /* Don't instantiate loop-closed-ssa phi nodes. */
2035 if (TREE_CODE (res) == SSA_NAME
2036 && (loop_containing_stmt (SSA_NAME_DEF_STMT (res)) == NULL
2037 || (loop_depth (loop_containing_stmt (SSA_NAME_DEF_STMT (res)))
2038 > loop_depth (def_loop))))
2040 if (res == chrec)
2041 res = loop_closed_phi_def (chrec);
2042 else
2043 res = chrec;
2045 if (res == NULL_TREE)
2046 res = chrec_dont_know;
2049 else if (res != chrec_dont_know)
2050 res = instantiate_scev_1 (instantiation_loop, evolution_loop, res,
2051 fold_conversions, cache, size_expr);
2053 bitmap_clear_bit (already_instantiated, SSA_NAME_VERSION (chrec));
2055 /* Store the correct value to the cache. */
2056 set_instantiated_value (cache, chrec, res);
2057 return res;
2059 case POLYNOMIAL_CHREC:
2060 op0 = instantiate_scev_1 (instantiation_loop, evolution_loop,
2061 CHREC_LEFT (chrec), fold_conversions, cache,
2062 size_expr);
2063 if (op0 == chrec_dont_know)
2064 return chrec_dont_know;
2066 op1 = instantiate_scev_1 (instantiation_loop, evolution_loop,
2067 CHREC_RIGHT (chrec), fold_conversions, cache,
2068 size_expr);
2069 if (op1 == chrec_dont_know)
2070 return chrec_dont_know;
2072 if (CHREC_LEFT (chrec) != op0
2073 || CHREC_RIGHT (chrec) != op1)
2075 op1 = chrec_convert_rhs (chrec_type (op0), op1, NULL_TREE);
2076 chrec = build_polynomial_chrec (CHREC_VARIABLE (chrec), op0, op1);
2078 return chrec;
2080 case POINTER_PLUS_EXPR:
2081 case PLUS_EXPR:
2082 op0 = instantiate_scev_1 (instantiation_loop, evolution_loop,
2083 TREE_OPERAND (chrec, 0), fold_conversions, cache,
2084 size_expr);
2085 if (op0 == chrec_dont_know)
2086 return chrec_dont_know;
2088 op1 = instantiate_scev_1 (instantiation_loop, evolution_loop,
2089 TREE_OPERAND (chrec, 1), fold_conversions, cache,
2090 size_expr);
2091 if (op1 == chrec_dont_know)
2092 return chrec_dont_know;
2094 if (TREE_OPERAND (chrec, 0) != op0
2095 || TREE_OPERAND (chrec, 1) != op1)
2097 op0 = chrec_convert (type, op0, NULL_TREE);
2098 op1 = chrec_convert_rhs (type, op1, NULL_TREE);
2099 chrec = chrec_fold_plus (type, op0, op1);
2101 return chrec;
2103 case MINUS_EXPR:
2104 op0 = instantiate_scev_1 (instantiation_loop, evolution_loop,
2105 TREE_OPERAND (chrec, 0), fold_conversions, cache,
2106 size_expr);
2107 if (op0 == chrec_dont_know)
2108 return chrec_dont_know;
2110 op1 = instantiate_scev_1 (instantiation_loop, evolution_loop,
2111 TREE_OPERAND (chrec, 1),
2112 fold_conversions, cache, size_expr);
2113 if (op1 == chrec_dont_know)
2114 return chrec_dont_know;
2116 if (TREE_OPERAND (chrec, 0) != op0
2117 || TREE_OPERAND (chrec, 1) != op1)
2119 op0 = chrec_convert (type, op0, NULL_TREE);
2120 op1 = chrec_convert (type, op1, NULL_TREE);
2121 chrec = chrec_fold_minus (type, op0, op1);
2123 return chrec;
2125 case MULT_EXPR:
2126 op0 = instantiate_scev_1 (instantiation_loop, evolution_loop,
2127 TREE_OPERAND (chrec, 0),
2128 fold_conversions, cache, size_expr);
2129 if (op0 == chrec_dont_know)
2130 return chrec_dont_know;
2132 op1 = instantiate_scev_1 (instantiation_loop, evolution_loop,
2133 TREE_OPERAND (chrec, 1),
2134 fold_conversions, cache, size_expr);
2135 if (op1 == chrec_dont_know)
2136 return chrec_dont_know;
2138 if (TREE_OPERAND (chrec, 0) != op0
2139 || TREE_OPERAND (chrec, 1) != op1)
2141 op0 = chrec_convert (type, op0, NULL_TREE);
2142 op1 = chrec_convert (type, op1, NULL_TREE);
2143 chrec = chrec_fold_multiply (type, op0, op1);
2145 return chrec;
2147 CASE_CONVERT:
2148 op0 = instantiate_scev_1 (instantiation_loop, evolution_loop,
2149 TREE_OPERAND (chrec, 0),
2150 fold_conversions, cache, size_expr);
2151 if (op0 == chrec_dont_know)
2152 return chrec_dont_know;
2154 if (fold_conversions)
2156 tree tmp = chrec_convert_aggressive (TREE_TYPE (chrec), op0);
2157 if (tmp)
2158 return tmp;
2161 if (op0 == TREE_OPERAND (chrec, 0))
2162 return chrec;
2164 /* If we used chrec_convert_aggressive, we can no longer assume that
2165 signed chrecs do not overflow, as chrec_convert does, so avoid
2166 calling it in that case. */
2167 if (fold_conversions)
2168 return fold_convert (TREE_TYPE (chrec), op0);
2170 return chrec_convert (TREE_TYPE (chrec), op0, NULL_TREE);
2172 case SCEV_NOT_KNOWN:
2173 return chrec_dont_know;
2175 case SCEV_KNOWN:
2176 return chrec_known;
2178 default:
2179 break;
2182 gcc_assert (!VL_EXP_CLASS_P (chrec));
2183 switch (TREE_CODE_LENGTH (TREE_CODE (chrec)))
2185 case 3:
2186 op0 = instantiate_scev_1 (instantiation_loop, evolution_loop,
2187 TREE_OPERAND (chrec, 0),
2188 fold_conversions, cache, size_expr);
2189 if (op0 == chrec_dont_know)
2190 return chrec_dont_know;
2192 op1 = instantiate_scev_1 (instantiation_loop, evolution_loop,
2193 TREE_OPERAND (chrec, 1),
2194 fold_conversions, cache, size_expr);
2195 if (op1 == chrec_dont_know)
2196 return chrec_dont_know;
2198 op2 = instantiate_scev_1 (instantiation_loop, evolution_loop,
2199 TREE_OPERAND (chrec, 2),
2200 fold_conversions, cache, size_expr);
2201 if (op2 == chrec_dont_know)
2202 return chrec_dont_know;
2204 if (op0 == TREE_OPERAND (chrec, 0)
2205 && op1 == TREE_OPERAND (chrec, 1)
2206 && op2 == TREE_OPERAND (chrec, 2))
2207 return chrec;
2209 return fold_build3 (TREE_CODE (chrec),
2210 TREE_TYPE (chrec), op0, op1, op2);
2212 case 2:
2213 op0 = instantiate_scev_1 (instantiation_loop, evolution_loop,
2214 TREE_OPERAND (chrec, 0),
2215 fold_conversions, cache, size_expr);
2216 if (op0 == chrec_dont_know)
2217 return chrec_dont_know;
2219 op1 = instantiate_scev_1 (instantiation_loop, evolution_loop,
2220 TREE_OPERAND (chrec, 1),
2221 fold_conversions, cache, size_expr);
2222 if (op1 == chrec_dont_know)
2223 return chrec_dont_know;
2225 if (op0 == TREE_OPERAND (chrec, 0)
2226 && op1 == TREE_OPERAND (chrec, 1))
2227 return chrec;
2228 return fold_build2 (TREE_CODE (chrec), TREE_TYPE (chrec), op0, op1);
2230 case 1:
2231 op0 = instantiate_scev_1 (instantiation_loop, evolution_loop,
2232 TREE_OPERAND (chrec, 0),
2233 fold_conversions, cache, size_expr);
2234 if (op0 == chrec_dont_know)
2235 return chrec_dont_know;
2236 if (op0 == TREE_OPERAND (chrec, 0))
2237 return chrec;
2238 return fold_build1 (TREE_CODE (chrec), TREE_TYPE (chrec), op0);
2240 case 0:
2241 return chrec;
2243 default:
2244 break;
2247 /* Too complicated to handle. */
2248 return chrec_dont_know;
2251 /* Analyze all the parameters of the chrec that were left under a
2252 symbolic form. INSTANTIATION_LOOP is the loop in which symbolic
2253 names have to be instantiated, and EVOLUTION_LOOP is the loop in
2254 which the evolution of scalars have to be analyzed. */
2256 tree
2257 instantiate_scev (struct loop *instantiation_loop, struct loop *evolution_loop,
2258 tree chrec)
2260 tree res;
2261 htab_t cache = htab_create (10, hash_scev_info, eq_scev_info, del_scev_info);
2263 if (dump_file && (dump_flags & TDF_DETAILS))
2265 fprintf (dump_file, "(instantiate_scev \n");
2266 fprintf (dump_file, " (instantiation_loop = %d)\n", instantiation_loop->num);
2267 fprintf (dump_file, " (evolution_loop = %d)\n", evolution_loop->num);
2268 fprintf (dump_file, " (chrec = ");
2269 print_generic_expr (dump_file, chrec, 0);
2270 fprintf (dump_file, ")\n");
2273 res = instantiate_scev_1 (instantiation_loop, evolution_loop, chrec, false,
2274 cache, 0);
2276 if (dump_file && (dump_flags & TDF_DETAILS))
2278 fprintf (dump_file, " (res = ");
2279 print_generic_expr (dump_file, res, 0);
2280 fprintf (dump_file, "))\n");
2283 htab_delete (cache);
2285 return res;
2288 /* Similar to instantiate_parameters, but does not introduce the
2289 evolutions in outer loops for LOOP invariants in CHREC, and does not
2290 care about causing overflows, as long as they do not affect value
2291 of an expression. */
2293 tree
2294 resolve_mixers (struct loop *loop, tree chrec)
2296 htab_t cache = htab_create (10, hash_scev_info, eq_scev_info, del_scev_info);
2297 tree ret = instantiate_scev_1 (loop, loop, chrec, true, cache, 0);
2298 htab_delete (cache);
2299 return ret;
2302 /* Entry point for the analysis of the number of iterations pass.
2303 This function tries to safely approximate the number of iterations
2304 the loop will run. When this property is not decidable at compile
2305 time, the result is chrec_dont_know. Otherwise the result is
2306 a scalar or a symbolic parameter.
2308 Example of analysis: suppose that the loop has an exit condition:
2310 "if (b > 49) goto end_loop;"
2312 and that in a previous analysis we have determined that the
2313 variable 'b' has an evolution function:
2315 "EF = {23, +, 5}_2".
2317 When we evaluate the function at the point 5, i.e. the value of the
2318 variable 'b' after 5 iterations in the loop, we have EF (5) = 48,
2319 and EF (6) = 53. In this case the value of 'b' on exit is '53' and
2320 the loop body has been executed 6 times. */
2322 tree
2323 number_of_latch_executions (struct loop *loop)
2325 tree res, type;
2326 edge exit;
2327 struct tree_niter_desc niter_desc;
2329 /* Determine whether the number_of_iterations_in_loop has already
2330 been computed. */
2331 res = loop->nb_iterations;
2332 if (res)
2333 return res;
2334 res = chrec_dont_know;
2336 if (dump_file && (dump_flags & TDF_DETAILS))
2337 fprintf (dump_file, "(number_of_iterations_in_loop\n");
2339 exit = single_exit (loop);
2340 if (!exit)
2341 goto end;
2343 if (!number_of_iterations_exit (loop, exit, &niter_desc, false))
2344 goto end;
2346 type = TREE_TYPE (niter_desc.niter);
2347 if (integer_nonzerop (niter_desc.may_be_zero))
2348 res = build_int_cst (type, 0);
2349 else if (integer_zerop (niter_desc.may_be_zero))
2350 res = niter_desc.niter;
2351 else
2352 res = chrec_dont_know;
2354 end:
2355 return set_nb_iterations_in_loop (loop, res);
2358 /* Returns the number of executions of the exit condition of LOOP,
2359 i.e., the number by one higher than number_of_latch_executions.
2360 Note that unline number_of_latch_executions, this number does
2361 not necessarily fit in the unsigned variant of the type of
2362 the control variable -- if the number of iterations is a constant,
2363 we return chrec_dont_know if adding one to number_of_latch_executions
2364 overflows; however, in case the number of iterations is symbolic
2365 expression, the caller is responsible for dealing with this
2366 the possible overflow. */
2368 tree
2369 number_of_exit_cond_executions (struct loop *loop)
2371 tree ret = number_of_latch_executions (loop);
2372 tree type = chrec_type (ret);
2374 if (chrec_contains_undetermined (ret))
2375 return ret;
2377 ret = chrec_fold_plus (type, ret, build_int_cst (type, 1));
2378 if (TREE_CODE (ret) == INTEGER_CST
2379 && TREE_OVERFLOW (ret))
2380 return chrec_dont_know;
2382 return ret;
2385 /* One of the drivers for testing the scalar evolutions analysis.
2386 This function computes the number of iterations for all the loops
2387 from the EXIT_CONDITIONS array. */
2389 static void
2390 number_of_iterations_for_all_loops (VEC(tree,heap) **exit_conditions)
2392 unsigned int i;
2393 unsigned nb_chrec_dont_know_loops = 0;
2394 unsigned nb_static_loops = 0;
2395 tree cond;
2397 for (i = 0; VEC_iterate (tree, *exit_conditions, i, cond); i++)
2399 tree res = number_of_latch_executions (loop_containing_stmt (cond));
2400 if (chrec_contains_undetermined (res))
2401 nb_chrec_dont_know_loops++;
2402 else
2403 nb_static_loops++;
2406 if (dump_file)
2408 fprintf (dump_file, "\n(\n");
2409 fprintf (dump_file, "-----------------------------------------\n");
2410 fprintf (dump_file, "%d\tnb_chrec_dont_know_loops\n", nb_chrec_dont_know_loops);
2411 fprintf (dump_file, "%d\tnb_static_loops\n", nb_static_loops);
2412 fprintf (dump_file, "%d\tnb_total_loops\n", number_of_loops ());
2413 fprintf (dump_file, "-----------------------------------------\n");
2414 fprintf (dump_file, ")\n\n");
2416 print_loops (dump_file, 3);
2422 /* Counters for the stats. */
2424 struct chrec_stats
2426 unsigned nb_chrecs;
2427 unsigned nb_affine;
2428 unsigned nb_affine_multivar;
2429 unsigned nb_higher_poly;
2430 unsigned nb_chrec_dont_know;
2431 unsigned nb_undetermined;
2434 /* Reset the counters. */
2436 static inline void
2437 reset_chrecs_counters (struct chrec_stats *stats)
2439 stats->nb_chrecs = 0;
2440 stats->nb_affine = 0;
2441 stats->nb_affine_multivar = 0;
2442 stats->nb_higher_poly = 0;
2443 stats->nb_chrec_dont_know = 0;
2444 stats->nb_undetermined = 0;
2447 /* Dump the contents of a CHREC_STATS structure. */
2449 static void
2450 dump_chrecs_stats (FILE *file, struct chrec_stats *stats)
2452 fprintf (file, "\n(\n");
2453 fprintf (file, "-----------------------------------------\n");
2454 fprintf (file, "%d\taffine univariate chrecs\n", stats->nb_affine);
2455 fprintf (file, "%d\taffine multivariate chrecs\n", stats->nb_affine_multivar);
2456 fprintf (file, "%d\tdegree greater than 2 polynomials\n",
2457 stats->nb_higher_poly);
2458 fprintf (file, "%d\tchrec_dont_know chrecs\n", stats->nb_chrec_dont_know);
2459 fprintf (file, "-----------------------------------------\n");
2460 fprintf (file, "%d\ttotal chrecs\n", stats->nb_chrecs);
2461 fprintf (file, "%d\twith undetermined coefficients\n",
2462 stats->nb_undetermined);
2463 fprintf (file, "-----------------------------------------\n");
2464 fprintf (file, "%d\tchrecs in the scev database\n",
2465 (int) htab_elements (scalar_evolution_info));
2466 fprintf (file, "%d\tsets in the scev database\n", nb_set_scev);
2467 fprintf (file, "%d\tgets in the scev database\n", nb_get_scev);
2468 fprintf (file, "-----------------------------------------\n");
2469 fprintf (file, ")\n\n");
2472 /* Gather statistics about CHREC. */
2474 static void
2475 gather_chrec_stats (tree chrec, struct chrec_stats *stats)
2477 if (dump_file && (dump_flags & TDF_STATS))
2479 fprintf (dump_file, "(classify_chrec ");
2480 print_generic_expr (dump_file, chrec, 0);
2481 fprintf (dump_file, "\n");
2484 stats->nb_chrecs++;
2486 if (chrec == NULL_TREE)
2488 stats->nb_undetermined++;
2489 return;
2492 switch (TREE_CODE (chrec))
2494 case POLYNOMIAL_CHREC:
2495 if (evolution_function_is_affine_p (chrec))
2497 if (dump_file && (dump_flags & TDF_STATS))
2498 fprintf (dump_file, " affine_univariate\n");
2499 stats->nb_affine++;
2501 else if (evolution_function_is_affine_multivariate_p (chrec, 0))
2503 if (dump_file && (dump_flags & TDF_STATS))
2504 fprintf (dump_file, " affine_multivariate\n");
2505 stats->nb_affine_multivar++;
2507 else
2509 if (dump_file && (dump_flags & TDF_STATS))
2510 fprintf (dump_file, " higher_degree_polynomial\n");
2511 stats->nb_higher_poly++;
2514 break;
2516 default:
2517 break;
2520 if (chrec_contains_undetermined (chrec))
2522 if (dump_file && (dump_flags & TDF_STATS))
2523 fprintf (dump_file, " undetermined\n");
2524 stats->nb_undetermined++;
2527 if (dump_file && (dump_flags & TDF_STATS))
2528 fprintf (dump_file, ")\n");
2531 /* One of the drivers for testing the scalar evolutions analysis.
2532 This function analyzes the scalar evolution of all the scalars
2533 defined as loop phi nodes in one of the loops from the
2534 EXIT_CONDITIONS array.
2536 TODO Optimization: A loop is in canonical form if it contains only
2537 a single scalar loop phi node. All the other scalars that have an
2538 evolution in the loop are rewritten in function of this single
2539 index. This allows the parallelization of the loop. */
2541 static void
2542 analyze_scalar_evolution_for_all_loop_phi_nodes (VEC(tree,heap) **exit_conditions)
2544 unsigned int i;
2545 struct chrec_stats stats;
2546 tree cond;
2548 reset_chrecs_counters (&stats);
2550 for (i = 0; VEC_iterate (tree, *exit_conditions, i, cond); i++)
2552 struct loop *loop;
2553 basic_block bb;
2554 tree phi, chrec;
2556 loop = loop_containing_stmt (cond);
2557 bb = loop->header;
2559 for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
2560 if (is_gimple_reg (PHI_RESULT (phi)))
2562 chrec = instantiate_parameters
2563 (loop,
2564 analyze_scalar_evolution (loop, PHI_RESULT (phi)));
2566 if (dump_file && (dump_flags & TDF_STATS))
2567 gather_chrec_stats (chrec, &stats);
2571 if (dump_file && (dump_flags & TDF_STATS))
2572 dump_chrecs_stats (dump_file, &stats);
2575 /* Callback for htab_traverse, gathers information on chrecs in the
2576 hashtable. */
2578 static int
2579 gather_stats_on_scev_database_1 (void **slot, void *stats)
2581 struct scev_info_str *entry = (struct scev_info_str *) *slot;
2583 gather_chrec_stats (entry->chrec, (struct chrec_stats *) stats);
2585 return 1;
2588 /* Classify the chrecs of the whole database. */
2590 void
2591 gather_stats_on_scev_database (void)
2593 struct chrec_stats stats;
2595 if (!dump_file)
2596 return;
2598 reset_chrecs_counters (&stats);
2600 htab_traverse (scalar_evolution_info, gather_stats_on_scev_database_1,
2601 &stats);
2603 dump_chrecs_stats (dump_file, &stats);
2608 /* Initializer. */
2610 static void
2611 initialize_scalar_evolutions_analyzer (void)
2613 /* The elements below are unique. */
2614 if (chrec_dont_know == NULL_TREE)
2616 chrec_not_analyzed_yet = NULL_TREE;
2617 chrec_dont_know = make_node (SCEV_NOT_KNOWN);
2618 chrec_known = make_node (SCEV_KNOWN);
2619 TREE_TYPE (chrec_dont_know) = void_type_node;
2620 TREE_TYPE (chrec_known) = void_type_node;
2624 /* Initialize the analysis of scalar evolutions for LOOPS. */
2626 void
2627 scev_initialize (void)
2629 loop_iterator li;
2630 struct loop *loop;
2632 scalar_evolution_info = htab_create_alloc (100,
2633 hash_scev_info,
2634 eq_scev_info,
2635 del_scev_info,
2636 ggc_calloc,
2637 ggc_free);
2638 already_instantiated = BITMAP_ALLOC (NULL);
2640 initialize_scalar_evolutions_analyzer ();
2642 FOR_EACH_LOOP (li, loop, 0)
2644 loop->nb_iterations = NULL_TREE;
2648 /* Cleans up the information cached by the scalar evolutions analysis. */
2650 void
2651 scev_reset (void)
2653 loop_iterator li;
2654 struct loop *loop;
2656 if (!scalar_evolution_info || !current_loops)
2657 return;
2659 htab_empty (scalar_evolution_info);
2660 FOR_EACH_LOOP (li, loop, 0)
2662 loop->nb_iterations = NULL_TREE;
2666 /* Checks whether OP behaves as a simple affine iv of LOOP in STMT and returns
2667 its base and step in IV if possible. If ALLOW_NONCONSTANT_STEP is true, we
2668 want step to be invariant in LOOP. Otherwise we require it to be an
2669 integer constant. IV->no_overflow is set to true if we are sure the iv cannot
2670 overflow (e.g. because it is computed in signed arithmetics). */
2672 bool
2673 simple_iv (struct loop *loop, tree stmt, tree op, affine_iv *iv,
2674 bool allow_nonconstant_step)
2676 basic_block bb = bb_for_stmt (stmt);
2677 tree type, ev;
2678 bool folded_casts;
2680 iv->base = NULL_TREE;
2681 iv->step = NULL_TREE;
2682 iv->no_overflow = false;
2684 type = TREE_TYPE (op);
2685 if (TREE_CODE (type) != INTEGER_TYPE
2686 && TREE_CODE (type) != POINTER_TYPE)
2687 return false;
2689 ev = analyze_scalar_evolution_in_loop (loop, bb->loop_father, op,
2690 &folded_casts);
2691 if (chrec_contains_undetermined (ev))
2692 return false;
2694 if (tree_does_not_contain_chrecs (ev)
2695 && !chrec_contains_symbols_defined_in_loop (ev, loop->num))
2697 iv->base = ev;
2698 iv->step = build_int_cst (TREE_TYPE (ev), 0);
2699 iv->no_overflow = true;
2700 return true;
2703 if (TREE_CODE (ev) != POLYNOMIAL_CHREC
2704 || CHREC_VARIABLE (ev) != (unsigned) loop->num)
2705 return false;
2707 iv->step = CHREC_RIGHT (ev);
2708 if (allow_nonconstant_step)
2710 if (tree_contains_chrecs (iv->step, NULL)
2711 || chrec_contains_symbols_defined_in_loop (iv->step, loop->num))
2712 return false;
2714 else if (TREE_CODE (iv->step) != INTEGER_CST)
2715 return false;
2717 iv->base = CHREC_LEFT (ev);
2718 if (tree_contains_chrecs (iv->base, NULL)
2719 || chrec_contains_symbols_defined_in_loop (iv->base, loop->num))
2720 return false;
2722 iv->no_overflow = !folded_casts && TYPE_OVERFLOW_UNDEFINED (type);
2724 return true;
2727 /* Runs the analysis of scalar evolutions. */
2729 void
2730 scev_analysis (void)
2732 VEC(tree,heap) *exit_conditions;
2734 exit_conditions = VEC_alloc (tree, heap, 37);
2735 select_loops_exit_conditions (&exit_conditions);
2737 if (dump_file && (dump_flags & TDF_STATS))
2738 analyze_scalar_evolution_for_all_loop_phi_nodes (&exit_conditions);
2740 number_of_iterations_for_all_loops (&exit_conditions);
2741 VEC_free (tree, heap, exit_conditions);
2744 /* Finalize the scalar evolution analysis. */
2746 void
2747 scev_finalize (void)
2749 if (!scalar_evolution_info)
2750 return;
2751 htab_delete (scalar_evolution_info);
2752 BITMAP_FREE (already_instantiated);
2753 scalar_evolution_info = NULL;
2756 /* Replace ssa names for that scev can prove they are constant by the
2757 appropriate constants. Also perform final value replacement in loops,
2758 in case the replacement expressions are cheap.
2760 We only consider SSA names defined by phi nodes; rest is left to the
2761 ordinary constant propagation pass. */
2763 unsigned int
2764 scev_const_prop (void)
2766 basic_block bb;
2767 tree name, phi, next_phi, type, ev;
2768 struct loop *loop, *ex_loop;
2769 bitmap ssa_names_to_remove = NULL;
2770 unsigned i;
2771 loop_iterator li;
2773 if (number_of_loops () <= 1)
2774 return 0;
2776 FOR_EACH_BB (bb)
2778 loop = bb->loop_father;
2780 for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
2782 name = PHI_RESULT (phi);
2784 if (!is_gimple_reg (name))
2785 continue;
2787 type = TREE_TYPE (name);
2789 if (!POINTER_TYPE_P (type)
2790 && !INTEGRAL_TYPE_P (type))
2791 continue;
2793 ev = resolve_mixers (loop, analyze_scalar_evolution (loop, name));
2794 if (!is_gimple_min_invariant (ev)
2795 || !may_propagate_copy (name, ev))
2796 continue;
2798 /* Replace the uses of the name. */
2799 if (name != ev)
2800 replace_uses_by (name, ev);
2802 if (!ssa_names_to_remove)
2803 ssa_names_to_remove = BITMAP_ALLOC (NULL);
2804 bitmap_set_bit (ssa_names_to_remove, SSA_NAME_VERSION (name));
2808 /* Remove the ssa names that were replaced by constants. We do not
2809 remove them directly in the previous cycle, since this
2810 invalidates scev cache. */
2811 if (ssa_names_to_remove)
2813 bitmap_iterator bi;
2815 EXECUTE_IF_SET_IN_BITMAP (ssa_names_to_remove, 0, i, bi)
2817 name = ssa_name (i);
2818 phi = SSA_NAME_DEF_STMT (name);
2820 gcc_assert (TREE_CODE (phi) == PHI_NODE);
2821 remove_phi_node (phi, NULL, true);
2824 BITMAP_FREE (ssa_names_to_remove);
2825 scev_reset ();
2828 /* Now the regular final value replacement. */
2829 FOR_EACH_LOOP (li, loop, LI_FROM_INNERMOST)
2831 edge exit;
2832 tree def, rslt, ass, niter;
2833 block_stmt_iterator bsi;
2835 /* If we do not know exact number of iterations of the loop, we cannot
2836 replace the final value. */
2837 exit = single_exit (loop);
2838 if (!exit)
2839 continue;
2841 niter = number_of_latch_executions (loop);
2842 /* We used to check here whether the computation of NITER is expensive,
2843 and avoided final value elimination if that is the case. The problem
2844 is that it is hard to evaluate whether the expression is too
2845 expensive, as we do not know what optimization opportunities the
2846 the elimination of the final value may reveal. Therefore, we now
2847 eliminate the final values of induction variables unconditionally. */
2848 if (niter == chrec_dont_know)
2849 continue;
2851 /* Ensure that it is possible to insert new statements somewhere. */
2852 if (!single_pred_p (exit->dest))
2853 split_loop_exit_edge (exit);
2854 bsi = bsi_after_labels (exit->dest);
2856 ex_loop = superloop_at_depth (loop,
2857 loop_depth (exit->dest->loop_father) + 1);
2859 for (phi = phi_nodes (exit->dest); phi; phi = next_phi)
2861 next_phi = PHI_CHAIN (phi);
2862 rslt = PHI_RESULT (phi);
2863 def = PHI_ARG_DEF_FROM_EDGE (phi, exit);
2864 if (!is_gimple_reg (def))
2865 continue;
2867 if (!POINTER_TYPE_P (TREE_TYPE (def))
2868 && !INTEGRAL_TYPE_P (TREE_TYPE (def)))
2869 continue;
2871 def = analyze_scalar_evolution_in_loop (ex_loop, loop, def, NULL);
2872 def = compute_overall_effect_of_inner_loop (ex_loop, def);
2873 if (!tree_does_not_contain_chrecs (def)
2874 || chrec_contains_symbols_defined_in_loop (def, ex_loop->num)
2875 /* Moving the computation from the loop may prolong life range
2876 of some ssa names, which may cause problems if they appear
2877 on abnormal edges. */
2878 || contains_abnormal_ssa_name_p (def))
2879 continue;
2881 /* Eliminate the PHI node and replace it by a computation outside
2882 the loop. */
2883 def = unshare_expr (def);
2884 remove_phi_node (phi, NULL_TREE, false);
2886 ass = build_gimple_modify_stmt (rslt, NULL_TREE);
2887 SSA_NAME_DEF_STMT (rslt) = ass;
2889 block_stmt_iterator dest = bsi;
2890 bsi_insert_before (&dest, ass, BSI_NEW_STMT);
2891 def = force_gimple_operand_bsi (&dest, def, false, NULL_TREE,
2892 true, BSI_SAME_STMT);
2894 GIMPLE_STMT_OPERAND (ass, 1) = def;
2895 update_stmt (ass);
2898 return 0;
2901 #include "gt-tree-scalar-evolution.h"