2012-03-17 Janne Blomqvist <jb@gcc.gnu.org>
[official-gcc.git] / gcc / tree-scalar-evolution.c
blobc719984a6920516d76b5c18eebfdbde691d7a19b
1 /* Scalar evolution detector.
2 Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
3 Free Software Foundation, Inc.
4 Contributed by Sebastian Pop <s.pop@laposte.net>
6 This file is part of GCC.
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 for more details.
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
23 Description:
25 This pass analyzes the evolution of scalar variables in loop
26 structures. The algorithm is based on the SSA representation,
27 and on the loop hierarchy tree. This algorithm is not based on
28 the notion of versions of a variable, as it was the case for the
29 previous implementations of the scalar evolution algorithm, but
30 it assumes that each defined name is unique.
32 The notation used in this file is called "chains of recurrences",
33 and has been proposed by Eugene Zima, Robert Van Engelen, and
34 others for describing induction variables in programs. For example
35 "b -> {0, +, 2}_1" means that the scalar variable "b" is equal to 0
36 when entering in the loop_1 and has a step 2 in this loop, in other
37 words "for (b = 0; b < N; b+=2);". Note that the coefficients of
38 this chain of recurrence (or chrec [shrek]) can contain the name of
39 other variables, in which case they are called parametric chrecs.
40 For example, "b -> {a, +, 2}_1" means that the initial value of "b"
41 is the value of "a". In most of the cases these parametric chrecs
42 are fully instantiated before their use because symbolic names can
43 hide some difficult cases such as self-references described later
44 (see the Fibonacci example).
46 A short sketch of the algorithm is:
48 Given a scalar variable to be analyzed, follow the SSA edge to
49 its definition:
51 - When the definition is a GIMPLE_ASSIGN: if the right hand side
52 (RHS) of the definition cannot be statically analyzed, the answer
53 of the analyzer is: "don't know".
54 Otherwise, for all the variables that are not yet analyzed in the
55 RHS, try to determine their evolution, and finally try to
56 evaluate the operation of the RHS that gives the evolution
57 function of the analyzed variable.
59 - When the definition is a condition-phi-node: determine the
60 evolution function for all the branches of the phi node, and
61 finally merge these evolutions (see chrec_merge).
63 - When the definition is a loop-phi-node: determine its initial
64 condition, that is the SSA edge defined in an outer loop, and
65 keep it symbolic. Then determine the SSA edges that are defined
66 in the body of the loop. Follow the inner edges until ending on
67 another loop-phi-node of the same analyzed loop. If the reached
68 loop-phi-node is not the starting loop-phi-node, then we keep
69 this definition under a symbolic form. If the reached
70 loop-phi-node is the same as the starting one, then we compute a
71 symbolic stride on the return path. The result is then the
72 symbolic chrec {initial_condition, +, symbolic_stride}_loop.
74 Examples:
76 Example 1: Illustration of the basic algorithm.
78 | a = 3
79 | loop_1
80 | b = phi (a, c)
81 | c = b + 1
82 | if (c > 10) exit_loop
83 | endloop
85 Suppose that we want to know the number of iterations of the
86 loop_1. The exit_loop is controlled by a COND_EXPR (c > 10). We
87 ask the scalar evolution analyzer two questions: what's the
88 scalar evolution (scev) of "c", and what's the scev of "10". For
89 "10" the answer is "10" since it is a scalar constant. For the
90 scalar variable "c", it follows the SSA edge to its definition,
91 "c = b + 1", and then asks again what's the scev of "b".
92 Following the SSA edge, we end on a loop-phi-node "b = phi (a,
93 c)", where the initial condition is "a", and the inner loop edge
94 is "c". The initial condition is kept under a symbolic form (it
95 may be the case that the copy constant propagation has done its
96 work and we end with the constant "3" as one of the edges of the
97 loop-phi-node). The update edge is followed to the end of the
98 loop, and until reaching again the starting loop-phi-node: b -> c
99 -> b. At this point we have drawn a path from "b" to "b" from
100 which we compute the stride in the loop: in this example it is
101 "+1". The resulting scev for "b" is "b -> {a, +, 1}_1". Now
102 that the scev for "b" is known, it is possible to compute the
103 scev for "c", that is "c -> {a + 1, +, 1}_1". In order to
104 determine the number of iterations in the loop_1, we have to
105 instantiate_parameters (loop_1, {a + 1, +, 1}_1), that gives after some
106 more analysis the scev {4, +, 1}_1, or in other words, this is
107 the function "f (x) = x + 4", where x is the iteration count of
108 the loop_1. Now we have to solve the inequality "x + 4 > 10",
109 and take the smallest iteration number for which the loop is
110 exited: x = 7. This loop runs from x = 0 to x = 7, and in total
111 there are 8 iterations. In terms of loop normalization, we have
112 created a variable that is implicitly defined, "x" or just "_1",
113 and all the other analyzed scalars of the loop are defined in
114 function of this variable:
116 a -> 3
117 b -> {3, +, 1}_1
118 c -> {4, +, 1}_1
120 or in terms of a C program:
122 | a = 3
123 | for (x = 0; x <= 7; x++)
125 | b = x + 3
126 | c = x + 4
129 Example 2a: Illustration of the algorithm on nested loops.
131 | loop_1
132 | a = phi (1, b)
133 | c = a + 2
134 | loop_2 10 times
135 | b = phi (c, d)
136 | d = b + 3
137 | endloop
138 | endloop
140 For analyzing the scalar evolution of "a", the algorithm follows
141 the SSA edge into the loop's body: "a -> b". "b" is an inner
142 loop-phi-node, and its analysis as in Example 1, gives:
144 b -> {c, +, 3}_2
145 d -> {c + 3, +, 3}_2
147 Following the SSA edge for the initial condition, we end on "c = a
148 + 2", and then on the starting loop-phi-node "a". From this point,
149 the loop stride is computed: back on "c = a + 2" we get a "+2" in
150 the loop_1, then on the loop-phi-node "b" we compute the overall
151 effect of the inner loop that is "b = c + 30", and we get a "+30"
152 in the loop_1. That means that the overall stride in loop_1 is
153 equal to "+32", and the result is:
155 a -> {1, +, 32}_1
156 c -> {3, +, 32}_1
158 Example 2b: Multivariate chains of recurrences.
160 | loop_1
161 | k = phi (0, k + 1)
162 | loop_2 4 times
163 | j = phi (0, j + 1)
164 | loop_3 4 times
165 | i = phi (0, i + 1)
166 | A[j + k] = ...
167 | endloop
168 | endloop
169 | endloop
171 Analyzing the access function of array A with
172 instantiate_parameters (loop_1, "j + k"), we obtain the
173 instantiation and the analysis of the scalar variables "j" and "k"
174 in loop_1. This leads to the scalar evolution {4, +, 1}_1: the end
175 value of loop_2 for "j" is 4, and the evolution of "k" in loop_1 is
176 {0, +, 1}_1. To obtain the evolution function in loop_3 and
177 instantiate the scalar variables up to loop_1, one has to use:
178 instantiate_scev (block_before_loop (loop_1), loop_3, "j + k").
179 The result of this call is {{0, +, 1}_1, +, 1}_2.
181 Example 3: Higher degree polynomials.
183 | loop_1
184 | a = phi (2, b)
185 | c = phi (5, d)
186 | b = a + 1
187 | d = c + a
188 | endloop
190 a -> {2, +, 1}_1
191 b -> {3, +, 1}_1
192 c -> {5, +, a}_1
193 d -> {5 + a, +, a}_1
195 instantiate_parameters (loop_1, {5, +, a}_1) -> {5, +, 2, +, 1}_1
196 instantiate_parameters (loop_1, {5 + a, +, a}_1) -> {7, +, 3, +, 1}_1
198 Example 4: Lucas, Fibonacci, or mixers in general.
200 | loop_1
201 | a = phi (1, b)
202 | c = phi (3, d)
203 | b = c
204 | d = c + a
205 | endloop
207 a -> (1, c)_1
208 c -> {3, +, a}_1
210 The syntax "(1, c)_1" stands for a PEELED_CHREC that has the
211 following semantics: during the first iteration of the loop_1, the
212 variable contains the value 1, and then it contains the value "c".
213 Note that this syntax is close to the syntax of the loop-phi-node:
214 "a -> (1, c)_1" vs. "a = phi (1, c)".
216 The symbolic chrec representation contains all the semantics of the
217 original code. What is more difficult is to use this information.
219 Example 5: Flip-flops, or exchangers.
221 | loop_1
222 | a = phi (1, b)
223 | c = phi (3, d)
224 | b = c
225 | d = a
226 | endloop
228 a -> (1, c)_1
229 c -> (3, a)_1
231 Based on these symbolic chrecs, it is possible to refine this
232 information into the more precise PERIODIC_CHRECs:
234 a -> |1, 3|_1
235 c -> |3, 1|_1
237 This transformation is not yet implemented.
239 Further readings:
241 You can find a more detailed description of the algorithm in:
242 http://icps.u-strasbg.fr/~pop/DEA_03_Pop.pdf
243 http://icps.u-strasbg.fr/~pop/DEA_03_Pop.ps.gz. But note that
244 this is a preliminary report and some of the details of the
245 algorithm have changed. I'm working on a research report that
246 updates the description of the algorithms to reflect the design
247 choices used in this implementation.
249 A set of slides show a high level overview of the algorithm and run
250 an example through the scalar evolution analyzer:
251 http://cri.ensmp.fr/~pop/gcc/mar04/slides.pdf
253 The slides that I have presented at the GCC Summit'04 are available
254 at: http://cri.ensmp.fr/~pop/gcc/20040604/gccsummit-lno-spop.pdf
257 #include "config.h"
258 #include "system.h"
259 #include "coretypes.h"
260 #include "gimple-pretty-print.h"
261 #include "tree-flow.h"
262 #include "cfgloop.h"
263 #include "tree-chrec.h"
264 #include "tree-scalar-evolution.h"
265 #include "tree-pass.h"
266 #include "params.h"
268 static tree analyze_scalar_evolution_1 (struct loop *, tree, tree);
269 static tree analyze_scalar_evolution_for_address_of (struct loop *loop,
270 tree var);
272 /* The cached information about an SSA name VAR, claiming that below
273 basic block INSTANTIATED_BELOW, the value of VAR can be expressed
274 as CHREC. */
276 struct GTY(()) scev_info_str {
277 basic_block instantiated_below;
278 tree var;
279 tree chrec;
282 /* Counters for the scev database. */
283 static unsigned nb_set_scev = 0;
284 static unsigned nb_get_scev = 0;
286 /* The following trees are unique elements. Thus the comparison of
287 another element to these elements should be done on the pointer to
288 these trees, and not on their value. */
290 /* The SSA_NAMEs that are not yet analyzed are qualified with NULL_TREE. */
291 tree chrec_not_analyzed_yet;
293 /* Reserved to the cases where the analyzer has detected an
294 undecidable property at compile time. */
295 tree chrec_dont_know;
297 /* When the analyzer has detected that a property will never
298 happen, then it qualifies it with chrec_known. */
299 tree chrec_known;
301 static GTY ((param_is (struct scev_info_str))) htab_t scalar_evolution_info;
304 /* Constructs a new SCEV_INFO_STR structure for VAR and INSTANTIATED_BELOW. */
306 static inline struct scev_info_str *
307 new_scev_info_str (basic_block instantiated_below, tree var)
309 struct scev_info_str *res;
311 res = ggc_alloc_scev_info_str ();
312 res->var = var;
313 res->chrec = chrec_not_analyzed_yet;
314 res->instantiated_below = instantiated_below;
316 return res;
319 /* Computes a hash function for database element ELT. */
321 static hashval_t
322 hash_scev_info (const void *elt)
324 return SSA_NAME_VERSION (((const struct scev_info_str *) elt)->var);
327 /* Compares database elements E1 and E2. */
329 static int
330 eq_scev_info (const void *e1, const void *e2)
332 const struct scev_info_str *elt1 = (const struct scev_info_str *) e1;
333 const struct scev_info_str *elt2 = (const struct scev_info_str *) e2;
335 return (elt1->var == elt2->var
336 && elt1->instantiated_below == elt2->instantiated_below);
339 /* Deletes database element E. */
341 static void
342 del_scev_info (void *e)
344 ggc_free (e);
347 /* Get the scalar evolution of VAR for INSTANTIATED_BELOW basic block.
348 A first query on VAR returns chrec_not_analyzed_yet. */
350 static tree *
351 find_var_scev_info (basic_block instantiated_below, tree var)
353 struct scev_info_str *res;
354 struct scev_info_str tmp;
355 PTR *slot;
357 tmp.var = var;
358 tmp.instantiated_below = instantiated_below;
359 slot = htab_find_slot (scalar_evolution_info, &tmp, INSERT);
361 if (!*slot)
362 *slot = new_scev_info_str (instantiated_below, var);
363 res = (struct scev_info_str *) *slot;
365 return &res->chrec;
368 /* Return true when CHREC contains symbolic names defined in
369 LOOP_NB. */
371 bool
372 chrec_contains_symbols_defined_in_loop (const_tree chrec, unsigned loop_nb)
374 int i, n;
376 if (chrec == NULL_TREE)
377 return false;
379 if (is_gimple_min_invariant (chrec))
380 return false;
382 if (TREE_CODE (chrec) == SSA_NAME)
384 gimple def;
385 loop_p def_loop, loop;
387 if (SSA_NAME_IS_DEFAULT_DEF (chrec))
388 return false;
390 def = SSA_NAME_DEF_STMT (chrec);
391 def_loop = loop_containing_stmt (def);
392 loop = get_loop (loop_nb);
394 if (def_loop == NULL)
395 return false;
397 if (loop == def_loop || flow_loop_nested_p (loop, def_loop))
398 return true;
400 return false;
403 n = TREE_OPERAND_LENGTH (chrec);
404 for (i = 0; i < n; i++)
405 if (chrec_contains_symbols_defined_in_loop (TREE_OPERAND (chrec, i),
406 loop_nb))
407 return true;
408 return false;
411 /* Return true when PHI is a loop-phi-node. */
413 static bool
414 loop_phi_node_p (gimple phi)
416 /* The implementation of this function is based on the following
417 property: "all the loop-phi-nodes of a loop are contained in the
418 loop's header basic block". */
420 return loop_containing_stmt (phi)->header == gimple_bb (phi);
423 /* Compute the scalar evolution for EVOLUTION_FN after crossing LOOP.
424 In general, in the case of multivariate evolutions we want to get
425 the evolution in different loops. LOOP specifies the level for
426 which to get the evolution.
428 Example:
430 | for (j = 0; j < 100; j++)
432 | for (k = 0; k < 100; k++)
434 | i = k + j; - Here the value of i is a function of j, k.
436 | ... = i - Here the value of i is a function of j.
438 | ... = i - Here the value of i is a scalar.
440 Example:
442 | i_0 = ...
443 | loop_1 10 times
444 | i_1 = phi (i_0, i_2)
445 | i_2 = i_1 + 2
446 | endloop
448 This loop has the same effect as:
449 LOOP_1 has the same effect as:
451 | i_1 = i_0 + 20
453 The overall effect of the loop, "i_0 + 20" in the previous example,
454 is obtained by passing in the parameters: LOOP = 1,
455 EVOLUTION_FN = {i_0, +, 2}_1.
458 tree
459 compute_overall_effect_of_inner_loop (struct loop *loop, tree evolution_fn)
461 bool val = false;
463 if (evolution_fn == chrec_dont_know)
464 return chrec_dont_know;
466 else if (TREE_CODE (evolution_fn) == POLYNOMIAL_CHREC)
468 struct loop *inner_loop = get_chrec_loop (evolution_fn);
470 if (inner_loop == loop
471 || flow_loop_nested_p (loop, inner_loop))
473 tree nb_iter = number_of_latch_executions (inner_loop);
475 if (nb_iter == chrec_dont_know)
476 return chrec_dont_know;
477 else
479 tree res;
481 /* evolution_fn is the evolution function in LOOP. Get
482 its value in the nb_iter-th iteration. */
483 res = chrec_apply (inner_loop->num, evolution_fn, nb_iter);
485 if (chrec_contains_symbols_defined_in_loop (res, loop->num))
486 res = instantiate_parameters (loop, res);
488 /* Continue the computation until ending on a parent of LOOP. */
489 return compute_overall_effect_of_inner_loop (loop, res);
492 else
493 return evolution_fn;
496 /* If the evolution function is an invariant, there is nothing to do. */
497 else if (no_evolution_in_loop_p (evolution_fn, loop->num, &val) && val)
498 return evolution_fn;
500 else
501 return chrec_dont_know;
504 /* Determine whether the CHREC is always positive/negative. If the expression
505 cannot be statically analyzed, return false, otherwise set the answer into
506 VALUE. */
508 bool
509 chrec_is_positive (tree chrec, bool *value)
511 bool value0, value1, value2;
512 tree end_value, nb_iter;
514 switch (TREE_CODE (chrec))
516 case POLYNOMIAL_CHREC:
517 if (!chrec_is_positive (CHREC_LEFT (chrec), &value0)
518 || !chrec_is_positive (CHREC_RIGHT (chrec), &value1))
519 return false;
521 /* FIXME -- overflows. */
522 if (value0 == value1)
524 *value = value0;
525 return true;
528 /* Otherwise the chrec is under the form: "{-197, +, 2}_1",
529 and the proof consists in showing that the sign never
530 changes during the execution of the loop, from 0 to
531 loop->nb_iterations. */
532 if (!evolution_function_is_affine_p (chrec))
533 return false;
535 nb_iter = number_of_latch_executions (get_chrec_loop (chrec));
536 if (chrec_contains_undetermined (nb_iter))
537 return false;
539 #if 0
540 /* TODO -- If the test is after the exit, we may decrease the number of
541 iterations by one. */
542 if (after_exit)
543 nb_iter = chrec_fold_minus (type, nb_iter, build_int_cst (type, 1));
544 #endif
546 end_value = chrec_apply (CHREC_VARIABLE (chrec), chrec, nb_iter);
548 if (!chrec_is_positive (end_value, &value2))
549 return false;
551 *value = value0;
552 return value0 == value1;
554 case INTEGER_CST:
555 *value = (tree_int_cst_sgn (chrec) == 1);
556 return true;
558 default:
559 return false;
563 /* Associate CHREC to SCALAR. */
565 static void
566 set_scalar_evolution (basic_block instantiated_below, tree scalar, tree chrec)
568 tree *scalar_info;
570 if (TREE_CODE (scalar) != SSA_NAME)
571 return;
573 scalar_info = find_var_scev_info (instantiated_below, scalar);
575 if (dump_file)
577 if (dump_flags & TDF_SCEV)
579 fprintf (dump_file, "(set_scalar_evolution \n");
580 fprintf (dump_file, " instantiated_below = %d \n",
581 instantiated_below->index);
582 fprintf (dump_file, " (scalar = ");
583 print_generic_expr (dump_file, scalar, 0);
584 fprintf (dump_file, ")\n (scalar_evolution = ");
585 print_generic_expr (dump_file, chrec, 0);
586 fprintf (dump_file, "))\n");
588 if (dump_flags & TDF_STATS)
589 nb_set_scev++;
592 *scalar_info = chrec;
595 /* Retrieve the chrec associated to SCALAR instantiated below
596 INSTANTIATED_BELOW block. */
598 static tree
599 get_scalar_evolution (basic_block instantiated_below, tree scalar)
601 tree res;
603 if (dump_file)
605 if (dump_flags & TDF_SCEV)
607 fprintf (dump_file, "(get_scalar_evolution \n");
608 fprintf (dump_file, " (scalar = ");
609 print_generic_expr (dump_file, scalar, 0);
610 fprintf (dump_file, ")\n");
612 if (dump_flags & TDF_STATS)
613 nb_get_scev++;
616 switch (TREE_CODE (scalar))
618 case SSA_NAME:
619 res = *find_var_scev_info (instantiated_below, scalar);
620 break;
622 case REAL_CST:
623 case FIXED_CST:
624 case INTEGER_CST:
625 res = scalar;
626 break;
628 default:
629 res = chrec_not_analyzed_yet;
630 break;
633 if (dump_file && (dump_flags & TDF_SCEV))
635 fprintf (dump_file, " (scalar_evolution = ");
636 print_generic_expr (dump_file, res, 0);
637 fprintf (dump_file, "))\n");
640 return res;
643 /* Helper function for add_to_evolution. Returns the evolution
644 function for an assignment of the form "a = b + c", where "a" and
645 "b" are on the strongly connected component. CHREC_BEFORE is the
646 information that we already have collected up to this point.
647 TO_ADD is the evolution of "c".
649 When CHREC_BEFORE has an evolution part in LOOP_NB, add to this
650 evolution the expression TO_ADD, otherwise construct an evolution
651 part for this loop. */
653 static tree
654 add_to_evolution_1 (unsigned loop_nb, tree chrec_before, tree to_add,
655 gimple at_stmt)
657 tree type, left, right;
658 struct loop *loop = get_loop (loop_nb), *chloop;
660 switch (TREE_CODE (chrec_before))
662 case POLYNOMIAL_CHREC:
663 chloop = get_chrec_loop (chrec_before);
664 if (chloop == loop
665 || flow_loop_nested_p (chloop, loop))
667 unsigned var;
669 type = chrec_type (chrec_before);
671 /* When there is no evolution part in this loop, build it. */
672 if (chloop != loop)
674 var = loop_nb;
675 left = chrec_before;
676 right = SCALAR_FLOAT_TYPE_P (type)
677 ? build_real (type, dconst0)
678 : build_int_cst (type, 0);
680 else
682 var = CHREC_VARIABLE (chrec_before);
683 left = CHREC_LEFT (chrec_before);
684 right = CHREC_RIGHT (chrec_before);
687 to_add = chrec_convert (type, to_add, at_stmt);
688 right = chrec_convert_rhs (type, right, at_stmt);
689 right = chrec_fold_plus (chrec_type (right), right, to_add);
690 return build_polynomial_chrec (var, left, right);
692 else
694 gcc_assert (flow_loop_nested_p (loop, chloop));
696 /* Search the evolution in LOOP_NB. */
697 left = add_to_evolution_1 (loop_nb, CHREC_LEFT (chrec_before),
698 to_add, at_stmt);
699 right = CHREC_RIGHT (chrec_before);
700 right = chrec_convert_rhs (chrec_type (left), right, at_stmt);
701 return build_polynomial_chrec (CHREC_VARIABLE (chrec_before),
702 left, right);
705 default:
706 /* These nodes do not depend on a loop. */
707 if (chrec_before == chrec_dont_know)
708 return chrec_dont_know;
710 left = chrec_before;
711 right = chrec_convert_rhs (chrec_type (left), to_add, at_stmt);
712 return build_polynomial_chrec (loop_nb, left, right);
716 /* Add TO_ADD to the evolution part of CHREC_BEFORE in the dimension
717 of LOOP_NB.
719 Description (provided for completeness, for those who read code in
720 a plane, and for my poor 62 bytes brain that would have forgotten
721 all this in the next two or three months):
723 The algorithm of translation of programs from the SSA representation
724 into the chrecs syntax is based on a pattern matching. After having
725 reconstructed the overall tree expression for a loop, there are only
726 two cases that can arise:
728 1. a = loop-phi (init, a + expr)
729 2. a = loop-phi (init, expr)
731 where EXPR is either a scalar constant with respect to the analyzed
732 loop (this is a degree 0 polynomial), or an expression containing
733 other loop-phi definitions (these are higher degree polynomials).
735 Examples:
738 | init = ...
739 | loop_1
740 | a = phi (init, a + 5)
741 | endloop
744 | inita = ...
745 | initb = ...
746 | loop_1
747 | a = phi (inita, 2 * b + 3)
748 | b = phi (initb, b + 1)
749 | endloop
751 For the first case, the semantics of the SSA representation is:
753 | a (x) = init + \sum_{j = 0}^{x - 1} expr (j)
755 that is, there is a loop index "x" that determines the scalar value
756 of the variable during the loop execution. During the first
757 iteration, the value is that of the initial condition INIT, while
758 during the subsequent iterations, it is the sum of the initial
759 condition with the sum of all the values of EXPR from the initial
760 iteration to the before last considered iteration.
762 For the second case, the semantics of the SSA program is:
764 | a (x) = init, if x = 0;
765 | expr (x - 1), otherwise.
767 The second case corresponds to the PEELED_CHREC, whose syntax is
768 close to the syntax of a loop-phi-node:
770 | phi (init, expr) vs. (init, expr)_x
772 The proof of the translation algorithm for the first case is a
773 proof by structural induction based on the degree of EXPR.
775 Degree 0:
776 When EXPR is a constant with respect to the analyzed loop, or in
777 other words when EXPR is a polynomial of degree 0, the evolution of
778 the variable A in the loop is an affine function with an initial
779 condition INIT, and a step EXPR. In order to show this, we start
780 from the semantics of the SSA representation:
782 f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
784 and since "expr (j)" is a constant with respect to "j",
786 f (x) = init + x * expr
788 Finally, based on the semantics of the pure sum chrecs, by
789 identification we get the corresponding chrecs syntax:
791 f (x) = init * \binom{x}{0} + expr * \binom{x}{1}
792 f (x) -> {init, +, expr}_x
794 Higher degree:
795 Suppose that EXPR is a polynomial of degree N with respect to the
796 analyzed loop_x for which we have already determined that it is
797 written under the chrecs syntax:
799 | expr (x) -> {b_0, +, b_1, +, ..., +, b_{n-1}} (x)
801 We start from the semantics of the SSA program:
803 | f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
805 | f (x) = init + \sum_{j = 0}^{x - 1}
806 | (b_0 * \binom{j}{0} + ... + b_{n-1} * \binom{j}{n-1})
808 | f (x) = init + \sum_{j = 0}^{x - 1}
809 | \sum_{k = 0}^{n - 1} (b_k * \binom{j}{k})
811 | f (x) = init + \sum_{k = 0}^{n - 1}
812 | (b_k * \sum_{j = 0}^{x - 1} \binom{j}{k})
814 | f (x) = init + \sum_{k = 0}^{n - 1}
815 | (b_k * \binom{x}{k + 1})
817 | f (x) = init + b_0 * \binom{x}{1} + ...
818 | + b_{n-1} * \binom{x}{n}
820 | f (x) = init * \binom{x}{0} + b_0 * \binom{x}{1} + ...
821 | + b_{n-1} * \binom{x}{n}
824 And finally from the definition of the chrecs syntax, we identify:
825 | f (x) -> {init, +, b_0, +, ..., +, b_{n-1}}_x
827 This shows the mechanism that stands behind the add_to_evolution
828 function. An important point is that the use of symbolic
829 parameters avoids the need of an analysis schedule.
831 Example:
833 | inita = ...
834 | initb = ...
835 | loop_1
836 | a = phi (inita, a + 2 + b)
837 | b = phi (initb, b + 1)
838 | endloop
840 When analyzing "a", the algorithm keeps "b" symbolically:
842 | a -> {inita, +, 2 + b}_1
844 Then, after instantiation, the analyzer ends on the evolution:
846 | a -> {inita, +, 2 + initb, +, 1}_1
850 static tree
851 add_to_evolution (unsigned loop_nb, tree chrec_before, enum tree_code code,
852 tree to_add, gimple at_stmt)
854 tree type = chrec_type (to_add);
855 tree res = NULL_TREE;
857 if (to_add == NULL_TREE)
858 return chrec_before;
860 /* TO_ADD is either a scalar, or a parameter. TO_ADD is not
861 instantiated at this point. */
862 if (TREE_CODE (to_add) == POLYNOMIAL_CHREC)
863 /* This should not happen. */
864 return chrec_dont_know;
866 if (dump_file && (dump_flags & TDF_SCEV))
868 fprintf (dump_file, "(add_to_evolution \n");
869 fprintf (dump_file, " (loop_nb = %d)\n", loop_nb);
870 fprintf (dump_file, " (chrec_before = ");
871 print_generic_expr (dump_file, chrec_before, 0);
872 fprintf (dump_file, ")\n (to_add = ");
873 print_generic_expr (dump_file, to_add, 0);
874 fprintf (dump_file, ")\n");
877 if (code == MINUS_EXPR)
878 to_add = chrec_fold_multiply (type, to_add, SCALAR_FLOAT_TYPE_P (type)
879 ? build_real (type, dconstm1)
880 : build_int_cst_type (type, -1));
882 res = add_to_evolution_1 (loop_nb, chrec_before, to_add, at_stmt);
884 if (dump_file && (dump_flags & TDF_SCEV))
886 fprintf (dump_file, " (res = ");
887 print_generic_expr (dump_file, res, 0);
888 fprintf (dump_file, "))\n");
891 return res;
896 /* This section selects the loops that will be good candidates for the
897 scalar evolution analysis. For the moment, greedily select all the
898 loop nests we could analyze. */
900 /* For a loop with a single exit edge, return the COND_EXPR that
901 guards the exit edge. If the expression is too difficult to
902 analyze, then give up. */
904 gimple
905 get_loop_exit_condition (const struct loop *loop)
907 gimple res = NULL;
908 edge exit_edge = single_exit (loop);
910 if (dump_file && (dump_flags & TDF_SCEV))
911 fprintf (dump_file, "(get_loop_exit_condition \n ");
913 if (exit_edge)
915 gimple stmt;
917 stmt = last_stmt (exit_edge->src);
918 if (gimple_code (stmt) == GIMPLE_COND)
919 res = stmt;
922 if (dump_file && (dump_flags & TDF_SCEV))
924 print_gimple_stmt (dump_file, res, 0, 0);
925 fprintf (dump_file, ")\n");
928 return res;
931 /* Recursively determine and enqueue the exit conditions for a loop. */
933 static void
934 get_exit_conditions_rec (struct loop *loop,
935 VEC(gimple,heap) **exit_conditions)
937 if (!loop)
938 return;
940 /* Recurse on the inner loops, then on the next (sibling) loops. */
941 get_exit_conditions_rec (loop->inner, exit_conditions);
942 get_exit_conditions_rec (loop->next, exit_conditions);
944 if (single_exit (loop))
946 gimple loop_condition = get_loop_exit_condition (loop);
948 if (loop_condition)
949 VEC_safe_push (gimple, heap, *exit_conditions, loop_condition);
953 /* Select the candidate loop nests for the analysis. This function
954 initializes the EXIT_CONDITIONS array. */
956 static void
957 select_loops_exit_conditions (VEC(gimple,heap) **exit_conditions)
959 struct loop *function_body = current_loops->tree_root;
961 get_exit_conditions_rec (function_body->inner, exit_conditions);
965 /* Depth first search algorithm. */
967 typedef enum t_bool {
968 t_false,
969 t_true,
970 t_dont_know
971 } t_bool;
974 static t_bool follow_ssa_edge (struct loop *loop, gimple, gimple, tree *, int);
976 /* Follow the ssa edge into the binary expression RHS0 CODE RHS1.
977 Return true if the strongly connected component has been found. */
979 static t_bool
980 follow_ssa_edge_binary (struct loop *loop, gimple at_stmt,
981 tree type, tree rhs0, enum tree_code code, tree rhs1,
982 gimple halting_phi, tree *evolution_of_loop, int limit)
984 t_bool res = t_false;
985 tree evol;
987 switch (code)
989 case POINTER_PLUS_EXPR:
990 case PLUS_EXPR:
991 if (TREE_CODE (rhs0) == SSA_NAME)
993 if (TREE_CODE (rhs1) == SSA_NAME)
995 /* Match an assignment under the form:
996 "a = b + c". */
998 /* We want only assignments of form "name + name" contribute to
999 LIMIT, as the other cases do not necessarily contribute to
1000 the complexity of the expression. */
1001 limit++;
1003 evol = *evolution_of_loop;
1004 res = follow_ssa_edge
1005 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi, &evol, limit);
1007 if (res == t_true)
1008 *evolution_of_loop = add_to_evolution
1009 (loop->num,
1010 chrec_convert (type, evol, at_stmt),
1011 code, rhs1, at_stmt);
1013 else if (res == t_false)
1015 res = follow_ssa_edge
1016 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
1017 evolution_of_loop, limit);
1019 if (res == t_true)
1020 *evolution_of_loop = add_to_evolution
1021 (loop->num,
1022 chrec_convert (type, *evolution_of_loop, at_stmt),
1023 code, rhs0, at_stmt);
1025 else if (res == t_dont_know)
1026 *evolution_of_loop = chrec_dont_know;
1029 else if (res == t_dont_know)
1030 *evolution_of_loop = chrec_dont_know;
1033 else
1035 /* Match an assignment under the form:
1036 "a = b + ...". */
1037 res = follow_ssa_edge
1038 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
1039 evolution_of_loop, limit);
1040 if (res == t_true)
1041 *evolution_of_loop = add_to_evolution
1042 (loop->num, chrec_convert (type, *evolution_of_loop,
1043 at_stmt),
1044 code, rhs1, at_stmt);
1046 else if (res == t_dont_know)
1047 *evolution_of_loop = chrec_dont_know;
1051 else if (TREE_CODE (rhs1) == SSA_NAME)
1053 /* Match an assignment under the form:
1054 "a = ... + c". */
1055 res = follow_ssa_edge
1056 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
1057 evolution_of_loop, limit);
1058 if (res == t_true)
1059 *evolution_of_loop = add_to_evolution
1060 (loop->num, chrec_convert (type, *evolution_of_loop,
1061 at_stmt),
1062 code, rhs0, at_stmt);
1064 else if (res == t_dont_know)
1065 *evolution_of_loop = chrec_dont_know;
1068 else
1069 /* Otherwise, match an assignment under the form:
1070 "a = ... + ...". */
1071 /* And there is nothing to do. */
1072 res = t_false;
1073 break;
1075 case MINUS_EXPR:
1076 /* This case is under the form "opnd0 = rhs0 - rhs1". */
1077 if (TREE_CODE (rhs0) == SSA_NAME)
1079 /* Match an assignment under the form:
1080 "a = b - ...". */
1082 /* We want only assignments of form "name - name" contribute to
1083 LIMIT, as the other cases do not necessarily contribute to
1084 the complexity of the expression. */
1085 if (TREE_CODE (rhs1) == SSA_NAME)
1086 limit++;
1088 res = follow_ssa_edge (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
1089 evolution_of_loop, limit);
1090 if (res == t_true)
1091 *evolution_of_loop = add_to_evolution
1092 (loop->num, chrec_convert (type, *evolution_of_loop, at_stmt),
1093 MINUS_EXPR, rhs1, at_stmt);
1095 else if (res == t_dont_know)
1096 *evolution_of_loop = chrec_dont_know;
1098 else
1099 /* Otherwise, match an assignment under the form:
1100 "a = ... - ...". */
1101 /* And there is nothing to do. */
1102 res = t_false;
1103 break;
1105 default:
1106 res = t_false;
1109 return res;
1112 /* Follow the ssa edge into the expression EXPR.
1113 Return true if the strongly connected component has been found. */
1115 static t_bool
1116 follow_ssa_edge_expr (struct loop *loop, gimple at_stmt, tree expr,
1117 gimple halting_phi, tree *evolution_of_loop, int limit)
1119 enum tree_code code = TREE_CODE (expr);
1120 tree type = TREE_TYPE (expr), rhs0, rhs1;
1121 t_bool res;
1123 /* The EXPR is one of the following cases:
1124 - an SSA_NAME,
1125 - an INTEGER_CST,
1126 - a PLUS_EXPR,
1127 - a POINTER_PLUS_EXPR,
1128 - a MINUS_EXPR,
1129 - an ASSERT_EXPR,
1130 - other cases are not yet handled. */
1132 switch (code)
1134 CASE_CONVERT:
1135 /* This assignment is under the form "a_1 = (cast) rhs. */
1136 res = follow_ssa_edge_expr (loop, at_stmt, TREE_OPERAND (expr, 0),
1137 halting_phi, evolution_of_loop, limit);
1138 *evolution_of_loop = chrec_convert (type, *evolution_of_loop, at_stmt);
1139 break;
1141 case INTEGER_CST:
1142 /* This assignment is under the form "a_1 = 7". */
1143 res = t_false;
1144 break;
1146 case SSA_NAME:
1147 /* This assignment is under the form: "a_1 = b_2". */
1148 res = follow_ssa_edge
1149 (loop, SSA_NAME_DEF_STMT (expr), halting_phi, evolution_of_loop, limit);
1150 break;
1152 case POINTER_PLUS_EXPR:
1153 case PLUS_EXPR:
1154 case MINUS_EXPR:
1155 /* This case is under the form "rhs0 +- rhs1". */
1156 rhs0 = TREE_OPERAND (expr, 0);
1157 rhs1 = TREE_OPERAND (expr, 1);
1158 type = TREE_TYPE (rhs0);
1159 STRIP_USELESS_TYPE_CONVERSION (rhs0);
1160 STRIP_USELESS_TYPE_CONVERSION (rhs1);
1161 res = follow_ssa_edge_binary (loop, at_stmt, type, rhs0, code, rhs1,
1162 halting_phi, evolution_of_loop, limit);
1163 break;
1165 case ADDR_EXPR:
1166 /* Handle &MEM[ptr + CST] which is equivalent to POINTER_PLUS_EXPR. */
1167 if (TREE_CODE (TREE_OPERAND (expr, 0)) == MEM_REF)
1169 expr = TREE_OPERAND (expr, 0);
1170 rhs0 = TREE_OPERAND (expr, 0);
1171 rhs1 = TREE_OPERAND (expr, 1);
1172 type = TREE_TYPE (rhs0);
1173 STRIP_USELESS_TYPE_CONVERSION (rhs0);
1174 STRIP_USELESS_TYPE_CONVERSION (rhs1);
1175 res = follow_ssa_edge_binary (loop, at_stmt, type,
1176 rhs0, POINTER_PLUS_EXPR, rhs1,
1177 halting_phi, evolution_of_loop, limit);
1179 else
1180 res = t_false;
1181 break;
1183 case ASSERT_EXPR:
1184 /* This assignment is of the form: "a_1 = ASSERT_EXPR <a_2, ...>"
1185 It must be handled as a copy assignment of the form a_1 = a_2. */
1186 rhs0 = ASSERT_EXPR_VAR (expr);
1187 if (TREE_CODE (rhs0) == SSA_NAME)
1188 res = follow_ssa_edge (loop, SSA_NAME_DEF_STMT (rhs0),
1189 halting_phi, evolution_of_loop, limit);
1190 else
1191 res = t_false;
1192 break;
1194 default:
1195 res = t_false;
1196 break;
1199 return res;
1202 /* Follow the ssa edge into the right hand side of an assignment STMT.
1203 Return true if the strongly connected component has been found. */
1205 static t_bool
1206 follow_ssa_edge_in_rhs (struct loop *loop, gimple stmt,
1207 gimple halting_phi, tree *evolution_of_loop, int limit)
1209 enum tree_code code = gimple_assign_rhs_code (stmt);
1210 tree type = gimple_expr_type (stmt), rhs1, rhs2;
1211 t_bool res;
1213 switch (code)
1215 CASE_CONVERT:
1216 /* This assignment is under the form "a_1 = (cast) rhs. */
1217 res = follow_ssa_edge_expr (loop, stmt, gimple_assign_rhs1 (stmt),
1218 halting_phi, evolution_of_loop, limit);
1219 *evolution_of_loop = chrec_convert (type, *evolution_of_loop, stmt);
1220 break;
1222 case POINTER_PLUS_EXPR:
1223 case PLUS_EXPR:
1224 case MINUS_EXPR:
1225 rhs1 = gimple_assign_rhs1 (stmt);
1226 rhs2 = gimple_assign_rhs2 (stmt);
1227 type = TREE_TYPE (rhs1);
1228 res = follow_ssa_edge_binary (loop, stmt, type, rhs1, code, rhs2,
1229 halting_phi, evolution_of_loop, limit);
1230 break;
1232 default:
1233 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1234 res = follow_ssa_edge_expr (loop, stmt, gimple_assign_rhs1 (stmt),
1235 halting_phi, evolution_of_loop, limit);
1236 else
1237 res = t_false;
1238 break;
1241 return res;
1244 /* Checks whether the I-th argument of a PHI comes from a backedge. */
1246 static bool
1247 backedge_phi_arg_p (gimple phi, int i)
1249 const_edge e = gimple_phi_arg_edge (phi, i);
1251 /* We would in fact like to test EDGE_DFS_BACK here, but we do not care
1252 about updating it anywhere, and this should work as well most of the
1253 time. */
1254 if (e->flags & EDGE_IRREDUCIBLE_LOOP)
1255 return true;
1257 return false;
1260 /* Helper function for one branch of the condition-phi-node. Return
1261 true if the strongly connected component has been found following
1262 this path. */
1264 static inline t_bool
1265 follow_ssa_edge_in_condition_phi_branch (int i,
1266 struct loop *loop,
1267 gimple condition_phi,
1268 gimple halting_phi,
1269 tree *evolution_of_branch,
1270 tree init_cond, int limit)
1272 tree branch = PHI_ARG_DEF (condition_phi, i);
1273 *evolution_of_branch = chrec_dont_know;
1275 /* Do not follow back edges (they must belong to an irreducible loop, which
1276 we really do not want to worry about). */
1277 if (backedge_phi_arg_p (condition_phi, i))
1278 return t_false;
1280 if (TREE_CODE (branch) == SSA_NAME)
1282 *evolution_of_branch = init_cond;
1283 return follow_ssa_edge (loop, SSA_NAME_DEF_STMT (branch), halting_phi,
1284 evolution_of_branch, limit);
1287 /* This case occurs when one of the condition branches sets
1288 the variable to a constant: i.e. a phi-node like
1289 "a_2 = PHI <a_7(5), 2(6)>;".
1291 FIXME: This case have to be refined correctly:
1292 in some cases it is possible to say something better than
1293 chrec_dont_know, for example using a wrap-around notation. */
1294 return t_false;
1297 /* This function merges the branches of a condition-phi-node in a
1298 loop. */
1300 static t_bool
1301 follow_ssa_edge_in_condition_phi (struct loop *loop,
1302 gimple condition_phi,
1303 gimple halting_phi,
1304 tree *evolution_of_loop, int limit)
1306 int i, n;
1307 tree init = *evolution_of_loop;
1308 tree evolution_of_branch;
1309 t_bool res = follow_ssa_edge_in_condition_phi_branch (0, 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 = evolution_of_branch;
1318 n = gimple_phi_num_args (condition_phi);
1319 for (i = 1; i < n; i++)
1321 /* Quickly give up when the evolution of one of the branches is
1322 not known. */
1323 if (*evolution_of_loop == chrec_dont_know)
1324 return t_true;
1326 /* Increase the limit by the PHI argument number to avoid exponential
1327 time and memory complexity. */
1328 res = follow_ssa_edge_in_condition_phi_branch (i, loop, condition_phi,
1329 halting_phi,
1330 &evolution_of_branch,
1331 init, limit + i);
1332 if (res == t_false || res == t_dont_know)
1333 return res;
1335 *evolution_of_loop = chrec_merge (*evolution_of_loop,
1336 evolution_of_branch);
1339 return t_true;
1342 /* Follow an SSA edge in an inner loop. It computes the overall
1343 effect of the loop, and following the symbolic initial conditions,
1344 it follows the edges in the parent loop. The inner loop is
1345 considered as a single statement. */
1347 static t_bool
1348 follow_ssa_edge_inner_loop_phi (struct loop *outer_loop,
1349 gimple loop_phi_node,
1350 gimple halting_phi,
1351 tree *evolution_of_loop, int limit)
1353 struct loop *loop = loop_containing_stmt (loop_phi_node);
1354 tree ev = analyze_scalar_evolution (loop, PHI_RESULT (loop_phi_node));
1356 /* Sometimes, the inner loop is too difficult to analyze, and the
1357 result of the analysis is a symbolic parameter. */
1358 if (ev == PHI_RESULT (loop_phi_node))
1360 t_bool res = t_false;
1361 int i, n = gimple_phi_num_args (loop_phi_node);
1363 for (i = 0; i < n; i++)
1365 tree arg = PHI_ARG_DEF (loop_phi_node, i);
1366 basic_block bb;
1368 /* Follow the edges that exit the inner loop. */
1369 bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1370 if (!flow_bb_inside_loop_p (loop, bb))
1371 res = follow_ssa_edge_expr (outer_loop, loop_phi_node,
1372 arg, halting_phi,
1373 evolution_of_loop, limit);
1374 if (res == t_true)
1375 break;
1378 /* If the path crosses this loop-phi, give up. */
1379 if (res == t_true)
1380 *evolution_of_loop = chrec_dont_know;
1382 return res;
1385 /* Otherwise, compute the overall effect of the inner loop. */
1386 ev = compute_overall_effect_of_inner_loop (loop, ev);
1387 return follow_ssa_edge_expr (outer_loop, loop_phi_node, ev, halting_phi,
1388 evolution_of_loop, limit);
1391 /* Follow an SSA edge from a loop-phi-node to itself, constructing a
1392 path that is analyzed on the return walk. */
1394 static t_bool
1395 follow_ssa_edge (struct loop *loop, gimple def, gimple halting_phi,
1396 tree *evolution_of_loop, int limit)
1398 struct loop *def_loop;
1400 if (gimple_nop_p (def))
1401 return t_false;
1403 /* Give up if the path is longer than the MAX that we allow. */
1404 if (limit > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_COMPLEXITY))
1405 return t_dont_know;
1407 def_loop = loop_containing_stmt (def);
1409 switch (gimple_code (def))
1411 case GIMPLE_PHI:
1412 if (!loop_phi_node_p (def))
1413 /* DEF is a condition-phi-node. Follow the branches, and
1414 record their evolutions. Finally, merge the collected
1415 information and set the approximation to the main
1416 variable. */
1417 return follow_ssa_edge_in_condition_phi
1418 (loop, def, halting_phi, evolution_of_loop, limit);
1420 /* When the analyzed phi is the halting_phi, the
1421 depth-first search is over: we have found a path from
1422 the halting_phi to itself in the loop. */
1423 if (def == halting_phi)
1424 return t_true;
1426 /* Otherwise, the evolution of the HALTING_PHI depends
1427 on the evolution of another loop-phi-node, i.e. the
1428 evolution function is a higher degree polynomial. */
1429 if (def_loop == loop)
1430 return t_false;
1432 /* Inner loop. */
1433 if (flow_loop_nested_p (loop, def_loop))
1434 return follow_ssa_edge_inner_loop_phi
1435 (loop, def, halting_phi, evolution_of_loop, limit + 1);
1437 /* Outer loop. */
1438 return t_false;
1440 case GIMPLE_ASSIGN:
1441 return follow_ssa_edge_in_rhs (loop, def, halting_phi,
1442 evolution_of_loop, limit);
1444 default:
1445 /* At this level of abstraction, the program is just a set
1446 of GIMPLE_ASSIGNs and PHI_NODEs. In principle there is no
1447 other node to be handled. */
1448 return t_false;
1454 /* Given a LOOP_PHI_NODE, this function determines the evolution
1455 function from LOOP_PHI_NODE to LOOP_PHI_NODE in the loop. */
1457 static tree
1458 analyze_evolution_in_loop (gimple loop_phi_node,
1459 tree init_cond)
1461 int i, n = gimple_phi_num_args (loop_phi_node);
1462 tree evolution_function = chrec_not_analyzed_yet;
1463 struct loop *loop = loop_containing_stmt (loop_phi_node);
1464 basic_block bb;
1466 if (dump_file && (dump_flags & TDF_SCEV))
1468 fprintf (dump_file, "(analyze_evolution_in_loop \n");
1469 fprintf (dump_file, " (loop_phi_node = ");
1470 print_gimple_stmt (dump_file, loop_phi_node, 0, 0);
1471 fprintf (dump_file, ")\n");
1474 for (i = 0; i < n; i++)
1476 tree arg = PHI_ARG_DEF (loop_phi_node, i);
1477 gimple ssa_chain;
1478 tree ev_fn;
1479 t_bool res;
1481 /* Select the edges that enter the loop body. */
1482 bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1483 if (!flow_bb_inside_loop_p (loop, bb))
1484 continue;
1486 if (TREE_CODE (arg) == SSA_NAME)
1488 bool val = false;
1490 ssa_chain = SSA_NAME_DEF_STMT (arg);
1492 /* Pass in the initial condition to the follow edge function. */
1493 ev_fn = init_cond;
1494 res = follow_ssa_edge (loop, ssa_chain, loop_phi_node, &ev_fn, 0);
1496 /* If ev_fn has no evolution in the inner loop, and the
1497 init_cond is not equal to ev_fn, then we have an
1498 ambiguity between two possible values, as we cannot know
1499 the number of iterations at this point. */
1500 if (TREE_CODE (ev_fn) != POLYNOMIAL_CHREC
1501 && no_evolution_in_loop_p (ev_fn, loop->num, &val) && val
1502 && !operand_equal_p (init_cond, ev_fn, 0))
1503 ev_fn = chrec_dont_know;
1505 else
1506 res = t_false;
1508 /* When it is impossible to go back on the same
1509 loop_phi_node by following the ssa edges, the
1510 evolution is represented by a peeled chrec, i.e. the
1511 first iteration, EV_FN has the value INIT_COND, then
1512 all the other iterations it has the value of ARG.
1513 For the moment, PEELED_CHREC nodes are not built. */
1514 if (res != t_true)
1515 ev_fn = chrec_dont_know;
1517 /* When there are multiple back edges of the loop (which in fact never
1518 happens currently, but nevertheless), merge their evolutions. */
1519 evolution_function = chrec_merge (evolution_function, ev_fn);
1522 if (dump_file && (dump_flags & TDF_SCEV))
1524 fprintf (dump_file, " (evolution_function = ");
1525 print_generic_expr (dump_file, evolution_function, 0);
1526 fprintf (dump_file, "))\n");
1529 return evolution_function;
1532 /* Given a loop-phi-node, return the initial conditions of the
1533 variable on entry of the loop. When the CCP has propagated
1534 constants into the loop-phi-node, the initial condition is
1535 instantiated, otherwise the initial condition is kept symbolic.
1536 This analyzer does not analyze the evolution outside the current
1537 loop, and leaves this task to the on-demand tree reconstructor. */
1539 static tree
1540 analyze_initial_condition (gimple loop_phi_node)
1542 int i, n;
1543 tree init_cond = chrec_not_analyzed_yet;
1544 struct loop *loop = loop_containing_stmt (loop_phi_node);
1546 if (dump_file && (dump_flags & TDF_SCEV))
1548 fprintf (dump_file, "(analyze_initial_condition \n");
1549 fprintf (dump_file, " (loop_phi_node = \n");
1550 print_gimple_stmt (dump_file, loop_phi_node, 0, 0);
1551 fprintf (dump_file, ")\n");
1554 n = gimple_phi_num_args (loop_phi_node);
1555 for (i = 0; i < n; i++)
1557 tree branch = PHI_ARG_DEF (loop_phi_node, i);
1558 basic_block bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1560 /* When the branch is oriented to the loop's body, it does
1561 not contribute to the initial condition. */
1562 if (flow_bb_inside_loop_p (loop, bb))
1563 continue;
1565 if (init_cond == chrec_not_analyzed_yet)
1567 init_cond = branch;
1568 continue;
1571 if (TREE_CODE (branch) == SSA_NAME)
1573 init_cond = chrec_dont_know;
1574 break;
1577 init_cond = chrec_merge (init_cond, branch);
1580 /* Ooops -- a loop without an entry??? */
1581 if (init_cond == chrec_not_analyzed_yet)
1582 init_cond = chrec_dont_know;
1584 /* During early loop unrolling we do not have fully constant propagated IL.
1585 Handle degenerate PHIs here to not miss important unrollings. */
1586 if (TREE_CODE (init_cond) == SSA_NAME)
1588 gimple def = SSA_NAME_DEF_STMT (init_cond);
1589 tree res;
1590 if (gimple_code (def) == GIMPLE_PHI
1591 && (res = degenerate_phi_result (def)) != NULL_TREE
1592 /* Only allow invariants here, otherwise we may break
1593 loop-closed SSA form. */
1594 && is_gimple_min_invariant (res))
1595 init_cond = res;
1598 if (dump_file && (dump_flags & TDF_SCEV))
1600 fprintf (dump_file, " (init_cond = ");
1601 print_generic_expr (dump_file, init_cond, 0);
1602 fprintf (dump_file, "))\n");
1605 return init_cond;
1608 /* Analyze the scalar evolution for LOOP_PHI_NODE. */
1610 static tree
1611 interpret_loop_phi (struct loop *loop, gimple loop_phi_node)
1613 tree res;
1614 struct loop *phi_loop = loop_containing_stmt (loop_phi_node);
1615 tree init_cond;
1617 if (phi_loop != loop)
1619 struct loop *subloop;
1620 tree evolution_fn = analyze_scalar_evolution
1621 (phi_loop, PHI_RESULT (loop_phi_node));
1623 /* Dive one level deeper. */
1624 subloop = superloop_at_depth (phi_loop, loop_depth (loop) + 1);
1626 /* Interpret the subloop. */
1627 res = compute_overall_effect_of_inner_loop (subloop, evolution_fn);
1628 return res;
1631 /* Otherwise really interpret the loop phi. */
1632 init_cond = analyze_initial_condition (loop_phi_node);
1633 res = analyze_evolution_in_loop (loop_phi_node, init_cond);
1635 /* Verify we maintained the correct initial condition throughout
1636 possible conversions in the SSA chain. */
1637 if (res != chrec_dont_know)
1639 tree new_init = res;
1640 if (CONVERT_EXPR_P (res)
1641 && TREE_CODE (TREE_OPERAND (res, 0)) == POLYNOMIAL_CHREC)
1642 new_init = fold_convert (TREE_TYPE (res),
1643 CHREC_LEFT (TREE_OPERAND (res, 0)));
1644 else if (TREE_CODE (res) == POLYNOMIAL_CHREC)
1645 new_init = CHREC_LEFT (res);
1646 STRIP_USELESS_TYPE_CONVERSION (new_init);
1647 if (TREE_CODE (new_init) == POLYNOMIAL_CHREC
1648 || !operand_equal_p (init_cond, new_init, 0))
1649 return chrec_dont_know;
1652 return res;
1655 /* This function merges the branches of a condition-phi-node,
1656 contained in the outermost loop, and whose arguments are already
1657 analyzed. */
1659 static tree
1660 interpret_condition_phi (struct loop *loop, gimple condition_phi)
1662 int i, n = gimple_phi_num_args (condition_phi);
1663 tree res = chrec_not_analyzed_yet;
1665 for (i = 0; i < n; i++)
1667 tree branch_chrec;
1669 if (backedge_phi_arg_p (condition_phi, i))
1671 res = chrec_dont_know;
1672 break;
1675 branch_chrec = analyze_scalar_evolution
1676 (loop, PHI_ARG_DEF (condition_phi, i));
1678 res = chrec_merge (res, branch_chrec);
1681 return res;
1684 /* Interpret the operation RHS1 OP RHS2. If we didn't
1685 analyze this node before, follow the definitions until ending
1686 either on an analyzed GIMPLE_ASSIGN, or on a loop-phi-node. On the
1687 return path, this function propagates evolutions (ala constant copy
1688 propagation). OPND1 is not a GIMPLE expression because we could
1689 analyze the effect of an inner loop: see interpret_loop_phi. */
1691 static tree
1692 interpret_rhs_expr (struct loop *loop, gimple at_stmt,
1693 tree type, tree rhs1, enum tree_code code, tree rhs2)
1695 tree res, chrec1, chrec2;
1697 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1699 if (is_gimple_min_invariant (rhs1))
1700 return chrec_convert (type, rhs1, at_stmt);
1702 if (code == SSA_NAME)
1703 return chrec_convert (type, analyze_scalar_evolution (loop, rhs1),
1704 at_stmt);
1706 if (code == ASSERT_EXPR)
1708 rhs1 = ASSERT_EXPR_VAR (rhs1);
1709 return chrec_convert (type, analyze_scalar_evolution (loop, rhs1),
1710 at_stmt);
1714 switch (code)
1716 case ADDR_EXPR:
1717 if (TREE_CODE (TREE_OPERAND (rhs1, 0)) == MEM_REF
1718 || handled_component_p (TREE_OPERAND (rhs1, 0)))
1720 enum machine_mode mode;
1721 HOST_WIDE_INT bitsize, bitpos;
1722 int unsignedp;
1723 int volatilep = 0;
1724 tree base, offset;
1725 tree chrec3;
1726 tree unitpos;
1728 base = get_inner_reference (TREE_OPERAND (rhs1, 0),
1729 &bitsize, &bitpos, &offset,
1730 &mode, &unsignedp, &volatilep, false);
1732 if (TREE_CODE (base) == MEM_REF)
1734 rhs2 = TREE_OPERAND (base, 1);
1735 rhs1 = TREE_OPERAND (base, 0);
1737 chrec1 = analyze_scalar_evolution (loop, rhs1);
1738 chrec2 = analyze_scalar_evolution (loop, rhs2);
1739 chrec1 = chrec_convert (type, chrec1, at_stmt);
1740 chrec2 = chrec_convert (TREE_TYPE (rhs2), chrec2, at_stmt);
1741 res = chrec_fold_plus (type, chrec1, chrec2);
1743 else
1745 chrec1 = analyze_scalar_evolution_for_address_of (loop, base);
1746 chrec1 = chrec_convert (type, chrec1, at_stmt);
1747 res = chrec1;
1750 if (offset != NULL_TREE)
1752 chrec2 = analyze_scalar_evolution (loop, offset);
1753 chrec2 = chrec_convert (TREE_TYPE (offset), chrec2, at_stmt);
1754 res = chrec_fold_plus (type, res, chrec2);
1757 if (bitpos != 0)
1759 gcc_assert ((bitpos % BITS_PER_UNIT) == 0);
1761 unitpos = size_int_kind (bitpos / BITS_PER_UNIT, SIZETYPE);
1762 chrec3 = analyze_scalar_evolution (loop, unitpos);
1763 chrec3 = chrec_convert (TREE_TYPE (unitpos), chrec3, at_stmt);
1764 res = chrec_fold_plus (type, res, chrec3);
1767 else
1768 res = chrec_dont_know;
1769 break;
1771 case POINTER_PLUS_EXPR:
1772 chrec1 = analyze_scalar_evolution (loop, rhs1);
1773 chrec2 = analyze_scalar_evolution (loop, rhs2);
1774 chrec1 = chrec_convert (type, chrec1, at_stmt);
1775 chrec2 = chrec_convert (TREE_TYPE (rhs2), chrec2, at_stmt);
1776 res = chrec_fold_plus (type, chrec1, chrec2);
1777 break;
1779 case PLUS_EXPR:
1780 chrec1 = analyze_scalar_evolution (loop, rhs1);
1781 chrec2 = analyze_scalar_evolution (loop, rhs2);
1782 chrec1 = chrec_convert (type, chrec1, at_stmt);
1783 chrec2 = chrec_convert (type, chrec2, at_stmt);
1784 res = chrec_fold_plus (type, chrec1, chrec2);
1785 break;
1787 case MINUS_EXPR:
1788 chrec1 = analyze_scalar_evolution (loop, rhs1);
1789 chrec2 = analyze_scalar_evolution (loop, rhs2);
1790 chrec1 = chrec_convert (type, chrec1, at_stmt);
1791 chrec2 = chrec_convert (type, chrec2, at_stmt);
1792 res = chrec_fold_minus (type, chrec1, chrec2);
1793 break;
1795 case NEGATE_EXPR:
1796 chrec1 = analyze_scalar_evolution (loop, rhs1);
1797 chrec1 = chrec_convert (type, chrec1, at_stmt);
1798 /* TYPE may be integer, real or complex, so use fold_convert. */
1799 res = chrec_fold_multiply (type, chrec1,
1800 fold_convert (type, integer_minus_one_node));
1801 break;
1803 case BIT_NOT_EXPR:
1804 /* Handle ~X as -1 - X. */
1805 chrec1 = analyze_scalar_evolution (loop, rhs1);
1806 chrec1 = chrec_convert (type, chrec1, at_stmt);
1807 res = chrec_fold_minus (type,
1808 fold_convert (type, integer_minus_one_node),
1809 chrec1);
1810 break;
1812 case MULT_EXPR:
1813 chrec1 = analyze_scalar_evolution (loop, rhs1);
1814 chrec2 = analyze_scalar_evolution (loop, rhs2);
1815 chrec1 = chrec_convert (type, chrec1, at_stmt);
1816 chrec2 = chrec_convert (type, chrec2, at_stmt);
1817 res = chrec_fold_multiply (type, chrec1, chrec2);
1818 break;
1820 CASE_CONVERT:
1821 chrec1 = analyze_scalar_evolution (loop, rhs1);
1822 res = chrec_convert (type, chrec1, at_stmt);
1823 break;
1825 default:
1826 res = chrec_dont_know;
1827 break;
1830 return res;
1833 /* Interpret the expression EXPR. */
1835 static tree
1836 interpret_expr (struct loop *loop, gimple at_stmt, tree expr)
1838 enum tree_code code;
1839 tree type = TREE_TYPE (expr), op0, op1;
1841 if (automatically_generated_chrec_p (expr))
1842 return expr;
1844 if (TREE_CODE (expr) == POLYNOMIAL_CHREC
1845 || get_gimple_rhs_class (TREE_CODE (expr)) == GIMPLE_TERNARY_RHS)
1846 return chrec_dont_know;
1848 extract_ops_from_tree (expr, &code, &op0, &op1);
1850 return interpret_rhs_expr (loop, at_stmt, type,
1851 op0, code, op1);
1854 /* Interpret the rhs of the assignment STMT. */
1856 static tree
1857 interpret_gimple_assign (struct loop *loop, gimple stmt)
1859 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
1860 enum tree_code code = gimple_assign_rhs_code (stmt);
1862 return interpret_rhs_expr (loop, stmt, type,
1863 gimple_assign_rhs1 (stmt), code,
1864 gimple_assign_rhs2 (stmt));
1869 /* This section contains all the entry points:
1870 - number_of_iterations_in_loop,
1871 - analyze_scalar_evolution,
1872 - instantiate_parameters.
1875 /* Compute and return the evolution function in WRTO_LOOP, the nearest
1876 common ancestor of DEF_LOOP and USE_LOOP. */
1878 static tree
1879 compute_scalar_evolution_in_loop (struct loop *wrto_loop,
1880 struct loop *def_loop,
1881 tree ev)
1883 bool val;
1884 tree res;
1886 if (def_loop == wrto_loop)
1887 return ev;
1889 def_loop = superloop_at_depth (def_loop, loop_depth (wrto_loop) + 1);
1890 res = compute_overall_effect_of_inner_loop (def_loop, ev);
1892 if (no_evolution_in_loop_p (res, wrto_loop->num, &val) && val)
1893 return res;
1895 return analyze_scalar_evolution_1 (wrto_loop, res, chrec_not_analyzed_yet);
1898 /* Helper recursive function. */
1900 static tree
1901 analyze_scalar_evolution_1 (struct loop *loop, tree var, tree res)
1903 tree type = TREE_TYPE (var);
1904 gimple def;
1905 basic_block bb;
1906 struct loop *def_loop;
1908 if (loop == NULL || TREE_CODE (type) == VECTOR_TYPE)
1909 return chrec_dont_know;
1911 if (TREE_CODE (var) != SSA_NAME)
1912 return interpret_expr (loop, NULL, var);
1914 def = SSA_NAME_DEF_STMT (var);
1915 bb = gimple_bb (def);
1916 def_loop = bb ? bb->loop_father : NULL;
1918 if (bb == NULL
1919 || !flow_bb_inside_loop_p (loop, bb))
1921 /* Keep the symbolic form. */
1922 res = var;
1923 goto set_and_end;
1926 if (res != chrec_not_analyzed_yet)
1928 if (loop != bb->loop_father)
1929 res = compute_scalar_evolution_in_loop
1930 (find_common_loop (loop, bb->loop_father), bb->loop_father, res);
1932 goto set_and_end;
1935 if (loop != def_loop)
1937 res = analyze_scalar_evolution_1 (def_loop, var, chrec_not_analyzed_yet);
1938 res = compute_scalar_evolution_in_loop (loop, def_loop, res);
1940 goto set_and_end;
1943 switch (gimple_code (def))
1945 case GIMPLE_ASSIGN:
1946 res = interpret_gimple_assign (loop, def);
1947 break;
1949 case GIMPLE_PHI:
1950 if (loop_phi_node_p (def))
1951 res = interpret_loop_phi (loop, def);
1952 else
1953 res = interpret_condition_phi (loop, def);
1954 break;
1956 default:
1957 res = chrec_dont_know;
1958 break;
1961 set_and_end:
1963 /* Keep the symbolic form. */
1964 if (res == chrec_dont_know)
1965 res = var;
1967 if (loop == def_loop)
1968 set_scalar_evolution (block_before_loop (loop), var, res);
1970 return res;
1973 /* Analyzes and returns the scalar evolution of the ssa_name VAR in
1974 LOOP. LOOP is the loop in which the variable is used.
1976 Example of use: having a pointer VAR to a SSA_NAME node, STMT a
1977 pointer to the statement that uses this variable, in order to
1978 determine the evolution function of the variable, use the following
1979 calls:
1981 loop_p loop = loop_containing_stmt (stmt);
1982 tree chrec_with_symbols = analyze_scalar_evolution (loop, var);
1983 tree chrec_instantiated = instantiate_parameters (loop, chrec_with_symbols);
1986 tree
1987 analyze_scalar_evolution (struct loop *loop, tree var)
1989 tree res;
1991 if (dump_file && (dump_flags & TDF_SCEV))
1993 fprintf (dump_file, "(analyze_scalar_evolution \n");
1994 fprintf (dump_file, " (loop_nb = %d)\n", loop->num);
1995 fprintf (dump_file, " (scalar = ");
1996 print_generic_expr (dump_file, var, 0);
1997 fprintf (dump_file, ")\n");
2000 res = get_scalar_evolution (block_before_loop (loop), var);
2001 res = analyze_scalar_evolution_1 (loop, var, res);
2003 if (dump_file && (dump_flags & TDF_SCEV))
2004 fprintf (dump_file, ")\n");
2006 return res;
2009 /* Analyzes and returns the scalar evolution of VAR address in LOOP. */
2011 static tree
2012 analyze_scalar_evolution_for_address_of (struct loop *loop, tree var)
2014 return analyze_scalar_evolution (loop, build_fold_addr_expr (var));
2017 /* Analyze scalar evolution of use of VERSION in USE_LOOP with respect to
2018 WRTO_LOOP (which should be a superloop of USE_LOOP)
2020 FOLDED_CASTS is set to true if resolve_mixers used
2021 chrec_convert_aggressive (TODO -- not really, we are way too conservative
2022 at the moment in order to keep things simple).
2024 To illustrate the meaning of USE_LOOP and WRTO_LOOP, consider the following
2025 example:
2027 for (i = 0; i < 100; i++) -- loop 1
2029 for (j = 0; j < 100; j++) -- loop 2
2031 k1 = i;
2032 k2 = j;
2034 use2 (k1, k2);
2036 for (t = 0; t < 100; t++) -- loop 3
2037 use3 (k1, k2);
2040 use1 (k1, k2);
2043 Both k1 and k2 are invariants in loop3, thus
2044 analyze_scalar_evolution_in_loop (loop3, loop3, k1) = k1
2045 analyze_scalar_evolution_in_loop (loop3, loop3, k2) = k2
2047 As they are invariant, it does not matter whether we consider their
2048 usage in loop 3 or loop 2, hence
2049 analyze_scalar_evolution_in_loop (loop2, loop3, k1) =
2050 analyze_scalar_evolution_in_loop (loop2, loop2, k1) = i
2051 analyze_scalar_evolution_in_loop (loop2, loop3, k2) =
2052 analyze_scalar_evolution_in_loop (loop2, loop2, k2) = [0,+,1]_2
2054 Similarly for their evolutions with respect to loop 1. The values of K2
2055 in the use in loop 2 vary independently on loop 1, thus we cannot express
2056 the evolution with respect to loop 1:
2057 analyze_scalar_evolution_in_loop (loop1, loop3, k1) =
2058 analyze_scalar_evolution_in_loop (loop1, loop2, k1) = [0,+,1]_1
2059 analyze_scalar_evolution_in_loop (loop1, loop3, k2) =
2060 analyze_scalar_evolution_in_loop (loop1, loop2, k2) = dont_know
2062 The value of k2 in the use in loop 1 is known, though:
2063 analyze_scalar_evolution_in_loop (loop1, loop1, k1) = [0,+,1]_1
2064 analyze_scalar_evolution_in_loop (loop1, loop1, k2) = 100
2067 static tree
2068 analyze_scalar_evolution_in_loop (struct loop *wrto_loop, struct loop *use_loop,
2069 tree version, bool *folded_casts)
2071 bool val = false;
2072 tree ev = version, tmp;
2074 /* We cannot just do
2076 tmp = analyze_scalar_evolution (use_loop, version);
2077 ev = resolve_mixers (wrto_loop, tmp);
2079 as resolve_mixers would query the scalar evolution with respect to
2080 wrto_loop. For example, in the situation described in the function
2081 comment, suppose that wrto_loop = loop1, use_loop = loop3 and
2082 version = k2. Then
2084 analyze_scalar_evolution (use_loop, version) = k2
2086 and resolve_mixers (loop1, k2) finds that the value of k2 in loop 1
2087 is 100, which is a wrong result, since we are interested in the
2088 value in loop 3.
2090 Instead, we need to proceed from use_loop to wrto_loop loop by loop,
2091 each time checking that there is no evolution in the inner loop. */
2093 if (folded_casts)
2094 *folded_casts = false;
2095 while (1)
2097 tmp = analyze_scalar_evolution (use_loop, ev);
2098 ev = resolve_mixers (use_loop, tmp);
2100 if (folded_casts && tmp != ev)
2101 *folded_casts = true;
2103 if (use_loop == wrto_loop)
2104 return ev;
2106 /* If the value of the use changes in the inner loop, we cannot express
2107 its value in the outer loop (we might try to return interval chrec,
2108 but we do not have a user for it anyway) */
2109 if (!no_evolution_in_loop_p (ev, use_loop->num, &val)
2110 || !val)
2111 return chrec_dont_know;
2113 use_loop = loop_outer (use_loop);
2117 /* Returns from CACHE the value for VERSION instantiated below
2118 INSTANTIATED_BELOW block. */
2120 static tree
2121 get_instantiated_value (htab_t cache, basic_block instantiated_below,
2122 tree version)
2124 struct scev_info_str *info, pattern;
2126 pattern.var = version;
2127 pattern.instantiated_below = instantiated_below;
2128 info = (struct scev_info_str *) htab_find (cache, &pattern);
2130 if (info)
2131 return info->chrec;
2132 else
2133 return NULL_TREE;
2136 /* Sets in CACHE the value of VERSION instantiated below basic block
2137 INSTANTIATED_BELOW to VAL. */
2139 static void
2140 set_instantiated_value (htab_t cache, basic_block instantiated_below,
2141 tree version, tree val)
2143 struct scev_info_str *info, pattern;
2144 PTR *slot;
2146 pattern.var = version;
2147 pattern.instantiated_below = instantiated_below;
2148 slot = htab_find_slot (cache, &pattern, INSERT);
2150 if (!*slot)
2151 *slot = new_scev_info_str (instantiated_below, version);
2152 info = (struct scev_info_str *) *slot;
2153 info->chrec = val;
2156 /* Return the closed_loop_phi node for VAR. If there is none, return
2157 NULL_TREE. */
2159 static tree
2160 loop_closed_phi_def (tree var)
2162 struct loop *loop;
2163 edge exit;
2164 gimple phi;
2165 gimple_stmt_iterator psi;
2167 if (var == NULL_TREE
2168 || TREE_CODE (var) != SSA_NAME)
2169 return NULL_TREE;
2171 loop = loop_containing_stmt (SSA_NAME_DEF_STMT (var));
2172 exit = single_exit (loop);
2173 if (!exit)
2174 return NULL_TREE;
2176 for (psi = gsi_start_phis (exit->dest); !gsi_end_p (psi); gsi_next (&psi))
2178 phi = gsi_stmt (psi);
2179 if (PHI_ARG_DEF_FROM_EDGE (phi, exit) == var)
2180 return PHI_RESULT (phi);
2183 return NULL_TREE;
2186 static tree instantiate_scev_r (basic_block, struct loop *, tree, bool,
2187 htab_t, int);
2189 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2190 and EVOLUTION_LOOP, that were left under a symbolic form.
2192 CHREC is an SSA_NAME to be instantiated.
2194 CACHE is the cache of already instantiated values.
2196 FOLD_CONVERSIONS should be set to true when the conversions that
2197 may wrap in signed/pointer type are folded, as long as the value of
2198 the chrec is preserved.
2200 SIZE_EXPR is used for computing the size of the expression to be
2201 instantiated, and to stop if it exceeds some limit. */
2203 static tree
2204 instantiate_scev_name (basic_block instantiate_below,
2205 struct loop *evolution_loop, tree chrec,
2206 bool fold_conversions, htab_t cache, int size_expr)
2208 tree res;
2209 struct loop *def_loop;
2210 basic_block def_bb = gimple_bb (SSA_NAME_DEF_STMT (chrec));
2212 /* A parameter (or loop invariant and we do not want to include
2213 evolutions in outer loops), nothing to do. */
2214 if (!def_bb
2215 || loop_depth (def_bb->loop_father) == 0
2216 || dominated_by_p (CDI_DOMINATORS, instantiate_below, def_bb))
2217 return chrec;
2219 /* We cache the value of instantiated variable to avoid exponential
2220 time complexity due to reevaluations. We also store the convenient
2221 value in the cache in order to prevent infinite recursion -- we do
2222 not want to instantiate the SSA_NAME if it is in a mixer
2223 structure. This is used for avoiding the instantiation of
2224 recursively defined functions, such as:
2226 | a_2 -> {0, +, 1, +, a_2}_1 */
2228 res = get_instantiated_value (cache, instantiate_below, chrec);
2229 if (res)
2230 return res;
2232 res = chrec_dont_know;
2233 set_instantiated_value (cache, instantiate_below, chrec, res);
2235 def_loop = find_common_loop (evolution_loop, def_bb->loop_father);
2237 /* If the analysis yields a parametric chrec, instantiate the
2238 result again. */
2239 res = analyze_scalar_evolution (def_loop, chrec);
2241 /* Don't instantiate default definitions. */
2242 if (TREE_CODE (res) == SSA_NAME
2243 && SSA_NAME_IS_DEFAULT_DEF (res))
2246 /* Don't instantiate loop-closed-ssa phi nodes. */
2247 else if (TREE_CODE (res) == SSA_NAME
2248 && loop_depth (loop_containing_stmt (SSA_NAME_DEF_STMT (res)))
2249 > loop_depth (def_loop))
2251 if (res == chrec)
2252 res = loop_closed_phi_def (chrec);
2253 else
2254 res = chrec;
2256 /* When there is no loop_closed_phi_def, it means that the
2257 variable is not used after the loop: try to still compute the
2258 value of the variable when exiting the loop. */
2259 if (res == NULL_TREE)
2261 loop_p loop = loop_containing_stmt (SSA_NAME_DEF_STMT (chrec));
2262 res = analyze_scalar_evolution (loop, chrec);
2263 res = compute_overall_effect_of_inner_loop (loop, res);
2264 res = instantiate_scev_r (instantiate_below, evolution_loop, res,
2265 fold_conversions, cache, size_expr);
2267 else if (!dominated_by_p (CDI_DOMINATORS, instantiate_below,
2268 gimple_bb (SSA_NAME_DEF_STMT (res))))
2269 res = chrec_dont_know;
2272 else if (res != chrec_dont_know)
2273 res = instantiate_scev_r (instantiate_below, evolution_loop, res,
2274 fold_conversions, cache, size_expr);
2276 /* Store the correct value to the cache. */
2277 set_instantiated_value (cache, instantiate_below, chrec, res);
2278 return res;
2281 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2282 and EVOLUTION_LOOP, that were left under a symbolic form.
2284 CHREC is a polynomial chain of recurrence to be instantiated.
2286 CACHE is the cache of already instantiated values.
2288 FOLD_CONVERSIONS should be set to true when the conversions that
2289 may wrap in signed/pointer type are folded, as long as the value of
2290 the chrec is preserved.
2292 SIZE_EXPR is used for computing the size of the expression to be
2293 instantiated, and to stop if it exceeds some limit. */
2295 static tree
2296 instantiate_scev_poly (basic_block instantiate_below,
2297 struct loop *evolution_loop, tree chrec,
2298 bool fold_conversions, htab_t cache, int size_expr)
2300 tree op1;
2301 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2302 CHREC_LEFT (chrec), fold_conversions, cache,
2303 size_expr);
2304 if (op0 == chrec_dont_know)
2305 return chrec_dont_know;
2307 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2308 CHREC_RIGHT (chrec), fold_conversions, cache,
2309 size_expr);
2310 if (op1 == chrec_dont_know)
2311 return chrec_dont_know;
2313 if (CHREC_LEFT (chrec) != op0
2314 || CHREC_RIGHT (chrec) != op1)
2316 unsigned var = CHREC_VARIABLE (chrec);
2318 /* When the instantiated stride or base has an evolution in an
2319 innermost loop, return chrec_dont_know, as this is not a
2320 valid SCEV representation. In the reduced testcase for
2321 PR40281 we would have {0, +, {1, +, 1}_2}_1 that has no
2322 meaning. */
2323 if ((tree_is_chrec (op0) && CHREC_VARIABLE (op0) > var)
2324 || (tree_is_chrec (op1) && CHREC_VARIABLE (op1) > var))
2325 return chrec_dont_know;
2327 op1 = chrec_convert_rhs (chrec_type (op0), op1, NULL);
2328 chrec = build_polynomial_chrec (var, op0, op1);
2331 return chrec;
2334 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2335 and EVOLUTION_LOOP, that were left under a symbolic form.
2337 "C0 CODE C1" is a binary expression of type TYPE to be instantiated.
2339 CACHE is the cache of already instantiated values.
2341 FOLD_CONVERSIONS should be set to true when the conversions that
2342 may wrap in signed/pointer type are folded, as long as the value of
2343 the chrec is preserved.
2345 SIZE_EXPR is used for computing the size of the expression to be
2346 instantiated, and to stop if it exceeds some limit. */
2348 static tree
2349 instantiate_scev_binary (basic_block instantiate_below,
2350 struct loop *evolution_loop, tree chrec, enum tree_code code,
2351 tree type, tree c0, tree c1,
2352 bool fold_conversions, htab_t cache, int size_expr)
2354 tree op1;
2355 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2356 c0, fold_conversions, cache,
2357 size_expr);
2358 if (op0 == chrec_dont_know)
2359 return chrec_dont_know;
2361 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2362 c1, fold_conversions, cache,
2363 size_expr);
2364 if (op1 == chrec_dont_know)
2365 return chrec_dont_know;
2367 if (c0 != op0
2368 || c1 != op1)
2370 op0 = chrec_convert (type, op0, NULL);
2371 op1 = chrec_convert_rhs (type, op1, NULL);
2373 switch (code)
2375 case POINTER_PLUS_EXPR:
2376 case PLUS_EXPR:
2377 return chrec_fold_plus (type, op0, op1);
2379 case MINUS_EXPR:
2380 return chrec_fold_minus (type, op0, op1);
2382 case MULT_EXPR:
2383 return chrec_fold_multiply (type, op0, op1);
2385 default:
2386 gcc_unreachable ();
2390 return chrec ? chrec : fold_build2 (code, type, c0, c1);
2393 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2394 and EVOLUTION_LOOP, that were left under a symbolic form.
2396 "CHREC" is an array reference to be instantiated.
2398 CACHE is the cache of already instantiated values.
2400 FOLD_CONVERSIONS should be set to true when the conversions that
2401 may wrap in signed/pointer type are folded, as long as the value of
2402 the chrec is preserved.
2404 SIZE_EXPR is used for computing the size of the expression to be
2405 instantiated, and to stop if it exceeds some limit. */
2407 static tree
2408 instantiate_array_ref (basic_block instantiate_below,
2409 struct loop *evolution_loop, tree chrec,
2410 bool fold_conversions, htab_t cache, int size_expr)
2412 tree res;
2413 tree index = TREE_OPERAND (chrec, 1);
2414 tree op1 = instantiate_scev_r (instantiate_below, evolution_loop, index,
2415 fold_conversions, cache, size_expr);
2417 if (op1 == chrec_dont_know)
2418 return chrec_dont_know;
2420 if (chrec && op1 == index)
2421 return chrec;
2423 res = unshare_expr (chrec);
2424 TREE_OPERAND (res, 1) = op1;
2425 return res;
2428 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2429 and EVOLUTION_LOOP, that were left under a symbolic form.
2431 "CHREC" that stands for a convert expression "(TYPE) OP" is to be
2432 instantiated.
2434 CACHE is the cache of already instantiated values.
2436 FOLD_CONVERSIONS should be set to true when the conversions that
2437 may wrap in signed/pointer type are folded, as long as the value of
2438 the chrec is preserved.
2440 SIZE_EXPR is used for computing the size of the expression to be
2441 instantiated, and to stop if it exceeds some limit. */
2443 static tree
2444 instantiate_scev_convert (basic_block instantiate_below,
2445 struct loop *evolution_loop, tree chrec,
2446 tree type, tree op,
2447 bool fold_conversions, htab_t cache, int size_expr)
2449 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop, op,
2450 fold_conversions, cache, size_expr);
2452 if (op0 == chrec_dont_know)
2453 return chrec_dont_know;
2455 if (fold_conversions)
2457 tree tmp = chrec_convert_aggressive (type, op0);
2458 if (tmp)
2459 return tmp;
2462 if (chrec && op0 == op)
2463 return chrec;
2465 /* If we used chrec_convert_aggressive, we can no longer assume that
2466 signed chrecs do not overflow, as chrec_convert does, so avoid
2467 calling it in that case. */
2468 if (fold_conversions)
2469 return fold_convert (type, op0);
2471 return chrec_convert (type, op0, NULL);
2474 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2475 and EVOLUTION_LOOP, that were left under a symbolic form.
2477 CHREC is a BIT_NOT_EXPR or a NEGATE_EXPR expression to be instantiated.
2478 Handle ~X as -1 - X.
2479 Handle -X as -1 * X.
2481 CACHE is the cache of already instantiated values.
2483 FOLD_CONVERSIONS should be set to true when the conversions that
2484 may wrap in signed/pointer type are folded, as long as the value of
2485 the chrec is preserved.
2487 SIZE_EXPR is used for computing the size of the expression to be
2488 instantiated, and to stop if it exceeds some limit. */
2490 static tree
2491 instantiate_scev_not (basic_block instantiate_below,
2492 struct loop *evolution_loop, tree chrec,
2493 enum tree_code code, tree type, tree op,
2494 bool fold_conversions, htab_t cache, int size_expr)
2496 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop, op,
2497 fold_conversions, cache, size_expr);
2499 if (op0 == chrec_dont_know)
2500 return chrec_dont_know;
2502 if (op != op0)
2504 op0 = chrec_convert (type, op0, NULL);
2506 switch (code)
2508 case BIT_NOT_EXPR:
2509 return chrec_fold_minus
2510 (type, fold_convert (type, integer_minus_one_node), op0);
2512 case NEGATE_EXPR:
2513 return chrec_fold_multiply
2514 (type, fold_convert (type, integer_minus_one_node), op0);
2516 default:
2517 gcc_unreachable ();
2521 return chrec ? chrec : fold_build1 (code, type, op0);
2524 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2525 and EVOLUTION_LOOP, that were left under a symbolic form.
2527 CHREC is an expression with 3 operands to be instantiated.
2529 CACHE is the cache of already instantiated values.
2531 FOLD_CONVERSIONS should be set to true when the conversions that
2532 may wrap in signed/pointer type are folded, as long as the value of
2533 the chrec is preserved.
2535 SIZE_EXPR is used for computing the size of the expression to be
2536 instantiated, and to stop if it exceeds some limit. */
2538 static tree
2539 instantiate_scev_3 (basic_block instantiate_below,
2540 struct loop *evolution_loop, tree chrec,
2541 bool fold_conversions, htab_t cache, int size_expr)
2543 tree op1, op2;
2544 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2545 TREE_OPERAND (chrec, 0),
2546 fold_conversions, cache, size_expr);
2547 if (op0 == chrec_dont_know)
2548 return chrec_dont_know;
2550 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2551 TREE_OPERAND (chrec, 1),
2552 fold_conversions, cache, size_expr);
2553 if (op1 == chrec_dont_know)
2554 return chrec_dont_know;
2556 op2 = instantiate_scev_r (instantiate_below, evolution_loop,
2557 TREE_OPERAND (chrec, 2),
2558 fold_conversions, cache, size_expr);
2559 if (op2 == chrec_dont_know)
2560 return chrec_dont_know;
2562 if (op0 == TREE_OPERAND (chrec, 0)
2563 && op1 == TREE_OPERAND (chrec, 1)
2564 && op2 == TREE_OPERAND (chrec, 2))
2565 return chrec;
2567 return fold_build3 (TREE_CODE (chrec),
2568 TREE_TYPE (chrec), op0, op1, op2);
2571 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2572 and EVOLUTION_LOOP, that were left under a symbolic form.
2574 CHREC is an expression with 2 operands to be instantiated.
2576 CACHE is the cache of already instantiated values.
2578 FOLD_CONVERSIONS should be set to true when the conversions that
2579 may wrap in signed/pointer type are folded, as long as the value of
2580 the chrec is preserved.
2582 SIZE_EXPR is used for computing the size of the expression to be
2583 instantiated, and to stop if it exceeds some limit. */
2585 static tree
2586 instantiate_scev_2 (basic_block instantiate_below,
2587 struct loop *evolution_loop, tree chrec,
2588 bool fold_conversions, htab_t cache, int size_expr)
2590 tree op1;
2591 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2592 TREE_OPERAND (chrec, 0),
2593 fold_conversions, cache, size_expr);
2594 if (op0 == chrec_dont_know)
2595 return chrec_dont_know;
2597 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2598 TREE_OPERAND (chrec, 1),
2599 fold_conversions, cache, size_expr);
2600 if (op1 == chrec_dont_know)
2601 return chrec_dont_know;
2603 if (op0 == TREE_OPERAND (chrec, 0)
2604 && op1 == TREE_OPERAND (chrec, 1))
2605 return chrec;
2607 return fold_build2 (TREE_CODE (chrec), TREE_TYPE (chrec), op0, op1);
2610 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2611 and EVOLUTION_LOOP, that were left under a symbolic form.
2613 CHREC is an expression with 2 operands to be instantiated.
2615 CACHE is the cache of already instantiated values.
2617 FOLD_CONVERSIONS should be set to true when the conversions that
2618 may wrap in signed/pointer type are folded, as long as the value of
2619 the chrec is preserved.
2621 SIZE_EXPR is used for computing the size of the expression to be
2622 instantiated, and to stop if it exceeds some limit. */
2624 static tree
2625 instantiate_scev_1 (basic_block instantiate_below,
2626 struct loop *evolution_loop, tree chrec,
2627 bool fold_conversions, htab_t cache, int size_expr)
2629 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2630 TREE_OPERAND (chrec, 0),
2631 fold_conversions, cache, size_expr);
2633 if (op0 == chrec_dont_know)
2634 return chrec_dont_know;
2636 if (op0 == TREE_OPERAND (chrec, 0))
2637 return chrec;
2639 return fold_build1 (TREE_CODE (chrec), TREE_TYPE (chrec), op0);
2642 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2643 and EVOLUTION_LOOP, that were left under a symbolic form.
2645 CHREC is the scalar evolution to instantiate.
2647 CACHE is the cache of already instantiated values.
2649 FOLD_CONVERSIONS should be set to true when the conversions that
2650 may wrap in signed/pointer type are folded, as long as the value of
2651 the chrec is preserved.
2653 SIZE_EXPR is used for computing the size of the expression to be
2654 instantiated, and to stop if it exceeds some limit. */
2656 static tree
2657 instantiate_scev_r (basic_block instantiate_below,
2658 struct loop *evolution_loop, tree chrec,
2659 bool fold_conversions, htab_t cache, int size_expr)
2661 /* Give up if the expression is larger than the MAX that we allow. */
2662 if (size_expr++ > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_SIZE))
2663 return chrec_dont_know;
2665 if (chrec == NULL_TREE
2666 || automatically_generated_chrec_p (chrec)
2667 || is_gimple_min_invariant (chrec))
2668 return chrec;
2670 switch (TREE_CODE (chrec))
2672 case SSA_NAME:
2673 return instantiate_scev_name (instantiate_below, evolution_loop, chrec,
2674 fold_conversions, cache, size_expr);
2676 case POLYNOMIAL_CHREC:
2677 return instantiate_scev_poly (instantiate_below, evolution_loop, chrec,
2678 fold_conversions, cache, size_expr);
2680 case POINTER_PLUS_EXPR:
2681 case PLUS_EXPR:
2682 case MINUS_EXPR:
2683 case MULT_EXPR:
2684 return instantiate_scev_binary (instantiate_below, evolution_loop, chrec,
2685 TREE_CODE (chrec), chrec_type (chrec),
2686 TREE_OPERAND (chrec, 0),
2687 TREE_OPERAND (chrec, 1),
2688 fold_conversions, cache, size_expr);
2690 CASE_CONVERT:
2691 return instantiate_scev_convert (instantiate_below, evolution_loop, chrec,
2692 TREE_TYPE (chrec), TREE_OPERAND (chrec, 0),
2693 fold_conversions, cache, size_expr);
2695 case NEGATE_EXPR:
2696 case BIT_NOT_EXPR:
2697 return instantiate_scev_not (instantiate_below, evolution_loop, chrec,
2698 TREE_CODE (chrec), TREE_TYPE (chrec),
2699 TREE_OPERAND (chrec, 0),
2700 fold_conversions, cache, size_expr);
2702 case ADDR_EXPR:
2703 case SCEV_NOT_KNOWN:
2704 return chrec_dont_know;
2706 case SCEV_KNOWN:
2707 return chrec_known;
2709 case ARRAY_REF:
2710 return instantiate_array_ref (instantiate_below, evolution_loop, chrec,
2711 fold_conversions, cache, size_expr);
2713 default:
2714 break;
2717 if (VL_EXP_CLASS_P (chrec))
2718 return chrec_dont_know;
2720 switch (TREE_CODE_LENGTH (TREE_CODE (chrec)))
2722 case 3:
2723 return instantiate_scev_3 (instantiate_below, evolution_loop, chrec,
2724 fold_conversions, cache, size_expr);
2726 case 2:
2727 return instantiate_scev_2 (instantiate_below, evolution_loop, chrec,
2728 fold_conversions, cache, size_expr);
2730 case 1:
2731 return instantiate_scev_1 (instantiate_below, evolution_loop, chrec,
2732 fold_conversions, cache, size_expr);
2734 case 0:
2735 return chrec;
2737 default:
2738 break;
2741 /* Too complicated to handle. */
2742 return chrec_dont_know;
2745 /* Analyze all the parameters of the chrec that were left under a
2746 symbolic form. INSTANTIATE_BELOW is the basic block that stops the
2747 recursive instantiation of parameters: a parameter is a variable
2748 that is defined in a basic block that dominates INSTANTIATE_BELOW or
2749 a function parameter. */
2751 tree
2752 instantiate_scev (basic_block instantiate_below, struct loop *evolution_loop,
2753 tree chrec)
2755 tree res;
2756 htab_t cache = htab_create (10, hash_scev_info, eq_scev_info, del_scev_info);
2758 if (dump_file && (dump_flags & TDF_SCEV))
2760 fprintf (dump_file, "(instantiate_scev \n");
2761 fprintf (dump_file, " (instantiate_below = %d)\n", instantiate_below->index);
2762 fprintf (dump_file, " (evolution_loop = %d)\n", evolution_loop->num);
2763 fprintf (dump_file, " (chrec = ");
2764 print_generic_expr (dump_file, chrec, 0);
2765 fprintf (dump_file, ")\n");
2768 res = instantiate_scev_r (instantiate_below, evolution_loop, chrec, false,
2769 cache, 0);
2771 if (dump_file && (dump_flags & TDF_SCEV))
2773 fprintf (dump_file, " (res = ");
2774 print_generic_expr (dump_file, res, 0);
2775 fprintf (dump_file, "))\n");
2778 htab_delete (cache);
2780 return res;
2783 /* Similar to instantiate_parameters, but does not introduce the
2784 evolutions in outer loops for LOOP invariants in CHREC, and does not
2785 care about causing overflows, as long as they do not affect value
2786 of an expression. */
2788 tree
2789 resolve_mixers (struct loop *loop, tree chrec)
2791 htab_t cache = htab_create (10, hash_scev_info, eq_scev_info, del_scev_info);
2792 tree ret = instantiate_scev_r (block_before_loop (loop), loop, chrec, true,
2793 cache, 0);
2794 htab_delete (cache);
2795 return ret;
2798 /* Entry point for the analysis of the number of iterations pass.
2799 This function tries to safely approximate the number of iterations
2800 the loop will run. When this property is not decidable at compile
2801 time, the result is chrec_dont_know. Otherwise the result is a
2802 scalar or a symbolic parameter. When the number of iterations may
2803 be equal to zero and the property cannot be determined at compile
2804 time, the result is a COND_EXPR that represents in a symbolic form
2805 the conditions under which the number of iterations is not zero.
2807 Example of analysis: suppose that the loop has an exit condition:
2809 "if (b > 49) goto end_loop;"
2811 and that in a previous analysis we have determined that the
2812 variable 'b' has an evolution function:
2814 "EF = {23, +, 5}_2".
2816 When we evaluate the function at the point 5, i.e. the value of the
2817 variable 'b' after 5 iterations in the loop, we have EF (5) = 48,
2818 and EF (6) = 53. In this case the value of 'b' on exit is '53' and
2819 the loop body has been executed 6 times. */
2821 tree
2822 number_of_latch_executions (struct loop *loop)
2824 edge exit;
2825 struct tree_niter_desc niter_desc;
2826 tree may_be_zero;
2827 tree res;
2829 /* Determine whether the number of iterations in loop has already
2830 been computed. */
2831 res = loop->nb_iterations;
2832 if (res)
2833 return res;
2835 may_be_zero = NULL_TREE;
2837 if (dump_file && (dump_flags & TDF_SCEV))
2838 fprintf (dump_file, "(number_of_iterations_in_loop = \n");
2840 res = chrec_dont_know;
2841 exit = single_exit (loop);
2843 if (exit && number_of_iterations_exit (loop, exit, &niter_desc, false))
2845 may_be_zero = niter_desc.may_be_zero;
2846 res = niter_desc.niter;
2849 if (res == chrec_dont_know
2850 || !may_be_zero
2851 || integer_zerop (may_be_zero))
2853 else if (integer_nonzerop (may_be_zero))
2854 res = build_int_cst (TREE_TYPE (res), 0);
2856 else if (COMPARISON_CLASS_P (may_be_zero))
2857 res = fold_build3 (COND_EXPR, TREE_TYPE (res), may_be_zero,
2858 build_int_cst (TREE_TYPE (res), 0), res);
2859 else
2860 res = chrec_dont_know;
2862 if (dump_file && (dump_flags & TDF_SCEV))
2864 fprintf (dump_file, " (set_nb_iterations_in_loop = ");
2865 print_generic_expr (dump_file, res, 0);
2866 fprintf (dump_file, "))\n");
2869 loop->nb_iterations = res;
2870 return res;
2873 /* Returns the number of executions of the exit condition of LOOP,
2874 i.e., the number by one higher than number_of_latch_executions.
2875 Note that unlike number_of_latch_executions, this number does
2876 not necessarily fit in the unsigned variant of the type of
2877 the control variable -- if the number of iterations is a constant,
2878 we return chrec_dont_know if adding one to number_of_latch_executions
2879 overflows; however, in case the number of iterations is symbolic
2880 expression, the caller is responsible for dealing with this
2881 the possible overflow. */
2883 tree
2884 number_of_exit_cond_executions (struct loop *loop)
2886 tree ret = number_of_latch_executions (loop);
2887 tree type = chrec_type (ret);
2889 if (chrec_contains_undetermined (ret))
2890 return ret;
2892 ret = chrec_fold_plus (type, ret, build_int_cst (type, 1));
2893 if (TREE_CODE (ret) == INTEGER_CST
2894 && TREE_OVERFLOW (ret))
2895 return chrec_dont_know;
2897 return ret;
2900 /* One of the drivers for testing the scalar evolutions analysis.
2901 This function computes the number of iterations for all the loops
2902 from the EXIT_CONDITIONS array. */
2904 static void
2905 number_of_iterations_for_all_loops (VEC(gimple,heap) **exit_conditions)
2907 unsigned int i;
2908 unsigned nb_chrec_dont_know_loops = 0;
2909 unsigned nb_static_loops = 0;
2910 gimple cond;
2912 FOR_EACH_VEC_ELT (gimple, *exit_conditions, i, cond)
2914 tree res = number_of_latch_executions (loop_containing_stmt (cond));
2915 if (chrec_contains_undetermined (res))
2916 nb_chrec_dont_know_loops++;
2917 else
2918 nb_static_loops++;
2921 if (dump_file)
2923 fprintf (dump_file, "\n(\n");
2924 fprintf (dump_file, "-----------------------------------------\n");
2925 fprintf (dump_file, "%d\tnb_chrec_dont_know_loops\n", nb_chrec_dont_know_loops);
2926 fprintf (dump_file, "%d\tnb_static_loops\n", nb_static_loops);
2927 fprintf (dump_file, "%d\tnb_total_loops\n", number_of_loops ());
2928 fprintf (dump_file, "-----------------------------------------\n");
2929 fprintf (dump_file, ")\n\n");
2931 print_loops (dump_file, 3);
2937 /* Counters for the stats. */
2939 struct chrec_stats
2941 unsigned nb_chrecs;
2942 unsigned nb_affine;
2943 unsigned nb_affine_multivar;
2944 unsigned nb_higher_poly;
2945 unsigned nb_chrec_dont_know;
2946 unsigned nb_undetermined;
2949 /* Reset the counters. */
2951 static inline void
2952 reset_chrecs_counters (struct chrec_stats *stats)
2954 stats->nb_chrecs = 0;
2955 stats->nb_affine = 0;
2956 stats->nb_affine_multivar = 0;
2957 stats->nb_higher_poly = 0;
2958 stats->nb_chrec_dont_know = 0;
2959 stats->nb_undetermined = 0;
2962 /* Dump the contents of a CHREC_STATS structure. */
2964 static void
2965 dump_chrecs_stats (FILE *file, struct chrec_stats *stats)
2967 fprintf (file, "\n(\n");
2968 fprintf (file, "-----------------------------------------\n");
2969 fprintf (file, "%d\taffine univariate chrecs\n", stats->nb_affine);
2970 fprintf (file, "%d\taffine multivariate chrecs\n", stats->nb_affine_multivar);
2971 fprintf (file, "%d\tdegree greater than 2 polynomials\n",
2972 stats->nb_higher_poly);
2973 fprintf (file, "%d\tchrec_dont_know chrecs\n", stats->nb_chrec_dont_know);
2974 fprintf (file, "-----------------------------------------\n");
2975 fprintf (file, "%d\ttotal chrecs\n", stats->nb_chrecs);
2976 fprintf (file, "%d\twith undetermined coefficients\n",
2977 stats->nb_undetermined);
2978 fprintf (file, "-----------------------------------------\n");
2979 fprintf (file, "%d\tchrecs in the scev database\n",
2980 (int) htab_elements (scalar_evolution_info));
2981 fprintf (file, "%d\tsets in the scev database\n", nb_set_scev);
2982 fprintf (file, "%d\tgets in the scev database\n", nb_get_scev);
2983 fprintf (file, "-----------------------------------------\n");
2984 fprintf (file, ")\n\n");
2987 /* Gather statistics about CHREC. */
2989 static void
2990 gather_chrec_stats (tree chrec, struct chrec_stats *stats)
2992 if (dump_file && (dump_flags & TDF_STATS))
2994 fprintf (dump_file, "(classify_chrec ");
2995 print_generic_expr (dump_file, chrec, 0);
2996 fprintf (dump_file, "\n");
2999 stats->nb_chrecs++;
3001 if (chrec == NULL_TREE)
3003 stats->nb_undetermined++;
3004 return;
3007 switch (TREE_CODE (chrec))
3009 case POLYNOMIAL_CHREC:
3010 if (evolution_function_is_affine_p (chrec))
3012 if (dump_file && (dump_flags & TDF_STATS))
3013 fprintf (dump_file, " affine_univariate\n");
3014 stats->nb_affine++;
3016 else if (evolution_function_is_affine_multivariate_p (chrec, 0))
3018 if (dump_file && (dump_flags & TDF_STATS))
3019 fprintf (dump_file, " affine_multivariate\n");
3020 stats->nb_affine_multivar++;
3022 else
3024 if (dump_file && (dump_flags & TDF_STATS))
3025 fprintf (dump_file, " higher_degree_polynomial\n");
3026 stats->nb_higher_poly++;
3029 break;
3031 default:
3032 break;
3035 if (chrec_contains_undetermined (chrec))
3037 if (dump_file && (dump_flags & TDF_STATS))
3038 fprintf (dump_file, " undetermined\n");
3039 stats->nb_undetermined++;
3042 if (dump_file && (dump_flags & TDF_STATS))
3043 fprintf (dump_file, ")\n");
3046 /* One of the drivers for testing the scalar evolutions analysis.
3047 This function analyzes the scalar evolution of all the scalars
3048 defined as loop phi nodes in one of the loops from the
3049 EXIT_CONDITIONS array.
3051 TODO Optimization: A loop is in canonical form if it contains only
3052 a single scalar loop phi node. All the other scalars that have an
3053 evolution in the loop are rewritten in function of this single
3054 index. This allows the parallelization of the loop. */
3056 static void
3057 analyze_scalar_evolution_for_all_loop_phi_nodes (VEC(gimple,heap) **exit_conditions)
3059 unsigned int i;
3060 struct chrec_stats stats;
3061 gimple cond, phi;
3062 gimple_stmt_iterator psi;
3064 reset_chrecs_counters (&stats);
3066 FOR_EACH_VEC_ELT (gimple, *exit_conditions, i, cond)
3068 struct loop *loop;
3069 basic_block bb;
3070 tree chrec;
3072 loop = loop_containing_stmt (cond);
3073 bb = loop->header;
3075 for (psi = gsi_start_phis (bb); !gsi_end_p (psi); gsi_next (&psi))
3077 phi = gsi_stmt (psi);
3078 if (is_gimple_reg (PHI_RESULT (phi)))
3080 chrec = instantiate_parameters
3081 (loop,
3082 analyze_scalar_evolution (loop, PHI_RESULT (phi)));
3084 if (dump_file && (dump_flags & TDF_STATS))
3085 gather_chrec_stats (chrec, &stats);
3090 if (dump_file && (dump_flags & TDF_STATS))
3091 dump_chrecs_stats (dump_file, &stats);
3094 /* Callback for htab_traverse, gathers information on chrecs in the
3095 hashtable. */
3097 static int
3098 gather_stats_on_scev_database_1 (void **slot, void *stats)
3100 struct scev_info_str *entry = (struct scev_info_str *) *slot;
3102 gather_chrec_stats (entry->chrec, (struct chrec_stats *) stats);
3104 return 1;
3107 /* Classify the chrecs of the whole database. */
3109 void
3110 gather_stats_on_scev_database (void)
3112 struct chrec_stats stats;
3114 if (!dump_file)
3115 return;
3117 reset_chrecs_counters (&stats);
3119 htab_traverse (scalar_evolution_info, gather_stats_on_scev_database_1,
3120 &stats);
3122 dump_chrecs_stats (dump_file, &stats);
3127 /* Initializer. */
3129 static void
3130 initialize_scalar_evolutions_analyzer (void)
3132 /* The elements below are unique. */
3133 if (chrec_dont_know == NULL_TREE)
3135 chrec_not_analyzed_yet = NULL_TREE;
3136 chrec_dont_know = make_node (SCEV_NOT_KNOWN);
3137 chrec_known = make_node (SCEV_KNOWN);
3138 TREE_TYPE (chrec_dont_know) = void_type_node;
3139 TREE_TYPE (chrec_known) = void_type_node;
3143 /* Initialize the analysis of scalar evolutions for LOOPS. */
3145 void
3146 scev_initialize (void)
3148 loop_iterator li;
3149 struct loop *loop;
3152 scalar_evolution_info = htab_create_ggc (100, hash_scev_info, eq_scev_info,
3153 del_scev_info);
3155 initialize_scalar_evolutions_analyzer ();
3157 FOR_EACH_LOOP (li, loop, 0)
3159 loop->nb_iterations = NULL_TREE;
3163 /* Cleans up the information cached by the scalar evolutions analysis
3164 in the hash table. */
3166 void
3167 scev_reset_htab (void)
3169 if (!scalar_evolution_info)
3170 return;
3172 htab_empty (scalar_evolution_info);
3175 /* Cleans up the information cached by the scalar evolutions analysis
3176 in the hash table and in the loop->nb_iterations. */
3178 void
3179 scev_reset (void)
3181 loop_iterator li;
3182 struct loop *loop;
3184 scev_reset_htab ();
3186 if (!current_loops)
3187 return;
3189 FOR_EACH_LOOP (li, loop, 0)
3191 loop->nb_iterations = NULL_TREE;
3195 /* Checks whether use of OP in USE_LOOP behaves as a simple affine iv with
3196 respect to WRTO_LOOP and returns its base and step in IV if possible
3197 (see analyze_scalar_evolution_in_loop for more details on USE_LOOP
3198 and WRTO_LOOP). If ALLOW_NONCONSTANT_STEP is true, we want step to be
3199 invariant in LOOP. Otherwise we require it to be an integer constant.
3201 IV->no_overflow is set to true if we are sure the iv cannot overflow (e.g.
3202 because it is computed in signed arithmetics). Consequently, adding an
3203 induction variable
3205 for (i = IV->base; ; i += IV->step)
3207 is only safe if IV->no_overflow is false, or TYPE_OVERFLOW_UNDEFINED is
3208 false for the type of the induction variable, or you can prove that i does
3209 not wrap by some other argument. Otherwise, this might introduce undefined
3210 behavior, and
3212 for (i = iv->base; ; i = (type) ((unsigned type) i + (unsigned type) iv->step))
3214 must be used instead. */
3216 bool
3217 simple_iv (struct loop *wrto_loop, struct loop *use_loop, tree op,
3218 affine_iv *iv, bool allow_nonconstant_step)
3220 tree type, ev;
3221 bool folded_casts;
3223 iv->base = NULL_TREE;
3224 iv->step = NULL_TREE;
3225 iv->no_overflow = false;
3227 type = TREE_TYPE (op);
3228 if (!POINTER_TYPE_P (type)
3229 && !INTEGRAL_TYPE_P (type))
3230 return false;
3232 ev = analyze_scalar_evolution_in_loop (wrto_loop, use_loop, op,
3233 &folded_casts);
3234 if (chrec_contains_undetermined (ev)
3235 || chrec_contains_symbols_defined_in_loop (ev, wrto_loop->num))
3236 return false;
3238 if (tree_does_not_contain_chrecs (ev))
3240 iv->base = ev;
3241 iv->step = build_int_cst (TREE_TYPE (ev), 0);
3242 iv->no_overflow = true;
3243 return true;
3246 if (TREE_CODE (ev) != POLYNOMIAL_CHREC
3247 || CHREC_VARIABLE (ev) != (unsigned) wrto_loop->num)
3248 return false;
3250 iv->step = CHREC_RIGHT (ev);
3251 if ((!allow_nonconstant_step && TREE_CODE (iv->step) != INTEGER_CST)
3252 || tree_contains_chrecs (iv->step, NULL))
3253 return false;
3255 iv->base = CHREC_LEFT (ev);
3256 if (tree_contains_chrecs (iv->base, NULL))
3257 return false;
3259 iv->no_overflow = !folded_casts && TYPE_OVERFLOW_UNDEFINED (type);
3261 return true;
3264 /* Runs the analysis of scalar evolutions. */
3266 void
3267 scev_analysis (void)
3269 VEC(gimple,heap) *exit_conditions;
3271 exit_conditions = VEC_alloc (gimple, heap, 37);
3272 select_loops_exit_conditions (&exit_conditions);
3274 if (dump_file && (dump_flags & TDF_STATS))
3275 analyze_scalar_evolution_for_all_loop_phi_nodes (&exit_conditions);
3277 number_of_iterations_for_all_loops (&exit_conditions);
3278 VEC_free (gimple, heap, exit_conditions);
3281 /* Finalize the scalar evolution analysis. */
3283 void
3284 scev_finalize (void)
3286 if (!scalar_evolution_info)
3287 return;
3288 htab_delete (scalar_evolution_info);
3289 scalar_evolution_info = NULL;
3292 /* Returns true if the expression EXPR is considered to be too expensive
3293 for scev_const_prop. */
3295 bool
3296 expression_expensive_p (tree expr)
3298 enum tree_code code;
3300 if (is_gimple_val (expr))
3301 return false;
3303 code = TREE_CODE (expr);
3304 if (code == TRUNC_DIV_EXPR
3305 || code == CEIL_DIV_EXPR
3306 || code == FLOOR_DIV_EXPR
3307 || code == ROUND_DIV_EXPR
3308 || code == TRUNC_MOD_EXPR
3309 || code == CEIL_MOD_EXPR
3310 || code == FLOOR_MOD_EXPR
3311 || code == ROUND_MOD_EXPR
3312 || code == EXACT_DIV_EXPR)
3314 /* Division by power of two is usually cheap, so we allow it.
3315 Forbid anything else. */
3316 if (!integer_pow2p (TREE_OPERAND (expr, 1)))
3317 return true;
3320 switch (TREE_CODE_CLASS (code))
3322 case tcc_binary:
3323 case tcc_comparison:
3324 if (expression_expensive_p (TREE_OPERAND (expr, 1)))
3325 return true;
3327 /* Fallthru. */
3328 case tcc_unary:
3329 return expression_expensive_p (TREE_OPERAND (expr, 0));
3331 default:
3332 return true;
3336 /* Replace ssa names for that scev can prove they are constant by the
3337 appropriate constants. Also perform final value replacement in loops,
3338 in case the replacement expressions are cheap.
3340 We only consider SSA names defined by phi nodes; rest is left to the
3341 ordinary constant propagation pass. */
3343 unsigned int
3344 scev_const_prop (void)
3346 basic_block bb;
3347 tree name, type, ev;
3348 gimple phi, ass;
3349 struct loop *loop, *ex_loop;
3350 bitmap ssa_names_to_remove = NULL;
3351 unsigned i;
3352 loop_iterator li;
3353 gimple_stmt_iterator psi;
3355 if (number_of_loops () <= 1)
3356 return 0;
3358 FOR_EACH_BB (bb)
3360 loop = bb->loop_father;
3362 for (psi = gsi_start_phis (bb); !gsi_end_p (psi); gsi_next (&psi))
3364 phi = gsi_stmt (psi);
3365 name = PHI_RESULT (phi);
3367 if (!is_gimple_reg (name))
3368 continue;
3370 type = TREE_TYPE (name);
3372 if (!POINTER_TYPE_P (type)
3373 && !INTEGRAL_TYPE_P (type))
3374 continue;
3376 ev = resolve_mixers (loop, analyze_scalar_evolution (loop, name));
3377 if (!is_gimple_min_invariant (ev)
3378 || !may_propagate_copy (name, ev))
3379 continue;
3381 /* Replace the uses of the name. */
3382 if (name != ev)
3383 replace_uses_by (name, ev);
3385 if (!ssa_names_to_remove)
3386 ssa_names_to_remove = BITMAP_ALLOC (NULL);
3387 bitmap_set_bit (ssa_names_to_remove, SSA_NAME_VERSION (name));
3391 /* Remove the ssa names that were replaced by constants. We do not
3392 remove them directly in the previous cycle, since this
3393 invalidates scev cache. */
3394 if (ssa_names_to_remove)
3396 bitmap_iterator bi;
3398 EXECUTE_IF_SET_IN_BITMAP (ssa_names_to_remove, 0, i, bi)
3400 gimple_stmt_iterator psi;
3401 name = ssa_name (i);
3402 phi = SSA_NAME_DEF_STMT (name);
3404 gcc_assert (gimple_code (phi) == GIMPLE_PHI);
3405 psi = gsi_for_stmt (phi);
3406 remove_phi_node (&psi, true);
3409 BITMAP_FREE (ssa_names_to_remove);
3410 scev_reset ();
3413 /* Now the regular final value replacement. */
3414 FOR_EACH_LOOP (li, loop, LI_FROM_INNERMOST)
3416 edge exit;
3417 tree def, rslt, niter;
3418 gimple_stmt_iterator bsi;
3420 /* If we do not know exact number of iterations of the loop, we cannot
3421 replace the final value. */
3422 exit = single_exit (loop);
3423 if (!exit)
3424 continue;
3426 niter = number_of_latch_executions (loop);
3427 if (niter == chrec_dont_know)
3428 continue;
3430 /* Ensure that it is possible to insert new statements somewhere. */
3431 if (!single_pred_p (exit->dest))
3432 split_loop_exit_edge (exit);
3433 bsi = gsi_after_labels (exit->dest);
3435 ex_loop = superloop_at_depth (loop,
3436 loop_depth (exit->dest->loop_father) + 1);
3438 for (psi = gsi_start_phis (exit->dest); !gsi_end_p (psi); )
3440 phi = gsi_stmt (psi);
3441 rslt = PHI_RESULT (phi);
3442 def = PHI_ARG_DEF_FROM_EDGE (phi, exit);
3443 if (!is_gimple_reg (def))
3445 gsi_next (&psi);
3446 continue;
3449 if (!POINTER_TYPE_P (TREE_TYPE (def))
3450 && !INTEGRAL_TYPE_P (TREE_TYPE (def)))
3452 gsi_next (&psi);
3453 continue;
3456 def = analyze_scalar_evolution_in_loop (ex_loop, loop, def, NULL);
3457 def = compute_overall_effect_of_inner_loop (ex_loop, def);
3458 if (!tree_does_not_contain_chrecs (def)
3459 || chrec_contains_symbols_defined_in_loop (def, ex_loop->num)
3460 /* Moving the computation from the loop may prolong life range
3461 of some ssa names, which may cause problems if they appear
3462 on abnormal edges. */
3463 || contains_abnormal_ssa_name_p (def)
3464 /* Do not emit expensive expressions. The rationale is that
3465 when someone writes a code like
3467 while (n > 45) n -= 45;
3469 he probably knows that n is not large, and does not want it
3470 to be turned into n %= 45. */
3471 || expression_expensive_p (def))
3473 gsi_next (&psi);
3474 continue;
3477 /* Eliminate the PHI node and replace it by a computation outside
3478 the loop. */
3479 def = unshare_expr (def);
3480 remove_phi_node (&psi, false);
3482 def = force_gimple_operand_gsi (&bsi, def, false, NULL_TREE,
3483 true, GSI_SAME_STMT);
3484 ass = gimple_build_assign (rslt, def);
3485 gsi_insert_before (&bsi, ass, GSI_SAME_STMT);
3488 return 0;
3491 #include "gt-tree-scalar-evolution.h"