Fix bootstrap/PR63632
[official-gcc.git] / gcc / tree-scalar-evolution.c
blob248bb8db069150c13f160a6d193ad74cdabd4e2d
1 /* Scalar evolution detector.
2 Copyright (C) 2003-2014 Free Software Foundation, Inc.
3 Contributed by Sebastian Pop <s.pop@laposte.net>
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
22 Description:
24 This pass analyzes the evolution of scalar variables in loop
25 structures. The algorithm is based on the SSA representation,
26 and on the loop hierarchy tree. This algorithm is not based on
27 the notion of versions of a variable, as it was the case for the
28 previous implementations of the scalar evolution algorithm, but
29 it assumes that each defined name is unique.
31 The notation used in this file is called "chains of recurrences",
32 and has been proposed by Eugene Zima, Robert Van Engelen, and
33 others for describing induction variables in programs. For example
34 "b -> {0, +, 2}_1" means that the scalar variable "b" is equal to 0
35 when entering in the loop_1 and has a step 2 in this loop, in other
36 words "for (b = 0; b < N; b+=2);". Note that the coefficients of
37 this chain of recurrence (or chrec [shrek]) can contain the name of
38 other variables, in which case they are called parametric chrecs.
39 For example, "b -> {a, +, 2}_1" means that the initial value of "b"
40 is the value of "a". In most of the cases these parametric chrecs
41 are fully instantiated before their use because symbolic names can
42 hide some difficult cases such as self-references described later
43 (see the Fibonacci example).
45 A short sketch of the algorithm is:
47 Given a scalar variable to be analyzed, follow the SSA edge to
48 its definition:
50 - When the definition is a GIMPLE_ASSIGN: if the right hand side
51 (RHS) of the definition cannot be statically analyzed, the answer
52 of the analyzer is: "don't know".
53 Otherwise, for all the variables that are not yet analyzed in the
54 RHS, try to determine their evolution, and finally try to
55 evaluate the operation of the RHS that gives the evolution
56 function of the analyzed variable.
58 - When the definition is a condition-phi-node: determine the
59 evolution function for all the branches of the phi node, and
60 finally merge these evolutions (see chrec_merge).
62 - When the definition is a loop-phi-node: determine its initial
63 condition, that is the SSA edge defined in an outer loop, and
64 keep it symbolic. Then determine the SSA edges that are defined
65 in the body of the loop. Follow the inner edges until ending on
66 another loop-phi-node of the same analyzed loop. If the reached
67 loop-phi-node is not the starting loop-phi-node, then we keep
68 this definition under a symbolic form. If the reached
69 loop-phi-node is the same as the starting one, then we compute a
70 symbolic stride on the return path. The result is then the
71 symbolic chrec {initial_condition, +, symbolic_stride}_loop.
73 Examples:
75 Example 1: Illustration of the basic algorithm.
77 | a = 3
78 | loop_1
79 | b = phi (a, c)
80 | c = b + 1
81 | if (c > 10) exit_loop
82 | endloop
84 Suppose that we want to know the number of iterations of the
85 loop_1. The exit_loop is controlled by a COND_EXPR (c > 10). We
86 ask the scalar evolution analyzer two questions: what's the
87 scalar evolution (scev) of "c", and what's the scev of "10". For
88 "10" the answer is "10" since it is a scalar constant. For the
89 scalar variable "c", it follows the SSA edge to its definition,
90 "c = b + 1", and then asks again what's the scev of "b".
91 Following the SSA edge, we end on a loop-phi-node "b = phi (a,
92 c)", where the initial condition is "a", and the inner loop edge
93 is "c". The initial condition is kept under a symbolic form (it
94 may be the case that the copy constant propagation has done its
95 work and we end with the constant "3" as one of the edges of the
96 loop-phi-node). The update edge is followed to the end of the
97 loop, and until reaching again the starting loop-phi-node: b -> c
98 -> b. At this point we have drawn a path from "b" to "b" from
99 which we compute the stride in the loop: in this example it is
100 "+1". The resulting scev for "b" is "b -> {a, +, 1}_1". Now
101 that the scev for "b" is known, it is possible to compute the
102 scev for "c", that is "c -> {a + 1, +, 1}_1". In order to
103 determine the number of iterations in the loop_1, we have to
104 instantiate_parameters (loop_1, {a + 1, +, 1}_1), that gives after some
105 more analysis the scev {4, +, 1}_1, or in other words, this is
106 the function "f (x) = x + 4", where x is the iteration count of
107 the loop_1. Now we have to solve the inequality "x + 4 > 10",
108 and take the smallest iteration number for which the loop is
109 exited: x = 7. This loop runs from x = 0 to x = 7, and in total
110 there are 8 iterations. In terms of loop normalization, we have
111 created a variable that is implicitly defined, "x" or just "_1",
112 and all the other analyzed scalars of the loop are defined in
113 function of this variable:
115 a -> 3
116 b -> {3, +, 1}_1
117 c -> {4, +, 1}_1
119 or in terms of a C program:
121 | a = 3
122 | for (x = 0; x <= 7; x++)
124 | b = x + 3
125 | c = x + 4
128 Example 2a: Illustration of the algorithm on nested loops.
130 | loop_1
131 | a = phi (1, b)
132 | c = a + 2
133 | loop_2 10 times
134 | b = phi (c, d)
135 | d = b + 3
136 | endloop
137 | endloop
139 For analyzing the scalar evolution of "a", the algorithm follows
140 the SSA edge into the loop's body: "a -> b". "b" is an inner
141 loop-phi-node, and its analysis as in Example 1, gives:
143 b -> {c, +, 3}_2
144 d -> {c + 3, +, 3}_2
146 Following the SSA edge for the initial condition, we end on "c = a
147 + 2", and then on the starting loop-phi-node "a". From this point,
148 the loop stride is computed: back on "c = a + 2" we get a "+2" in
149 the loop_1, then on the loop-phi-node "b" we compute the overall
150 effect of the inner loop that is "b = c + 30", and we get a "+30"
151 in the loop_1. That means that the overall stride in loop_1 is
152 equal to "+32", and the result is:
154 a -> {1, +, 32}_1
155 c -> {3, +, 32}_1
157 Example 2b: Multivariate chains of recurrences.
159 | loop_1
160 | k = phi (0, k + 1)
161 | loop_2 4 times
162 | j = phi (0, j + 1)
163 | loop_3 4 times
164 | i = phi (0, i + 1)
165 | A[j + k] = ...
166 | endloop
167 | endloop
168 | endloop
170 Analyzing the access function of array A with
171 instantiate_parameters (loop_1, "j + k"), we obtain the
172 instantiation and the analysis of the scalar variables "j" and "k"
173 in loop_1. This leads to the scalar evolution {4, +, 1}_1: the end
174 value of loop_2 for "j" is 4, and the evolution of "k" in loop_1 is
175 {0, +, 1}_1. To obtain the evolution function in loop_3 and
176 instantiate the scalar variables up to loop_1, one has to use:
177 instantiate_scev (block_before_loop (loop_1), loop_3, "j + k").
178 The result of this call is {{0, +, 1}_1, +, 1}_2.
180 Example 3: Higher degree polynomials.
182 | loop_1
183 | a = phi (2, b)
184 | c = phi (5, d)
185 | b = a + 1
186 | d = c + a
187 | endloop
189 a -> {2, +, 1}_1
190 b -> {3, +, 1}_1
191 c -> {5, +, a}_1
192 d -> {5 + a, +, a}_1
194 instantiate_parameters (loop_1, {5, +, a}_1) -> {5, +, 2, +, 1}_1
195 instantiate_parameters (loop_1, {5 + a, +, a}_1) -> {7, +, 3, +, 1}_1
197 Example 4: Lucas, Fibonacci, or mixers in general.
199 | loop_1
200 | a = phi (1, b)
201 | c = phi (3, d)
202 | b = c
203 | d = c + a
204 | endloop
206 a -> (1, c)_1
207 c -> {3, +, a}_1
209 The syntax "(1, c)_1" stands for a PEELED_CHREC that has the
210 following semantics: during the first iteration of the loop_1, the
211 variable contains the value 1, and then it contains the value "c".
212 Note that this syntax is close to the syntax of the loop-phi-node:
213 "a -> (1, c)_1" vs. "a = phi (1, c)".
215 The symbolic chrec representation contains all the semantics of the
216 original code. What is more difficult is to use this information.
218 Example 5: Flip-flops, or exchangers.
220 | loop_1
221 | a = phi (1, b)
222 | c = phi (3, d)
223 | b = c
224 | d = a
225 | endloop
227 a -> (1, c)_1
228 c -> (3, a)_1
230 Based on these symbolic chrecs, it is possible to refine this
231 information into the more precise PERIODIC_CHRECs:
233 a -> |1, 3|_1
234 c -> |3, 1|_1
236 This transformation is not yet implemented.
238 Further readings:
240 You can find a more detailed description of the algorithm in:
241 http://icps.u-strasbg.fr/~pop/DEA_03_Pop.pdf
242 http://icps.u-strasbg.fr/~pop/DEA_03_Pop.ps.gz. But note that
243 this is a preliminary report and some of the details of the
244 algorithm have changed. I'm working on a research report that
245 updates the description of the algorithms to reflect the design
246 choices used in this implementation.
248 A set of slides show a high level overview of the algorithm and run
249 an example through the scalar evolution analyzer:
250 http://cri.ensmp.fr/~pop/gcc/mar04/slides.pdf
252 The slides that I have presented at the GCC Summit'04 are available
253 at: http://cri.ensmp.fr/~pop/gcc/20040604/gccsummit-lno-spop.pdf
256 #include "config.h"
257 #include "system.h"
258 #include "coretypes.h"
259 #include "tree.h"
260 #include "expr.h"
261 #include "gimple-pretty-print.h"
262 #include "basic-block.h"
263 #include "tree-ssa-alias.h"
264 #include "internal-fn.h"
265 #include "gimple-expr.h"
266 #include "is-a.h"
267 #include "gimple.h"
268 #include "gimplify.h"
269 #include "gimple-iterator.h"
270 #include "gimplify-me.h"
271 #include "gimple-ssa.h"
272 #include "tree-cfg.h"
273 #include "tree-phinodes.h"
274 #include "stringpool.h"
275 #include "tree-ssanames.h"
276 #include "tree-ssa-loop-ivopts.h"
277 #include "tree-ssa-loop-manip.h"
278 #include "tree-ssa-loop-niter.h"
279 #include "tree-ssa-loop.h"
280 #include "tree-ssa.h"
281 #include "cfgloop.h"
282 #include "tree-chrec.h"
283 #include "tree-affine.h"
284 #include "tree-scalar-evolution.h"
285 #include "dumpfile.h"
286 #include "params.h"
287 #include "tree-ssa-propagate.h"
288 #include "gimple-fold.h"
289 #include "gimplify-me.h"
291 static tree analyze_scalar_evolution_1 (struct loop *, tree, tree);
292 static tree analyze_scalar_evolution_for_address_of (struct loop *loop,
293 tree var);
295 /* The cached information about an SSA name with version NAME_VERSION,
296 claiming that below basic block with index INSTANTIATED_BELOW, the
297 value of the SSA name can be expressed as CHREC. */
299 struct GTY(()) scev_info_str {
300 unsigned int name_version;
301 int instantiated_below;
302 tree chrec;
305 /* Counters for the scev database. */
306 static unsigned nb_set_scev = 0;
307 static unsigned nb_get_scev = 0;
309 /* The following trees are unique elements. Thus the comparison of
310 another element to these elements should be done on the pointer to
311 these trees, and not on their value. */
313 /* The SSA_NAMEs that are not yet analyzed are qualified with NULL_TREE. */
314 tree chrec_not_analyzed_yet;
316 /* Reserved to the cases where the analyzer has detected an
317 undecidable property at compile time. */
318 tree chrec_dont_know;
320 /* When the analyzer has detected that a property will never
321 happen, then it qualifies it with chrec_known. */
322 tree chrec_known;
324 static GTY ((param_is (struct scev_info_str))) htab_t scalar_evolution_info;
327 /* Constructs a new SCEV_INFO_STR structure for VAR and INSTANTIATED_BELOW. */
329 static inline struct scev_info_str *
330 new_scev_info_str (basic_block instantiated_below, tree var)
332 struct scev_info_str *res;
334 res = ggc_alloc<scev_info_str> ();
335 res->name_version = SSA_NAME_VERSION (var);
336 res->chrec = chrec_not_analyzed_yet;
337 res->instantiated_below = instantiated_below->index;
339 return res;
342 /* Computes a hash function for database element ELT. */
344 static inline hashval_t
345 hash_scev_info (const void *elt_)
347 const struct scev_info_str *elt = (const struct scev_info_str *) elt_;
348 return elt->name_version ^ elt->instantiated_below;
351 /* Compares database elements E1 and E2. */
353 static inline int
354 eq_scev_info (const void *e1, const void *e2)
356 const struct scev_info_str *elt1 = (const struct scev_info_str *) e1;
357 const struct scev_info_str *elt2 = (const struct scev_info_str *) e2;
359 return (elt1->name_version == elt2->name_version
360 && elt1->instantiated_below == elt2->instantiated_below);
363 /* Deletes database element E. */
365 static void
366 del_scev_info (void *e)
368 ggc_free (e);
372 /* Get the scalar evolution of VAR for INSTANTIATED_BELOW basic block.
373 A first query on VAR returns chrec_not_analyzed_yet. */
375 static tree *
376 find_var_scev_info (basic_block instantiated_below, tree var)
378 struct scev_info_str *res;
379 struct scev_info_str tmp;
380 PTR *slot;
382 tmp.name_version = SSA_NAME_VERSION (var);
383 tmp.instantiated_below = instantiated_below->index;
384 slot = htab_find_slot (scalar_evolution_info, &tmp, INSERT);
386 if (!*slot)
387 *slot = new_scev_info_str (instantiated_below, var);
388 res = (struct scev_info_str *) *slot;
390 return &res->chrec;
393 /* Return true when CHREC contains symbolic names defined in
394 LOOP_NB. */
396 bool
397 chrec_contains_symbols_defined_in_loop (const_tree chrec, unsigned loop_nb)
399 int i, n;
401 if (chrec == NULL_TREE)
402 return false;
404 if (is_gimple_min_invariant (chrec))
405 return false;
407 if (TREE_CODE (chrec) == SSA_NAME)
409 gimple def;
410 loop_p def_loop, loop;
412 if (SSA_NAME_IS_DEFAULT_DEF (chrec))
413 return false;
415 def = SSA_NAME_DEF_STMT (chrec);
416 def_loop = loop_containing_stmt (def);
417 loop = get_loop (cfun, loop_nb);
419 if (def_loop == NULL)
420 return false;
422 if (loop == def_loop || flow_loop_nested_p (loop, def_loop))
423 return true;
425 return false;
428 n = TREE_OPERAND_LENGTH (chrec);
429 for (i = 0; i < n; i++)
430 if (chrec_contains_symbols_defined_in_loop (TREE_OPERAND (chrec, i),
431 loop_nb))
432 return true;
433 return false;
436 /* Return true when PHI is a loop-phi-node. */
438 static bool
439 loop_phi_node_p (gimple phi)
441 /* The implementation of this function is based on the following
442 property: "all the loop-phi-nodes of a loop are contained in the
443 loop's header basic block". */
445 return loop_containing_stmt (phi)->header == gimple_bb (phi);
448 /* Compute the scalar evolution for EVOLUTION_FN after crossing LOOP.
449 In general, in the case of multivariate evolutions we want to get
450 the evolution in different loops. LOOP specifies the level for
451 which to get the evolution.
453 Example:
455 | for (j = 0; j < 100; j++)
457 | for (k = 0; k < 100; k++)
459 | i = k + j; - Here the value of i is a function of j, k.
461 | ... = i - Here the value of i is a function of j.
463 | ... = i - Here the value of i is a scalar.
465 Example:
467 | i_0 = ...
468 | loop_1 10 times
469 | i_1 = phi (i_0, i_2)
470 | i_2 = i_1 + 2
471 | endloop
473 This loop has the same effect as:
474 LOOP_1 has the same effect as:
476 | i_1 = i_0 + 20
478 The overall effect of the loop, "i_0 + 20" in the previous example,
479 is obtained by passing in the parameters: LOOP = 1,
480 EVOLUTION_FN = {i_0, +, 2}_1.
483 tree
484 compute_overall_effect_of_inner_loop (struct loop *loop, tree evolution_fn)
486 bool val = false;
488 if (evolution_fn == chrec_dont_know)
489 return chrec_dont_know;
491 else if (TREE_CODE (evolution_fn) == POLYNOMIAL_CHREC)
493 struct loop *inner_loop = get_chrec_loop (evolution_fn);
495 if (inner_loop == loop
496 || flow_loop_nested_p (loop, inner_loop))
498 tree nb_iter = number_of_latch_executions (inner_loop);
500 if (nb_iter == chrec_dont_know)
501 return chrec_dont_know;
502 else
504 tree res;
506 /* evolution_fn is the evolution function in LOOP. Get
507 its value in the nb_iter-th iteration. */
508 res = chrec_apply (inner_loop->num, evolution_fn, nb_iter);
510 if (chrec_contains_symbols_defined_in_loop (res, loop->num))
511 res = instantiate_parameters (loop, res);
513 /* Continue the computation until ending on a parent of LOOP. */
514 return compute_overall_effect_of_inner_loop (loop, res);
517 else
518 return evolution_fn;
521 /* If the evolution function is an invariant, there is nothing to do. */
522 else if (no_evolution_in_loop_p (evolution_fn, loop->num, &val) && val)
523 return evolution_fn;
525 else
526 return chrec_dont_know;
529 /* Associate CHREC to SCALAR. */
531 static void
532 set_scalar_evolution (basic_block instantiated_below, tree scalar, tree chrec)
534 tree *scalar_info;
536 if (TREE_CODE (scalar) != SSA_NAME)
537 return;
539 scalar_info = find_var_scev_info (instantiated_below, scalar);
541 if (dump_file)
543 if (dump_flags & TDF_SCEV)
545 fprintf (dump_file, "(set_scalar_evolution \n");
546 fprintf (dump_file, " instantiated_below = %d \n",
547 instantiated_below->index);
548 fprintf (dump_file, " (scalar = ");
549 print_generic_expr (dump_file, scalar, 0);
550 fprintf (dump_file, ")\n (scalar_evolution = ");
551 print_generic_expr (dump_file, chrec, 0);
552 fprintf (dump_file, "))\n");
554 if (dump_flags & TDF_STATS)
555 nb_set_scev++;
558 *scalar_info = chrec;
561 /* Retrieve the chrec associated to SCALAR instantiated below
562 INSTANTIATED_BELOW block. */
564 static tree
565 get_scalar_evolution (basic_block instantiated_below, tree scalar)
567 tree res;
569 if (dump_file)
571 if (dump_flags & TDF_SCEV)
573 fprintf (dump_file, "(get_scalar_evolution \n");
574 fprintf (dump_file, " (scalar = ");
575 print_generic_expr (dump_file, scalar, 0);
576 fprintf (dump_file, ")\n");
578 if (dump_flags & TDF_STATS)
579 nb_get_scev++;
582 switch (TREE_CODE (scalar))
584 case SSA_NAME:
585 res = *find_var_scev_info (instantiated_below, scalar);
586 break;
588 case REAL_CST:
589 case FIXED_CST:
590 case INTEGER_CST:
591 res = scalar;
592 break;
594 default:
595 res = chrec_not_analyzed_yet;
596 break;
599 if (dump_file && (dump_flags & TDF_SCEV))
601 fprintf (dump_file, " (scalar_evolution = ");
602 print_generic_expr (dump_file, res, 0);
603 fprintf (dump_file, "))\n");
606 return res;
609 /* Helper function for add_to_evolution. Returns the evolution
610 function for an assignment of the form "a = b + c", where "a" and
611 "b" are on the strongly connected component. CHREC_BEFORE is the
612 information that we already have collected up to this point.
613 TO_ADD is the evolution of "c".
615 When CHREC_BEFORE has an evolution part in LOOP_NB, add to this
616 evolution the expression TO_ADD, otherwise construct an evolution
617 part for this loop. */
619 static tree
620 add_to_evolution_1 (unsigned loop_nb, tree chrec_before, tree to_add,
621 gimple at_stmt)
623 tree type, left, right;
624 struct loop *loop = get_loop (cfun, loop_nb), *chloop;
626 switch (TREE_CODE (chrec_before))
628 case POLYNOMIAL_CHREC:
629 chloop = get_chrec_loop (chrec_before);
630 if (chloop == loop
631 || flow_loop_nested_p (chloop, loop))
633 unsigned var;
635 type = chrec_type (chrec_before);
637 /* When there is no evolution part in this loop, build it. */
638 if (chloop != loop)
640 var = loop_nb;
641 left = chrec_before;
642 right = SCALAR_FLOAT_TYPE_P (type)
643 ? build_real (type, dconst0)
644 : build_int_cst (type, 0);
646 else
648 var = CHREC_VARIABLE (chrec_before);
649 left = CHREC_LEFT (chrec_before);
650 right = CHREC_RIGHT (chrec_before);
653 to_add = chrec_convert (type, to_add, at_stmt);
654 right = chrec_convert_rhs (type, right, at_stmt);
655 right = chrec_fold_plus (chrec_type (right), right, to_add);
656 return build_polynomial_chrec (var, left, right);
658 else
660 gcc_assert (flow_loop_nested_p (loop, chloop));
662 /* Search the evolution in LOOP_NB. */
663 left = add_to_evolution_1 (loop_nb, CHREC_LEFT (chrec_before),
664 to_add, at_stmt);
665 right = CHREC_RIGHT (chrec_before);
666 right = chrec_convert_rhs (chrec_type (left), right, at_stmt);
667 return build_polynomial_chrec (CHREC_VARIABLE (chrec_before),
668 left, right);
671 default:
672 /* These nodes do not depend on a loop. */
673 if (chrec_before == chrec_dont_know)
674 return chrec_dont_know;
676 left = chrec_before;
677 right = chrec_convert_rhs (chrec_type (left), to_add, at_stmt);
678 return build_polynomial_chrec (loop_nb, left, right);
682 /* Add TO_ADD to the evolution part of CHREC_BEFORE in the dimension
683 of LOOP_NB.
685 Description (provided for completeness, for those who read code in
686 a plane, and for my poor 62 bytes brain that would have forgotten
687 all this in the next two or three months):
689 The algorithm of translation of programs from the SSA representation
690 into the chrecs syntax is based on a pattern matching. After having
691 reconstructed the overall tree expression for a loop, there are only
692 two cases that can arise:
694 1. a = loop-phi (init, a + expr)
695 2. a = loop-phi (init, expr)
697 where EXPR is either a scalar constant with respect to the analyzed
698 loop (this is a degree 0 polynomial), or an expression containing
699 other loop-phi definitions (these are higher degree polynomials).
701 Examples:
704 | init = ...
705 | loop_1
706 | a = phi (init, a + 5)
707 | endloop
710 | inita = ...
711 | initb = ...
712 | loop_1
713 | a = phi (inita, 2 * b + 3)
714 | b = phi (initb, b + 1)
715 | endloop
717 For the first case, the semantics of the SSA representation is:
719 | a (x) = init + \sum_{j = 0}^{x - 1} expr (j)
721 that is, there is a loop index "x" that determines the scalar value
722 of the variable during the loop execution. During the first
723 iteration, the value is that of the initial condition INIT, while
724 during the subsequent iterations, it is the sum of the initial
725 condition with the sum of all the values of EXPR from the initial
726 iteration to the before last considered iteration.
728 For the second case, the semantics of the SSA program is:
730 | a (x) = init, if x = 0;
731 | expr (x - 1), otherwise.
733 The second case corresponds to the PEELED_CHREC, whose syntax is
734 close to the syntax of a loop-phi-node:
736 | phi (init, expr) vs. (init, expr)_x
738 The proof of the translation algorithm for the first case is a
739 proof by structural induction based on the degree of EXPR.
741 Degree 0:
742 When EXPR is a constant with respect to the analyzed loop, or in
743 other words when EXPR is a polynomial of degree 0, the evolution of
744 the variable A in the loop is an affine function with an initial
745 condition INIT, and a step EXPR. In order to show this, we start
746 from the semantics of the SSA representation:
748 f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
750 and since "expr (j)" is a constant with respect to "j",
752 f (x) = init + x * expr
754 Finally, based on the semantics of the pure sum chrecs, by
755 identification we get the corresponding chrecs syntax:
757 f (x) = init * \binom{x}{0} + expr * \binom{x}{1}
758 f (x) -> {init, +, expr}_x
760 Higher degree:
761 Suppose that EXPR is a polynomial of degree N with respect to the
762 analyzed loop_x for which we have already determined that it is
763 written under the chrecs syntax:
765 | expr (x) -> {b_0, +, b_1, +, ..., +, b_{n-1}} (x)
767 We start from the semantics of the SSA program:
769 | f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
771 | f (x) = init + \sum_{j = 0}^{x - 1}
772 | (b_0 * \binom{j}{0} + ... + b_{n-1} * \binom{j}{n-1})
774 | f (x) = init + \sum_{j = 0}^{x - 1}
775 | \sum_{k = 0}^{n - 1} (b_k * \binom{j}{k})
777 | f (x) = init + \sum_{k = 0}^{n - 1}
778 | (b_k * \sum_{j = 0}^{x - 1} \binom{j}{k})
780 | f (x) = init + \sum_{k = 0}^{n - 1}
781 | (b_k * \binom{x}{k + 1})
783 | f (x) = init + b_0 * \binom{x}{1} + ...
784 | + b_{n-1} * \binom{x}{n}
786 | f (x) = init * \binom{x}{0} + b_0 * \binom{x}{1} + ...
787 | + b_{n-1} * \binom{x}{n}
790 And finally from the definition of the chrecs syntax, we identify:
791 | f (x) -> {init, +, b_0, +, ..., +, b_{n-1}}_x
793 This shows the mechanism that stands behind the add_to_evolution
794 function. An important point is that the use of symbolic
795 parameters avoids the need of an analysis schedule.
797 Example:
799 | inita = ...
800 | initb = ...
801 | loop_1
802 | a = phi (inita, a + 2 + b)
803 | b = phi (initb, b + 1)
804 | endloop
806 When analyzing "a", the algorithm keeps "b" symbolically:
808 | a -> {inita, +, 2 + b}_1
810 Then, after instantiation, the analyzer ends on the evolution:
812 | a -> {inita, +, 2 + initb, +, 1}_1
816 static tree
817 add_to_evolution (unsigned loop_nb, tree chrec_before, enum tree_code code,
818 tree to_add, gimple at_stmt)
820 tree type = chrec_type (to_add);
821 tree res = NULL_TREE;
823 if (to_add == NULL_TREE)
824 return chrec_before;
826 /* TO_ADD is either a scalar, or a parameter. TO_ADD is not
827 instantiated at this point. */
828 if (TREE_CODE (to_add) == POLYNOMIAL_CHREC)
829 /* This should not happen. */
830 return chrec_dont_know;
832 if (dump_file && (dump_flags & TDF_SCEV))
834 fprintf (dump_file, "(add_to_evolution \n");
835 fprintf (dump_file, " (loop_nb = %d)\n", loop_nb);
836 fprintf (dump_file, " (chrec_before = ");
837 print_generic_expr (dump_file, chrec_before, 0);
838 fprintf (dump_file, ")\n (to_add = ");
839 print_generic_expr (dump_file, to_add, 0);
840 fprintf (dump_file, ")\n");
843 if (code == MINUS_EXPR)
844 to_add = chrec_fold_multiply (type, to_add, SCALAR_FLOAT_TYPE_P (type)
845 ? build_real (type, dconstm1)
846 : build_int_cst_type (type, -1));
848 res = add_to_evolution_1 (loop_nb, chrec_before, to_add, at_stmt);
850 if (dump_file && (dump_flags & TDF_SCEV))
852 fprintf (dump_file, " (res = ");
853 print_generic_expr (dump_file, res, 0);
854 fprintf (dump_file, "))\n");
857 return res;
862 /* This section selects the loops that will be good candidates for the
863 scalar evolution analysis. For the moment, greedily select all the
864 loop nests we could analyze. */
866 /* For a loop with a single exit edge, return the COND_EXPR that
867 guards the exit edge. If the expression is too difficult to
868 analyze, then give up. */
870 gimple
871 get_loop_exit_condition (const struct loop *loop)
873 gimple res = NULL;
874 edge exit_edge = single_exit (loop);
876 if (dump_file && (dump_flags & TDF_SCEV))
877 fprintf (dump_file, "(get_loop_exit_condition \n ");
879 if (exit_edge)
881 gimple stmt;
883 stmt = last_stmt (exit_edge->src);
884 if (gimple_code (stmt) == GIMPLE_COND)
885 res = stmt;
888 if (dump_file && (dump_flags & TDF_SCEV))
890 print_gimple_stmt (dump_file, res, 0, 0);
891 fprintf (dump_file, ")\n");
894 return res;
898 /* Depth first search algorithm. */
900 typedef enum t_bool {
901 t_false,
902 t_true,
903 t_dont_know
904 } t_bool;
907 static t_bool follow_ssa_edge (struct loop *loop, gimple, gimple, tree *, int);
909 /* Follow the ssa edge into the binary expression RHS0 CODE RHS1.
910 Return true if the strongly connected component has been found. */
912 static t_bool
913 follow_ssa_edge_binary (struct loop *loop, gimple at_stmt,
914 tree type, tree rhs0, enum tree_code code, tree rhs1,
915 gimple halting_phi, tree *evolution_of_loop, int limit)
917 t_bool res = t_false;
918 tree evol;
920 switch (code)
922 case POINTER_PLUS_EXPR:
923 case PLUS_EXPR:
924 if (TREE_CODE (rhs0) == SSA_NAME)
926 if (TREE_CODE (rhs1) == SSA_NAME)
928 /* Match an assignment under the form:
929 "a = b + c". */
931 /* We want only assignments of form "name + name" contribute to
932 LIMIT, as the other cases do not necessarily contribute to
933 the complexity of the expression. */
934 limit++;
936 evol = *evolution_of_loop;
937 res = follow_ssa_edge
938 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi, &evol, limit);
940 if (res == t_true)
941 *evolution_of_loop = add_to_evolution
942 (loop->num,
943 chrec_convert (type, evol, at_stmt),
944 code, rhs1, at_stmt);
946 else if (res == t_false)
948 res = follow_ssa_edge
949 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
950 evolution_of_loop, limit);
952 if (res == t_true)
953 *evolution_of_loop = add_to_evolution
954 (loop->num,
955 chrec_convert (type, *evolution_of_loop, at_stmt),
956 code, rhs0, at_stmt);
958 else if (res == t_dont_know)
959 *evolution_of_loop = chrec_dont_know;
962 else if (res == t_dont_know)
963 *evolution_of_loop = chrec_dont_know;
966 else
968 /* Match an assignment under the form:
969 "a = b + ...". */
970 res = follow_ssa_edge
971 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
972 evolution_of_loop, limit);
973 if (res == t_true)
974 *evolution_of_loop = add_to_evolution
975 (loop->num, chrec_convert (type, *evolution_of_loop,
976 at_stmt),
977 code, rhs1, at_stmt);
979 else if (res == t_dont_know)
980 *evolution_of_loop = chrec_dont_know;
984 else if (TREE_CODE (rhs1) == SSA_NAME)
986 /* Match an assignment under the form:
987 "a = ... + c". */
988 res = follow_ssa_edge
989 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
990 evolution_of_loop, limit);
991 if (res == t_true)
992 *evolution_of_loop = add_to_evolution
993 (loop->num, chrec_convert (type, *evolution_of_loop,
994 at_stmt),
995 code, rhs0, at_stmt);
997 else if (res == t_dont_know)
998 *evolution_of_loop = chrec_dont_know;
1001 else
1002 /* Otherwise, match an assignment under the form:
1003 "a = ... + ...". */
1004 /* And there is nothing to do. */
1005 res = t_false;
1006 break;
1008 case MINUS_EXPR:
1009 /* This case is under the form "opnd0 = rhs0 - rhs1". */
1010 if (TREE_CODE (rhs0) == SSA_NAME)
1012 /* Match an assignment under the form:
1013 "a = b - ...". */
1015 /* We want only assignments of form "name - name" contribute to
1016 LIMIT, as the other cases do not necessarily contribute to
1017 the complexity of the expression. */
1018 if (TREE_CODE (rhs1) == SSA_NAME)
1019 limit++;
1021 res = follow_ssa_edge (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
1022 evolution_of_loop, limit);
1023 if (res == t_true)
1024 *evolution_of_loop = add_to_evolution
1025 (loop->num, chrec_convert (type, *evolution_of_loop, at_stmt),
1026 MINUS_EXPR, rhs1, at_stmt);
1028 else if (res == t_dont_know)
1029 *evolution_of_loop = chrec_dont_know;
1031 else
1032 /* Otherwise, match an assignment under the form:
1033 "a = ... - ...". */
1034 /* And there is nothing to do. */
1035 res = t_false;
1036 break;
1038 default:
1039 res = t_false;
1042 return res;
1045 /* Follow the ssa edge into the expression EXPR.
1046 Return true if the strongly connected component has been found. */
1048 static t_bool
1049 follow_ssa_edge_expr (struct loop *loop, gimple at_stmt, tree expr,
1050 gimple halting_phi, tree *evolution_of_loop, int limit)
1052 enum tree_code code = TREE_CODE (expr);
1053 tree type = TREE_TYPE (expr), rhs0, rhs1;
1054 t_bool res;
1056 /* The EXPR is one of the following cases:
1057 - an SSA_NAME,
1058 - an INTEGER_CST,
1059 - a PLUS_EXPR,
1060 - a POINTER_PLUS_EXPR,
1061 - a MINUS_EXPR,
1062 - an ASSERT_EXPR,
1063 - other cases are not yet handled. */
1065 switch (code)
1067 CASE_CONVERT:
1068 /* This assignment is under the form "a_1 = (cast) rhs. */
1069 res = follow_ssa_edge_expr (loop, at_stmt, TREE_OPERAND (expr, 0),
1070 halting_phi, evolution_of_loop, limit);
1071 *evolution_of_loop = chrec_convert (type, *evolution_of_loop, at_stmt);
1072 break;
1074 case INTEGER_CST:
1075 /* This assignment is under the form "a_1 = 7". */
1076 res = t_false;
1077 break;
1079 case SSA_NAME:
1080 /* This assignment is under the form: "a_1 = b_2". */
1081 res = follow_ssa_edge
1082 (loop, SSA_NAME_DEF_STMT (expr), halting_phi, evolution_of_loop, limit);
1083 break;
1085 case POINTER_PLUS_EXPR:
1086 case PLUS_EXPR:
1087 case MINUS_EXPR:
1088 /* This case is under the form "rhs0 +- rhs1". */
1089 rhs0 = TREE_OPERAND (expr, 0);
1090 rhs1 = TREE_OPERAND (expr, 1);
1091 type = TREE_TYPE (rhs0);
1092 STRIP_USELESS_TYPE_CONVERSION (rhs0);
1093 STRIP_USELESS_TYPE_CONVERSION (rhs1);
1094 res = follow_ssa_edge_binary (loop, at_stmt, type, rhs0, code, rhs1,
1095 halting_phi, evolution_of_loop, limit);
1096 break;
1098 case ADDR_EXPR:
1099 /* Handle &MEM[ptr + CST] which is equivalent to POINTER_PLUS_EXPR. */
1100 if (TREE_CODE (TREE_OPERAND (expr, 0)) == MEM_REF)
1102 expr = TREE_OPERAND (expr, 0);
1103 rhs0 = TREE_OPERAND (expr, 0);
1104 rhs1 = TREE_OPERAND (expr, 1);
1105 type = TREE_TYPE (rhs0);
1106 STRIP_USELESS_TYPE_CONVERSION (rhs0);
1107 STRIP_USELESS_TYPE_CONVERSION (rhs1);
1108 res = follow_ssa_edge_binary (loop, at_stmt, type,
1109 rhs0, POINTER_PLUS_EXPR, rhs1,
1110 halting_phi, evolution_of_loop, limit);
1112 else
1113 res = t_false;
1114 break;
1116 case ASSERT_EXPR:
1117 /* This assignment is of the form: "a_1 = ASSERT_EXPR <a_2, ...>"
1118 It must be handled as a copy assignment of the form a_1 = a_2. */
1119 rhs0 = ASSERT_EXPR_VAR (expr);
1120 if (TREE_CODE (rhs0) == SSA_NAME)
1121 res = follow_ssa_edge (loop, SSA_NAME_DEF_STMT (rhs0),
1122 halting_phi, evolution_of_loop, limit);
1123 else
1124 res = t_false;
1125 break;
1127 default:
1128 res = t_false;
1129 break;
1132 return res;
1135 /* Follow the ssa edge into the right hand side of an assignment STMT.
1136 Return true if the strongly connected component has been found. */
1138 static t_bool
1139 follow_ssa_edge_in_rhs (struct loop *loop, gimple stmt,
1140 gimple halting_phi, tree *evolution_of_loop, int limit)
1142 enum tree_code code = gimple_assign_rhs_code (stmt);
1143 tree type = gimple_expr_type (stmt), rhs1, rhs2;
1144 t_bool res;
1146 switch (code)
1148 CASE_CONVERT:
1149 /* This assignment is under the form "a_1 = (cast) rhs. */
1150 res = follow_ssa_edge_expr (loop, stmt, gimple_assign_rhs1 (stmt),
1151 halting_phi, evolution_of_loop, limit);
1152 *evolution_of_loop = chrec_convert (type, *evolution_of_loop, stmt);
1153 break;
1155 case POINTER_PLUS_EXPR:
1156 case PLUS_EXPR:
1157 case MINUS_EXPR:
1158 rhs1 = gimple_assign_rhs1 (stmt);
1159 rhs2 = gimple_assign_rhs2 (stmt);
1160 type = TREE_TYPE (rhs1);
1161 res = follow_ssa_edge_binary (loop, stmt, type, rhs1, code, rhs2,
1162 halting_phi, evolution_of_loop, limit);
1163 break;
1165 default:
1166 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1167 res = follow_ssa_edge_expr (loop, stmt, gimple_assign_rhs1 (stmt),
1168 halting_phi, evolution_of_loop, limit);
1169 else
1170 res = t_false;
1171 break;
1174 return res;
1177 /* Checks whether the I-th argument of a PHI comes from a backedge. */
1179 static bool
1180 backedge_phi_arg_p (gimple phi, int i)
1182 const_edge e = gimple_phi_arg_edge (phi, i);
1184 /* We would in fact like to test EDGE_DFS_BACK here, but we do not care
1185 about updating it anywhere, and this should work as well most of the
1186 time. */
1187 if (e->flags & EDGE_IRREDUCIBLE_LOOP)
1188 return true;
1190 return false;
1193 /* Helper function for one branch of the condition-phi-node. Return
1194 true if the strongly connected component has been found following
1195 this path. */
1197 static inline t_bool
1198 follow_ssa_edge_in_condition_phi_branch (int i,
1199 struct loop *loop,
1200 gimple condition_phi,
1201 gimple halting_phi,
1202 tree *evolution_of_branch,
1203 tree init_cond, int limit)
1205 tree branch = PHI_ARG_DEF (condition_phi, i);
1206 *evolution_of_branch = chrec_dont_know;
1208 /* Do not follow back edges (they must belong to an irreducible loop, which
1209 we really do not want to worry about). */
1210 if (backedge_phi_arg_p (condition_phi, i))
1211 return t_false;
1213 if (TREE_CODE (branch) == SSA_NAME)
1215 *evolution_of_branch = init_cond;
1216 return follow_ssa_edge (loop, SSA_NAME_DEF_STMT (branch), halting_phi,
1217 evolution_of_branch, limit);
1220 /* This case occurs when one of the condition branches sets
1221 the variable to a constant: i.e. a phi-node like
1222 "a_2 = PHI <a_7(5), 2(6)>;".
1224 FIXME: This case have to be refined correctly:
1225 in some cases it is possible to say something better than
1226 chrec_dont_know, for example using a wrap-around notation. */
1227 return t_false;
1230 /* This function merges the branches of a condition-phi-node in a
1231 loop. */
1233 static t_bool
1234 follow_ssa_edge_in_condition_phi (struct loop *loop,
1235 gimple condition_phi,
1236 gimple halting_phi,
1237 tree *evolution_of_loop, int limit)
1239 int i, n;
1240 tree init = *evolution_of_loop;
1241 tree evolution_of_branch;
1242 t_bool res = follow_ssa_edge_in_condition_phi_branch (0, loop, condition_phi,
1243 halting_phi,
1244 &evolution_of_branch,
1245 init, limit);
1246 if (res == t_false || res == t_dont_know)
1247 return res;
1249 *evolution_of_loop = evolution_of_branch;
1251 n = gimple_phi_num_args (condition_phi);
1252 for (i = 1; i < n; i++)
1254 /* Quickly give up when the evolution of one of the branches is
1255 not known. */
1256 if (*evolution_of_loop == chrec_dont_know)
1257 return t_true;
1259 /* Increase the limit by the PHI argument number to avoid exponential
1260 time and memory complexity. */
1261 res = follow_ssa_edge_in_condition_phi_branch (i, loop, condition_phi,
1262 halting_phi,
1263 &evolution_of_branch,
1264 init, limit + i);
1265 if (res == t_false || res == t_dont_know)
1266 return res;
1268 *evolution_of_loop = chrec_merge (*evolution_of_loop,
1269 evolution_of_branch);
1272 return t_true;
1275 /* Follow an SSA edge in an inner loop. It computes the overall
1276 effect of the loop, and following the symbolic initial conditions,
1277 it follows the edges in the parent loop. The inner loop is
1278 considered as a single statement. */
1280 static t_bool
1281 follow_ssa_edge_inner_loop_phi (struct loop *outer_loop,
1282 gimple loop_phi_node,
1283 gimple halting_phi,
1284 tree *evolution_of_loop, int limit)
1286 struct loop *loop = loop_containing_stmt (loop_phi_node);
1287 tree ev = analyze_scalar_evolution (loop, PHI_RESULT (loop_phi_node));
1289 /* Sometimes, the inner loop is too difficult to analyze, and the
1290 result of the analysis is a symbolic parameter. */
1291 if (ev == PHI_RESULT (loop_phi_node))
1293 t_bool res = t_false;
1294 int i, n = gimple_phi_num_args (loop_phi_node);
1296 for (i = 0; i < n; i++)
1298 tree arg = PHI_ARG_DEF (loop_phi_node, i);
1299 basic_block bb;
1301 /* Follow the edges that exit the inner loop. */
1302 bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1303 if (!flow_bb_inside_loop_p (loop, bb))
1304 res = follow_ssa_edge_expr (outer_loop, loop_phi_node,
1305 arg, halting_phi,
1306 evolution_of_loop, limit);
1307 if (res == t_true)
1308 break;
1311 /* If the path crosses this loop-phi, give up. */
1312 if (res == t_true)
1313 *evolution_of_loop = chrec_dont_know;
1315 return res;
1318 /* Otherwise, compute the overall effect of the inner loop. */
1319 ev = compute_overall_effect_of_inner_loop (loop, ev);
1320 return follow_ssa_edge_expr (outer_loop, loop_phi_node, ev, halting_phi,
1321 evolution_of_loop, limit);
1324 /* Follow an SSA edge from a loop-phi-node to itself, constructing a
1325 path that is analyzed on the return walk. */
1327 static t_bool
1328 follow_ssa_edge (struct loop *loop, gimple def, gimple halting_phi,
1329 tree *evolution_of_loop, int limit)
1331 struct loop *def_loop;
1333 if (gimple_nop_p (def))
1334 return t_false;
1336 /* Give up if the path is longer than the MAX that we allow. */
1337 if (limit > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_COMPLEXITY))
1338 return t_dont_know;
1340 def_loop = loop_containing_stmt (def);
1342 switch (gimple_code (def))
1344 case GIMPLE_PHI:
1345 if (!loop_phi_node_p (def))
1346 /* DEF is a condition-phi-node. Follow the branches, and
1347 record their evolutions. Finally, merge the collected
1348 information and set the approximation to the main
1349 variable. */
1350 return follow_ssa_edge_in_condition_phi
1351 (loop, def, halting_phi, evolution_of_loop, limit);
1353 /* When the analyzed phi is the halting_phi, the
1354 depth-first search is over: we have found a path from
1355 the halting_phi to itself in the loop. */
1356 if (def == halting_phi)
1357 return t_true;
1359 /* Otherwise, the evolution of the HALTING_PHI depends
1360 on the evolution of another loop-phi-node, i.e. the
1361 evolution function is a higher degree polynomial. */
1362 if (def_loop == loop)
1363 return t_false;
1365 /* Inner loop. */
1366 if (flow_loop_nested_p (loop, def_loop))
1367 return follow_ssa_edge_inner_loop_phi
1368 (loop, def, halting_phi, evolution_of_loop, limit + 1);
1370 /* Outer loop. */
1371 return t_false;
1373 case GIMPLE_ASSIGN:
1374 return follow_ssa_edge_in_rhs (loop, def, halting_phi,
1375 evolution_of_loop, limit);
1377 default:
1378 /* At this level of abstraction, the program is just a set
1379 of GIMPLE_ASSIGNs and PHI_NODEs. In principle there is no
1380 other node to be handled. */
1381 return t_false;
1386 /* Simplify PEELED_CHREC represented by (init_cond, arg) in LOOP.
1387 Handle below case and return the corresponding POLYNOMIAL_CHREC:
1389 # i_17 = PHI <i_13(5), 0(3)>
1390 # _20 = PHI <_5(5), start_4(D)(3)>
1392 i_13 = i_17 + 1;
1393 _5 = start_4(D) + i_13;
1395 Though variable _20 appears as a PEELED_CHREC in the form of
1396 (start_4, _5)_LOOP, it's a POLYNOMIAL_CHREC like {start_4, 1}_LOOP.
1398 See PR41488. */
1400 static tree
1401 simplify_peeled_chrec (struct loop *loop, tree arg, tree init_cond)
1403 aff_tree aff1, aff2;
1404 tree ev, left, right, type, step_val;
1405 hash_map<tree, name_expansion *> *peeled_chrec_map = NULL;
1407 ev = instantiate_parameters (loop, analyze_scalar_evolution (loop, arg));
1408 if (ev == NULL_TREE || TREE_CODE (ev) != POLYNOMIAL_CHREC)
1409 return chrec_dont_know;
1411 left = CHREC_LEFT (ev);
1412 right = CHREC_RIGHT (ev);
1413 type = TREE_TYPE (left);
1414 step_val = chrec_fold_plus (type, init_cond, right);
1416 /* Transform (init, {left, right}_LOOP)_LOOP to {init, right}_LOOP
1417 if "left" equals to "init + right". */
1418 if (operand_equal_p (left, step_val, 0))
1420 if (dump_file && (dump_flags & TDF_SCEV))
1421 fprintf (dump_file, "Simplify PEELED_CHREC into POLYNOMIAL_CHREC.\n");
1423 return build_polynomial_chrec (loop->num, init_cond, right);
1426 /* Try harder to check if they are equal. */
1427 tree_to_aff_combination_expand (left, type, &aff1, &peeled_chrec_map);
1428 tree_to_aff_combination_expand (step_val, type, &aff2, &peeled_chrec_map);
1429 free_affine_expand_cache (&peeled_chrec_map);
1430 aff_combination_scale (&aff2, -1);
1431 aff_combination_add (&aff1, &aff2);
1433 /* Transform (init, {left, right}_LOOP)_LOOP to {init, right}_LOOP
1434 if "left" equals to "init + right". */
1435 if (aff_combination_zero_p (&aff1))
1437 if (dump_file && (dump_flags & TDF_SCEV))
1438 fprintf (dump_file, "Simplify PEELED_CHREC into POLYNOMIAL_CHREC.\n");
1440 return build_polynomial_chrec (loop->num, init_cond, right);
1442 return chrec_dont_know;
1445 /* Given a LOOP_PHI_NODE, this function determines the evolution
1446 function from LOOP_PHI_NODE to LOOP_PHI_NODE in the loop. */
1448 static tree
1449 analyze_evolution_in_loop (gimple loop_phi_node,
1450 tree init_cond)
1452 int i, n = gimple_phi_num_args (loop_phi_node);
1453 tree evolution_function = chrec_not_analyzed_yet;
1454 struct loop *loop = loop_containing_stmt (loop_phi_node);
1455 basic_block bb;
1456 static bool simplify_peeled_chrec_p = true;
1458 if (dump_file && (dump_flags & TDF_SCEV))
1460 fprintf (dump_file, "(analyze_evolution_in_loop \n");
1461 fprintf (dump_file, " (loop_phi_node = ");
1462 print_gimple_stmt (dump_file, loop_phi_node, 0, 0);
1463 fprintf (dump_file, ")\n");
1466 for (i = 0; i < n; i++)
1468 tree arg = PHI_ARG_DEF (loop_phi_node, i);
1469 gimple ssa_chain;
1470 tree ev_fn;
1471 t_bool res;
1473 /* Select the edges that enter the loop body. */
1474 bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1475 if (!flow_bb_inside_loop_p (loop, bb))
1476 continue;
1478 if (TREE_CODE (arg) == SSA_NAME)
1480 bool val = false;
1482 ssa_chain = SSA_NAME_DEF_STMT (arg);
1484 /* Pass in the initial condition to the follow edge function. */
1485 ev_fn = init_cond;
1486 res = follow_ssa_edge (loop, ssa_chain, loop_phi_node, &ev_fn, 0);
1488 /* If ev_fn has no evolution in the inner loop, and the
1489 init_cond is not equal to ev_fn, then we have an
1490 ambiguity between two possible values, as we cannot know
1491 the number of iterations at this point. */
1492 if (TREE_CODE (ev_fn) != POLYNOMIAL_CHREC
1493 && no_evolution_in_loop_p (ev_fn, loop->num, &val) && val
1494 && !operand_equal_p (init_cond, ev_fn, 0))
1495 ev_fn = chrec_dont_know;
1497 else
1498 res = t_false;
1500 /* When it is impossible to go back on the same
1501 loop_phi_node by following the ssa edges, the
1502 evolution is represented by a peeled chrec, i.e. the
1503 first iteration, EV_FN has the value INIT_COND, then
1504 all the other iterations it has the value of ARG.
1505 For the moment, PEELED_CHREC nodes are not built. */
1506 if (res != t_true)
1508 ev_fn = chrec_dont_know;
1509 /* Try to recognize POLYNOMIAL_CHREC which appears in
1510 the form of PEELED_CHREC, but guard the process with
1511 a bool variable to keep the analyzer from infinite
1512 recurrence for real PEELED_RECs. */
1513 if (simplify_peeled_chrec_p && TREE_CODE (arg) == SSA_NAME)
1515 simplify_peeled_chrec_p = false;
1516 ev_fn = simplify_peeled_chrec (loop, arg, init_cond);
1517 simplify_peeled_chrec_p = true;
1521 /* When there are multiple back edges of the loop (which in fact never
1522 happens currently, but nevertheless), merge their evolutions. */
1523 evolution_function = chrec_merge (evolution_function, ev_fn);
1526 if (dump_file && (dump_flags & TDF_SCEV))
1528 fprintf (dump_file, " (evolution_function = ");
1529 print_generic_expr (dump_file, evolution_function, 0);
1530 fprintf (dump_file, "))\n");
1533 return evolution_function;
1536 /* Given a loop-phi-node, return the initial conditions of the
1537 variable on entry of the loop. When the CCP has propagated
1538 constants into the loop-phi-node, the initial condition is
1539 instantiated, otherwise the initial condition is kept symbolic.
1540 This analyzer does not analyze the evolution outside the current
1541 loop, and leaves this task to the on-demand tree reconstructor. */
1543 static tree
1544 analyze_initial_condition (gimple loop_phi_node)
1546 int i, n;
1547 tree init_cond = chrec_not_analyzed_yet;
1548 struct loop *loop = loop_containing_stmt (loop_phi_node);
1550 if (dump_file && (dump_flags & TDF_SCEV))
1552 fprintf (dump_file, "(analyze_initial_condition \n");
1553 fprintf (dump_file, " (loop_phi_node = \n");
1554 print_gimple_stmt (dump_file, loop_phi_node, 0, 0);
1555 fprintf (dump_file, ")\n");
1558 n = gimple_phi_num_args (loop_phi_node);
1559 for (i = 0; i < n; i++)
1561 tree branch = PHI_ARG_DEF (loop_phi_node, i);
1562 basic_block bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1564 /* When the branch is oriented to the loop's body, it does
1565 not contribute to the initial condition. */
1566 if (flow_bb_inside_loop_p (loop, bb))
1567 continue;
1569 if (init_cond == chrec_not_analyzed_yet)
1571 init_cond = branch;
1572 continue;
1575 if (TREE_CODE (branch) == SSA_NAME)
1577 init_cond = chrec_dont_know;
1578 break;
1581 init_cond = chrec_merge (init_cond, branch);
1584 /* Ooops -- a loop without an entry??? */
1585 if (init_cond == chrec_not_analyzed_yet)
1586 init_cond = chrec_dont_know;
1588 /* During early loop unrolling we do not have fully constant propagated IL.
1589 Handle degenerate PHIs here to not miss important unrollings. */
1590 if (TREE_CODE (init_cond) == SSA_NAME)
1592 gimple def = SSA_NAME_DEF_STMT (init_cond);
1593 tree res;
1594 if (gimple_code (def) == GIMPLE_PHI
1595 && (res = degenerate_phi_result (def)) != NULL_TREE
1596 /* Only allow invariants here, otherwise we may break
1597 loop-closed SSA form. */
1598 && is_gimple_min_invariant (res))
1599 init_cond = res;
1602 if (dump_file && (dump_flags & TDF_SCEV))
1604 fprintf (dump_file, " (init_cond = ");
1605 print_generic_expr (dump_file, init_cond, 0);
1606 fprintf (dump_file, "))\n");
1609 return init_cond;
1612 /* Analyze the scalar evolution for LOOP_PHI_NODE. */
1614 static tree
1615 interpret_loop_phi (struct loop *loop, gimple loop_phi_node)
1617 tree res;
1618 struct loop *phi_loop = loop_containing_stmt (loop_phi_node);
1619 tree init_cond;
1621 if (phi_loop != loop)
1623 struct loop *subloop;
1624 tree evolution_fn = analyze_scalar_evolution
1625 (phi_loop, PHI_RESULT (loop_phi_node));
1627 /* Dive one level deeper. */
1628 subloop = superloop_at_depth (phi_loop, loop_depth (loop) + 1);
1630 /* Interpret the subloop. */
1631 res = compute_overall_effect_of_inner_loop (subloop, evolution_fn);
1632 return res;
1635 /* Otherwise really interpret the loop phi. */
1636 init_cond = analyze_initial_condition (loop_phi_node);
1637 res = analyze_evolution_in_loop (loop_phi_node, init_cond);
1639 /* Verify we maintained the correct initial condition throughout
1640 possible conversions in the SSA chain. */
1641 if (res != chrec_dont_know)
1643 tree new_init = res;
1644 if (CONVERT_EXPR_P (res)
1645 && TREE_CODE (TREE_OPERAND (res, 0)) == POLYNOMIAL_CHREC)
1646 new_init = fold_convert (TREE_TYPE (res),
1647 CHREC_LEFT (TREE_OPERAND (res, 0)));
1648 else if (TREE_CODE (res) == POLYNOMIAL_CHREC)
1649 new_init = CHREC_LEFT (res);
1650 STRIP_USELESS_TYPE_CONVERSION (new_init);
1651 if (TREE_CODE (new_init) == POLYNOMIAL_CHREC
1652 || !operand_equal_p (init_cond, new_init, 0))
1653 return chrec_dont_know;
1656 return res;
1659 /* This function merges the branches of a condition-phi-node,
1660 contained in the outermost loop, and whose arguments are already
1661 analyzed. */
1663 static tree
1664 interpret_condition_phi (struct loop *loop, gimple condition_phi)
1666 int i, n = gimple_phi_num_args (condition_phi);
1667 tree res = chrec_not_analyzed_yet;
1669 for (i = 0; i < n; i++)
1671 tree branch_chrec;
1673 if (backedge_phi_arg_p (condition_phi, i))
1675 res = chrec_dont_know;
1676 break;
1679 branch_chrec = analyze_scalar_evolution
1680 (loop, PHI_ARG_DEF (condition_phi, i));
1682 res = chrec_merge (res, branch_chrec);
1685 return res;
1688 /* Interpret the operation RHS1 OP RHS2. If we didn't
1689 analyze this node before, follow the definitions until ending
1690 either on an analyzed GIMPLE_ASSIGN, or on a loop-phi-node. On the
1691 return path, this function propagates evolutions (ala constant copy
1692 propagation). OPND1 is not a GIMPLE expression because we could
1693 analyze the effect of an inner loop: see interpret_loop_phi. */
1695 static tree
1696 interpret_rhs_expr (struct loop *loop, gimple at_stmt,
1697 tree type, tree rhs1, enum tree_code code, tree rhs2)
1699 tree res, chrec1, chrec2;
1700 gimple def;
1702 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1704 if (is_gimple_min_invariant (rhs1))
1705 return chrec_convert (type, rhs1, at_stmt);
1707 if (code == SSA_NAME)
1708 return chrec_convert (type, analyze_scalar_evolution (loop, rhs1),
1709 at_stmt);
1711 if (code == ASSERT_EXPR)
1713 rhs1 = ASSERT_EXPR_VAR (rhs1);
1714 return chrec_convert (type, analyze_scalar_evolution (loop, rhs1),
1715 at_stmt);
1719 switch (code)
1721 case ADDR_EXPR:
1722 if (TREE_CODE (TREE_OPERAND (rhs1, 0)) == MEM_REF
1723 || handled_component_p (TREE_OPERAND (rhs1, 0)))
1725 enum machine_mode mode;
1726 HOST_WIDE_INT bitsize, bitpos;
1727 int unsignedp;
1728 int volatilep = 0;
1729 tree base, offset;
1730 tree chrec3;
1731 tree unitpos;
1733 base = get_inner_reference (TREE_OPERAND (rhs1, 0),
1734 &bitsize, &bitpos, &offset,
1735 &mode, &unsignedp, &volatilep, false);
1737 if (TREE_CODE (base) == MEM_REF)
1739 rhs2 = TREE_OPERAND (base, 1);
1740 rhs1 = TREE_OPERAND (base, 0);
1742 chrec1 = analyze_scalar_evolution (loop, rhs1);
1743 chrec2 = analyze_scalar_evolution (loop, rhs2);
1744 chrec1 = chrec_convert (type, chrec1, at_stmt);
1745 chrec2 = chrec_convert (TREE_TYPE (rhs2), chrec2, at_stmt);
1746 chrec1 = instantiate_parameters (loop, chrec1);
1747 chrec2 = instantiate_parameters (loop, chrec2);
1748 res = chrec_fold_plus (type, chrec1, chrec2);
1750 else
1752 chrec1 = analyze_scalar_evolution_for_address_of (loop, base);
1753 chrec1 = chrec_convert (type, chrec1, at_stmt);
1754 res = chrec1;
1757 if (offset != NULL_TREE)
1759 chrec2 = analyze_scalar_evolution (loop, offset);
1760 chrec2 = chrec_convert (TREE_TYPE (offset), chrec2, at_stmt);
1761 chrec2 = instantiate_parameters (loop, chrec2);
1762 res = chrec_fold_plus (type, res, chrec2);
1765 if (bitpos != 0)
1767 gcc_assert ((bitpos % BITS_PER_UNIT) == 0);
1769 unitpos = size_int (bitpos / BITS_PER_UNIT);
1770 chrec3 = analyze_scalar_evolution (loop, unitpos);
1771 chrec3 = chrec_convert (TREE_TYPE (unitpos), chrec3, at_stmt);
1772 chrec3 = instantiate_parameters (loop, chrec3);
1773 res = chrec_fold_plus (type, res, chrec3);
1776 else
1777 res = chrec_dont_know;
1778 break;
1780 case POINTER_PLUS_EXPR:
1781 chrec1 = analyze_scalar_evolution (loop, rhs1);
1782 chrec2 = analyze_scalar_evolution (loop, rhs2);
1783 chrec1 = chrec_convert (type, chrec1, at_stmt);
1784 chrec2 = chrec_convert (TREE_TYPE (rhs2), chrec2, at_stmt);
1785 chrec1 = instantiate_parameters (loop, chrec1);
1786 chrec2 = instantiate_parameters (loop, chrec2);
1787 res = chrec_fold_plus (type, chrec1, chrec2);
1788 break;
1790 case PLUS_EXPR:
1791 chrec1 = analyze_scalar_evolution (loop, rhs1);
1792 chrec2 = analyze_scalar_evolution (loop, rhs2);
1793 chrec1 = chrec_convert (type, chrec1, at_stmt);
1794 chrec2 = chrec_convert (type, chrec2, at_stmt);
1795 chrec1 = instantiate_parameters (loop, chrec1);
1796 chrec2 = instantiate_parameters (loop, chrec2);
1797 res = chrec_fold_plus (type, chrec1, chrec2);
1798 break;
1800 case MINUS_EXPR:
1801 chrec1 = analyze_scalar_evolution (loop, rhs1);
1802 chrec2 = analyze_scalar_evolution (loop, rhs2);
1803 chrec1 = chrec_convert (type, chrec1, at_stmt);
1804 chrec2 = chrec_convert (type, chrec2, at_stmt);
1805 chrec1 = instantiate_parameters (loop, chrec1);
1806 chrec2 = instantiate_parameters (loop, chrec2);
1807 res = chrec_fold_minus (type, chrec1, chrec2);
1808 break;
1810 case NEGATE_EXPR:
1811 chrec1 = analyze_scalar_evolution (loop, rhs1);
1812 chrec1 = chrec_convert (type, chrec1, at_stmt);
1813 /* TYPE may be integer, real or complex, so use fold_convert. */
1814 chrec1 = instantiate_parameters (loop, chrec1);
1815 res = chrec_fold_multiply (type, chrec1,
1816 fold_convert (type, integer_minus_one_node));
1817 break;
1819 case BIT_NOT_EXPR:
1820 /* Handle ~X as -1 - X. */
1821 chrec1 = analyze_scalar_evolution (loop, rhs1);
1822 chrec1 = chrec_convert (type, chrec1, at_stmt);
1823 chrec1 = instantiate_parameters (loop, chrec1);
1824 res = chrec_fold_minus (type,
1825 fold_convert (type, integer_minus_one_node),
1826 chrec1);
1827 break;
1829 case MULT_EXPR:
1830 chrec1 = analyze_scalar_evolution (loop, rhs1);
1831 chrec2 = analyze_scalar_evolution (loop, rhs2);
1832 chrec1 = chrec_convert (type, chrec1, at_stmt);
1833 chrec2 = chrec_convert (type, chrec2, at_stmt);
1834 chrec1 = instantiate_parameters (loop, chrec1);
1835 chrec2 = instantiate_parameters (loop, chrec2);
1836 res = chrec_fold_multiply (type, chrec1, chrec2);
1837 break;
1839 CASE_CONVERT:
1840 /* In case we have a truncation of a widened operation that in
1841 the truncated type has undefined overflow behavior analyze
1842 the operation done in an unsigned type of the same precision
1843 as the final truncation. We cannot derive a scalar evolution
1844 for the widened operation but for the truncated result. */
1845 if (TREE_CODE (type) == INTEGER_TYPE
1846 && TREE_CODE (TREE_TYPE (rhs1)) == INTEGER_TYPE
1847 && TYPE_PRECISION (type) < TYPE_PRECISION (TREE_TYPE (rhs1))
1848 && TYPE_OVERFLOW_UNDEFINED (type)
1849 && TREE_CODE (rhs1) == SSA_NAME
1850 && (def = SSA_NAME_DEF_STMT (rhs1))
1851 && is_gimple_assign (def)
1852 && TREE_CODE_CLASS (gimple_assign_rhs_code (def)) == tcc_binary
1853 && TREE_CODE (gimple_assign_rhs2 (def)) == INTEGER_CST)
1855 tree utype = unsigned_type_for (type);
1856 chrec1 = interpret_rhs_expr (loop, at_stmt, utype,
1857 gimple_assign_rhs1 (def),
1858 gimple_assign_rhs_code (def),
1859 gimple_assign_rhs2 (def));
1861 else
1862 chrec1 = analyze_scalar_evolution (loop, rhs1);
1863 res = chrec_convert (type, chrec1, at_stmt);
1864 break;
1866 default:
1867 res = chrec_dont_know;
1868 break;
1871 return res;
1874 /* Interpret the expression EXPR. */
1876 static tree
1877 interpret_expr (struct loop *loop, gimple at_stmt, tree expr)
1879 enum tree_code code;
1880 tree type = TREE_TYPE (expr), op0, op1;
1882 if (automatically_generated_chrec_p (expr))
1883 return expr;
1885 if (TREE_CODE (expr) == POLYNOMIAL_CHREC
1886 || get_gimple_rhs_class (TREE_CODE (expr)) == GIMPLE_TERNARY_RHS)
1887 return chrec_dont_know;
1889 extract_ops_from_tree (expr, &code, &op0, &op1);
1891 return interpret_rhs_expr (loop, at_stmt, type,
1892 op0, code, op1);
1895 /* Interpret the rhs of the assignment STMT. */
1897 static tree
1898 interpret_gimple_assign (struct loop *loop, gimple stmt)
1900 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
1901 enum tree_code code = gimple_assign_rhs_code (stmt);
1903 return interpret_rhs_expr (loop, stmt, type,
1904 gimple_assign_rhs1 (stmt), code,
1905 gimple_assign_rhs2 (stmt));
1910 /* This section contains all the entry points:
1911 - number_of_iterations_in_loop,
1912 - analyze_scalar_evolution,
1913 - instantiate_parameters.
1916 /* Compute and return the evolution function in WRTO_LOOP, the nearest
1917 common ancestor of DEF_LOOP and USE_LOOP. */
1919 static tree
1920 compute_scalar_evolution_in_loop (struct loop *wrto_loop,
1921 struct loop *def_loop,
1922 tree ev)
1924 bool val;
1925 tree res;
1927 if (def_loop == wrto_loop)
1928 return ev;
1930 def_loop = superloop_at_depth (def_loop, loop_depth (wrto_loop) + 1);
1931 res = compute_overall_effect_of_inner_loop (def_loop, ev);
1933 if (no_evolution_in_loop_p (res, wrto_loop->num, &val) && val)
1934 return res;
1936 return analyze_scalar_evolution_1 (wrto_loop, res, chrec_not_analyzed_yet);
1939 /* Helper recursive function. */
1941 static tree
1942 analyze_scalar_evolution_1 (struct loop *loop, tree var, tree res)
1944 tree type = TREE_TYPE (var);
1945 gimple def;
1946 basic_block bb;
1947 struct loop *def_loop;
1949 if (loop == NULL || TREE_CODE (type) == VECTOR_TYPE)
1950 return chrec_dont_know;
1952 if (TREE_CODE (var) != SSA_NAME)
1953 return interpret_expr (loop, NULL, var);
1955 def = SSA_NAME_DEF_STMT (var);
1956 bb = gimple_bb (def);
1957 def_loop = bb ? bb->loop_father : NULL;
1959 if (bb == NULL
1960 || !flow_bb_inside_loop_p (loop, bb))
1962 /* Keep the symbolic form. */
1963 res = var;
1964 goto set_and_end;
1967 if (res != chrec_not_analyzed_yet)
1969 if (loop != bb->loop_father)
1970 res = compute_scalar_evolution_in_loop
1971 (find_common_loop (loop, bb->loop_father), bb->loop_father, res);
1973 goto set_and_end;
1976 if (loop != def_loop)
1978 res = analyze_scalar_evolution_1 (def_loop, var, chrec_not_analyzed_yet);
1979 res = compute_scalar_evolution_in_loop (loop, def_loop, res);
1981 goto set_and_end;
1984 switch (gimple_code (def))
1986 case GIMPLE_ASSIGN:
1987 res = interpret_gimple_assign (loop, def);
1988 break;
1990 case GIMPLE_PHI:
1991 if (loop_phi_node_p (def))
1992 res = interpret_loop_phi (loop, def);
1993 else
1994 res = interpret_condition_phi (loop, def);
1995 break;
1997 default:
1998 res = chrec_dont_know;
1999 break;
2002 set_and_end:
2004 /* Keep the symbolic form. */
2005 if (res == chrec_dont_know)
2006 res = var;
2008 if (loop == def_loop)
2009 set_scalar_evolution (block_before_loop (loop), var, res);
2011 return res;
2014 /* Analyzes and returns the scalar evolution of the ssa_name VAR in
2015 LOOP. LOOP is the loop in which the variable is used.
2017 Example of use: having a pointer VAR to a SSA_NAME node, STMT a
2018 pointer to the statement that uses this variable, in order to
2019 determine the evolution function of the variable, use the following
2020 calls:
2022 loop_p loop = loop_containing_stmt (stmt);
2023 tree chrec_with_symbols = analyze_scalar_evolution (loop, var);
2024 tree chrec_instantiated = instantiate_parameters (loop, chrec_with_symbols);
2027 tree
2028 analyze_scalar_evolution (struct loop *loop, tree var)
2030 tree res;
2032 if (dump_file && (dump_flags & TDF_SCEV))
2034 fprintf (dump_file, "(analyze_scalar_evolution \n");
2035 fprintf (dump_file, " (loop_nb = %d)\n", loop->num);
2036 fprintf (dump_file, " (scalar = ");
2037 print_generic_expr (dump_file, var, 0);
2038 fprintf (dump_file, ")\n");
2041 res = get_scalar_evolution (block_before_loop (loop), var);
2042 res = analyze_scalar_evolution_1 (loop, var, res);
2044 if (dump_file && (dump_flags & TDF_SCEV))
2045 fprintf (dump_file, ")\n");
2047 return res;
2050 /* Analyzes and returns the scalar evolution of VAR address in LOOP. */
2052 static tree
2053 analyze_scalar_evolution_for_address_of (struct loop *loop, tree var)
2055 return analyze_scalar_evolution (loop, build_fold_addr_expr (var));
2058 /* Analyze scalar evolution of use of VERSION in USE_LOOP with respect to
2059 WRTO_LOOP (which should be a superloop of USE_LOOP)
2061 FOLDED_CASTS is set to true if resolve_mixers used
2062 chrec_convert_aggressive (TODO -- not really, we are way too conservative
2063 at the moment in order to keep things simple).
2065 To illustrate the meaning of USE_LOOP and WRTO_LOOP, consider the following
2066 example:
2068 for (i = 0; i < 100; i++) -- loop 1
2070 for (j = 0; j < 100; j++) -- loop 2
2072 k1 = i;
2073 k2 = j;
2075 use2 (k1, k2);
2077 for (t = 0; t < 100; t++) -- loop 3
2078 use3 (k1, k2);
2081 use1 (k1, k2);
2084 Both k1 and k2 are invariants in loop3, thus
2085 analyze_scalar_evolution_in_loop (loop3, loop3, k1) = k1
2086 analyze_scalar_evolution_in_loop (loop3, loop3, k2) = k2
2088 As they are invariant, it does not matter whether we consider their
2089 usage in loop 3 or loop 2, hence
2090 analyze_scalar_evolution_in_loop (loop2, loop3, k1) =
2091 analyze_scalar_evolution_in_loop (loop2, loop2, k1) = i
2092 analyze_scalar_evolution_in_loop (loop2, loop3, k2) =
2093 analyze_scalar_evolution_in_loop (loop2, loop2, k2) = [0,+,1]_2
2095 Similarly for their evolutions with respect to loop 1. The values of K2
2096 in the use in loop 2 vary independently on loop 1, thus we cannot express
2097 the evolution with respect to loop 1:
2098 analyze_scalar_evolution_in_loop (loop1, loop3, k1) =
2099 analyze_scalar_evolution_in_loop (loop1, loop2, k1) = [0,+,1]_1
2100 analyze_scalar_evolution_in_loop (loop1, loop3, k2) =
2101 analyze_scalar_evolution_in_loop (loop1, loop2, k2) = dont_know
2103 The value of k2 in the use in loop 1 is known, though:
2104 analyze_scalar_evolution_in_loop (loop1, loop1, k1) = [0,+,1]_1
2105 analyze_scalar_evolution_in_loop (loop1, loop1, k2) = 100
2108 static tree
2109 analyze_scalar_evolution_in_loop (struct loop *wrto_loop, struct loop *use_loop,
2110 tree version, bool *folded_casts)
2112 bool val = false;
2113 tree ev = version, tmp;
2115 /* We cannot just do
2117 tmp = analyze_scalar_evolution (use_loop, version);
2118 ev = resolve_mixers (wrto_loop, tmp);
2120 as resolve_mixers would query the scalar evolution with respect to
2121 wrto_loop. For example, in the situation described in the function
2122 comment, suppose that wrto_loop = loop1, use_loop = loop3 and
2123 version = k2. Then
2125 analyze_scalar_evolution (use_loop, version) = k2
2127 and resolve_mixers (loop1, k2) finds that the value of k2 in loop 1
2128 is 100, which is a wrong result, since we are interested in the
2129 value in loop 3.
2131 Instead, we need to proceed from use_loop to wrto_loop loop by loop,
2132 each time checking that there is no evolution in the inner loop. */
2134 if (folded_casts)
2135 *folded_casts = false;
2136 while (1)
2138 tmp = analyze_scalar_evolution (use_loop, ev);
2139 ev = resolve_mixers (use_loop, tmp);
2141 if (folded_casts && tmp != ev)
2142 *folded_casts = true;
2144 if (use_loop == wrto_loop)
2145 return ev;
2147 /* If the value of the use changes in the inner loop, we cannot express
2148 its value in the outer loop (we might try to return interval chrec,
2149 but we do not have a user for it anyway) */
2150 if (!no_evolution_in_loop_p (ev, use_loop->num, &val)
2151 || !val)
2152 return chrec_dont_know;
2154 use_loop = loop_outer (use_loop);
2159 /* Hashtable helpers for a temporary hash-table used when
2160 instantiating a CHREC or resolving mixers. For this use
2161 instantiated_below is always the same. */
2163 struct instantiate_cache_type
2165 htab_t map;
2166 vec<scev_info_str> entries;
2168 instantiate_cache_type () : map (NULL), entries (vNULL) {}
2169 ~instantiate_cache_type ();
2170 tree get (unsigned slot) { return entries[slot].chrec; }
2171 void set (unsigned slot, tree chrec) { entries[slot].chrec = chrec; }
2174 instantiate_cache_type::~instantiate_cache_type ()
2176 if (map != NULL)
2178 htab_delete (map);
2179 entries.release ();
2183 /* Cache to avoid infinite recursion when instantiating an SSA name.
2184 Live during the outermost instantiate_scev or resolve_mixers call. */
2185 static instantiate_cache_type *global_cache;
2187 /* Computes a hash function for database element ELT. */
2189 static inline hashval_t
2190 hash_idx_scev_info (const void *elt_)
2192 unsigned idx = ((size_t) elt_) - 2;
2193 return hash_scev_info (&global_cache->entries[idx]);
2196 /* Compares database elements E1 and E2. */
2198 static inline int
2199 eq_idx_scev_info (const void *e1, const void *e2)
2201 unsigned idx1 = ((size_t) e1) - 2;
2202 return eq_scev_info (&global_cache->entries[idx1], e2);
2205 /* Returns from CACHE the slot number of the cached chrec for NAME. */
2207 static unsigned
2208 get_instantiated_value_entry (instantiate_cache_type &cache,
2209 tree name, basic_block instantiate_below)
2211 if (!cache.map)
2213 cache.map = htab_create (10, hash_idx_scev_info, eq_idx_scev_info, NULL);
2214 cache.entries.create (10);
2217 scev_info_str e;
2218 e.name_version = SSA_NAME_VERSION (name);
2219 e.instantiated_below = instantiate_below->index;
2220 void **slot = htab_find_slot_with_hash (cache.map, &e,
2221 hash_scev_info (&e), INSERT);
2222 if (!*slot)
2224 e.chrec = chrec_not_analyzed_yet;
2225 *slot = (void *)(size_t)(cache.entries.length () + 2);
2226 cache.entries.safe_push (e);
2229 return ((size_t)*slot) - 2;
2233 /* Return the closed_loop_phi node for VAR. If there is none, return
2234 NULL_TREE. */
2236 static tree
2237 loop_closed_phi_def (tree var)
2239 struct loop *loop;
2240 edge exit;
2241 gimple phi;
2242 gimple_stmt_iterator psi;
2244 if (var == NULL_TREE
2245 || TREE_CODE (var) != SSA_NAME)
2246 return NULL_TREE;
2248 loop = loop_containing_stmt (SSA_NAME_DEF_STMT (var));
2249 exit = single_exit (loop);
2250 if (!exit)
2251 return NULL_TREE;
2253 for (psi = gsi_start_phis (exit->dest); !gsi_end_p (psi); gsi_next (&psi))
2255 phi = gsi_stmt (psi);
2256 if (PHI_ARG_DEF_FROM_EDGE (phi, exit) == var)
2257 return PHI_RESULT (phi);
2260 return NULL_TREE;
2263 static tree instantiate_scev_r (basic_block, struct loop *, struct loop *,
2264 tree, bool, int);
2266 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2267 and EVOLUTION_LOOP, that were left under a symbolic form.
2269 CHREC is an SSA_NAME to be instantiated.
2271 CACHE is the cache of already instantiated values.
2273 FOLD_CONVERSIONS should be set to true when the conversions that
2274 may wrap in signed/pointer type are folded, as long as the value of
2275 the chrec is preserved.
2277 SIZE_EXPR is used for computing the size of the expression to be
2278 instantiated, and to stop if it exceeds some limit. */
2280 static tree
2281 instantiate_scev_name (basic_block instantiate_below,
2282 struct loop *evolution_loop, struct loop *inner_loop,
2283 tree chrec,
2284 bool fold_conversions,
2285 int size_expr)
2287 tree res;
2288 struct loop *def_loop;
2289 basic_block def_bb = gimple_bb (SSA_NAME_DEF_STMT (chrec));
2291 /* A parameter (or loop invariant and we do not want to include
2292 evolutions in outer loops), nothing to do. */
2293 if (!def_bb
2294 || loop_depth (def_bb->loop_father) == 0
2295 || dominated_by_p (CDI_DOMINATORS, instantiate_below, def_bb))
2296 return chrec;
2298 /* We cache the value of instantiated variable to avoid exponential
2299 time complexity due to reevaluations. We also store the convenient
2300 value in the cache in order to prevent infinite recursion -- we do
2301 not want to instantiate the SSA_NAME if it is in a mixer
2302 structure. This is used for avoiding the instantiation of
2303 recursively defined functions, such as:
2305 | a_2 -> {0, +, 1, +, a_2}_1 */
2307 unsigned si = get_instantiated_value_entry (*global_cache,
2308 chrec, instantiate_below);
2309 if (global_cache->get (si) != chrec_not_analyzed_yet)
2310 return global_cache->get (si);
2312 /* On recursion return chrec_dont_know. */
2313 global_cache->set (si, chrec_dont_know);
2315 def_loop = find_common_loop (evolution_loop, def_bb->loop_father);
2317 /* If the analysis yields a parametric chrec, instantiate the
2318 result again. */
2319 res = analyze_scalar_evolution (def_loop, chrec);
2321 /* Don't instantiate default definitions. */
2322 if (TREE_CODE (res) == SSA_NAME
2323 && SSA_NAME_IS_DEFAULT_DEF (res))
2326 /* Don't instantiate loop-closed-ssa phi nodes. */
2327 else if (TREE_CODE (res) == SSA_NAME
2328 && loop_depth (loop_containing_stmt (SSA_NAME_DEF_STMT (res)))
2329 > loop_depth (def_loop))
2331 if (res == chrec)
2332 res = loop_closed_phi_def (chrec);
2333 else
2334 res = chrec;
2336 /* When there is no loop_closed_phi_def, it means that the
2337 variable is not used after the loop: try to still compute the
2338 value of the variable when exiting the loop. */
2339 if (res == NULL_TREE)
2341 loop_p loop = loop_containing_stmt (SSA_NAME_DEF_STMT (chrec));
2342 res = analyze_scalar_evolution (loop, chrec);
2343 res = compute_overall_effect_of_inner_loop (loop, res);
2344 res = instantiate_scev_r (instantiate_below, evolution_loop,
2345 inner_loop, res,
2346 fold_conversions, size_expr);
2348 else if (!dominated_by_p (CDI_DOMINATORS, instantiate_below,
2349 gimple_bb (SSA_NAME_DEF_STMT (res))))
2350 res = chrec_dont_know;
2353 else if (res != chrec_dont_know)
2355 if (inner_loop
2356 && def_bb->loop_father != inner_loop
2357 && !flow_loop_nested_p (def_bb->loop_father, inner_loop))
2358 /* ??? We could try to compute the overall effect of the loop here. */
2359 res = chrec_dont_know;
2360 else
2361 res = instantiate_scev_r (instantiate_below, evolution_loop,
2362 inner_loop, res,
2363 fold_conversions, size_expr);
2366 /* Store the correct value to the cache. */
2367 global_cache->set (si, res);
2368 return res;
2371 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2372 and EVOLUTION_LOOP, that were left under a symbolic form.
2374 CHREC is a polynomial chain of recurrence to be instantiated.
2376 CACHE is the cache of already instantiated values.
2378 FOLD_CONVERSIONS should be set to true when the conversions that
2379 may wrap in signed/pointer type are folded, as long as the value of
2380 the chrec is preserved.
2382 SIZE_EXPR is used for computing the size of the expression to be
2383 instantiated, and to stop if it exceeds some limit. */
2385 static tree
2386 instantiate_scev_poly (basic_block instantiate_below,
2387 struct loop *evolution_loop, struct loop *,
2388 tree chrec, bool fold_conversions, int size_expr)
2390 tree op1;
2391 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2392 get_chrec_loop (chrec),
2393 CHREC_LEFT (chrec), fold_conversions,
2394 size_expr);
2395 if (op0 == chrec_dont_know)
2396 return chrec_dont_know;
2398 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2399 get_chrec_loop (chrec),
2400 CHREC_RIGHT (chrec), fold_conversions,
2401 size_expr);
2402 if (op1 == chrec_dont_know)
2403 return chrec_dont_know;
2405 if (CHREC_LEFT (chrec) != op0
2406 || CHREC_RIGHT (chrec) != op1)
2408 op1 = chrec_convert_rhs (chrec_type (op0), op1, NULL);
2409 chrec = build_polynomial_chrec (CHREC_VARIABLE (chrec), op0, op1);
2412 return chrec;
2415 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2416 and EVOLUTION_LOOP, that were left under a symbolic form.
2418 "C0 CODE C1" is a binary expression of type TYPE to be instantiated.
2420 CACHE is the cache of already instantiated values.
2422 FOLD_CONVERSIONS should be set to true when the conversions that
2423 may wrap in signed/pointer type are folded, as long as the value of
2424 the chrec is preserved.
2426 SIZE_EXPR is used for computing the size of the expression to be
2427 instantiated, and to stop if it exceeds some limit. */
2429 static tree
2430 instantiate_scev_binary (basic_block instantiate_below,
2431 struct loop *evolution_loop, struct loop *inner_loop,
2432 tree chrec, enum tree_code code,
2433 tree type, tree c0, tree c1,
2434 bool fold_conversions, int size_expr)
2436 tree op1;
2437 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop, inner_loop,
2438 c0, fold_conversions, size_expr);
2439 if (op0 == chrec_dont_know)
2440 return chrec_dont_know;
2442 op1 = instantiate_scev_r (instantiate_below, evolution_loop, inner_loop,
2443 c1, fold_conversions, size_expr);
2444 if (op1 == chrec_dont_know)
2445 return chrec_dont_know;
2447 if (c0 != op0
2448 || c1 != op1)
2450 op0 = chrec_convert (type, op0, NULL);
2451 op1 = chrec_convert_rhs (type, op1, NULL);
2453 switch (code)
2455 case POINTER_PLUS_EXPR:
2456 case PLUS_EXPR:
2457 return chrec_fold_plus (type, op0, op1);
2459 case MINUS_EXPR:
2460 return chrec_fold_minus (type, op0, op1);
2462 case MULT_EXPR:
2463 return chrec_fold_multiply (type, op0, op1);
2465 default:
2466 gcc_unreachable ();
2470 return chrec ? chrec : fold_build2 (code, type, c0, c1);
2473 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2474 and EVOLUTION_LOOP, that were left under a symbolic form.
2476 "CHREC" is an array reference to be instantiated.
2478 CACHE is the cache of already instantiated values.
2480 FOLD_CONVERSIONS should be set to true when the conversions that
2481 may wrap in signed/pointer type are folded, as long as the value of
2482 the chrec is preserved.
2484 SIZE_EXPR is used for computing the size of the expression to be
2485 instantiated, and to stop if it exceeds some limit. */
2487 static tree
2488 instantiate_array_ref (basic_block instantiate_below,
2489 struct loop *evolution_loop, struct loop *inner_loop,
2490 tree chrec, bool fold_conversions, int size_expr)
2492 tree res;
2493 tree index = TREE_OPERAND (chrec, 1);
2494 tree op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2495 inner_loop, index,
2496 fold_conversions, size_expr);
2498 if (op1 == chrec_dont_know)
2499 return chrec_dont_know;
2501 if (chrec && op1 == index)
2502 return chrec;
2504 res = unshare_expr (chrec);
2505 TREE_OPERAND (res, 1) = op1;
2506 return res;
2509 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2510 and EVOLUTION_LOOP, that were left under a symbolic form.
2512 "CHREC" that stands for a convert expression "(TYPE) OP" is to be
2513 instantiated.
2515 CACHE is the cache of already instantiated values.
2517 FOLD_CONVERSIONS should be set to true when the conversions that
2518 may wrap in signed/pointer type are folded, as long as the value of
2519 the chrec is preserved.
2521 SIZE_EXPR is used for computing the size of the expression to be
2522 instantiated, and to stop if it exceeds some limit. */
2524 static tree
2525 instantiate_scev_convert (basic_block instantiate_below,
2526 struct loop *evolution_loop, struct loop *inner_loop,
2527 tree chrec, tree type, tree op,
2528 bool fold_conversions, int size_expr)
2530 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2531 inner_loop, op,
2532 fold_conversions, size_expr);
2534 if (op0 == chrec_dont_know)
2535 return chrec_dont_know;
2537 if (fold_conversions)
2539 tree tmp = chrec_convert_aggressive (type, op0);
2540 if (tmp)
2541 return tmp;
2544 if (chrec && op0 == op)
2545 return chrec;
2547 /* If we used chrec_convert_aggressive, we can no longer assume that
2548 signed chrecs do not overflow, as chrec_convert does, so avoid
2549 calling it in that case. */
2550 if (fold_conversions)
2551 return fold_convert (type, op0);
2553 return chrec_convert (type, op0, NULL);
2556 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2557 and EVOLUTION_LOOP, that were left under a symbolic form.
2559 CHREC is a BIT_NOT_EXPR or a NEGATE_EXPR expression to be instantiated.
2560 Handle ~X as -1 - X.
2561 Handle -X as -1 * X.
2563 CACHE is the cache of already instantiated values.
2565 FOLD_CONVERSIONS should be set to true when the conversions that
2566 may wrap in signed/pointer type are folded, as long as the value of
2567 the chrec is preserved.
2569 SIZE_EXPR is used for computing the size of the expression to be
2570 instantiated, and to stop if it exceeds some limit. */
2572 static tree
2573 instantiate_scev_not (basic_block instantiate_below,
2574 struct loop *evolution_loop, struct loop *inner_loop,
2575 tree chrec,
2576 enum tree_code code, tree type, tree op,
2577 bool fold_conversions, int size_expr)
2579 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2580 inner_loop, op,
2581 fold_conversions, size_expr);
2583 if (op0 == chrec_dont_know)
2584 return chrec_dont_know;
2586 if (op != op0)
2588 op0 = chrec_convert (type, op0, NULL);
2590 switch (code)
2592 case BIT_NOT_EXPR:
2593 return chrec_fold_minus
2594 (type, fold_convert (type, integer_minus_one_node), op0);
2596 case NEGATE_EXPR:
2597 return chrec_fold_multiply
2598 (type, fold_convert (type, integer_minus_one_node), op0);
2600 default:
2601 gcc_unreachable ();
2605 return chrec ? chrec : fold_build1 (code, type, op0);
2608 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2609 and EVOLUTION_LOOP, that were left under a symbolic form.
2611 CHREC is an expression with 3 operands to be instantiated.
2613 CACHE is the cache of already instantiated values.
2615 FOLD_CONVERSIONS should be set to true when the conversions that
2616 may wrap in signed/pointer type are folded, as long as the value of
2617 the chrec is preserved.
2619 SIZE_EXPR is used for computing the size of the expression to be
2620 instantiated, and to stop if it exceeds some limit. */
2622 static tree
2623 instantiate_scev_3 (basic_block instantiate_below,
2624 struct loop *evolution_loop, struct loop *inner_loop,
2625 tree chrec,
2626 bool fold_conversions, int size_expr)
2628 tree op1, op2;
2629 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2630 inner_loop, TREE_OPERAND (chrec, 0),
2631 fold_conversions, size_expr);
2632 if (op0 == chrec_dont_know)
2633 return chrec_dont_know;
2635 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2636 inner_loop, TREE_OPERAND (chrec, 1),
2637 fold_conversions, size_expr);
2638 if (op1 == chrec_dont_know)
2639 return chrec_dont_know;
2641 op2 = instantiate_scev_r (instantiate_below, evolution_loop,
2642 inner_loop, TREE_OPERAND (chrec, 2),
2643 fold_conversions, size_expr);
2644 if (op2 == chrec_dont_know)
2645 return chrec_dont_know;
2647 if (op0 == TREE_OPERAND (chrec, 0)
2648 && op1 == TREE_OPERAND (chrec, 1)
2649 && op2 == TREE_OPERAND (chrec, 2))
2650 return chrec;
2652 return fold_build3 (TREE_CODE (chrec),
2653 TREE_TYPE (chrec), op0, op1, op2);
2656 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2657 and EVOLUTION_LOOP, that were left under a symbolic form.
2659 CHREC is an expression with 2 operands to be instantiated.
2661 CACHE is the cache of already instantiated values.
2663 FOLD_CONVERSIONS should be set to true when the conversions that
2664 may wrap in signed/pointer type are folded, as long as the value of
2665 the chrec is preserved.
2667 SIZE_EXPR is used for computing the size of the expression to be
2668 instantiated, and to stop if it exceeds some limit. */
2670 static tree
2671 instantiate_scev_2 (basic_block instantiate_below,
2672 struct loop *evolution_loop, struct loop *inner_loop,
2673 tree chrec,
2674 bool fold_conversions, int size_expr)
2676 tree op1;
2677 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2678 inner_loop, TREE_OPERAND (chrec, 0),
2679 fold_conversions, size_expr);
2680 if (op0 == chrec_dont_know)
2681 return chrec_dont_know;
2683 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2684 inner_loop, TREE_OPERAND (chrec, 1),
2685 fold_conversions, size_expr);
2686 if (op1 == chrec_dont_know)
2687 return chrec_dont_know;
2689 if (op0 == TREE_OPERAND (chrec, 0)
2690 && op1 == TREE_OPERAND (chrec, 1))
2691 return chrec;
2693 return fold_build2 (TREE_CODE (chrec), TREE_TYPE (chrec), op0, op1);
2696 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2697 and EVOLUTION_LOOP, that were left under a symbolic form.
2699 CHREC is an expression with 2 operands to be instantiated.
2701 CACHE is the cache of already instantiated values.
2703 FOLD_CONVERSIONS should be set to true when the conversions that
2704 may wrap in signed/pointer type are folded, as long as the value of
2705 the chrec is preserved.
2707 SIZE_EXPR is used for computing the size of the expression to be
2708 instantiated, and to stop if it exceeds some limit. */
2710 static tree
2711 instantiate_scev_1 (basic_block instantiate_below,
2712 struct loop *evolution_loop, struct loop *inner_loop,
2713 tree chrec,
2714 bool fold_conversions, int size_expr)
2716 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2717 inner_loop, TREE_OPERAND (chrec, 0),
2718 fold_conversions, size_expr);
2720 if (op0 == chrec_dont_know)
2721 return chrec_dont_know;
2723 if (op0 == TREE_OPERAND (chrec, 0))
2724 return chrec;
2726 return fold_build1 (TREE_CODE (chrec), TREE_TYPE (chrec), op0);
2729 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2730 and EVOLUTION_LOOP, that were left under a symbolic form.
2732 CHREC is the scalar evolution to instantiate.
2734 CACHE is the cache of already instantiated values.
2736 FOLD_CONVERSIONS should be set to true when the conversions that
2737 may wrap in signed/pointer type are folded, as long as the value of
2738 the chrec is preserved.
2740 SIZE_EXPR is used for computing the size of the expression to be
2741 instantiated, and to stop if it exceeds some limit. */
2743 static tree
2744 instantiate_scev_r (basic_block instantiate_below,
2745 struct loop *evolution_loop, struct loop *inner_loop,
2746 tree chrec,
2747 bool fold_conversions, int size_expr)
2749 /* Give up if the expression is larger than the MAX that we allow. */
2750 if (size_expr++ > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_SIZE))
2751 return chrec_dont_know;
2753 if (chrec == NULL_TREE
2754 || automatically_generated_chrec_p (chrec)
2755 || is_gimple_min_invariant (chrec))
2756 return chrec;
2758 switch (TREE_CODE (chrec))
2760 case SSA_NAME:
2761 return instantiate_scev_name (instantiate_below, evolution_loop,
2762 inner_loop, chrec,
2763 fold_conversions, size_expr);
2765 case POLYNOMIAL_CHREC:
2766 return instantiate_scev_poly (instantiate_below, evolution_loop,
2767 inner_loop, chrec,
2768 fold_conversions, size_expr);
2770 case POINTER_PLUS_EXPR:
2771 case PLUS_EXPR:
2772 case MINUS_EXPR:
2773 case MULT_EXPR:
2774 return instantiate_scev_binary (instantiate_below, evolution_loop,
2775 inner_loop, chrec,
2776 TREE_CODE (chrec), chrec_type (chrec),
2777 TREE_OPERAND (chrec, 0),
2778 TREE_OPERAND (chrec, 1),
2779 fold_conversions, size_expr);
2781 CASE_CONVERT:
2782 return instantiate_scev_convert (instantiate_below, evolution_loop,
2783 inner_loop, chrec,
2784 TREE_TYPE (chrec), TREE_OPERAND (chrec, 0),
2785 fold_conversions, size_expr);
2787 case NEGATE_EXPR:
2788 case BIT_NOT_EXPR:
2789 return instantiate_scev_not (instantiate_below, evolution_loop,
2790 inner_loop, chrec,
2791 TREE_CODE (chrec), TREE_TYPE (chrec),
2792 TREE_OPERAND (chrec, 0),
2793 fold_conversions, size_expr);
2795 case ADDR_EXPR:
2796 case SCEV_NOT_KNOWN:
2797 return chrec_dont_know;
2799 case SCEV_KNOWN:
2800 return chrec_known;
2802 case ARRAY_REF:
2803 return instantiate_array_ref (instantiate_below, evolution_loop,
2804 inner_loop, chrec,
2805 fold_conversions, size_expr);
2807 default:
2808 break;
2811 if (VL_EXP_CLASS_P (chrec))
2812 return chrec_dont_know;
2814 switch (TREE_CODE_LENGTH (TREE_CODE (chrec)))
2816 case 3:
2817 return instantiate_scev_3 (instantiate_below, evolution_loop,
2818 inner_loop, chrec,
2819 fold_conversions, size_expr);
2821 case 2:
2822 return instantiate_scev_2 (instantiate_below, evolution_loop,
2823 inner_loop, chrec,
2824 fold_conversions, size_expr);
2826 case 1:
2827 return instantiate_scev_1 (instantiate_below, evolution_loop,
2828 inner_loop, chrec,
2829 fold_conversions, size_expr);
2831 case 0:
2832 return chrec;
2834 default:
2835 break;
2838 /* Too complicated to handle. */
2839 return chrec_dont_know;
2842 /* Analyze all the parameters of the chrec that were left under a
2843 symbolic form. INSTANTIATE_BELOW is the basic block that stops the
2844 recursive instantiation of parameters: a parameter is a variable
2845 that is defined in a basic block that dominates INSTANTIATE_BELOW or
2846 a function parameter. */
2848 tree
2849 instantiate_scev (basic_block instantiate_below, struct loop *evolution_loop,
2850 tree chrec)
2852 tree res;
2854 if (dump_file && (dump_flags & TDF_SCEV))
2856 fprintf (dump_file, "(instantiate_scev \n");
2857 fprintf (dump_file, " (instantiate_below = %d)\n", instantiate_below->index);
2858 fprintf (dump_file, " (evolution_loop = %d)\n", evolution_loop->num);
2859 fprintf (dump_file, " (chrec = ");
2860 print_generic_expr (dump_file, chrec, 0);
2861 fprintf (dump_file, ")\n");
2864 bool destr = false;
2865 if (!global_cache)
2867 global_cache = new instantiate_cache_type;
2868 destr = true;
2871 res = instantiate_scev_r (instantiate_below, evolution_loop,
2872 NULL, chrec, false, 0);
2874 if (destr)
2876 delete global_cache;
2877 global_cache = NULL;
2880 if (dump_file && (dump_flags & TDF_SCEV))
2882 fprintf (dump_file, " (res = ");
2883 print_generic_expr (dump_file, res, 0);
2884 fprintf (dump_file, "))\n");
2887 return res;
2890 /* Similar to instantiate_parameters, but does not introduce the
2891 evolutions in outer loops for LOOP invariants in CHREC, and does not
2892 care about causing overflows, as long as they do not affect value
2893 of an expression. */
2895 tree
2896 resolve_mixers (struct loop *loop, tree chrec)
2898 bool destr = false;
2899 if (!global_cache)
2901 global_cache = new instantiate_cache_type;
2902 destr = true;
2905 tree ret = instantiate_scev_r (block_before_loop (loop), loop, NULL,
2906 chrec, true, 0);
2908 if (destr)
2910 delete global_cache;
2911 global_cache = NULL;
2914 return ret;
2917 /* Entry point for the analysis of the number of iterations pass.
2918 This function tries to safely approximate the number of iterations
2919 the loop will run. When this property is not decidable at compile
2920 time, the result is chrec_dont_know. Otherwise the result is a
2921 scalar or a symbolic parameter. When the number of iterations may
2922 be equal to zero and the property cannot be determined at compile
2923 time, the result is a COND_EXPR that represents in a symbolic form
2924 the conditions under which the number of iterations is not zero.
2926 Example of analysis: suppose that the loop has an exit condition:
2928 "if (b > 49) goto end_loop;"
2930 and that in a previous analysis we have determined that the
2931 variable 'b' has an evolution function:
2933 "EF = {23, +, 5}_2".
2935 When we evaluate the function at the point 5, i.e. the value of the
2936 variable 'b' after 5 iterations in the loop, we have EF (5) = 48,
2937 and EF (6) = 53. In this case the value of 'b' on exit is '53' and
2938 the loop body has been executed 6 times. */
2940 tree
2941 number_of_latch_executions (struct loop *loop)
2943 edge exit;
2944 struct tree_niter_desc niter_desc;
2945 tree may_be_zero;
2946 tree res;
2948 /* Determine whether the number of iterations in loop has already
2949 been computed. */
2950 res = loop->nb_iterations;
2951 if (res)
2952 return res;
2954 may_be_zero = NULL_TREE;
2956 if (dump_file && (dump_flags & TDF_SCEV))
2957 fprintf (dump_file, "(number_of_iterations_in_loop = \n");
2959 res = chrec_dont_know;
2960 exit = single_exit (loop);
2962 if (exit && number_of_iterations_exit (loop, exit, &niter_desc, false))
2964 may_be_zero = niter_desc.may_be_zero;
2965 res = niter_desc.niter;
2968 if (res == chrec_dont_know
2969 || !may_be_zero
2970 || integer_zerop (may_be_zero))
2972 else if (integer_nonzerop (may_be_zero))
2973 res = build_int_cst (TREE_TYPE (res), 0);
2975 else if (COMPARISON_CLASS_P (may_be_zero))
2976 res = fold_build3 (COND_EXPR, TREE_TYPE (res), may_be_zero,
2977 build_int_cst (TREE_TYPE (res), 0), res);
2978 else
2979 res = chrec_dont_know;
2981 if (dump_file && (dump_flags & TDF_SCEV))
2983 fprintf (dump_file, " (set_nb_iterations_in_loop = ");
2984 print_generic_expr (dump_file, res, 0);
2985 fprintf (dump_file, "))\n");
2988 loop->nb_iterations = res;
2989 return res;
2993 /* Counters for the stats. */
2995 struct chrec_stats
2997 unsigned nb_chrecs;
2998 unsigned nb_affine;
2999 unsigned nb_affine_multivar;
3000 unsigned nb_higher_poly;
3001 unsigned nb_chrec_dont_know;
3002 unsigned nb_undetermined;
3005 /* Reset the counters. */
3007 static inline void
3008 reset_chrecs_counters (struct chrec_stats *stats)
3010 stats->nb_chrecs = 0;
3011 stats->nb_affine = 0;
3012 stats->nb_affine_multivar = 0;
3013 stats->nb_higher_poly = 0;
3014 stats->nb_chrec_dont_know = 0;
3015 stats->nb_undetermined = 0;
3018 /* Dump the contents of a CHREC_STATS structure. */
3020 static void
3021 dump_chrecs_stats (FILE *file, struct chrec_stats *stats)
3023 fprintf (file, "\n(\n");
3024 fprintf (file, "-----------------------------------------\n");
3025 fprintf (file, "%d\taffine univariate chrecs\n", stats->nb_affine);
3026 fprintf (file, "%d\taffine multivariate chrecs\n", stats->nb_affine_multivar);
3027 fprintf (file, "%d\tdegree greater than 2 polynomials\n",
3028 stats->nb_higher_poly);
3029 fprintf (file, "%d\tchrec_dont_know chrecs\n", stats->nb_chrec_dont_know);
3030 fprintf (file, "-----------------------------------------\n");
3031 fprintf (file, "%d\ttotal chrecs\n", stats->nb_chrecs);
3032 fprintf (file, "%d\twith undetermined coefficients\n",
3033 stats->nb_undetermined);
3034 fprintf (file, "-----------------------------------------\n");
3035 fprintf (file, "%d\tchrecs in the scev database\n",
3036 (int) htab_elements (scalar_evolution_info));
3037 fprintf (file, "%d\tsets in the scev database\n", nb_set_scev);
3038 fprintf (file, "%d\tgets in the scev database\n", nb_get_scev);
3039 fprintf (file, "-----------------------------------------\n");
3040 fprintf (file, ")\n\n");
3043 /* Gather statistics about CHREC. */
3045 static void
3046 gather_chrec_stats (tree chrec, struct chrec_stats *stats)
3048 if (dump_file && (dump_flags & TDF_STATS))
3050 fprintf (dump_file, "(classify_chrec ");
3051 print_generic_expr (dump_file, chrec, 0);
3052 fprintf (dump_file, "\n");
3055 stats->nb_chrecs++;
3057 if (chrec == NULL_TREE)
3059 stats->nb_undetermined++;
3060 return;
3063 switch (TREE_CODE (chrec))
3065 case POLYNOMIAL_CHREC:
3066 if (evolution_function_is_affine_p (chrec))
3068 if (dump_file && (dump_flags & TDF_STATS))
3069 fprintf (dump_file, " affine_univariate\n");
3070 stats->nb_affine++;
3072 else if (evolution_function_is_affine_multivariate_p (chrec, 0))
3074 if (dump_file && (dump_flags & TDF_STATS))
3075 fprintf (dump_file, " affine_multivariate\n");
3076 stats->nb_affine_multivar++;
3078 else
3080 if (dump_file && (dump_flags & TDF_STATS))
3081 fprintf (dump_file, " higher_degree_polynomial\n");
3082 stats->nb_higher_poly++;
3085 break;
3087 default:
3088 break;
3091 if (chrec_contains_undetermined (chrec))
3093 if (dump_file && (dump_flags & TDF_STATS))
3094 fprintf (dump_file, " undetermined\n");
3095 stats->nb_undetermined++;
3098 if (dump_file && (dump_flags & TDF_STATS))
3099 fprintf (dump_file, ")\n");
3102 /* Callback for htab_traverse, gathers information on chrecs in the
3103 hashtable. */
3105 static int
3106 gather_stats_on_scev_database_1 (void **slot, void *stats)
3108 struct scev_info_str *entry = (struct scev_info_str *) *slot;
3110 gather_chrec_stats (entry->chrec, (struct chrec_stats *) stats);
3112 return 1;
3115 /* Classify the chrecs of the whole database. */
3117 void
3118 gather_stats_on_scev_database (void)
3120 struct chrec_stats stats;
3122 if (!dump_file)
3123 return;
3125 reset_chrecs_counters (&stats);
3127 htab_traverse (scalar_evolution_info, gather_stats_on_scev_database_1,
3128 &stats);
3130 dump_chrecs_stats (dump_file, &stats);
3135 /* Initializer. */
3137 static void
3138 initialize_scalar_evolutions_analyzer (void)
3140 /* The elements below are unique. */
3141 if (chrec_dont_know == NULL_TREE)
3143 chrec_not_analyzed_yet = NULL_TREE;
3144 chrec_dont_know = make_node (SCEV_NOT_KNOWN);
3145 chrec_known = make_node (SCEV_KNOWN);
3146 TREE_TYPE (chrec_dont_know) = void_type_node;
3147 TREE_TYPE (chrec_known) = void_type_node;
3151 /* Initialize the analysis of scalar evolutions for LOOPS. */
3153 void
3154 scev_initialize (void)
3156 struct loop *loop;
3158 scalar_evolution_info = htab_create_ggc (100, hash_scev_info, eq_scev_info,
3159 del_scev_info);
3161 initialize_scalar_evolutions_analyzer ();
3163 FOR_EACH_LOOP (loop, 0)
3165 loop->nb_iterations = NULL_TREE;
3169 /* Return true if SCEV is initialized. */
3171 bool
3172 scev_initialized_p (void)
3174 return scalar_evolution_info != NULL;
3177 /* Cleans up the information cached by the scalar evolutions analysis
3178 in the hash table. */
3180 void
3181 scev_reset_htab (void)
3183 if (!scalar_evolution_info)
3184 return;
3186 htab_empty (scalar_evolution_info);
3189 /* Cleans up the information cached by the scalar evolutions analysis
3190 in the hash table and in the loop->nb_iterations. */
3192 void
3193 scev_reset (void)
3195 struct loop *loop;
3197 scev_reset_htab ();
3199 FOR_EACH_LOOP (loop, 0)
3201 loop->nb_iterations = NULL_TREE;
3205 /* Checks whether use of OP in USE_LOOP behaves as a simple affine iv with
3206 respect to WRTO_LOOP and returns its base and step in IV if possible
3207 (see analyze_scalar_evolution_in_loop for more details on USE_LOOP
3208 and WRTO_LOOP). If ALLOW_NONCONSTANT_STEP is true, we want step to be
3209 invariant in LOOP. Otherwise we require it to be an integer constant.
3211 IV->no_overflow is set to true if we are sure the iv cannot overflow (e.g.
3212 because it is computed in signed arithmetics). Consequently, adding an
3213 induction variable
3215 for (i = IV->base; ; i += IV->step)
3217 is only safe if IV->no_overflow is false, or TYPE_OVERFLOW_UNDEFINED is
3218 false for the type of the induction variable, or you can prove that i does
3219 not wrap by some other argument. Otherwise, this might introduce undefined
3220 behavior, and
3222 for (i = iv->base; ; i = (type) ((unsigned type) i + (unsigned type) iv->step))
3224 must be used instead. */
3226 bool
3227 simple_iv (struct loop *wrto_loop, struct loop *use_loop, tree op,
3228 affine_iv *iv, bool allow_nonconstant_step)
3230 tree type, ev;
3231 bool folded_casts;
3233 iv->base = NULL_TREE;
3234 iv->step = NULL_TREE;
3235 iv->no_overflow = false;
3237 type = TREE_TYPE (op);
3238 if (!POINTER_TYPE_P (type)
3239 && !INTEGRAL_TYPE_P (type))
3240 return false;
3242 ev = analyze_scalar_evolution_in_loop (wrto_loop, use_loop, op,
3243 &folded_casts);
3244 if (chrec_contains_undetermined (ev)
3245 || chrec_contains_symbols_defined_in_loop (ev, wrto_loop->num))
3246 return false;
3248 if (tree_does_not_contain_chrecs (ev))
3250 iv->base = ev;
3251 iv->step = build_int_cst (TREE_TYPE (ev), 0);
3252 iv->no_overflow = true;
3253 return true;
3256 if (TREE_CODE (ev) != POLYNOMIAL_CHREC
3257 || CHREC_VARIABLE (ev) != (unsigned) wrto_loop->num)
3258 return false;
3260 iv->step = CHREC_RIGHT (ev);
3261 if ((!allow_nonconstant_step && TREE_CODE (iv->step) != INTEGER_CST)
3262 || tree_contains_chrecs (iv->step, NULL))
3263 return false;
3265 iv->base = CHREC_LEFT (ev);
3266 if (tree_contains_chrecs (iv->base, NULL))
3267 return false;
3269 iv->no_overflow = !folded_casts && TYPE_OVERFLOW_UNDEFINED (type);
3271 return true;
3274 /* Finalize the scalar evolution analysis. */
3276 void
3277 scev_finalize (void)
3279 if (!scalar_evolution_info)
3280 return;
3281 htab_delete (scalar_evolution_info);
3282 scalar_evolution_info = NULL;
3285 /* Returns true if the expression EXPR is considered to be too expensive
3286 for scev_const_prop. */
3288 bool
3289 expression_expensive_p (tree expr)
3291 enum tree_code code;
3293 if (is_gimple_val (expr))
3294 return false;
3296 code = TREE_CODE (expr);
3297 if (code == TRUNC_DIV_EXPR
3298 || code == CEIL_DIV_EXPR
3299 || code == FLOOR_DIV_EXPR
3300 || code == ROUND_DIV_EXPR
3301 || code == TRUNC_MOD_EXPR
3302 || code == CEIL_MOD_EXPR
3303 || code == FLOOR_MOD_EXPR
3304 || code == ROUND_MOD_EXPR
3305 || code == EXACT_DIV_EXPR)
3307 /* Division by power of two is usually cheap, so we allow it.
3308 Forbid anything else. */
3309 if (!integer_pow2p (TREE_OPERAND (expr, 1)))
3310 return true;
3313 switch (TREE_CODE_CLASS (code))
3315 case tcc_binary:
3316 case tcc_comparison:
3317 if (expression_expensive_p (TREE_OPERAND (expr, 1)))
3318 return true;
3320 /* Fallthru. */
3321 case tcc_unary:
3322 return expression_expensive_p (TREE_OPERAND (expr, 0));
3324 default:
3325 return true;
3329 /* Replace ssa names for that scev can prove they are constant by the
3330 appropriate constants. Also perform final value replacement in loops,
3331 in case the replacement expressions are cheap.
3333 We only consider SSA names defined by phi nodes; rest is left to the
3334 ordinary constant propagation pass. */
3336 unsigned int
3337 scev_const_prop (void)
3339 basic_block bb;
3340 tree name, type, ev;
3341 gimple phi, ass;
3342 struct loop *loop, *ex_loop;
3343 bitmap ssa_names_to_remove = NULL;
3344 unsigned i;
3345 gimple_stmt_iterator psi;
3347 if (number_of_loops (cfun) <= 1)
3348 return 0;
3350 FOR_EACH_BB_FN (bb, cfun)
3352 loop = bb->loop_father;
3354 for (psi = gsi_start_phis (bb); !gsi_end_p (psi); gsi_next (&psi))
3356 phi = gsi_stmt (psi);
3357 name = PHI_RESULT (phi);
3359 if (virtual_operand_p (name))
3360 continue;
3362 type = TREE_TYPE (name);
3364 if (!POINTER_TYPE_P (type)
3365 && !INTEGRAL_TYPE_P (type))
3366 continue;
3368 ev = resolve_mixers (loop, analyze_scalar_evolution (loop, name));
3369 if (!is_gimple_min_invariant (ev)
3370 || !may_propagate_copy (name, ev))
3371 continue;
3373 /* Replace the uses of the name. */
3374 if (name != ev)
3375 replace_uses_by (name, ev);
3377 if (!ssa_names_to_remove)
3378 ssa_names_to_remove = BITMAP_ALLOC (NULL);
3379 bitmap_set_bit (ssa_names_to_remove, SSA_NAME_VERSION (name));
3383 /* Remove the ssa names that were replaced by constants. We do not
3384 remove them directly in the previous cycle, since this
3385 invalidates scev cache. */
3386 if (ssa_names_to_remove)
3388 bitmap_iterator bi;
3390 EXECUTE_IF_SET_IN_BITMAP (ssa_names_to_remove, 0, i, bi)
3392 gimple_stmt_iterator psi;
3393 name = ssa_name (i);
3394 phi = SSA_NAME_DEF_STMT (name);
3396 gcc_assert (gimple_code (phi) == GIMPLE_PHI);
3397 psi = gsi_for_stmt (phi);
3398 remove_phi_node (&psi, true);
3401 BITMAP_FREE (ssa_names_to_remove);
3402 scev_reset ();
3405 /* Now the regular final value replacement. */
3406 FOR_EACH_LOOP (loop, LI_FROM_INNERMOST)
3408 edge exit;
3409 tree def, rslt, niter;
3410 gimple_stmt_iterator gsi;
3412 /* If we do not know exact number of iterations of the loop, we cannot
3413 replace the final value. */
3414 exit = single_exit (loop);
3415 if (!exit)
3416 continue;
3418 niter = number_of_latch_executions (loop);
3419 if (niter == chrec_dont_know)
3420 continue;
3422 /* Ensure that it is possible to insert new statements somewhere. */
3423 if (!single_pred_p (exit->dest))
3424 split_loop_exit_edge (exit);
3425 gsi = gsi_after_labels (exit->dest);
3427 ex_loop = superloop_at_depth (loop,
3428 loop_depth (exit->dest->loop_father) + 1);
3430 for (psi = gsi_start_phis (exit->dest); !gsi_end_p (psi); )
3432 phi = gsi_stmt (psi);
3433 rslt = PHI_RESULT (phi);
3434 def = PHI_ARG_DEF_FROM_EDGE (phi, exit);
3435 if (virtual_operand_p (def))
3437 gsi_next (&psi);
3438 continue;
3441 if (!POINTER_TYPE_P (TREE_TYPE (def))
3442 && !INTEGRAL_TYPE_P (TREE_TYPE (def)))
3444 gsi_next (&psi);
3445 continue;
3448 bool folded_casts;
3449 def = analyze_scalar_evolution_in_loop (ex_loop, loop, def,
3450 &folded_casts);
3451 def = compute_overall_effect_of_inner_loop (ex_loop, def);
3452 if (!tree_does_not_contain_chrecs (def)
3453 || chrec_contains_symbols_defined_in_loop (def, ex_loop->num)
3454 /* Moving the computation from the loop may prolong life range
3455 of some ssa names, which may cause problems if they appear
3456 on abnormal edges. */
3457 || contains_abnormal_ssa_name_p (def)
3458 /* Do not emit expensive expressions. The rationale is that
3459 when someone writes a code like
3461 while (n > 45) n -= 45;
3463 he probably knows that n is not large, and does not want it
3464 to be turned into n %= 45. */
3465 || expression_expensive_p (def))
3467 if (dump_file && (dump_flags & TDF_DETAILS))
3469 fprintf (dump_file, "not replacing:\n ");
3470 print_gimple_stmt (dump_file, phi, 0, 0);
3471 fprintf (dump_file, "\n");
3473 gsi_next (&psi);
3474 continue;
3477 /* Eliminate the PHI node and replace it by a computation outside
3478 the loop. */
3479 if (dump_file)
3481 fprintf (dump_file, "\nfinal value replacement:\n ");
3482 print_gimple_stmt (dump_file, phi, 0, 0);
3483 fprintf (dump_file, " with\n ");
3485 def = unshare_expr (def);
3486 remove_phi_node (&psi, false);
3488 /* If def's type has undefined overflow and there were folded
3489 casts, rewrite all stmts added for def into arithmetics
3490 with defined overflow behavior. */
3491 if (folded_casts && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (def)))
3493 gimple_seq stmts;
3494 gimple_stmt_iterator gsi2;
3495 def = force_gimple_operand (def, &stmts, true, NULL_TREE);
3496 gsi2 = gsi_start (stmts);
3497 while (!gsi_end_p (gsi2))
3499 gimple stmt = gsi_stmt (gsi2);
3500 gimple_stmt_iterator gsi3 = gsi2;
3501 gsi_next (&gsi2);
3502 gsi_remove (&gsi3, false);
3503 if (is_gimple_assign (stmt)
3504 && arith_code_with_undefined_signed_overflow
3505 (gimple_assign_rhs_code (stmt)))
3506 gsi_insert_seq_before (&gsi,
3507 rewrite_to_defined_overflow (stmt),
3508 GSI_SAME_STMT);
3509 else
3510 gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
3513 else
3514 def = force_gimple_operand_gsi (&gsi, def, false, NULL_TREE,
3515 true, GSI_SAME_STMT);
3517 ass = gimple_build_assign (rslt, def);
3518 gsi_insert_before (&gsi, ass, GSI_SAME_STMT);
3519 if (dump_file)
3521 print_gimple_stmt (dump_file, ass, 0, 0);
3522 fprintf (dump_file, "\n");
3526 return 0;
3529 #include "gt-tree-scalar-evolution.h"