[AArch64, ARM] Introduce "mrs" type attribute.
[official-gcc.git] / gcc / tree-scalar-evolution.c
blobbed621fe052b785de8a0baac73b30fe2ed2bfaed
1 /* Scalar evolution detector.
2 Copyright (C) 2003-2013 Free Software Foundation, Inc.
3 Contributed by Sebastian Pop <s.pop@laposte.net>
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
22 Description:
24 This pass analyzes the evolution of scalar variables in loop
25 structures. The algorithm is based on the SSA representation,
26 and on the loop hierarchy tree. This algorithm is not based on
27 the notion of versions of a variable, as it was the case for the
28 previous implementations of the scalar evolution algorithm, but
29 it assumes that each defined name is unique.
31 The notation used in this file is called "chains of recurrences",
32 and has been proposed by Eugene Zima, Robert Van Engelen, and
33 others for describing induction variables in programs. For example
34 "b -> {0, +, 2}_1" means that the scalar variable "b" is equal to 0
35 when entering in the loop_1 and has a step 2 in this loop, in other
36 words "for (b = 0; b < N; b+=2);". Note that the coefficients of
37 this chain of recurrence (or chrec [shrek]) can contain the name of
38 other variables, in which case they are called parametric chrecs.
39 For example, "b -> {a, +, 2}_1" means that the initial value of "b"
40 is the value of "a". In most of the cases these parametric chrecs
41 are fully instantiated before their use because symbolic names can
42 hide some difficult cases such as self-references described later
43 (see the Fibonacci example).
45 A short sketch of the algorithm is:
47 Given a scalar variable to be analyzed, follow the SSA edge to
48 its definition:
50 - When the definition is a GIMPLE_ASSIGN: if the right hand side
51 (RHS) of the definition cannot be statically analyzed, the answer
52 of the analyzer is: "don't know".
53 Otherwise, for all the variables that are not yet analyzed in the
54 RHS, try to determine their evolution, and finally try to
55 evaluate the operation of the RHS that gives the evolution
56 function of the analyzed variable.
58 - When the definition is a condition-phi-node: determine the
59 evolution function for all the branches of the phi node, and
60 finally merge these evolutions (see chrec_merge).
62 - When the definition is a loop-phi-node: determine its initial
63 condition, that is the SSA edge defined in an outer loop, and
64 keep it symbolic. Then determine the SSA edges that are defined
65 in the body of the loop. Follow the inner edges until ending on
66 another loop-phi-node of the same analyzed loop. If the reached
67 loop-phi-node is not the starting loop-phi-node, then we keep
68 this definition under a symbolic form. If the reached
69 loop-phi-node is the same as the starting one, then we compute a
70 symbolic stride on the return path. The result is then the
71 symbolic chrec {initial_condition, +, symbolic_stride}_loop.
73 Examples:
75 Example 1: Illustration of the basic algorithm.
77 | a = 3
78 | loop_1
79 | b = phi (a, c)
80 | c = b + 1
81 | if (c > 10) exit_loop
82 | endloop
84 Suppose that we want to know the number of iterations of the
85 loop_1. The exit_loop is controlled by a COND_EXPR (c > 10). We
86 ask the scalar evolution analyzer two questions: what's the
87 scalar evolution (scev) of "c", and what's the scev of "10". For
88 "10" the answer is "10" since it is a scalar constant. For the
89 scalar variable "c", it follows the SSA edge to its definition,
90 "c = b + 1", and then asks again what's the scev of "b".
91 Following the SSA edge, we end on a loop-phi-node "b = phi (a,
92 c)", where the initial condition is "a", and the inner loop edge
93 is "c". The initial condition is kept under a symbolic form (it
94 may be the case that the copy constant propagation has done its
95 work and we end with the constant "3" as one of the edges of the
96 loop-phi-node). The update edge is followed to the end of the
97 loop, and until reaching again the starting loop-phi-node: b -> c
98 -> b. At this point we have drawn a path from "b" to "b" from
99 which we compute the stride in the loop: in this example it is
100 "+1". The resulting scev for "b" is "b -> {a, +, 1}_1". Now
101 that the scev for "b" is known, it is possible to compute the
102 scev for "c", that is "c -> {a + 1, +, 1}_1". In order to
103 determine the number of iterations in the loop_1, we have to
104 instantiate_parameters (loop_1, {a + 1, +, 1}_1), that gives after some
105 more analysis the scev {4, +, 1}_1, or in other words, this is
106 the function "f (x) = x + 4", where x is the iteration count of
107 the loop_1. Now we have to solve the inequality "x + 4 > 10",
108 and take the smallest iteration number for which the loop is
109 exited: x = 7. This loop runs from x = 0 to x = 7, and in total
110 there are 8 iterations. In terms of loop normalization, we have
111 created a variable that is implicitly defined, "x" or just "_1",
112 and all the other analyzed scalars of the loop are defined in
113 function of this variable:
115 a -> 3
116 b -> {3, +, 1}_1
117 c -> {4, +, 1}_1
119 or in terms of a C program:
121 | a = 3
122 | for (x = 0; x <= 7; x++)
124 | b = x + 3
125 | c = x + 4
128 Example 2a: Illustration of the algorithm on nested loops.
130 | loop_1
131 | a = phi (1, b)
132 | c = a + 2
133 | loop_2 10 times
134 | b = phi (c, d)
135 | d = b + 3
136 | endloop
137 | endloop
139 For analyzing the scalar evolution of "a", the algorithm follows
140 the SSA edge into the loop's body: "a -> b". "b" is an inner
141 loop-phi-node, and its analysis as in Example 1, gives:
143 b -> {c, +, 3}_2
144 d -> {c + 3, +, 3}_2
146 Following the SSA edge for the initial condition, we end on "c = a
147 + 2", and then on the starting loop-phi-node "a". From this point,
148 the loop stride is computed: back on "c = a + 2" we get a "+2" in
149 the loop_1, then on the loop-phi-node "b" we compute the overall
150 effect of the inner loop that is "b = c + 30", and we get a "+30"
151 in the loop_1. That means that the overall stride in loop_1 is
152 equal to "+32", and the result is:
154 a -> {1, +, 32}_1
155 c -> {3, +, 32}_1
157 Example 2b: Multivariate chains of recurrences.
159 | loop_1
160 | k = phi (0, k + 1)
161 | loop_2 4 times
162 | j = phi (0, j + 1)
163 | loop_3 4 times
164 | i = phi (0, i + 1)
165 | A[j + k] = ...
166 | endloop
167 | endloop
168 | endloop
170 Analyzing the access function of array A with
171 instantiate_parameters (loop_1, "j + k"), we obtain the
172 instantiation and the analysis of the scalar variables "j" and "k"
173 in loop_1. This leads to the scalar evolution {4, +, 1}_1: the end
174 value of loop_2 for "j" is 4, and the evolution of "k" in loop_1 is
175 {0, +, 1}_1. To obtain the evolution function in loop_3 and
176 instantiate the scalar variables up to loop_1, one has to use:
177 instantiate_scev (block_before_loop (loop_1), loop_3, "j + k").
178 The result of this call is {{0, +, 1}_1, +, 1}_2.
180 Example 3: Higher degree polynomials.
182 | loop_1
183 | a = phi (2, b)
184 | c = phi (5, d)
185 | b = a + 1
186 | d = c + a
187 | endloop
189 a -> {2, +, 1}_1
190 b -> {3, +, 1}_1
191 c -> {5, +, a}_1
192 d -> {5 + a, +, a}_1
194 instantiate_parameters (loop_1, {5, +, a}_1) -> {5, +, 2, +, 1}_1
195 instantiate_parameters (loop_1, {5 + a, +, a}_1) -> {7, +, 3, +, 1}_1
197 Example 4: Lucas, Fibonacci, or mixers in general.
199 | loop_1
200 | a = phi (1, b)
201 | c = phi (3, d)
202 | b = c
203 | d = c + a
204 | endloop
206 a -> (1, c)_1
207 c -> {3, +, a}_1
209 The syntax "(1, c)_1" stands for a PEELED_CHREC that has the
210 following semantics: during the first iteration of the loop_1, the
211 variable contains the value 1, and then it contains the value "c".
212 Note that this syntax is close to the syntax of the loop-phi-node:
213 "a -> (1, c)_1" vs. "a = phi (1, c)".
215 The symbolic chrec representation contains all the semantics of the
216 original code. What is more difficult is to use this information.
218 Example 5: Flip-flops, or exchangers.
220 | loop_1
221 | a = phi (1, b)
222 | c = phi (3, d)
223 | b = c
224 | d = a
225 | endloop
227 a -> (1, c)_1
228 c -> (3, a)_1
230 Based on these symbolic chrecs, it is possible to refine this
231 information into the more precise PERIODIC_CHRECs:
233 a -> |1, 3|_1
234 c -> |3, 1|_1
236 This transformation is not yet implemented.
238 Further readings:
240 You can find a more detailed description of the algorithm in:
241 http://icps.u-strasbg.fr/~pop/DEA_03_Pop.pdf
242 http://icps.u-strasbg.fr/~pop/DEA_03_Pop.ps.gz. But note that
243 this is a preliminary report and some of the details of the
244 algorithm have changed. I'm working on a research report that
245 updates the description of the algorithms to reflect the design
246 choices used in this implementation.
248 A set of slides show a high level overview of the algorithm and run
249 an example through the scalar evolution analyzer:
250 http://cri.ensmp.fr/~pop/gcc/mar04/slides.pdf
252 The slides that I have presented at the GCC Summit'04 are available
253 at: http://cri.ensmp.fr/~pop/gcc/20040604/gccsummit-lno-spop.pdf
256 #include "config.h"
257 #include "system.h"
258 #include "coretypes.h"
259 #include "hash-table.h"
260 #include "gimple-pretty-print.h"
261 #include "tree-flow.h"
262 #include "cfgloop.h"
263 #include "tree-chrec.h"
264 #include "tree-scalar-evolution.h"
265 #include "dumpfile.h"
266 #include "params.h"
268 static tree analyze_scalar_evolution_1 (struct loop *, tree, tree);
269 static tree analyze_scalar_evolution_for_address_of (struct loop *loop,
270 tree var);
272 /* The cached information about an SSA name VAR, claiming that below
273 basic block INSTANTIATED_BELOW, the value of VAR can be expressed
274 as CHREC. */
276 struct GTY(()) scev_info_str {
277 basic_block instantiated_below;
278 tree var;
279 tree chrec;
282 /* Counters for the scev database. */
283 static unsigned nb_set_scev = 0;
284 static unsigned nb_get_scev = 0;
286 /* The following trees are unique elements. Thus the comparison of
287 another element to these elements should be done on the pointer to
288 these trees, and not on their value. */
290 /* The SSA_NAMEs that are not yet analyzed are qualified with NULL_TREE. */
291 tree chrec_not_analyzed_yet;
293 /* Reserved to the cases where the analyzer has detected an
294 undecidable property at compile time. */
295 tree chrec_dont_know;
297 /* When the analyzer has detected that a property will never
298 happen, then it qualifies it with chrec_known. */
299 tree chrec_known;
301 static GTY ((param_is (struct scev_info_str))) htab_t scalar_evolution_info;
304 /* Constructs a new SCEV_INFO_STR structure for VAR and INSTANTIATED_BELOW. */
306 static inline struct scev_info_str *
307 new_scev_info_str (basic_block instantiated_below, tree var)
309 struct scev_info_str *res;
311 res = ggc_alloc_scev_info_str ();
312 res->var = var;
313 res->chrec = chrec_not_analyzed_yet;
314 res->instantiated_below = instantiated_below;
316 return res;
319 /* Computes a hash function for database element ELT. */
321 static inline hashval_t
322 hash_scev_info (const void *elt)
324 return SSA_NAME_VERSION (((const struct scev_info_str *) elt)->var);
327 /* Compares database elements E1 and E2. */
329 static inline int
330 eq_scev_info (const void *e1, const void *e2)
332 const struct scev_info_str *elt1 = (const struct scev_info_str *) e1;
333 const struct scev_info_str *elt2 = (const struct scev_info_str *) e2;
335 return (elt1->var == elt2->var
336 && elt1->instantiated_below == elt2->instantiated_below);
339 /* Deletes database element E. */
341 static void
342 del_scev_info (void *e)
344 ggc_free (e);
348 /* Get the scalar evolution of VAR for INSTANTIATED_BELOW basic block.
349 A first query on VAR returns chrec_not_analyzed_yet. */
351 static tree *
352 find_var_scev_info (basic_block instantiated_below, tree var)
354 struct scev_info_str *res;
355 struct scev_info_str tmp;
356 PTR *slot;
358 tmp.var = var;
359 tmp.instantiated_below = instantiated_below;
360 slot = htab_find_slot (scalar_evolution_info, &tmp, INSERT);
362 if (!*slot)
363 *slot = new_scev_info_str (instantiated_below, var);
364 res = (struct scev_info_str *) *slot;
366 return &res->chrec;
369 /* Return true when CHREC contains symbolic names defined in
370 LOOP_NB. */
372 bool
373 chrec_contains_symbols_defined_in_loop (const_tree chrec, unsigned loop_nb)
375 int i, n;
377 if (chrec == NULL_TREE)
378 return false;
380 if (is_gimple_min_invariant (chrec))
381 return false;
383 if (TREE_CODE (chrec) == SSA_NAME)
385 gimple def;
386 loop_p def_loop, loop;
388 if (SSA_NAME_IS_DEFAULT_DEF (chrec))
389 return false;
391 def = SSA_NAME_DEF_STMT (chrec);
392 def_loop = loop_containing_stmt (def);
393 loop = get_loop (cfun, loop_nb);
395 if (def_loop == NULL)
396 return false;
398 if (loop == def_loop || flow_loop_nested_p (loop, def_loop))
399 return true;
401 return false;
404 n = TREE_OPERAND_LENGTH (chrec);
405 for (i = 0; i < n; i++)
406 if (chrec_contains_symbols_defined_in_loop (TREE_OPERAND (chrec, i),
407 loop_nb))
408 return true;
409 return false;
412 /* Return true when PHI is a loop-phi-node. */
414 static bool
415 loop_phi_node_p (gimple phi)
417 /* The implementation of this function is based on the following
418 property: "all the loop-phi-nodes of a loop are contained in the
419 loop's header basic block". */
421 return loop_containing_stmt (phi)->header == gimple_bb (phi);
424 /* Compute the scalar evolution for EVOLUTION_FN after crossing LOOP.
425 In general, in the case of multivariate evolutions we want to get
426 the evolution in different loops. LOOP specifies the level for
427 which to get the evolution.
429 Example:
431 | for (j = 0; j < 100; j++)
433 | for (k = 0; k < 100; k++)
435 | i = k + j; - Here the value of i is a function of j, k.
437 | ... = i - Here the value of i is a function of j.
439 | ... = i - Here the value of i is a scalar.
441 Example:
443 | i_0 = ...
444 | loop_1 10 times
445 | i_1 = phi (i_0, i_2)
446 | i_2 = i_1 + 2
447 | endloop
449 This loop has the same effect as:
450 LOOP_1 has the same effect as:
452 | i_1 = i_0 + 20
454 The overall effect of the loop, "i_0 + 20" in the previous example,
455 is obtained by passing in the parameters: LOOP = 1,
456 EVOLUTION_FN = {i_0, +, 2}_1.
459 tree
460 compute_overall_effect_of_inner_loop (struct loop *loop, tree evolution_fn)
462 bool val = false;
464 if (evolution_fn == chrec_dont_know)
465 return chrec_dont_know;
467 else if (TREE_CODE (evolution_fn) == POLYNOMIAL_CHREC)
469 struct loop *inner_loop = get_chrec_loop (evolution_fn);
471 if (inner_loop == loop
472 || flow_loop_nested_p (loop, inner_loop))
474 tree nb_iter = number_of_latch_executions (inner_loop);
476 if (nb_iter == chrec_dont_know)
477 return chrec_dont_know;
478 else
480 tree res;
482 /* evolution_fn is the evolution function in LOOP. Get
483 its value in the nb_iter-th iteration. */
484 res = chrec_apply (inner_loop->num, evolution_fn, nb_iter);
486 if (chrec_contains_symbols_defined_in_loop (res, loop->num))
487 res = instantiate_parameters (loop, res);
489 /* Continue the computation until ending on a parent of LOOP. */
490 return compute_overall_effect_of_inner_loop (loop, res);
493 else
494 return evolution_fn;
497 /* If the evolution function is an invariant, there is nothing to do. */
498 else if (no_evolution_in_loop_p (evolution_fn, loop->num, &val) && val)
499 return evolution_fn;
501 else
502 return chrec_dont_know;
505 /* Associate CHREC to SCALAR. */
507 static void
508 set_scalar_evolution (basic_block instantiated_below, tree scalar, tree chrec)
510 tree *scalar_info;
512 if (TREE_CODE (scalar) != SSA_NAME)
513 return;
515 scalar_info = find_var_scev_info (instantiated_below, scalar);
517 if (dump_file)
519 if (dump_flags & TDF_SCEV)
521 fprintf (dump_file, "(set_scalar_evolution \n");
522 fprintf (dump_file, " instantiated_below = %d \n",
523 instantiated_below->index);
524 fprintf (dump_file, " (scalar = ");
525 print_generic_expr (dump_file, scalar, 0);
526 fprintf (dump_file, ")\n (scalar_evolution = ");
527 print_generic_expr (dump_file, chrec, 0);
528 fprintf (dump_file, "))\n");
530 if (dump_flags & TDF_STATS)
531 nb_set_scev++;
534 *scalar_info = chrec;
537 /* Retrieve the chrec associated to SCALAR instantiated below
538 INSTANTIATED_BELOW block. */
540 static tree
541 get_scalar_evolution (basic_block instantiated_below, tree scalar)
543 tree res;
545 if (dump_file)
547 if (dump_flags & TDF_SCEV)
549 fprintf (dump_file, "(get_scalar_evolution \n");
550 fprintf (dump_file, " (scalar = ");
551 print_generic_expr (dump_file, scalar, 0);
552 fprintf (dump_file, ")\n");
554 if (dump_flags & TDF_STATS)
555 nb_get_scev++;
558 switch (TREE_CODE (scalar))
560 case SSA_NAME:
561 res = *find_var_scev_info (instantiated_below, scalar);
562 break;
564 case REAL_CST:
565 case FIXED_CST:
566 case INTEGER_CST:
567 res = scalar;
568 break;
570 default:
571 res = chrec_not_analyzed_yet;
572 break;
575 if (dump_file && (dump_flags & TDF_SCEV))
577 fprintf (dump_file, " (scalar_evolution = ");
578 print_generic_expr (dump_file, res, 0);
579 fprintf (dump_file, "))\n");
582 return res;
585 /* Helper function for add_to_evolution. Returns the evolution
586 function for an assignment of the form "a = b + c", where "a" and
587 "b" are on the strongly connected component. CHREC_BEFORE is the
588 information that we already have collected up to this point.
589 TO_ADD is the evolution of "c".
591 When CHREC_BEFORE has an evolution part in LOOP_NB, add to this
592 evolution the expression TO_ADD, otherwise construct an evolution
593 part for this loop. */
595 static tree
596 add_to_evolution_1 (unsigned loop_nb, tree chrec_before, tree to_add,
597 gimple at_stmt)
599 tree type, left, right;
600 struct loop *loop = get_loop (cfun, loop_nb), *chloop;
602 switch (TREE_CODE (chrec_before))
604 case POLYNOMIAL_CHREC:
605 chloop = get_chrec_loop (chrec_before);
606 if (chloop == loop
607 || flow_loop_nested_p (chloop, loop))
609 unsigned var;
611 type = chrec_type (chrec_before);
613 /* When there is no evolution part in this loop, build it. */
614 if (chloop != loop)
616 var = loop_nb;
617 left = chrec_before;
618 right = SCALAR_FLOAT_TYPE_P (type)
619 ? build_real (type, dconst0)
620 : build_int_cst (type, 0);
622 else
624 var = CHREC_VARIABLE (chrec_before);
625 left = CHREC_LEFT (chrec_before);
626 right = CHREC_RIGHT (chrec_before);
629 to_add = chrec_convert (type, to_add, at_stmt);
630 right = chrec_convert_rhs (type, right, at_stmt);
631 right = chrec_fold_plus (chrec_type (right), right, to_add);
632 return build_polynomial_chrec (var, left, right);
634 else
636 gcc_assert (flow_loop_nested_p (loop, chloop));
638 /* Search the evolution in LOOP_NB. */
639 left = add_to_evolution_1 (loop_nb, CHREC_LEFT (chrec_before),
640 to_add, at_stmt);
641 right = CHREC_RIGHT (chrec_before);
642 right = chrec_convert_rhs (chrec_type (left), right, at_stmt);
643 return build_polynomial_chrec (CHREC_VARIABLE (chrec_before),
644 left, right);
647 default:
648 /* These nodes do not depend on a loop. */
649 if (chrec_before == chrec_dont_know)
650 return chrec_dont_know;
652 left = chrec_before;
653 right = chrec_convert_rhs (chrec_type (left), to_add, at_stmt);
654 return build_polynomial_chrec (loop_nb, left, right);
658 /* Add TO_ADD to the evolution part of CHREC_BEFORE in the dimension
659 of LOOP_NB.
661 Description (provided for completeness, for those who read code in
662 a plane, and for my poor 62 bytes brain that would have forgotten
663 all this in the next two or three months):
665 The algorithm of translation of programs from the SSA representation
666 into the chrecs syntax is based on a pattern matching. After having
667 reconstructed the overall tree expression for a loop, there are only
668 two cases that can arise:
670 1. a = loop-phi (init, a + expr)
671 2. a = loop-phi (init, expr)
673 where EXPR is either a scalar constant with respect to the analyzed
674 loop (this is a degree 0 polynomial), or an expression containing
675 other loop-phi definitions (these are higher degree polynomials).
677 Examples:
680 | init = ...
681 | loop_1
682 | a = phi (init, a + 5)
683 | endloop
686 | inita = ...
687 | initb = ...
688 | loop_1
689 | a = phi (inita, 2 * b + 3)
690 | b = phi (initb, b + 1)
691 | endloop
693 For the first case, the semantics of the SSA representation is:
695 | a (x) = init + \sum_{j = 0}^{x - 1} expr (j)
697 that is, there is a loop index "x" that determines the scalar value
698 of the variable during the loop execution. During the first
699 iteration, the value is that of the initial condition INIT, while
700 during the subsequent iterations, it is the sum of the initial
701 condition with the sum of all the values of EXPR from the initial
702 iteration to the before last considered iteration.
704 For the second case, the semantics of the SSA program is:
706 | a (x) = init, if x = 0;
707 | expr (x - 1), otherwise.
709 The second case corresponds to the PEELED_CHREC, whose syntax is
710 close to the syntax of a loop-phi-node:
712 | phi (init, expr) vs. (init, expr)_x
714 The proof of the translation algorithm for the first case is a
715 proof by structural induction based on the degree of EXPR.
717 Degree 0:
718 When EXPR is a constant with respect to the analyzed loop, or in
719 other words when EXPR is a polynomial of degree 0, the evolution of
720 the variable A in the loop is an affine function with an initial
721 condition INIT, and a step EXPR. In order to show this, we start
722 from the semantics of the SSA representation:
724 f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
726 and since "expr (j)" is a constant with respect to "j",
728 f (x) = init + x * expr
730 Finally, based on the semantics of the pure sum chrecs, by
731 identification we get the corresponding chrecs syntax:
733 f (x) = init * \binom{x}{0} + expr * \binom{x}{1}
734 f (x) -> {init, +, expr}_x
736 Higher degree:
737 Suppose that EXPR is a polynomial of degree N with respect to the
738 analyzed loop_x for which we have already determined that it is
739 written under the chrecs syntax:
741 | expr (x) -> {b_0, +, b_1, +, ..., +, b_{n-1}} (x)
743 We start from the semantics of the SSA program:
745 | f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
747 | f (x) = init + \sum_{j = 0}^{x - 1}
748 | (b_0 * \binom{j}{0} + ... + b_{n-1} * \binom{j}{n-1})
750 | f (x) = init + \sum_{j = 0}^{x - 1}
751 | \sum_{k = 0}^{n - 1} (b_k * \binom{j}{k})
753 | f (x) = init + \sum_{k = 0}^{n - 1}
754 | (b_k * \sum_{j = 0}^{x - 1} \binom{j}{k})
756 | f (x) = init + \sum_{k = 0}^{n - 1}
757 | (b_k * \binom{x}{k + 1})
759 | f (x) = init + b_0 * \binom{x}{1} + ...
760 | + b_{n-1} * \binom{x}{n}
762 | f (x) = init * \binom{x}{0} + b_0 * \binom{x}{1} + ...
763 | + b_{n-1} * \binom{x}{n}
766 And finally from the definition of the chrecs syntax, we identify:
767 | f (x) -> {init, +, b_0, +, ..., +, b_{n-1}}_x
769 This shows the mechanism that stands behind the add_to_evolution
770 function. An important point is that the use of symbolic
771 parameters avoids the need of an analysis schedule.
773 Example:
775 | inita = ...
776 | initb = ...
777 | loop_1
778 | a = phi (inita, a + 2 + b)
779 | b = phi (initb, b + 1)
780 | endloop
782 When analyzing "a", the algorithm keeps "b" symbolically:
784 | a -> {inita, +, 2 + b}_1
786 Then, after instantiation, the analyzer ends on the evolution:
788 | a -> {inita, +, 2 + initb, +, 1}_1
792 static tree
793 add_to_evolution (unsigned loop_nb, tree chrec_before, enum tree_code code,
794 tree to_add, gimple at_stmt)
796 tree type = chrec_type (to_add);
797 tree res = NULL_TREE;
799 if (to_add == NULL_TREE)
800 return chrec_before;
802 /* TO_ADD is either a scalar, or a parameter. TO_ADD is not
803 instantiated at this point. */
804 if (TREE_CODE (to_add) == POLYNOMIAL_CHREC)
805 /* This should not happen. */
806 return chrec_dont_know;
808 if (dump_file && (dump_flags & TDF_SCEV))
810 fprintf (dump_file, "(add_to_evolution \n");
811 fprintf (dump_file, " (loop_nb = %d)\n", loop_nb);
812 fprintf (dump_file, " (chrec_before = ");
813 print_generic_expr (dump_file, chrec_before, 0);
814 fprintf (dump_file, ")\n (to_add = ");
815 print_generic_expr (dump_file, to_add, 0);
816 fprintf (dump_file, ")\n");
819 if (code == MINUS_EXPR)
820 to_add = chrec_fold_multiply (type, to_add, SCALAR_FLOAT_TYPE_P (type)
821 ? build_real (type, dconstm1)
822 : build_int_cst_type (type, -1));
824 res = add_to_evolution_1 (loop_nb, chrec_before, to_add, at_stmt);
826 if (dump_file && (dump_flags & TDF_SCEV))
828 fprintf (dump_file, " (res = ");
829 print_generic_expr (dump_file, res, 0);
830 fprintf (dump_file, "))\n");
833 return res;
838 /* This section selects the loops that will be good candidates for the
839 scalar evolution analysis. For the moment, greedily select all the
840 loop nests we could analyze. */
842 /* For a loop with a single exit edge, return the COND_EXPR that
843 guards the exit edge. If the expression is too difficult to
844 analyze, then give up. */
846 gimple
847 get_loop_exit_condition (const struct loop *loop)
849 gimple res = NULL;
850 edge exit_edge = single_exit (loop);
852 if (dump_file && (dump_flags & TDF_SCEV))
853 fprintf (dump_file, "(get_loop_exit_condition \n ");
855 if (exit_edge)
857 gimple stmt;
859 stmt = last_stmt (exit_edge->src);
860 if (gimple_code (stmt) == GIMPLE_COND)
861 res = stmt;
864 if (dump_file && (dump_flags & TDF_SCEV))
866 print_gimple_stmt (dump_file, res, 0, 0);
867 fprintf (dump_file, ")\n");
870 return res;
874 /* Depth first search algorithm. */
876 typedef enum t_bool {
877 t_false,
878 t_true,
879 t_dont_know
880 } t_bool;
883 static t_bool follow_ssa_edge (struct loop *loop, gimple, gimple, tree *, int);
885 /* Follow the ssa edge into the binary expression RHS0 CODE RHS1.
886 Return true if the strongly connected component has been found. */
888 static t_bool
889 follow_ssa_edge_binary (struct loop *loop, gimple at_stmt,
890 tree type, tree rhs0, enum tree_code code, tree rhs1,
891 gimple halting_phi, tree *evolution_of_loop, int limit)
893 t_bool res = t_false;
894 tree evol;
896 switch (code)
898 case POINTER_PLUS_EXPR:
899 case PLUS_EXPR:
900 if (TREE_CODE (rhs0) == SSA_NAME)
902 if (TREE_CODE (rhs1) == SSA_NAME)
904 /* Match an assignment under the form:
905 "a = b + c". */
907 /* We want only assignments of form "name + name" contribute to
908 LIMIT, as the other cases do not necessarily contribute to
909 the complexity of the expression. */
910 limit++;
912 evol = *evolution_of_loop;
913 res = follow_ssa_edge
914 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi, &evol, limit);
916 if (res == t_true)
917 *evolution_of_loop = add_to_evolution
918 (loop->num,
919 chrec_convert (type, evol, at_stmt),
920 code, rhs1, at_stmt);
922 else if (res == t_false)
924 res = follow_ssa_edge
925 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
926 evolution_of_loop, limit);
928 if (res == t_true)
929 *evolution_of_loop = add_to_evolution
930 (loop->num,
931 chrec_convert (type, *evolution_of_loop, at_stmt),
932 code, rhs0, at_stmt);
934 else if (res == t_dont_know)
935 *evolution_of_loop = chrec_dont_know;
938 else if (res == t_dont_know)
939 *evolution_of_loop = chrec_dont_know;
942 else
944 /* Match an assignment under the form:
945 "a = b + ...". */
946 res = follow_ssa_edge
947 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
948 evolution_of_loop, limit);
949 if (res == t_true)
950 *evolution_of_loop = add_to_evolution
951 (loop->num, chrec_convert (type, *evolution_of_loop,
952 at_stmt),
953 code, rhs1, at_stmt);
955 else if (res == t_dont_know)
956 *evolution_of_loop = chrec_dont_know;
960 else if (TREE_CODE (rhs1) == SSA_NAME)
962 /* Match an assignment under the form:
963 "a = ... + c". */
964 res = follow_ssa_edge
965 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
966 evolution_of_loop, limit);
967 if (res == t_true)
968 *evolution_of_loop = add_to_evolution
969 (loop->num, chrec_convert (type, *evolution_of_loop,
970 at_stmt),
971 code, rhs0, at_stmt);
973 else if (res == t_dont_know)
974 *evolution_of_loop = chrec_dont_know;
977 else
978 /* Otherwise, match an assignment under the form:
979 "a = ... + ...". */
980 /* And there is nothing to do. */
981 res = t_false;
982 break;
984 case MINUS_EXPR:
985 /* This case is under the form "opnd0 = rhs0 - rhs1". */
986 if (TREE_CODE (rhs0) == SSA_NAME)
988 /* Match an assignment under the form:
989 "a = b - ...". */
991 /* We want only assignments of form "name - name" contribute to
992 LIMIT, as the other cases do not necessarily contribute to
993 the complexity of the expression. */
994 if (TREE_CODE (rhs1) == SSA_NAME)
995 limit++;
997 res = follow_ssa_edge (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
998 evolution_of_loop, limit);
999 if (res == t_true)
1000 *evolution_of_loop = add_to_evolution
1001 (loop->num, chrec_convert (type, *evolution_of_loop, at_stmt),
1002 MINUS_EXPR, rhs1, at_stmt);
1004 else if (res == t_dont_know)
1005 *evolution_of_loop = chrec_dont_know;
1007 else
1008 /* Otherwise, match an assignment under the form:
1009 "a = ... - ...". */
1010 /* And there is nothing to do. */
1011 res = t_false;
1012 break;
1014 default:
1015 res = t_false;
1018 return res;
1021 /* Follow the ssa edge into the expression EXPR.
1022 Return true if the strongly connected component has been found. */
1024 static t_bool
1025 follow_ssa_edge_expr (struct loop *loop, gimple at_stmt, tree expr,
1026 gimple halting_phi, tree *evolution_of_loop, int limit)
1028 enum tree_code code = TREE_CODE (expr);
1029 tree type = TREE_TYPE (expr), rhs0, rhs1;
1030 t_bool res;
1032 /* The EXPR is one of the following cases:
1033 - an SSA_NAME,
1034 - an INTEGER_CST,
1035 - a PLUS_EXPR,
1036 - a POINTER_PLUS_EXPR,
1037 - a MINUS_EXPR,
1038 - an ASSERT_EXPR,
1039 - other cases are not yet handled. */
1041 switch (code)
1043 CASE_CONVERT:
1044 /* This assignment is under the form "a_1 = (cast) rhs. */
1045 res = follow_ssa_edge_expr (loop, at_stmt, TREE_OPERAND (expr, 0),
1046 halting_phi, evolution_of_loop, limit);
1047 *evolution_of_loop = chrec_convert (type, *evolution_of_loop, at_stmt);
1048 break;
1050 case INTEGER_CST:
1051 /* This assignment is under the form "a_1 = 7". */
1052 res = t_false;
1053 break;
1055 case SSA_NAME:
1056 /* This assignment is under the form: "a_1 = b_2". */
1057 res = follow_ssa_edge
1058 (loop, SSA_NAME_DEF_STMT (expr), halting_phi, evolution_of_loop, limit);
1059 break;
1061 case POINTER_PLUS_EXPR:
1062 case PLUS_EXPR:
1063 case MINUS_EXPR:
1064 /* This case is under the form "rhs0 +- rhs1". */
1065 rhs0 = TREE_OPERAND (expr, 0);
1066 rhs1 = TREE_OPERAND (expr, 1);
1067 type = TREE_TYPE (rhs0);
1068 STRIP_USELESS_TYPE_CONVERSION (rhs0);
1069 STRIP_USELESS_TYPE_CONVERSION (rhs1);
1070 res = follow_ssa_edge_binary (loop, at_stmt, type, rhs0, code, rhs1,
1071 halting_phi, evolution_of_loop, limit);
1072 break;
1074 case ADDR_EXPR:
1075 /* Handle &MEM[ptr + CST] which is equivalent to POINTER_PLUS_EXPR. */
1076 if (TREE_CODE (TREE_OPERAND (expr, 0)) == MEM_REF)
1078 expr = TREE_OPERAND (expr, 0);
1079 rhs0 = TREE_OPERAND (expr, 0);
1080 rhs1 = TREE_OPERAND (expr, 1);
1081 type = TREE_TYPE (rhs0);
1082 STRIP_USELESS_TYPE_CONVERSION (rhs0);
1083 STRIP_USELESS_TYPE_CONVERSION (rhs1);
1084 res = follow_ssa_edge_binary (loop, at_stmt, type,
1085 rhs0, POINTER_PLUS_EXPR, rhs1,
1086 halting_phi, evolution_of_loop, limit);
1088 else
1089 res = t_false;
1090 break;
1092 case ASSERT_EXPR:
1093 /* This assignment is of the form: "a_1 = ASSERT_EXPR <a_2, ...>"
1094 It must be handled as a copy assignment of the form a_1 = a_2. */
1095 rhs0 = ASSERT_EXPR_VAR (expr);
1096 if (TREE_CODE (rhs0) == SSA_NAME)
1097 res = follow_ssa_edge (loop, SSA_NAME_DEF_STMT (rhs0),
1098 halting_phi, evolution_of_loop, limit);
1099 else
1100 res = t_false;
1101 break;
1103 default:
1104 res = t_false;
1105 break;
1108 return res;
1111 /* Follow the ssa edge into the right hand side of an assignment STMT.
1112 Return true if the strongly connected component has been found. */
1114 static t_bool
1115 follow_ssa_edge_in_rhs (struct loop *loop, gimple stmt,
1116 gimple halting_phi, tree *evolution_of_loop, int limit)
1118 enum tree_code code = gimple_assign_rhs_code (stmt);
1119 tree type = gimple_expr_type (stmt), rhs1, rhs2;
1120 t_bool res;
1122 switch (code)
1124 CASE_CONVERT:
1125 /* This assignment is under the form "a_1 = (cast) rhs. */
1126 res = follow_ssa_edge_expr (loop, stmt, gimple_assign_rhs1 (stmt),
1127 halting_phi, evolution_of_loop, limit);
1128 *evolution_of_loop = chrec_convert (type, *evolution_of_loop, stmt);
1129 break;
1131 case POINTER_PLUS_EXPR:
1132 case PLUS_EXPR:
1133 case MINUS_EXPR:
1134 rhs1 = gimple_assign_rhs1 (stmt);
1135 rhs2 = gimple_assign_rhs2 (stmt);
1136 type = TREE_TYPE (rhs1);
1137 res = follow_ssa_edge_binary (loop, stmt, type, rhs1, code, rhs2,
1138 halting_phi, evolution_of_loop, limit);
1139 break;
1141 default:
1142 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1143 res = follow_ssa_edge_expr (loop, stmt, gimple_assign_rhs1 (stmt),
1144 halting_phi, evolution_of_loop, limit);
1145 else
1146 res = t_false;
1147 break;
1150 return res;
1153 /* Checks whether the I-th argument of a PHI comes from a backedge. */
1155 static bool
1156 backedge_phi_arg_p (gimple phi, int i)
1158 const_edge e = gimple_phi_arg_edge (phi, i);
1160 /* We would in fact like to test EDGE_DFS_BACK here, but we do not care
1161 about updating it anywhere, and this should work as well most of the
1162 time. */
1163 if (e->flags & EDGE_IRREDUCIBLE_LOOP)
1164 return true;
1166 return false;
1169 /* Helper function for one branch of the condition-phi-node. Return
1170 true if the strongly connected component has been found following
1171 this path. */
1173 static inline t_bool
1174 follow_ssa_edge_in_condition_phi_branch (int i,
1175 struct loop *loop,
1176 gimple condition_phi,
1177 gimple halting_phi,
1178 tree *evolution_of_branch,
1179 tree init_cond, int limit)
1181 tree branch = PHI_ARG_DEF (condition_phi, i);
1182 *evolution_of_branch = chrec_dont_know;
1184 /* Do not follow back edges (they must belong to an irreducible loop, which
1185 we really do not want to worry about). */
1186 if (backedge_phi_arg_p (condition_phi, i))
1187 return t_false;
1189 if (TREE_CODE (branch) == SSA_NAME)
1191 *evolution_of_branch = init_cond;
1192 return follow_ssa_edge (loop, SSA_NAME_DEF_STMT (branch), halting_phi,
1193 evolution_of_branch, limit);
1196 /* This case occurs when one of the condition branches sets
1197 the variable to a constant: i.e. a phi-node like
1198 "a_2 = PHI <a_7(5), 2(6)>;".
1200 FIXME: This case have to be refined correctly:
1201 in some cases it is possible to say something better than
1202 chrec_dont_know, for example using a wrap-around notation. */
1203 return t_false;
1206 /* This function merges the branches of a condition-phi-node in a
1207 loop. */
1209 static t_bool
1210 follow_ssa_edge_in_condition_phi (struct loop *loop,
1211 gimple condition_phi,
1212 gimple halting_phi,
1213 tree *evolution_of_loop, int limit)
1215 int i, n;
1216 tree init = *evolution_of_loop;
1217 tree evolution_of_branch;
1218 t_bool res = follow_ssa_edge_in_condition_phi_branch (0, loop, condition_phi,
1219 halting_phi,
1220 &evolution_of_branch,
1221 init, limit);
1222 if (res == t_false || res == t_dont_know)
1223 return res;
1225 *evolution_of_loop = evolution_of_branch;
1227 n = gimple_phi_num_args (condition_phi);
1228 for (i = 1; i < n; i++)
1230 /* Quickly give up when the evolution of one of the branches is
1231 not known. */
1232 if (*evolution_of_loop == chrec_dont_know)
1233 return t_true;
1235 /* Increase the limit by the PHI argument number to avoid exponential
1236 time and memory complexity. */
1237 res = follow_ssa_edge_in_condition_phi_branch (i, loop, condition_phi,
1238 halting_phi,
1239 &evolution_of_branch,
1240 init, limit + i);
1241 if (res == t_false || res == t_dont_know)
1242 return res;
1244 *evolution_of_loop = chrec_merge (*evolution_of_loop,
1245 evolution_of_branch);
1248 return t_true;
1251 /* Follow an SSA edge in an inner loop. It computes the overall
1252 effect of the loop, and following the symbolic initial conditions,
1253 it follows the edges in the parent loop. The inner loop is
1254 considered as a single statement. */
1256 static t_bool
1257 follow_ssa_edge_inner_loop_phi (struct loop *outer_loop,
1258 gimple loop_phi_node,
1259 gimple halting_phi,
1260 tree *evolution_of_loop, int limit)
1262 struct loop *loop = loop_containing_stmt (loop_phi_node);
1263 tree ev = analyze_scalar_evolution (loop, PHI_RESULT (loop_phi_node));
1265 /* Sometimes, the inner loop is too difficult to analyze, and the
1266 result of the analysis is a symbolic parameter. */
1267 if (ev == PHI_RESULT (loop_phi_node))
1269 t_bool res = t_false;
1270 int i, n = gimple_phi_num_args (loop_phi_node);
1272 for (i = 0; i < n; i++)
1274 tree arg = PHI_ARG_DEF (loop_phi_node, i);
1275 basic_block bb;
1277 /* Follow the edges that exit the inner loop. */
1278 bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1279 if (!flow_bb_inside_loop_p (loop, bb))
1280 res = follow_ssa_edge_expr (outer_loop, loop_phi_node,
1281 arg, halting_phi,
1282 evolution_of_loop, limit);
1283 if (res == t_true)
1284 break;
1287 /* If the path crosses this loop-phi, give up. */
1288 if (res == t_true)
1289 *evolution_of_loop = chrec_dont_know;
1291 return res;
1294 /* Otherwise, compute the overall effect of the inner loop. */
1295 ev = compute_overall_effect_of_inner_loop (loop, ev);
1296 return follow_ssa_edge_expr (outer_loop, loop_phi_node, ev, halting_phi,
1297 evolution_of_loop, limit);
1300 /* Follow an SSA edge from a loop-phi-node to itself, constructing a
1301 path that is analyzed on the return walk. */
1303 static t_bool
1304 follow_ssa_edge (struct loop *loop, gimple def, gimple halting_phi,
1305 tree *evolution_of_loop, int limit)
1307 struct loop *def_loop;
1309 if (gimple_nop_p (def))
1310 return t_false;
1312 /* Give up if the path is longer than the MAX that we allow. */
1313 if (limit > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_COMPLEXITY))
1314 return t_dont_know;
1316 def_loop = loop_containing_stmt (def);
1318 switch (gimple_code (def))
1320 case GIMPLE_PHI:
1321 if (!loop_phi_node_p (def))
1322 /* DEF is a condition-phi-node. Follow the branches, and
1323 record their evolutions. Finally, merge the collected
1324 information and set the approximation to the main
1325 variable. */
1326 return follow_ssa_edge_in_condition_phi
1327 (loop, def, halting_phi, evolution_of_loop, limit);
1329 /* When the analyzed phi is the halting_phi, the
1330 depth-first search is over: we have found a path from
1331 the halting_phi to itself in the loop. */
1332 if (def == halting_phi)
1333 return t_true;
1335 /* Otherwise, the evolution of the HALTING_PHI depends
1336 on the evolution of another loop-phi-node, i.e. the
1337 evolution function is a higher degree polynomial. */
1338 if (def_loop == loop)
1339 return t_false;
1341 /* Inner loop. */
1342 if (flow_loop_nested_p (loop, def_loop))
1343 return follow_ssa_edge_inner_loop_phi
1344 (loop, def, halting_phi, evolution_of_loop, limit + 1);
1346 /* Outer loop. */
1347 return t_false;
1349 case GIMPLE_ASSIGN:
1350 return follow_ssa_edge_in_rhs (loop, def, halting_phi,
1351 evolution_of_loop, limit);
1353 default:
1354 /* At this level of abstraction, the program is just a set
1355 of GIMPLE_ASSIGNs and PHI_NODEs. In principle there is no
1356 other node to be handled. */
1357 return t_false;
1363 /* Given a LOOP_PHI_NODE, this function determines the evolution
1364 function from LOOP_PHI_NODE to LOOP_PHI_NODE in the loop. */
1366 static tree
1367 analyze_evolution_in_loop (gimple loop_phi_node,
1368 tree init_cond)
1370 int i, n = gimple_phi_num_args (loop_phi_node);
1371 tree evolution_function = chrec_not_analyzed_yet;
1372 struct loop *loop = loop_containing_stmt (loop_phi_node);
1373 basic_block bb;
1375 if (dump_file && (dump_flags & TDF_SCEV))
1377 fprintf (dump_file, "(analyze_evolution_in_loop \n");
1378 fprintf (dump_file, " (loop_phi_node = ");
1379 print_gimple_stmt (dump_file, loop_phi_node, 0, 0);
1380 fprintf (dump_file, ")\n");
1383 for (i = 0; i < n; i++)
1385 tree arg = PHI_ARG_DEF (loop_phi_node, i);
1386 gimple ssa_chain;
1387 tree ev_fn;
1388 t_bool res;
1390 /* Select the edges that enter the loop body. */
1391 bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1392 if (!flow_bb_inside_loop_p (loop, bb))
1393 continue;
1395 if (TREE_CODE (arg) == SSA_NAME)
1397 bool val = false;
1399 ssa_chain = SSA_NAME_DEF_STMT (arg);
1401 /* Pass in the initial condition to the follow edge function. */
1402 ev_fn = init_cond;
1403 res = follow_ssa_edge (loop, ssa_chain, loop_phi_node, &ev_fn, 0);
1405 /* If ev_fn has no evolution in the inner loop, and the
1406 init_cond is not equal to ev_fn, then we have an
1407 ambiguity between two possible values, as we cannot know
1408 the number of iterations at this point. */
1409 if (TREE_CODE (ev_fn) != POLYNOMIAL_CHREC
1410 && no_evolution_in_loop_p (ev_fn, loop->num, &val) && val
1411 && !operand_equal_p (init_cond, ev_fn, 0))
1412 ev_fn = chrec_dont_know;
1414 else
1415 res = t_false;
1417 /* When it is impossible to go back on the same
1418 loop_phi_node by following the ssa edges, the
1419 evolution is represented by a peeled chrec, i.e. the
1420 first iteration, EV_FN has the value INIT_COND, then
1421 all the other iterations it has the value of ARG.
1422 For the moment, PEELED_CHREC nodes are not built. */
1423 if (res != t_true)
1424 ev_fn = chrec_dont_know;
1426 /* When there are multiple back edges of the loop (which in fact never
1427 happens currently, but nevertheless), merge their evolutions. */
1428 evolution_function = chrec_merge (evolution_function, ev_fn);
1431 if (dump_file && (dump_flags & TDF_SCEV))
1433 fprintf (dump_file, " (evolution_function = ");
1434 print_generic_expr (dump_file, evolution_function, 0);
1435 fprintf (dump_file, "))\n");
1438 return evolution_function;
1441 /* Given a loop-phi-node, return the initial conditions of the
1442 variable on entry of the loop. When the CCP has propagated
1443 constants into the loop-phi-node, the initial condition is
1444 instantiated, otherwise the initial condition is kept symbolic.
1445 This analyzer does not analyze the evolution outside the current
1446 loop, and leaves this task to the on-demand tree reconstructor. */
1448 static tree
1449 analyze_initial_condition (gimple loop_phi_node)
1451 int i, n;
1452 tree init_cond = chrec_not_analyzed_yet;
1453 struct loop *loop = loop_containing_stmt (loop_phi_node);
1455 if (dump_file && (dump_flags & TDF_SCEV))
1457 fprintf (dump_file, "(analyze_initial_condition \n");
1458 fprintf (dump_file, " (loop_phi_node = \n");
1459 print_gimple_stmt (dump_file, loop_phi_node, 0, 0);
1460 fprintf (dump_file, ")\n");
1463 n = gimple_phi_num_args (loop_phi_node);
1464 for (i = 0; i < n; i++)
1466 tree branch = PHI_ARG_DEF (loop_phi_node, i);
1467 basic_block bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1469 /* When the branch is oriented to the loop's body, it does
1470 not contribute to the initial condition. */
1471 if (flow_bb_inside_loop_p (loop, bb))
1472 continue;
1474 if (init_cond == chrec_not_analyzed_yet)
1476 init_cond = branch;
1477 continue;
1480 if (TREE_CODE (branch) == SSA_NAME)
1482 init_cond = chrec_dont_know;
1483 break;
1486 init_cond = chrec_merge (init_cond, branch);
1489 /* Ooops -- a loop without an entry??? */
1490 if (init_cond == chrec_not_analyzed_yet)
1491 init_cond = chrec_dont_know;
1493 /* During early loop unrolling we do not have fully constant propagated IL.
1494 Handle degenerate PHIs here to not miss important unrollings. */
1495 if (TREE_CODE (init_cond) == SSA_NAME)
1497 gimple def = SSA_NAME_DEF_STMT (init_cond);
1498 tree res;
1499 if (gimple_code (def) == GIMPLE_PHI
1500 && (res = degenerate_phi_result (def)) != NULL_TREE
1501 /* Only allow invariants here, otherwise we may break
1502 loop-closed SSA form. */
1503 && is_gimple_min_invariant (res))
1504 init_cond = res;
1507 if (dump_file && (dump_flags & TDF_SCEV))
1509 fprintf (dump_file, " (init_cond = ");
1510 print_generic_expr (dump_file, init_cond, 0);
1511 fprintf (dump_file, "))\n");
1514 return init_cond;
1517 /* Analyze the scalar evolution for LOOP_PHI_NODE. */
1519 static tree
1520 interpret_loop_phi (struct loop *loop, gimple loop_phi_node)
1522 tree res;
1523 struct loop *phi_loop = loop_containing_stmt (loop_phi_node);
1524 tree init_cond;
1526 if (phi_loop != loop)
1528 struct loop *subloop;
1529 tree evolution_fn = analyze_scalar_evolution
1530 (phi_loop, PHI_RESULT (loop_phi_node));
1532 /* Dive one level deeper. */
1533 subloop = superloop_at_depth (phi_loop, loop_depth (loop) + 1);
1535 /* Interpret the subloop. */
1536 res = compute_overall_effect_of_inner_loop (subloop, evolution_fn);
1537 return res;
1540 /* Otherwise really interpret the loop phi. */
1541 init_cond = analyze_initial_condition (loop_phi_node);
1542 res = analyze_evolution_in_loop (loop_phi_node, init_cond);
1544 /* Verify we maintained the correct initial condition throughout
1545 possible conversions in the SSA chain. */
1546 if (res != chrec_dont_know)
1548 tree new_init = res;
1549 if (CONVERT_EXPR_P (res)
1550 && TREE_CODE (TREE_OPERAND (res, 0)) == POLYNOMIAL_CHREC)
1551 new_init = fold_convert (TREE_TYPE (res),
1552 CHREC_LEFT (TREE_OPERAND (res, 0)));
1553 else if (TREE_CODE (res) == POLYNOMIAL_CHREC)
1554 new_init = CHREC_LEFT (res);
1555 STRIP_USELESS_TYPE_CONVERSION (new_init);
1556 if (TREE_CODE (new_init) == POLYNOMIAL_CHREC
1557 || !operand_equal_p (init_cond, new_init, 0))
1558 return chrec_dont_know;
1561 return res;
1564 /* This function merges the branches of a condition-phi-node,
1565 contained in the outermost loop, and whose arguments are already
1566 analyzed. */
1568 static tree
1569 interpret_condition_phi (struct loop *loop, gimple condition_phi)
1571 int i, n = gimple_phi_num_args (condition_phi);
1572 tree res = chrec_not_analyzed_yet;
1574 for (i = 0; i < n; i++)
1576 tree branch_chrec;
1578 if (backedge_phi_arg_p (condition_phi, i))
1580 res = chrec_dont_know;
1581 break;
1584 branch_chrec = analyze_scalar_evolution
1585 (loop, PHI_ARG_DEF (condition_phi, i));
1587 res = chrec_merge (res, branch_chrec);
1590 return res;
1593 /* Interpret the operation RHS1 OP RHS2. If we didn't
1594 analyze this node before, follow the definitions until ending
1595 either on an analyzed GIMPLE_ASSIGN, or on a loop-phi-node. On the
1596 return path, this function propagates evolutions (ala constant copy
1597 propagation). OPND1 is not a GIMPLE expression because we could
1598 analyze the effect of an inner loop: see interpret_loop_phi. */
1600 static tree
1601 interpret_rhs_expr (struct loop *loop, gimple at_stmt,
1602 tree type, tree rhs1, enum tree_code code, tree rhs2)
1604 tree res, chrec1, chrec2;
1605 gimple def;
1607 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1609 if (is_gimple_min_invariant (rhs1))
1610 return chrec_convert (type, rhs1, at_stmt);
1612 if (code == SSA_NAME)
1613 return chrec_convert (type, analyze_scalar_evolution (loop, rhs1),
1614 at_stmt);
1616 if (code == ASSERT_EXPR)
1618 rhs1 = ASSERT_EXPR_VAR (rhs1);
1619 return chrec_convert (type, analyze_scalar_evolution (loop, rhs1),
1620 at_stmt);
1624 switch (code)
1626 case ADDR_EXPR:
1627 if (TREE_CODE (TREE_OPERAND (rhs1, 0)) == MEM_REF
1628 || handled_component_p (TREE_OPERAND (rhs1, 0)))
1630 enum machine_mode mode;
1631 HOST_WIDE_INT bitsize, bitpos;
1632 int unsignedp;
1633 int volatilep = 0;
1634 tree base, offset;
1635 tree chrec3;
1636 tree unitpos;
1638 base = get_inner_reference (TREE_OPERAND (rhs1, 0),
1639 &bitsize, &bitpos, &offset,
1640 &mode, &unsignedp, &volatilep, false);
1642 if (TREE_CODE (base) == MEM_REF)
1644 rhs2 = TREE_OPERAND (base, 1);
1645 rhs1 = TREE_OPERAND (base, 0);
1647 chrec1 = analyze_scalar_evolution (loop, rhs1);
1648 chrec2 = analyze_scalar_evolution (loop, rhs2);
1649 chrec1 = chrec_convert (type, chrec1, at_stmt);
1650 chrec2 = chrec_convert (TREE_TYPE (rhs2), chrec2, at_stmt);
1651 res = chrec_fold_plus (type, chrec1, chrec2);
1653 else
1655 chrec1 = analyze_scalar_evolution_for_address_of (loop, base);
1656 chrec1 = chrec_convert (type, chrec1, at_stmt);
1657 res = chrec1;
1660 if (offset != NULL_TREE)
1662 chrec2 = analyze_scalar_evolution (loop, offset);
1663 chrec2 = chrec_convert (TREE_TYPE (offset), chrec2, at_stmt);
1664 res = chrec_fold_plus (type, res, chrec2);
1667 if (bitpos != 0)
1669 gcc_assert ((bitpos % BITS_PER_UNIT) == 0);
1671 unitpos = size_int (bitpos / BITS_PER_UNIT);
1672 chrec3 = analyze_scalar_evolution (loop, unitpos);
1673 chrec3 = chrec_convert (TREE_TYPE (unitpos), chrec3, at_stmt);
1674 res = chrec_fold_plus (type, res, chrec3);
1677 else
1678 res = chrec_dont_know;
1679 break;
1681 case POINTER_PLUS_EXPR:
1682 chrec1 = analyze_scalar_evolution (loop, rhs1);
1683 chrec2 = analyze_scalar_evolution (loop, rhs2);
1684 chrec1 = chrec_convert (type, chrec1, at_stmt);
1685 chrec2 = chrec_convert (TREE_TYPE (rhs2), chrec2, at_stmt);
1686 res = chrec_fold_plus (type, chrec1, chrec2);
1687 break;
1689 case PLUS_EXPR:
1690 chrec1 = analyze_scalar_evolution (loop, rhs1);
1691 chrec2 = analyze_scalar_evolution (loop, rhs2);
1692 chrec1 = chrec_convert (type, chrec1, at_stmt);
1693 chrec2 = chrec_convert (type, chrec2, at_stmt);
1694 res = chrec_fold_plus (type, chrec1, chrec2);
1695 break;
1697 case MINUS_EXPR:
1698 chrec1 = analyze_scalar_evolution (loop, rhs1);
1699 chrec2 = analyze_scalar_evolution (loop, rhs2);
1700 chrec1 = chrec_convert (type, chrec1, at_stmt);
1701 chrec2 = chrec_convert (type, chrec2, at_stmt);
1702 res = chrec_fold_minus (type, chrec1, chrec2);
1703 break;
1705 case NEGATE_EXPR:
1706 chrec1 = analyze_scalar_evolution (loop, rhs1);
1707 chrec1 = chrec_convert (type, chrec1, at_stmt);
1708 /* TYPE may be integer, real or complex, so use fold_convert. */
1709 res = chrec_fold_multiply (type, chrec1,
1710 fold_convert (type, integer_minus_one_node));
1711 break;
1713 case BIT_NOT_EXPR:
1714 /* Handle ~X as -1 - X. */
1715 chrec1 = analyze_scalar_evolution (loop, rhs1);
1716 chrec1 = chrec_convert (type, chrec1, at_stmt);
1717 res = chrec_fold_minus (type,
1718 fold_convert (type, integer_minus_one_node),
1719 chrec1);
1720 break;
1722 case MULT_EXPR:
1723 chrec1 = analyze_scalar_evolution (loop, rhs1);
1724 chrec2 = analyze_scalar_evolution (loop, rhs2);
1725 chrec1 = chrec_convert (type, chrec1, at_stmt);
1726 chrec2 = chrec_convert (type, chrec2, at_stmt);
1727 res = chrec_fold_multiply (type, chrec1, chrec2);
1728 break;
1730 CASE_CONVERT:
1731 /* In case we have a truncation of a widened operation that in
1732 the truncated type has undefined overflow behavior analyze
1733 the operation done in an unsigned type of the same precision
1734 as the final truncation. We cannot derive a scalar evolution
1735 for the widened operation but for the truncated result. */
1736 if (TREE_CODE (type) == INTEGER_TYPE
1737 && TREE_CODE (TREE_TYPE (rhs1)) == INTEGER_TYPE
1738 && TYPE_PRECISION (type) < TYPE_PRECISION (TREE_TYPE (rhs1))
1739 && TYPE_OVERFLOW_UNDEFINED (type)
1740 && TREE_CODE (rhs1) == SSA_NAME
1741 && (def = SSA_NAME_DEF_STMT (rhs1))
1742 && is_gimple_assign (def)
1743 && TREE_CODE_CLASS (gimple_assign_rhs_code (def)) == tcc_binary
1744 && TREE_CODE (gimple_assign_rhs2 (def)) == INTEGER_CST)
1746 tree utype = unsigned_type_for (type);
1747 chrec1 = interpret_rhs_expr (loop, at_stmt, utype,
1748 gimple_assign_rhs1 (def),
1749 gimple_assign_rhs_code (def),
1750 gimple_assign_rhs2 (def));
1752 else
1753 chrec1 = analyze_scalar_evolution (loop, rhs1);
1754 res = chrec_convert (type, chrec1, at_stmt);
1755 break;
1757 default:
1758 res = chrec_dont_know;
1759 break;
1762 return res;
1765 /* Interpret the expression EXPR. */
1767 static tree
1768 interpret_expr (struct loop *loop, gimple at_stmt, tree expr)
1770 enum tree_code code;
1771 tree type = TREE_TYPE (expr), op0, op1;
1773 if (automatically_generated_chrec_p (expr))
1774 return expr;
1776 if (TREE_CODE (expr) == POLYNOMIAL_CHREC
1777 || get_gimple_rhs_class (TREE_CODE (expr)) == GIMPLE_TERNARY_RHS)
1778 return chrec_dont_know;
1780 extract_ops_from_tree (expr, &code, &op0, &op1);
1782 return interpret_rhs_expr (loop, at_stmt, type,
1783 op0, code, op1);
1786 /* Interpret the rhs of the assignment STMT. */
1788 static tree
1789 interpret_gimple_assign (struct loop *loop, gimple stmt)
1791 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
1792 enum tree_code code = gimple_assign_rhs_code (stmt);
1794 return interpret_rhs_expr (loop, stmt, type,
1795 gimple_assign_rhs1 (stmt), code,
1796 gimple_assign_rhs2 (stmt));
1801 /* This section contains all the entry points:
1802 - number_of_iterations_in_loop,
1803 - analyze_scalar_evolution,
1804 - instantiate_parameters.
1807 /* Compute and return the evolution function in WRTO_LOOP, the nearest
1808 common ancestor of DEF_LOOP and USE_LOOP. */
1810 static tree
1811 compute_scalar_evolution_in_loop (struct loop *wrto_loop,
1812 struct loop *def_loop,
1813 tree ev)
1815 bool val;
1816 tree res;
1818 if (def_loop == wrto_loop)
1819 return ev;
1821 def_loop = superloop_at_depth (def_loop, loop_depth (wrto_loop) + 1);
1822 res = compute_overall_effect_of_inner_loop (def_loop, ev);
1824 if (no_evolution_in_loop_p (res, wrto_loop->num, &val) && val)
1825 return res;
1827 return analyze_scalar_evolution_1 (wrto_loop, res, chrec_not_analyzed_yet);
1830 /* Helper recursive function. */
1832 static tree
1833 analyze_scalar_evolution_1 (struct loop *loop, tree var, tree res)
1835 tree type = TREE_TYPE (var);
1836 gimple def;
1837 basic_block bb;
1838 struct loop *def_loop;
1840 if (loop == NULL || TREE_CODE (type) == VECTOR_TYPE)
1841 return chrec_dont_know;
1843 if (TREE_CODE (var) != SSA_NAME)
1844 return interpret_expr (loop, NULL, var);
1846 def = SSA_NAME_DEF_STMT (var);
1847 bb = gimple_bb (def);
1848 def_loop = bb ? bb->loop_father : NULL;
1850 if (bb == NULL
1851 || !flow_bb_inside_loop_p (loop, bb))
1853 /* Keep the symbolic form. */
1854 res = var;
1855 goto set_and_end;
1858 if (res != chrec_not_analyzed_yet)
1860 if (loop != bb->loop_father)
1861 res = compute_scalar_evolution_in_loop
1862 (find_common_loop (loop, bb->loop_father), bb->loop_father, res);
1864 goto set_and_end;
1867 if (loop != def_loop)
1869 res = analyze_scalar_evolution_1 (def_loop, var, chrec_not_analyzed_yet);
1870 res = compute_scalar_evolution_in_loop (loop, def_loop, res);
1872 goto set_and_end;
1875 switch (gimple_code (def))
1877 case GIMPLE_ASSIGN:
1878 res = interpret_gimple_assign (loop, def);
1879 break;
1881 case GIMPLE_PHI:
1882 if (loop_phi_node_p (def))
1883 res = interpret_loop_phi (loop, def);
1884 else
1885 res = interpret_condition_phi (loop, def);
1886 break;
1888 default:
1889 res = chrec_dont_know;
1890 break;
1893 set_and_end:
1895 /* Keep the symbolic form. */
1896 if (res == chrec_dont_know)
1897 res = var;
1899 if (loop == def_loop)
1900 set_scalar_evolution (block_before_loop (loop), var, res);
1902 return res;
1905 /* Analyzes and returns the scalar evolution of the ssa_name VAR in
1906 LOOP. LOOP is the loop in which the variable is used.
1908 Example of use: having a pointer VAR to a SSA_NAME node, STMT a
1909 pointer to the statement that uses this variable, in order to
1910 determine the evolution function of the variable, use the following
1911 calls:
1913 loop_p loop = loop_containing_stmt (stmt);
1914 tree chrec_with_symbols = analyze_scalar_evolution (loop, var);
1915 tree chrec_instantiated = instantiate_parameters (loop, chrec_with_symbols);
1918 tree
1919 analyze_scalar_evolution (struct loop *loop, tree var)
1921 tree res;
1923 if (dump_file && (dump_flags & TDF_SCEV))
1925 fprintf (dump_file, "(analyze_scalar_evolution \n");
1926 fprintf (dump_file, " (loop_nb = %d)\n", loop->num);
1927 fprintf (dump_file, " (scalar = ");
1928 print_generic_expr (dump_file, var, 0);
1929 fprintf (dump_file, ")\n");
1932 res = get_scalar_evolution (block_before_loop (loop), var);
1933 res = analyze_scalar_evolution_1 (loop, var, res);
1935 if (dump_file && (dump_flags & TDF_SCEV))
1936 fprintf (dump_file, ")\n");
1938 return res;
1941 /* Analyzes and returns the scalar evolution of VAR address in LOOP. */
1943 static tree
1944 analyze_scalar_evolution_for_address_of (struct loop *loop, tree var)
1946 return analyze_scalar_evolution (loop, build_fold_addr_expr (var));
1949 /* Analyze scalar evolution of use of VERSION in USE_LOOP with respect to
1950 WRTO_LOOP (which should be a superloop of USE_LOOP)
1952 FOLDED_CASTS is set to true if resolve_mixers used
1953 chrec_convert_aggressive (TODO -- not really, we are way too conservative
1954 at the moment in order to keep things simple).
1956 To illustrate the meaning of USE_LOOP and WRTO_LOOP, consider the following
1957 example:
1959 for (i = 0; i < 100; i++) -- loop 1
1961 for (j = 0; j < 100; j++) -- loop 2
1963 k1 = i;
1964 k2 = j;
1966 use2 (k1, k2);
1968 for (t = 0; t < 100; t++) -- loop 3
1969 use3 (k1, k2);
1972 use1 (k1, k2);
1975 Both k1 and k2 are invariants in loop3, thus
1976 analyze_scalar_evolution_in_loop (loop3, loop3, k1) = k1
1977 analyze_scalar_evolution_in_loop (loop3, loop3, k2) = k2
1979 As they are invariant, it does not matter whether we consider their
1980 usage in loop 3 or loop 2, hence
1981 analyze_scalar_evolution_in_loop (loop2, loop3, k1) =
1982 analyze_scalar_evolution_in_loop (loop2, loop2, k1) = i
1983 analyze_scalar_evolution_in_loop (loop2, loop3, k2) =
1984 analyze_scalar_evolution_in_loop (loop2, loop2, k2) = [0,+,1]_2
1986 Similarly for their evolutions with respect to loop 1. The values of K2
1987 in the use in loop 2 vary independently on loop 1, thus we cannot express
1988 the evolution with respect to loop 1:
1989 analyze_scalar_evolution_in_loop (loop1, loop3, k1) =
1990 analyze_scalar_evolution_in_loop (loop1, loop2, k1) = [0,+,1]_1
1991 analyze_scalar_evolution_in_loop (loop1, loop3, k2) =
1992 analyze_scalar_evolution_in_loop (loop1, loop2, k2) = dont_know
1994 The value of k2 in the use in loop 1 is known, though:
1995 analyze_scalar_evolution_in_loop (loop1, loop1, k1) = [0,+,1]_1
1996 analyze_scalar_evolution_in_loop (loop1, loop1, k2) = 100
1999 static tree
2000 analyze_scalar_evolution_in_loop (struct loop *wrto_loop, struct loop *use_loop,
2001 tree version, bool *folded_casts)
2003 bool val = false;
2004 tree ev = version, tmp;
2006 /* We cannot just do
2008 tmp = analyze_scalar_evolution (use_loop, version);
2009 ev = resolve_mixers (wrto_loop, tmp);
2011 as resolve_mixers would query the scalar evolution with respect to
2012 wrto_loop. For example, in the situation described in the function
2013 comment, suppose that wrto_loop = loop1, use_loop = loop3 and
2014 version = k2. Then
2016 analyze_scalar_evolution (use_loop, version) = k2
2018 and resolve_mixers (loop1, k2) finds that the value of k2 in loop 1
2019 is 100, which is a wrong result, since we are interested in the
2020 value in loop 3.
2022 Instead, we need to proceed from use_loop to wrto_loop loop by loop,
2023 each time checking that there is no evolution in the inner loop. */
2025 if (folded_casts)
2026 *folded_casts = false;
2027 while (1)
2029 tmp = analyze_scalar_evolution (use_loop, ev);
2030 ev = resolve_mixers (use_loop, tmp);
2032 if (folded_casts && tmp != ev)
2033 *folded_casts = true;
2035 if (use_loop == wrto_loop)
2036 return ev;
2038 /* If the value of the use changes in the inner loop, we cannot express
2039 its value in the outer loop (we might try to return interval chrec,
2040 but we do not have a user for it anyway) */
2041 if (!no_evolution_in_loop_p (ev, use_loop->num, &val)
2042 || !val)
2043 return chrec_dont_know;
2045 use_loop = loop_outer (use_loop);
2050 /* Hashtable helpers for a temporary hash-table used when
2051 instantiating a CHREC or resolving mixers. For this use
2052 instantiated_below is always the same. */
2054 struct instantiate_cache_entry
2056 tree name;
2057 tree chrec;
2060 struct instantiate_cache_entry_hasher : typed_noop_remove <uintptr_t>
2062 typedef uintptr_t value_type;
2063 typedef instantiate_cache_entry compare_type;
2064 static inline hashval_t hash (const value_type *);
2065 static inline bool equal (const value_type *, const compare_type *);
2068 struct instantiate_cache_type
2070 hash_table <instantiate_cache_entry_hasher> htab;
2071 vec<instantiate_cache_entry> entries;
2073 ~instantiate_cache_type ();
2076 instantiate_cache_type::~instantiate_cache_type ()
2078 if (htab.is_created ())
2080 htab.dispose ();
2081 entries.release ();
2085 static instantiate_cache_type *ctbl;
2087 inline hashval_t
2088 instantiate_cache_entry_hasher::hash (const value_type *idx)
2090 instantiate_cache_entry *elt
2091 = &ctbl->entries[reinterpret_cast <uintptr_t> (idx) - 2];
2092 return SSA_NAME_VERSION (elt->name);
2095 inline bool
2096 instantiate_cache_entry_hasher::equal (const value_type *idx1,
2097 const compare_type *elt2)
2099 compare_type *elt1 = &ctbl->entries[reinterpret_cast <uintptr_t> (idx1) - 2];
2100 return elt1->name == elt2->name;
2103 /* Returns from CACHE a pointer to the cached chrec for NAME. */
2105 static tree *
2106 get_instantiated_value_entry (instantiate_cache_type &cache, tree name)
2108 struct instantiate_cache_entry e;
2109 uintptr_t **slot;
2111 if (!cache.htab.is_created ())
2113 cache.htab.create (10);
2114 cache.entries.create (10);
2117 ctbl = &cache;
2119 e.name = name;
2120 slot = cache.htab.find_slot_with_hash (&e, SSA_NAME_VERSION (name), INSERT);
2121 if (!*slot)
2123 e.chrec = chrec_not_analyzed_yet;
2124 cache.entries.safe_push (e);
2125 *slot = reinterpret_cast <uintptr_t *>
2126 ((uintptr_t) cache.entries.length () + 1);
2129 return &cache.entries[reinterpret_cast <uintptr_t> (*slot) - 2].chrec;
2132 /* Return the closed_loop_phi node for VAR. If there is none, return
2133 NULL_TREE. */
2135 static tree
2136 loop_closed_phi_def (tree var)
2138 struct loop *loop;
2139 edge exit;
2140 gimple phi;
2141 gimple_stmt_iterator psi;
2143 if (var == NULL_TREE
2144 || TREE_CODE (var) != SSA_NAME)
2145 return NULL_TREE;
2147 loop = loop_containing_stmt (SSA_NAME_DEF_STMT (var));
2148 exit = single_exit (loop);
2149 if (!exit)
2150 return NULL_TREE;
2152 for (psi = gsi_start_phis (exit->dest); !gsi_end_p (psi); gsi_next (&psi))
2154 phi = gsi_stmt (psi);
2155 if (PHI_ARG_DEF_FROM_EDGE (phi, exit) == var)
2156 return PHI_RESULT (phi);
2159 return NULL_TREE;
2162 static tree instantiate_scev_r (basic_block, struct loop *, struct loop *,
2163 tree, bool, instantiate_cache_type &, int);
2165 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2166 and EVOLUTION_LOOP, that were left under a symbolic form.
2168 CHREC is an SSA_NAME to be instantiated.
2170 CACHE is the cache of already instantiated values.
2172 FOLD_CONVERSIONS should be set to true when the conversions that
2173 may wrap in signed/pointer type are folded, as long as the value of
2174 the chrec is preserved.
2176 SIZE_EXPR is used for computing the size of the expression to be
2177 instantiated, and to stop if it exceeds some limit. */
2179 static tree
2180 instantiate_scev_name (basic_block instantiate_below,
2181 struct loop *evolution_loop, struct loop *inner_loop,
2182 tree chrec,
2183 bool fold_conversions, instantiate_cache_type &cache,
2184 int size_expr)
2186 tree res;
2187 struct loop *def_loop;
2188 basic_block def_bb = gimple_bb (SSA_NAME_DEF_STMT (chrec));
2190 /* A parameter (or loop invariant and we do not want to include
2191 evolutions in outer loops), nothing to do. */
2192 if (!def_bb
2193 || loop_depth (def_bb->loop_father) == 0
2194 || dominated_by_p (CDI_DOMINATORS, instantiate_below, def_bb))
2195 return chrec;
2197 /* We cache the value of instantiated variable to avoid exponential
2198 time complexity due to reevaluations. We also store the convenient
2199 value in the cache in order to prevent infinite recursion -- we do
2200 not want to instantiate the SSA_NAME if it is in a mixer
2201 structure. This is used for avoiding the instantiation of
2202 recursively defined functions, such as:
2204 | a_2 -> {0, +, 1, +, a_2}_1 */
2206 tree *si;
2207 si = get_instantiated_value_entry (cache, chrec);
2208 if (*si != chrec_not_analyzed_yet)
2209 return *si;
2211 /* On recursion return chrec_dont_know. */
2212 *si = chrec_dont_know;
2214 def_loop = find_common_loop (evolution_loop, def_bb->loop_father);
2216 /* If the analysis yields a parametric chrec, instantiate the
2217 result again. */
2218 res = analyze_scalar_evolution (def_loop, chrec);
2220 /* Don't instantiate default definitions. */
2221 if (TREE_CODE (res) == SSA_NAME
2222 && SSA_NAME_IS_DEFAULT_DEF (res))
2225 /* Don't instantiate loop-closed-ssa phi nodes. */
2226 else if (TREE_CODE (res) == SSA_NAME
2227 && loop_depth (loop_containing_stmt (SSA_NAME_DEF_STMT (res)))
2228 > loop_depth (def_loop))
2230 if (res == chrec)
2231 res = loop_closed_phi_def (chrec);
2232 else
2233 res = chrec;
2235 /* When there is no loop_closed_phi_def, it means that the
2236 variable is not used after the loop: try to still compute the
2237 value of the variable when exiting the loop. */
2238 if (res == NULL_TREE)
2240 loop_p loop = loop_containing_stmt (SSA_NAME_DEF_STMT (chrec));
2241 res = analyze_scalar_evolution (loop, chrec);
2242 res = compute_overall_effect_of_inner_loop (loop, res);
2243 res = instantiate_scev_r (instantiate_below, evolution_loop,
2244 inner_loop, res,
2245 fold_conversions, cache, size_expr);
2247 else if (!dominated_by_p (CDI_DOMINATORS, instantiate_below,
2248 gimple_bb (SSA_NAME_DEF_STMT (res))))
2249 res = chrec_dont_know;
2252 else if (res != chrec_dont_know)
2254 if (inner_loop
2255 && def_bb->loop_father != inner_loop
2256 && !flow_loop_nested_p (def_bb->loop_father, inner_loop))
2257 /* ??? We could try to compute the overall effect of the loop here. */
2258 res = chrec_dont_know;
2259 else
2260 res = instantiate_scev_r (instantiate_below, evolution_loop,
2261 inner_loop, res,
2262 fold_conversions, cache, size_expr);
2265 /* Store the correct value to the cache. */
2266 *si = res;
2267 return res;
2270 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2271 and EVOLUTION_LOOP, that were left under a symbolic form.
2273 CHREC is a polynomial chain of recurrence to be instantiated.
2275 CACHE is the cache of already instantiated values.
2277 FOLD_CONVERSIONS should be set to true when the conversions that
2278 may wrap in signed/pointer type are folded, as long as the value of
2279 the chrec is preserved.
2281 SIZE_EXPR is used for computing the size of the expression to be
2282 instantiated, and to stop if it exceeds some limit. */
2284 static tree
2285 instantiate_scev_poly (basic_block instantiate_below,
2286 struct loop *evolution_loop, struct loop *,
2287 tree chrec,
2288 bool fold_conversions, instantiate_cache_type &cache,
2289 int size_expr)
2291 tree op1;
2292 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2293 get_chrec_loop (chrec),
2294 CHREC_LEFT (chrec), fold_conversions, cache,
2295 size_expr);
2296 if (op0 == chrec_dont_know)
2297 return chrec_dont_know;
2299 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2300 get_chrec_loop (chrec),
2301 CHREC_RIGHT (chrec), fold_conversions, cache,
2302 size_expr);
2303 if (op1 == chrec_dont_know)
2304 return chrec_dont_know;
2306 if (CHREC_LEFT (chrec) != op0
2307 || CHREC_RIGHT (chrec) != op1)
2309 op1 = chrec_convert_rhs (chrec_type (op0), op1, NULL);
2310 chrec = build_polynomial_chrec (CHREC_VARIABLE (chrec), op0, op1);
2313 return chrec;
2316 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2317 and EVOLUTION_LOOP, that were left under a symbolic form.
2319 "C0 CODE C1" is a binary expression of type TYPE to be instantiated.
2321 CACHE is the cache of already instantiated values.
2323 FOLD_CONVERSIONS should be set to true when the conversions that
2324 may wrap in signed/pointer type are folded, as long as the value of
2325 the chrec is preserved.
2327 SIZE_EXPR is used for computing the size of the expression to be
2328 instantiated, and to stop if it exceeds some limit. */
2330 static tree
2331 instantiate_scev_binary (basic_block instantiate_below,
2332 struct loop *evolution_loop, struct loop *inner_loop,
2333 tree chrec, enum tree_code code,
2334 tree type, tree c0, tree c1,
2335 bool fold_conversions,
2336 instantiate_cache_type &cache,
2337 int size_expr)
2339 tree op1;
2340 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop, inner_loop,
2341 c0, fold_conversions, cache,
2342 size_expr);
2343 if (op0 == chrec_dont_know)
2344 return chrec_dont_know;
2346 op1 = instantiate_scev_r (instantiate_below, evolution_loop, inner_loop,
2347 c1, fold_conversions, cache,
2348 size_expr);
2349 if (op1 == chrec_dont_know)
2350 return chrec_dont_know;
2352 if (c0 != op0
2353 || c1 != op1)
2355 op0 = chrec_convert (type, op0, NULL);
2356 op1 = chrec_convert_rhs (type, op1, NULL);
2358 switch (code)
2360 case POINTER_PLUS_EXPR:
2361 case PLUS_EXPR:
2362 return chrec_fold_plus (type, op0, op1);
2364 case MINUS_EXPR:
2365 return chrec_fold_minus (type, op0, op1);
2367 case MULT_EXPR:
2368 return chrec_fold_multiply (type, op0, op1);
2370 default:
2371 gcc_unreachable ();
2375 return chrec ? chrec : fold_build2 (code, type, c0, c1);
2378 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2379 and EVOLUTION_LOOP, that were left under a symbolic form.
2381 "CHREC" is an array reference to be instantiated.
2383 CACHE is the cache of already instantiated values.
2385 FOLD_CONVERSIONS should be set to true when the conversions that
2386 may wrap in signed/pointer type are folded, as long as the value of
2387 the chrec is preserved.
2389 SIZE_EXPR is used for computing the size of the expression to be
2390 instantiated, and to stop if it exceeds some limit. */
2392 static tree
2393 instantiate_array_ref (basic_block instantiate_below,
2394 struct loop *evolution_loop, struct loop *inner_loop,
2395 tree chrec,
2396 bool fold_conversions, instantiate_cache_type &cache,
2397 int size_expr)
2399 tree res;
2400 tree index = TREE_OPERAND (chrec, 1);
2401 tree op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2402 inner_loop, index,
2403 fold_conversions, cache, size_expr);
2405 if (op1 == chrec_dont_know)
2406 return chrec_dont_know;
2408 if (chrec && op1 == index)
2409 return chrec;
2411 res = unshare_expr (chrec);
2412 TREE_OPERAND (res, 1) = op1;
2413 return res;
2416 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2417 and EVOLUTION_LOOP, that were left under a symbolic form.
2419 "CHREC" that stands for a convert expression "(TYPE) OP" is to be
2420 instantiated.
2422 CACHE is the cache of already instantiated values.
2424 FOLD_CONVERSIONS should be set to true when the conversions that
2425 may wrap in signed/pointer type are folded, as long as the value of
2426 the chrec is preserved.
2428 SIZE_EXPR is used for computing the size of the expression to be
2429 instantiated, and to stop if it exceeds some limit. */
2431 static tree
2432 instantiate_scev_convert (basic_block instantiate_below,
2433 struct loop *evolution_loop, struct loop *inner_loop,
2434 tree chrec,
2435 tree type, tree op,
2436 bool fold_conversions,
2437 instantiate_cache_type &cache, int size_expr)
2439 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2440 inner_loop, op,
2441 fold_conversions, cache, size_expr);
2443 if (op0 == chrec_dont_know)
2444 return chrec_dont_know;
2446 if (fold_conversions)
2448 tree tmp = chrec_convert_aggressive (type, op0);
2449 if (tmp)
2450 return tmp;
2453 if (chrec && op0 == op)
2454 return chrec;
2456 /* If we used chrec_convert_aggressive, we can no longer assume that
2457 signed chrecs do not overflow, as chrec_convert does, so avoid
2458 calling it in that case. */
2459 if (fold_conversions)
2460 return fold_convert (type, op0);
2462 return chrec_convert (type, op0, NULL);
2465 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2466 and EVOLUTION_LOOP, that were left under a symbolic form.
2468 CHREC is a BIT_NOT_EXPR or a NEGATE_EXPR expression to be instantiated.
2469 Handle ~X as -1 - X.
2470 Handle -X as -1 * X.
2472 CACHE is the cache of already instantiated values.
2474 FOLD_CONVERSIONS should be set to true when the conversions that
2475 may wrap in signed/pointer type are folded, as long as the value of
2476 the chrec is preserved.
2478 SIZE_EXPR is used for computing the size of the expression to be
2479 instantiated, and to stop if it exceeds some limit. */
2481 static tree
2482 instantiate_scev_not (basic_block instantiate_below,
2483 struct loop *evolution_loop, struct loop *inner_loop,
2484 tree chrec,
2485 enum tree_code code, tree type, tree op,
2486 bool fold_conversions, instantiate_cache_type &cache,
2487 int size_expr)
2489 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2490 inner_loop, op,
2491 fold_conversions, cache, size_expr);
2493 if (op0 == chrec_dont_know)
2494 return chrec_dont_know;
2496 if (op != op0)
2498 op0 = chrec_convert (type, op0, NULL);
2500 switch (code)
2502 case BIT_NOT_EXPR:
2503 return chrec_fold_minus
2504 (type, fold_convert (type, integer_minus_one_node), op0);
2506 case NEGATE_EXPR:
2507 return chrec_fold_multiply
2508 (type, fold_convert (type, integer_minus_one_node), op0);
2510 default:
2511 gcc_unreachable ();
2515 return chrec ? chrec : fold_build1 (code, type, op0);
2518 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2519 and EVOLUTION_LOOP, that were left under a symbolic form.
2521 CHREC is an expression with 3 operands to be instantiated.
2523 CACHE is the cache of already instantiated values.
2525 FOLD_CONVERSIONS should be set to true when the conversions that
2526 may wrap in signed/pointer type are folded, as long as the value of
2527 the chrec is preserved.
2529 SIZE_EXPR is used for computing the size of the expression to be
2530 instantiated, and to stop if it exceeds some limit. */
2532 static tree
2533 instantiate_scev_3 (basic_block instantiate_below,
2534 struct loop *evolution_loop, struct loop *inner_loop,
2535 tree chrec,
2536 bool fold_conversions, instantiate_cache_type &cache,
2537 int size_expr)
2539 tree op1, op2;
2540 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2541 inner_loop, TREE_OPERAND (chrec, 0),
2542 fold_conversions, cache, size_expr);
2543 if (op0 == chrec_dont_know)
2544 return chrec_dont_know;
2546 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2547 inner_loop, TREE_OPERAND (chrec, 1),
2548 fold_conversions, cache, size_expr);
2549 if (op1 == chrec_dont_know)
2550 return chrec_dont_know;
2552 op2 = instantiate_scev_r (instantiate_below, evolution_loop,
2553 inner_loop, TREE_OPERAND (chrec, 2),
2554 fold_conversions, cache, size_expr);
2555 if (op2 == chrec_dont_know)
2556 return chrec_dont_know;
2558 if (op0 == TREE_OPERAND (chrec, 0)
2559 && op1 == TREE_OPERAND (chrec, 1)
2560 && op2 == TREE_OPERAND (chrec, 2))
2561 return chrec;
2563 return fold_build3 (TREE_CODE (chrec),
2564 TREE_TYPE (chrec), op0, op1, op2);
2567 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2568 and EVOLUTION_LOOP, that were left under a symbolic form.
2570 CHREC is an expression with 2 operands to be instantiated.
2572 CACHE is the cache of already instantiated values.
2574 FOLD_CONVERSIONS should be set to true when the conversions that
2575 may wrap in signed/pointer type are folded, as long as the value of
2576 the chrec is preserved.
2578 SIZE_EXPR is used for computing the size of the expression to be
2579 instantiated, and to stop if it exceeds some limit. */
2581 static tree
2582 instantiate_scev_2 (basic_block instantiate_below,
2583 struct loop *evolution_loop, struct loop *inner_loop,
2584 tree chrec,
2585 bool fold_conversions, instantiate_cache_type &cache,
2586 int size_expr)
2588 tree op1;
2589 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2590 inner_loop, TREE_OPERAND (chrec, 0),
2591 fold_conversions, cache, size_expr);
2592 if (op0 == chrec_dont_know)
2593 return chrec_dont_know;
2595 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2596 inner_loop, TREE_OPERAND (chrec, 1),
2597 fold_conversions, cache, size_expr);
2598 if (op1 == chrec_dont_know)
2599 return chrec_dont_know;
2601 if (op0 == TREE_OPERAND (chrec, 0)
2602 && op1 == TREE_OPERAND (chrec, 1))
2603 return chrec;
2605 return fold_build2 (TREE_CODE (chrec), TREE_TYPE (chrec), op0, op1);
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 2 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_1 (basic_block instantiate_below,
2624 struct loop *evolution_loop, struct loop *inner_loop,
2625 tree chrec,
2626 bool fold_conversions, instantiate_cache_type &cache,
2627 int size_expr)
2629 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2630 inner_loop, TREE_OPERAND (chrec, 0),
2631 fold_conversions, cache, size_expr);
2633 if (op0 == chrec_dont_know)
2634 return chrec_dont_know;
2636 if (op0 == TREE_OPERAND (chrec, 0))
2637 return chrec;
2639 return fold_build1 (TREE_CODE (chrec), TREE_TYPE (chrec), op0);
2642 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2643 and EVOLUTION_LOOP, that were left under a symbolic form.
2645 CHREC is the scalar evolution to instantiate.
2647 CACHE is the cache of already instantiated values.
2649 FOLD_CONVERSIONS should be set to true when the conversions that
2650 may wrap in signed/pointer type are folded, as long as the value of
2651 the chrec is preserved.
2653 SIZE_EXPR is used for computing the size of the expression to be
2654 instantiated, and to stop if it exceeds some limit. */
2656 static tree
2657 instantiate_scev_r (basic_block instantiate_below,
2658 struct loop *evolution_loop, struct loop *inner_loop,
2659 tree chrec,
2660 bool fold_conversions, instantiate_cache_type &cache,
2661 int size_expr)
2663 /* Give up if the expression is larger than the MAX that we allow. */
2664 if (size_expr++ > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_SIZE))
2665 return chrec_dont_know;
2667 if (chrec == NULL_TREE
2668 || automatically_generated_chrec_p (chrec)
2669 || is_gimple_min_invariant (chrec))
2670 return chrec;
2672 switch (TREE_CODE (chrec))
2674 case SSA_NAME:
2675 return instantiate_scev_name (instantiate_below, evolution_loop,
2676 inner_loop, chrec,
2677 fold_conversions, cache, size_expr);
2679 case POLYNOMIAL_CHREC:
2680 return instantiate_scev_poly (instantiate_below, evolution_loop,
2681 inner_loop, chrec,
2682 fold_conversions, cache, size_expr);
2684 case POINTER_PLUS_EXPR:
2685 case PLUS_EXPR:
2686 case MINUS_EXPR:
2687 case MULT_EXPR:
2688 return instantiate_scev_binary (instantiate_below, evolution_loop,
2689 inner_loop, chrec,
2690 TREE_CODE (chrec), chrec_type (chrec),
2691 TREE_OPERAND (chrec, 0),
2692 TREE_OPERAND (chrec, 1),
2693 fold_conversions, cache, size_expr);
2695 CASE_CONVERT:
2696 return instantiate_scev_convert (instantiate_below, evolution_loop,
2697 inner_loop, chrec,
2698 TREE_TYPE (chrec), TREE_OPERAND (chrec, 0),
2699 fold_conversions, cache, size_expr);
2701 case NEGATE_EXPR:
2702 case BIT_NOT_EXPR:
2703 return instantiate_scev_not (instantiate_below, evolution_loop,
2704 inner_loop, chrec,
2705 TREE_CODE (chrec), TREE_TYPE (chrec),
2706 TREE_OPERAND (chrec, 0),
2707 fold_conversions, cache, size_expr);
2709 case ADDR_EXPR:
2710 case SCEV_NOT_KNOWN:
2711 return chrec_dont_know;
2713 case SCEV_KNOWN:
2714 return chrec_known;
2716 case ARRAY_REF:
2717 return instantiate_array_ref (instantiate_below, evolution_loop,
2718 inner_loop, chrec,
2719 fold_conversions, cache, size_expr);
2721 default:
2722 break;
2725 if (VL_EXP_CLASS_P (chrec))
2726 return chrec_dont_know;
2728 switch (TREE_CODE_LENGTH (TREE_CODE (chrec)))
2730 case 3:
2731 return instantiate_scev_3 (instantiate_below, evolution_loop,
2732 inner_loop, chrec,
2733 fold_conversions, cache, size_expr);
2735 case 2:
2736 return instantiate_scev_2 (instantiate_below, evolution_loop,
2737 inner_loop, chrec,
2738 fold_conversions, cache, size_expr);
2740 case 1:
2741 return instantiate_scev_1 (instantiate_below, evolution_loop,
2742 inner_loop, chrec,
2743 fold_conversions, cache, size_expr);
2745 case 0:
2746 return chrec;
2748 default:
2749 break;
2752 /* Too complicated to handle. */
2753 return chrec_dont_know;
2756 /* Analyze all the parameters of the chrec that were left under a
2757 symbolic form. INSTANTIATE_BELOW is the basic block that stops the
2758 recursive instantiation of parameters: a parameter is a variable
2759 that is defined in a basic block that dominates INSTANTIATE_BELOW or
2760 a function parameter. */
2762 tree
2763 instantiate_scev (basic_block instantiate_below, struct loop *evolution_loop,
2764 tree chrec)
2766 tree res;
2767 instantiate_cache_type cache;
2769 if (dump_file && (dump_flags & TDF_SCEV))
2771 fprintf (dump_file, "(instantiate_scev \n");
2772 fprintf (dump_file, " (instantiate_below = %d)\n", instantiate_below->index);
2773 fprintf (dump_file, " (evolution_loop = %d)\n", evolution_loop->num);
2774 fprintf (dump_file, " (chrec = ");
2775 print_generic_expr (dump_file, chrec, 0);
2776 fprintf (dump_file, ")\n");
2779 res = instantiate_scev_r (instantiate_below, evolution_loop,
2780 NULL, chrec, false, cache, 0);
2782 if (dump_file && (dump_flags & TDF_SCEV))
2784 fprintf (dump_file, " (res = ");
2785 print_generic_expr (dump_file, res, 0);
2786 fprintf (dump_file, "))\n");
2789 return res;
2792 /* Similar to instantiate_parameters, but does not introduce the
2793 evolutions in outer loops for LOOP invariants in CHREC, and does not
2794 care about causing overflows, as long as they do not affect value
2795 of an expression. */
2797 tree
2798 resolve_mixers (struct loop *loop, tree chrec)
2800 instantiate_cache_type cache;
2801 tree ret = instantiate_scev_r (block_before_loop (loop), loop, NULL,
2802 chrec, true, cache, 0);
2803 return ret;
2806 /* Entry point for the analysis of the number of iterations pass.
2807 This function tries to safely approximate the number of iterations
2808 the loop will run. When this property is not decidable at compile
2809 time, the result is chrec_dont_know. Otherwise the result is a
2810 scalar or a symbolic parameter. When the number of iterations may
2811 be equal to zero and the property cannot be determined at compile
2812 time, the result is a COND_EXPR that represents in a symbolic form
2813 the conditions under which the number of iterations is not zero.
2815 Example of analysis: suppose that the loop has an exit condition:
2817 "if (b > 49) goto end_loop;"
2819 and that in a previous analysis we have determined that the
2820 variable 'b' has an evolution function:
2822 "EF = {23, +, 5}_2".
2824 When we evaluate the function at the point 5, i.e. the value of the
2825 variable 'b' after 5 iterations in the loop, we have EF (5) = 48,
2826 and EF (6) = 53. In this case the value of 'b' on exit is '53' and
2827 the loop body has been executed 6 times. */
2829 tree
2830 number_of_latch_executions (struct loop *loop)
2832 edge exit;
2833 struct tree_niter_desc niter_desc;
2834 tree may_be_zero;
2835 tree res;
2837 /* Determine whether the number of iterations in loop has already
2838 been computed. */
2839 res = loop->nb_iterations;
2840 if (res)
2841 return res;
2843 may_be_zero = NULL_TREE;
2845 if (dump_file && (dump_flags & TDF_SCEV))
2846 fprintf (dump_file, "(number_of_iterations_in_loop = \n");
2848 res = chrec_dont_know;
2849 exit = single_exit (loop);
2851 if (exit && number_of_iterations_exit (loop, exit, &niter_desc, false))
2853 may_be_zero = niter_desc.may_be_zero;
2854 res = niter_desc.niter;
2857 if (res == chrec_dont_know
2858 || !may_be_zero
2859 || integer_zerop (may_be_zero))
2861 else if (integer_nonzerop (may_be_zero))
2862 res = build_int_cst (TREE_TYPE (res), 0);
2864 else if (COMPARISON_CLASS_P (may_be_zero))
2865 res = fold_build3 (COND_EXPR, TREE_TYPE (res), may_be_zero,
2866 build_int_cst (TREE_TYPE (res), 0), res);
2867 else
2868 res = chrec_dont_know;
2870 if (dump_file && (dump_flags & TDF_SCEV))
2872 fprintf (dump_file, " (set_nb_iterations_in_loop = ");
2873 print_generic_expr (dump_file, res, 0);
2874 fprintf (dump_file, "))\n");
2877 loop->nb_iterations = res;
2878 return res;
2881 /* Returns the number of executions of the exit condition of LOOP,
2882 i.e., the number by one higher than number_of_latch_executions.
2883 Note that unlike number_of_latch_executions, this number does
2884 not necessarily fit in the unsigned variant of the type of
2885 the control variable -- if the number of iterations is a constant,
2886 we return chrec_dont_know if adding one to number_of_latch_executions
2887 overflows; however, in case the number of iterations is symbolic
2888 expression, the caller is responsible for dealing with this
2889 the possible overflow. */
2891 tree
2892 number_of_exit_cond_executions (struct loop *loop)
2894 tree ret = number_of_latch_executions (loop);
2895 tree type = chrec_type (ret);
2897 if (chrec_contains_undetermined (ret))
2898 return ret;
2900 ret = chrec_fold_plus (type, ret, build_int_cst (type, 1));
2901 if (TREE_CODE (ret) == INTEGER_CST
2902 && TREE_OVERFLOW (ret))
2903 return chrec_dont_know;
2905 return ret;
2910 /* Counters for the stats. */
2912 struct chrec_stats
2914 unsigned nb_chrecs;
2915 unsigned nb_affine;
2916 unsigned nb_affine_multivar;
2917 unsigned nb_higher_poly;
2918 unsigned nb_chrec_dont_know;
2919 unsigned nb_undetermined;
2922 /* Reset the counters. */
2924 static inline void
2925 reset_chrecs_counters (struct chrec_stats *stats)
2927 stats->nb_chrecs = 0;
2928 stats->nb_affine = 0;
2929 stats->nb_affine_multivar = 0;
2930 stats->nb_higher_poly = 0;
2931 stats->nb_chrec_dont_know = 0;
2932 stats->nb_undetermined = 0;
2935 /* Dump the contents of a CHREC_STATS structure. */
2937 static void
2938 dump_chrecs_stats (FILE *file, struct chrec_stats *stats)
2940 fprintf (file, "\n(\n");
2941 fprintf (file, "-----------------------------------------\n");
2942 fprintf (file, "%d\taffine univariate chrecs\n", stats->nb_affine);
2943 fprintf (file, "%d\taffine multivariate chrecs\n", stats->nb_affine_multivar);
2944 fprintf (file, "%d\tdegree greater than 2 polynomials\n",
2945 stats->nb_higher_poly);
2946 fprintf (file, "%d\tchrec_dont_know chrecs\n", stats->nb_chrec_dont_know);
2947 fprintf (file, "-----------------------------------------\n");
2948 fprintf (file, "%d\ttotal chrecs\n", stats->nb_chrecs);
2949 fprintf (file, "%d\twith undetermined coefficients\n",
2950 stats->nb_undetermined);
2951 fprintf (file, "-----------------------------------------\n");
2952 fprintf (file, "%d\tchrecs in the scev database\n",
2953 (int) htab_elements (scalar_evolution_info));
2954 fprintf (file, "%d\tsets in the scev database\n", nb_set_scev);
2955 fprintf (file, "%d\tgets in the scev database\n", nb_get_scev);
2956 fprintf (file, "-----------------------------------------\n");
2957 fprintf (file, ")\n\n");
2960 /* Gather statistics about CHREC. */
2962 static void
2963 gather_chrec_stats (tree chrec, struct chrec_stats *stats)
2965 if (dump_file && (dump_flags & TDF_STATS))
2967 fprintf (dump_file, "(classify_chrec ");
2968 print_generic_expr (dump_file, chrec, 0);
2969 fprintf (dump_file, "\n");
2972 stats->nb_chrecs++;
2974 if (chrec == NULL_TREE)
2976 stats->nb_undetermined++;
2977 return;
2980 switch (TREE_CODE (chrec))
2982 case POLYNOMIAL_CHREC:
2983 if (evolution_function_is_affine_p (chrec))
2985 if (dump_file && (dump_flags & TDF_STATS))
2986 fprintf (dump_file, " affine_univariate\n");
2987 stats->nb_affine++;
2989 else if (evolution_function_is_affine_multivariate_p (chrec, 0))
2991 if (dump_file && (dump_flags & TDF_STATS))
2992 fprintf (dump_file, " affine_multivariate\n");
2993 stats->nb_affine_multivar++;
2995 else
2997 if (dump_file && (dump_flags & TDF_STATS))
2998 fprintf (dump_file, " higher_degree_polynomial\n");
2999 stats->nb_higher_poly++;
3002 break;
3004 default:
3005 break;
3008 if (chrec_contains_undetermined (chrec))
3010 if (dump_file && (dump_flags & TDF_STATS))
3011 fprintf (dump_file, " undetermined\n");
3012 stats->nb_undetermined++;
3015 if (dump_file && (dump_flags & TDF_STATS))
3016 fprintf (dump_file, ")\n");
3019 /* Callback for htab_traverse, gathers information on chrecs in the
3020 hashtable. */
3022 static int
3023 gather_stats_on_scev_database_1 (void **slot, void *stats)
3025 struct scev_info_str *entry = (struct scev_info_str *) *slot;
3027 gather_chrec_stats (entry->chrec, (struct chrec_stats *) stats);
3029 return 1;
3032 /* Classify the chrecs of the whole database. */
3034 void
3035 gather_stats_on_scev_database (void)
3037 struct chrec_stats stats;
3039 if (!dump_file)
3040 return;
3042 reset_chrecs_counters (&stats);
3044 htab_traverse (scalar_evolution_info, gather_stats_on_scev_database_1,
3045 &stats);
3047 dump_chrecs_stats (dump_file, &stats);
3052 /* Initializer. */
3054 static void
3055 initialize_scalar_evolutions_analyzer (void)
3057 /* The elements below are unique. */
3058 if (chrec_dont_know == NULL_TREE)
3060 chrec_not_analyzed_yet = NULL_TREE;
3061 chrec_dont_know = make_node (SCEV_NOT_KNOWN);
3062 chrec_known = make_node (SCEV_KNOWN);
3063 TREE_TYPE (chrec_dont_know) = void_type_node;
3064 TREE_TYPE (chrec_known) = void_type_node;
3068 /* Initialize the analysis of scalar evolutions for LOOPS. */
3070 void
3071 scev_initialize (void)
3073 loop_iterator li;
3074 struct loop *loop;
3077 scalar_evolution_info = htab_create_ggc (100, hash_scev_info, eq_scev_info,
3078 del_scev_info);
3080 initialize_scalar_evolutions_analyzer ();
3082 FOR_EACH_LOOP (li, loop, 0)
3084 loop->nb_iterations = NULL_TREE;
3088 /* Return true if SCEV is initialized. */
3090 bool
3091 scev_initialized_p (void)
3093 return scalar_evolution_info != NULL;
3096 /* Cleans up the information cached by the scalar evolutions analysis
3097 in the hash table. */
3099 void
3100 scev_reset_htab (void)
3102 if (!scalar_evolution_info)
3103 return;
3105 htab_empty (scalar_evolution_info);
3108 /* Cleans up the information cached by the scalar evolutions analysis
3109 in the hash table and in the loop->nb_iterations. */
3111 void
3112 scev_reset (void)
3114 loop_iterator li;
3115 struct loop *loop;
3117 scev_reset_htab ();
3119 if (!current_loops)
3120 return;
3122 FOR_EACH_LOOP (li, loop, 0)
3124 loop->nb_iterations = NULL_TREE;
3128 /* Checks whether use of OP in USE_LOOP behaves as a simple affine iv with
3129 respect to WRTO_LOOP and returns its base and step in IV if possible
3130 (see analyze_scalar_evolution_in_loop for more details on USE_LOOP
3131 and WRTO_LOOP). If ALLOW_NONCONSTANT_STEP is true, we want step to be
3132 invariant in LOOP. Otherwise we require it to be an integer constant.
3134 IV->no_overflow is set to true if we are sure the iv cannot overflow (e.g.
3135 because it is computed in signed arithmetics). Consequently, adding an
3136 induction variable
3138 for (i = IV->base; ; i += IV->step)
3140 is only safe if IV->no_overflow is false, or TYPE_OVERFLOW_UNDEFINED is
3141 false for the type of the induction variable, or you can prove that i does
3142 not wrap by some other argument. Otherwise, this might introduce undefined
3143 behavior, and
3145 for (i = iv->base; ; i = (type) ((unsigned type) i + (unsigned type) iv->step))
3147 must be used instead. */
3149 bool
3150 simple_iv (struct loop *wrto_loop, struct loop *use_loop, tree op,
3151 affine_iv *iv, bool allow_nonconstant_step)
3153 tree type, ev;
3154 bool folded_casts;
3156 iv->base = NULL_TREE;
3157 iv->step = NULL_TREE;
3158 iv->no_overflow = false;
3160 type = TREE_TYPE (op);
3161 if (!POINTER_TYPE_P (type)
3162 && !INTEGRAL_TYPE_P (type))
3163 return false;
3165 ev = analyze_scalar_evolution_in_loop (wrto_loop, use_loop, op,
3166 &folded_casts);
3167 if (chrec_contains_undetermined (ev)
3168 || chrec_contains_symbols_defined_in_loop (ev, wrto_loop->num))
3169 return false;
3171 if (tree_does_not_contain_chrecs (ev))
3173 iv->base = ev;
3174 iv->step = build_int_cst (TREE_TYPE (ev), 0);
3175 iv->no_overflow = true;
3176 return true;
3179 if (TREE_CODE (ev) != POLYNOMIAL_CHREC
3180 || CHREC_VARIABLE (ev) != (unsigned) wrto_loop->num)
3181 return false;
3183 iv->step = CHREC_RIGHT (ev);
3184 if ((!allow_nonconstant_step && TREE_CODE (iv->step) != INTEGER_CST)
3185 || tree_contains_chrecs (iv->step, NULL))
3186 return false;
3188 iv->base = CHREC_LEFT (ev);
3189 if (tree_contains_chrecs (iv->base, NULL))
3190 return false;
3192 iv->no_overflow = !folded_casts && TYPE_OVERFLOW_UNDEFINED (type);
3194 return true;
3197 /* Finalize the scalar evolution analysis. */
3199 void
3200 scev_finalize (void)
3202 if (!scalar_evolution_info)
3203 return;
3204 htab_delete (scalar_evolution_info);
3205 scalar_evolution_info = NULL;
3208 /* Returns true if the expression EXPR is considered to be too expensive
3209 for scev_const_prop. */
3211 bool
3212 expression_expensive_p (tree expr)
3214 enum tree_code code;
3216 if (is_gimple_val (expr))
3217 return false;
3219 code = TREE_CODE (expr);
3220 if (code == TRUNC_DIV_EXPR
3221 || code == CEIL_DIV_EXPR
3222 || code == FLOOR_DIV_EXPR
3223 || code == ROUND_DIV_EXPR
3224 || code == TRUNC_MOD_EXPR
3225 || code == CEIL_MOD_EXPR
3226 || code == FLOOR_MOD_EXPR
3227 || code == ROUND_MOD_EXPR
3228 || code == EXACT_DIV_EXPR)
3230 /* Division by power of two is usually cheap, so we allow it.
3231 Forbid anything else. */
3232 if (!integer_pow2p (TREE_OPERAND (expr, 1)))
3233 return true;
3236 switch (TREE_CODE_CLASS (code))
3238 case tcc_binary:
3239 case tcc_comparison:
3240 if (expression_expensive_p (TREE_OPERAND (expr, 1)))
3241 return true;
3243 /* Fallthru. */
3244 case tcc_unary:
3245 return expression_expensive_p (TREE_OPERAND (expr, 0));
3247 default:
3248 return true;
3252 /* Replace ssa names for that scev can prove they are constant by the
3253 appropriate constants. Also perform final value replacement in loops,
3254 in case the replacement expressions are cheap.
3256 We only consider SSA names defined by phi nodes; rest is left to the
3257 ordinary constant propagation pass. */
3259 unsigned int
3260 scev_const_prop (void)
3262 basic_block bb;
3263 tree name, type, ev;
3264 gimple phi, ass;
3265 struct loop *loop, *ex_loop;
3266 bitmap ssa_names_to_remove = NULL;
3267 unsigned i;
3268 loop_iterator li;
3269 gimple_stmt_iterator psi;
3271 if (number_of_loops (cfun) <= 1)
3272 return 0;
3274 FOR_EACH_BB (bb)
3276 loop = bb->loop_father;
3278 for (psi = gsi_start_phis (bb); !gsi_end_p (psi); gsi_next (&psi))
3280 phi = gsi_stmt (psi);
3281 name = PHI_RESULT (phi);
3283 if (virtual_operand_p (name))
3284 continue;
3286 type = TREE_TYPE (name);
3288 if (!POINTER_TYPE_P (type)
3289 && !INTEGRAL_TYPE_P (type))
3290 continue;
3292 ev = resolve_mixers (loop, analyze_scalar_evolution (loop, name));
3293 if (!is_gimple_min_invariant (ev)
3294 || !may_propagate_copy (name, ev))
3295 continue;
3297 /* Replace the uses of the name. */
3298 if (name != ev)
3299 replace_uses_by (name, ev);
3301 if (!ssa_names_to_remove)
3302 ssa_names_to_remove = BITMAP_ALLOC (NULL);
3303 bitmap_set_bit (ssa_names_to_remove, SSA_NAME_VERSION (name));
3307 /* Remove the ssa names that were replaced by constants. We do not
3308 remove them directly in the previous cycle, since this
3309 invalidates scev cache. */
3310 if (ssa_names_to_remove)
3312 bitmap_iterator bi;
3314 EXECUTE_IF_SET_IN_BITMAP (ssa_names_to_remove, 0, i, bi)
3316 gimple_stmt_iterator psi;
3317 name = ssa_name (i);
3318 phi = SSA_NAME_DEF_STMT (name);
3320 gcc_assert (gimple_code (phi) == GIMPLE_PHI);
3321 psi = gsi_for_stmt (phi);
3322 remove_phi_node (&psi, true);
3325 BITMAP_FREE (ssa_names_to_remove);
3326 scev_reset ();
3329 /* Now the regular final value replacement. */
3330 FOR_EACH_LOOP (li, loop, LI_FROM_INNERMOST)
3332 edge exit;
3333 tree def, rslt, niter;
3334 gimple_stmt_iterator bsi;
3336 /* If we do not know exact number of iterations of the loop, we cannot
3337 replace the final value. */
3338 exit = single_exit (loop);
3339 if (!exit)
3340 continue;
3342 niter = number_of_latch_executions (loop);
3343 if (niter == chrec_dont_know)
3344 continue;
3346 /* Ensure that it is possible to insert new statements somewhere. */
3347 if (!single_pred_p (exit->dest))
3348 split_loop_exit_edge (exit);
3349 bsi = gsi_after_labels (exit->dest);
3351 ex_loop = superloop_at_depth (loop,
3352 loop_depth (exit->dest->loop_father) + 1);
3354 for (psi = gsi_start_phis (exit->dest); !gsi_end_p (psi); )
3356 phi = gsi_stmt (psi);
3357 rslt = PHI_RESULT (phi);
3358 def = PHI_ARG_DEF_FROM_EDGE (phi, exit);
3359 if (virtual_operand_p (def))
3361 gsi_next (&psi);
3362 continue;
3365 if (!POINTER_TYPE_P (TREE_TYPE (def))
3366 && !INTEGRAL_TYPE_P (TREE_TYPE (def)))
3368 gsi_next (&psi);
3369 continue;
3372 def = analyze_scalar_evolution_in_loop (ex_loop, loop, def, NULL);
3373 def = compute_overall_effect_of_inner_loop (ex_loop, def);
3374 if (!tree_does_not_contain_chrecs (def)
3375 || chrec_contains_symbols_defined_in_loop (def, ex_loop->num)
3376 /* Moving the computation from the loop may prolong life range
3377 of some ssa names, which may cause problems if they appear
3378 on abnormal edges. */
3379 || contains_abnormal_ssa_name_p (def)
3380 /* Do not emit expensive expressions. The rationale is that
3381 when someone writes a code like
3383 while (n > 45) n -= 45;
3385 he probably knows that n is not large, and does not want it
3386 to be turned into n %= 45. */
3387 || expression_expensive_p (def))
3389 if (dump_file && (dump_flags & TDF_DETAILS))
3391 fprintf (dump_file, "not replacing:\n ");
3392 print_gimple_stmt (dump_file, phi, 0, 0);
3393 fprintf (dump_file, "\n");
3395 gsi_next (&psi);
3396 continue;
3399 /* Eliminate the PHI node and replace it by a computation outside
3400 the loop. */
3401 if (dump_file)
3403 fprintf (dump_file, "\nfinal value replacement:\n ");
3404 print_gimple_stmt (dump_file, phi, 0, 0);
3405 fprintf (dump_file, " with\n ");
3407 def = unshare_expr (def);
3408 remove_phi_node (&psi, false);
3410 def = force_gimple_operand_gsi (&bsi, def, false, NULL_TREE,
3411 true, GSI_SAME_STMT);
3412 ass = gimple_build_assign (rslt, def);
3413 gsi_insert_before (&bsi, ass, GSI_SAME_STMT);
3414 if (dump_file)
3416 print_gimple_stmt (dump_file, ass, 0, 0);
3417 fprintf (dump_file, "\n");
3421 return 0;
3424 #include "gt-tree-scalar-evolution.h"