cgraph.c (cgraph_turn_edge_to_speculative): Fix debug output.
[official-gcc.git] / gcc / tree-scalar-evolution.c
blobc7e9d4b46cdfdda5eb6b7b0f557ce076d2281db5
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 && !flow_loop_nested_p (def_bb->loop_father, inner_loop))
2256 /* ??? We could try to compute the overall effect of the loop here. */
2257 res = chrec_dont_know;
2258 else
2259 res = instantiate_scev_r (instantiate_below, evolution_loop,
2260 inner_loop, res,
2261 fold_conversions, cache, size_expr);
2264 /* Store the correct value to the cache. */
2265 *si = res;
2266 return res;
2269 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2270 and EVOLUTION_LOOP, that were left under a symbolic form.
2272 CHREC is a polynomial chain of recurrence to be instantiated.
2274 CACHE is the cache of already instantiated values.
2276 FOLD_CONVERSIONS should be set to true when the conversions that
2277 may wrap in signed/pointer type are folded, as long as the value of
2278 the chrec is preserved.
2280 SIZE_EXPR is used for computing the size of the expression to be
2281 instantiated, and to stop if it exceeds some limit. */
2283 static tree
2284 instantiate_scev_poly (basic_block instantiate_below,
2285 struct loop *evolution_loop, struct loop *,
2286 tree chrec,
2287 bool fold_conversions, instantiate_cache_type &cache,
2288 int size_expr)
2290 tree op1;
2291 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2292 get_chrec_loop (chrec),
2293 CHREC_LEFT (chrec), fold_conversions, cache,
2294 size_expr);
2295 if (op0 == chrec_dont_know)
2296 return chrec_dont_know;
2298 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2299 get_chrec_loop (chrec),
2300 CHREC_RIGHT (chrec), fold_conversions, cache,
2301 size_expr);
2302 if (op1 == chrec_dont_know)
2303 return chrec_dont_know;
2305 if (CHREC_LEFT (chrec) != op0
2306 || CHREC_RIGHT (chrec) != op1)
2308 op1 = chrec_convert_rhs (chrec_type (op0), op1, NULL);
2309 chrec = build_polynomial_chrec (CHREC_VARIABLE (chrec), op0, op1);
2312 return chrec;
2315 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2316 and EVOLUTION_LOOP, that were left under a symbolic form.
2318 "C0 CODE C1" is a binary expression of type TYPE to be instantiated.
2320 CACHE is the cache of already instantiated values.
2322 FOLD_CONVERSIONS should be set to true when the conversions that
2323 may wrap in signed/pointer type are folded, as long as the value of
2324 the chrec is preserved.
2326 SIZE_EXPR is used for computing the size of the expression to be
2327 instantiated, and to stop if it exceeds some limit. */
2329 static tree
2330 instantiate_scev_binary (basic_block instantiate_below,
2331 struct loop *evolution_loop, struct loop *inner_loop,
2332 tree chrec, enum tree_code code,
2333 tree type, tree c0, tree c1,
2334 bool fold_conversions,
2335 instantiate_cache_type &cache,
2336 int size_expr)
2338 tree op1;
2339 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop, inner_loop,
2340 c0, fold_conversions, cache,
2341 size_expr);
2342 if (op0 == chrec_dont_know)
2343 return chrec_dont_know;
2345 op1 = instantiate_scev_r (instantiate_below, evolution_loop, inner_loop,
2346 c1, fold_conversions, cache,
2347 size_expr);
2348 if (op1 == chrec_dont_know)
2349 return chrec_dont_know;
2351 if (c0 != op0
2352 || c1 != op1)
2354 op0 = chrec_convert (type, op0, NULL);
2355 op1 = chrec_convert_rhs (type, op1, NULL);
2357 switch (code)
2359 case POINTER_PLUS_EXPR:
2360 case PLUS_EXPR:
2361 return chrec_fold_plus (type, op0, op1);
2363 case MINUS_EXPR:
2364 return chrec_fold_minus (type, op0, op1);
2366 case MULT_EXPR:
2367 return chrec_fold_multiply (type, op0, op1);
2369 default:
2370 gcc_unreachable ();
2374 return chrec ? chrec : fold_build2 (code, type, c0, c1);
2377 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2378 and EVOLUTION_LOOP, that were left under a symbolic form.
2380 "CHREC" is an array reference to be instantiated.
2382 CACHE is the cache of already instantiated values.
2384 FOLD_CONVERSIONS should be set to true when the conversions that
2385 may wrap in signed/pointer type are folded, as long as the value of
2386 the chrec is preserved.
2388 SIZE_EXPR is used for computing the size of the expression to be
2389 instantiated, and to stop if it exceeds some limit. */
2391 static tree
2392 instantiate_array_ref (basic_block instantiate_below,
2393 struct loop *evolution_loop, struct loop *inner_loop,
2394 tree chrec,
2395 bool fold_conversions, instantiate_cache_type &cache,
2396 int size_expr)
2398 tree res;
2399 tree index = TREE_OPERAND (chrec, 1);
2400 tree op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2401 inner_loop, index,
2402 fold_conversions, cache, size_expr);
2404 if (op1 == chrec_dont_know)
2405 return chrec_dont_know;
2407 if (chrec && op1 == index)
2408 return chrec;
2410 res = unshare_expr (chrec);
2411 TREE_OPERAND (res, 1) = op1;
2412 return res;
2415 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2416 and EVOLUTION_LOOP, that were left under a symbolic form.
2418 "CHREC" that stands for a convert expression "(TYPE) OP" is to be
2419 instantiated.
2421 CACHE is the cache of already instantiated values.
2423 FOLD_CONVERSIONS should be set to true when the conversions that
2424 may wrap in signed/pointer type are folded, as long as the value of
2425 the chrec is preserved.
2427 SIZE_EXPR is used for computing the size of the expression to be
2428 instantiated, and to stop if it exceeds some limit. */
2430 static tree
2431 instantiate_scev_convert (basic_block instantiate_below,
2432 struct loop *evolution_loop, struct loop *inner_loop,
2433 tree chrec,
2434 tree type, tree op,
2435 bool fold_conversions,
2436 instantiate_cache_type &cache, int size_expr)
2438 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2439 inner_loop, op,
2440 fold_conversions, cache, size_expr);
2442 if (op0 == chrec_dont_know)
2443 return chrec_dont_know;
2445 if (fold_conversions)
2447 tree tmp = chrec_convert_aggressive (type, op0);
2448 if (tmp)
2449 return tmp;
2452 if (chrec && op0 == op)
2453 return chrec;
2455 /* If we used chrec_convert_aggressive, we can no longer assume that
2456 signed chrecs do not overflow, as chrec_convert does, so avoid
2457 calling it in that case. */
2458 if (fold_conversions)
2459 return fold_convert (type, op0);
2461 return chrec_convert (type, op0, NULL);
2464 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2465 and EVOLUTION_LOOP, that were left under a symbolic form.
2467 CHREC is a BIT_NOT_EXPR or a NEGATE_EXPR expression to be instantiated.
2468 Handle ~X as -1 - X.
2469 Handle -X as -1 * X.
2471 CACHE is the cache of already instantiated values.
2473 FOLD_CONVERSIONS should be set to true when the conversions that
2474 may wrap in signed/pointer type are folded, as long as the value of
2475 the chrec is preserved.
2477 SIZE_EXPR is used for computing the size of the expression to be
2478 instantiated, and to stop if it exceeds some limit. */
2480 static tree
2481 instantiate_scev_not (basic_block instantiate_below,
2482 struct loop *evolution_loop, struct loop *inner_loop,
2483 tree chrec,
2484 enum tree_code code, tree type, tree op,
2485 bool fold_conversions, instantiate_cache_type &cache,
2486 int size_expr)
2488 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2489 inner_loop, op,
2490 fold_conversions, cache, size_expr);
2492 if (op0 == chrec_dont_know)
2493 return chrec_dont_know;
2495 if (op != op0)
2497 op0 = chrec_convert (type, op0, NULL);
2499 switch (code)
2501 case BIT_NOT_EXPR:
2502 return chrec_fold_minus
2503 (type, fold_convert (type, integer_minus_one_node), op0);
2505 case NEGATE_EXPR:
2506 return chrec_fold_multiply
2507 (type, fold_convert (type, integer_minus_one_node), op0);
2509 default:
2510 gcc_unreachable ();
2514 return chrec ? chrec : fold_build1 (code, type, op0);
2517 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2518 and EVOLUTION_LOOP, that were left under a symbolic form.
2520 CHREC is an expression with 3 operands to be instantiated.
2522 CACHE is the cache of already instantiated values.
2524 FOLD_CONVERSIONS should be set to true when the conversions that
2525 may wrap in signed/pointer type are folded, as long as the value of
2526 the chrec is preserved.
2528 SIZE_EXPR is used for computing the size of the expression to be
2529 instantiated, and to stop if it exceeds some limit. */
2531 static tree
2532 instantiate_scev_3 (basic_block instantiate_below,
2533 struct loop *evolution_loop, struct loop *inner_loop,
2534 tree chrec,
2535 bool fold_conversions, instantiate_cache_type &cache,
2536 int size_expr)
2538 tree op1, op2;
2539 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2540 inner_loop, TREE_OPERAND (chrec, 0),
2541 fold_conversions, cache, size_expr);
2542 if (op0 == chrec_dont_know)
2543 return chrec_dont_know;
2545 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2546 inner_loop, TREE_OPERAND (chrec, 1),
2547 fold_conversions, cache, size_expr);
2548 if (op1 == chrec_dont_know)
2549 return chrec_dont_know;
2551 op2 = instantiate_scev_r (instantiate_below, evolution_loop,
2552 inner_loop, TREE_OPERAND (chrec, 2),
2553 fold_conversions, cache, size_expr);
2554 if (op2 == chrec_dont_know)
2555 return chrec_dont_know;
2557 if (op0 == TREE_OPERAND (chrec, 0)
2558 && op1 == TREE_OPERAND (chrec, 1)
2559 && op2 == TREE_OPERAND (chrec, 2))
2560 return chrec;
2562 return fold_build3 (TREE_CODE (chrec),
2563 TREE_TYPE (chrec), op0, op1, op2);
2566 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2567 and EVOLUTION_LOOP, that were left under a symbolic form.
2569 CHREC is an expression with 2 operands to be instantiated.
2571 CACHE is the cache of already instantiated values.
2573 FOLD_CONVERSIONS should be set to true when the conversions that
2574 may wrap in signed/pointer type are folded, as long as the value of
2575 the chrec is preserved.
2577 SIZE_EXPR is used for computing the size of the expression to be
2578 instantiated, and to stop if it exceeds some limit. */
2580 static tree
2581 instantiate_scev_2 (basic_block instantiate_below,
2582 struct loop *evolution_loop, struct loop *inner_loop,
2583 tree chrec,
2584 bool fold_conversions, instantiate_cache_type &cache,
2585 int size_expr)
2587 tree op1;
2588 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2589 inner_loop, TREE_OPERAND (chrec, 0),
2590 fold_conversions, cache, size_expr);
2591 if (op0 == chrec_dont_know)
2592 return chrec_dont_know;
2594 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2595 inner_loop, TREE_OPERAND (chrec, 1),
2596 fold_conversions, cache, size_expr);
2597 if (op1 == chrec_dont_know)
2598 return chrec_dont_know;
2600 if (op0 == TREE_OPERAND (chrec, 0)
2601 && op1 == TREE_OPERAND (chrec, 1))
2602 return chrec;
2604 return fold_build2 (TREE_CODE (chrec), TREE_TYPE (chrec), op0, op1);
2607 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2608 and EVOLUTION_LOOP, that were left under a symbolic form.
2610 CHREC is an expression with 2 operands to be instantiated.
2612 CACHE is the cache of already instantiated values.
2614 FOLD_CONVERSIONS should be set to true when the conversions that
2615 may wrap in signed/pointer type are folded, as long as the value of
2616 the chrec is preserved.
2618 SIZE_EXPR is used for computing the size of the expression to be
2619 instantiated, and to stop if it exceeds some limit. */
2621 static tree
2622 instantiate_scev_1 (basic_block instantiate_below,
2623 struct loop *evolution_loop, struct loop *inner_loop,
2624 tree chrec,
2625 bool fold_conversions, instantiate_cache_type &cache,
2626 int size_expr)
2628 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2629 inner_loop, TREE_OPERAND (chrec, 0),
2630 fold_conversions, cache, size_expr);
2632 if (op0 == chrec_dont_know)
2633 return chrec_dont_know;
2635 if (op0 == TREE_OPERAND (chrec, 0))
2636 return chrec;
2638 return fold_build1 (TREE_CODE (chrec), TREE_TYPE (chrec), op0);
2641 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2642 and EVOLUTION_LOOP, that were left under a symbolic form.
2644 CHREC is the scalar evolution to instantiate.
2646 CACHE is the cache of already instantiated values.
2648 FOLD_CONVERSIONS should be set to true when the conversions that
2649 may wrap in signed/pointer type are folded, as long as the value of
2650 the chrec is preserved.
2652 SIZE_EXPR is used for computing the size of the expression to be
2653 instantiated, and to stop if it exceeds some limit. */
2655 static tree
2656 instantiate_scev_r (basic_block instantiate_below,
2657 struct loop *evolution_loop, struct loop *inner_loop,
2658 tree chrec,
2659 bool fold_conversions, instantiate_cache_type &cache,
2660 int size_expr)
2662 /* Give up if the expression is larger than the MAX that we allow. */
2663 if (size_expr++ > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_SIZE))
2664 return chrec_dont_know;
2666 if (chrec == NULL_TREE
2667 || automatically_generated_chrec_p (chrec)
2668 || is_gimple_min_invariant (chrec))
2669 return chrec;
2671 switch (TREE_CODE (chrec))
2673 case SSA_NAME:
2674 return instantiate_scev_name (instantiate_below, evolution_loop,
2675 inner_loop, chrec,
2676 fold_conversions, cache, size_expr);
2678 case POLYNOMIAL_CHREC:
2679 return instantiate_scev_poly (instantiate_below, evolution_loop,
2680 inner_loop, chrec,
2681 fold_conversions, cache, size_expr);
2683 case POINTER_PLUS_EXPR:
2684 case PLUS_EXPR:
2685 case MINUS_EXPR:
2686 case MULT_EXPR:
2687 return instantiate_scev_binary (instantiate_below, evolution_loop,
2688 inner_loop, chrec,
2689 TREE_CODE (chrec), chrec_type (chrec),
2690 TREE_OPERAND (chrec, 0),
2691 TREE_OPERAND (chrec, 1),
2692 fold_conversions, cache, size_expr);
2694 CASE_CONVERT:
2695 return instantiate_scev_convert (instantiate_below, evolution_loop,
2696 inner_loop, chrec,
2697 TREE_TYPE (chrec), TREE_OPERAND (chrec, 0),
2698 fold_conversions, cache, size_expr);
2700 case NEGATE_EXPR:
2701 case BIT_NOT_EXPR:
2702 return instantiate_scev_not (instantiate_below, evolution_loop,
2703 inner_loop, chrec,
2704 TREE_CODE (chrec), TREE_TYPE (chrec),
2705 TREE_OPERAND (chrec, 0),
2706 fold_conversions, cache, size_expr);
2708 case ADDR_EXPR:
2709 case SCEV_NOT_KNOWN:
2710 return chrec_dont_know;
2712 case SCEV_KNOWN:
2713 return chrec_known;
2715 case ARRAY_REF:
2716 return instantiate_array_ref (instantiate_below, evolution_loop,
2717 inner_loop, chrec,
2718 fold_conversions, cache, size_expr);
2720 default:
2721 break;
2724 if (VL_EXP_CLASS_P (chrec))
2725 return chrec_dont_know;
2727 switch (TREE_CODE_LENGTH (TREE_CODE (chrec)))
2729 case 3:
2730 return instantiate_scev_3 (instantiate_below, evolution_loop,
2731 inner_loop, chrec,
2732 fold_conversions, cache, size_expr);
2734 case 2:
2735 return instantiate_scev_2 (instantiate_below, evolution_loop,
2736 inner_loop, chrec,
2737 fold_conversions, cache, size_expr);
2739 case 1:
2740 return instantiate_scev_1 (instantiate_below, evolution_loop,
2741 inner_loop, chrec,
2742 fold_conversions, cache, size_expr);
2744 case 0:
2745 return chrec;
2747 default:
2748 break;
2751 /* Too complicated to handle. */
2752 return chrec_dont_know;
2755 /* Analyze all the parameters of the chrec that were left under a
2756 symbolic form. INSTANTIATE_BELOW is the basic block that stops the
2757 recursive instantiation of parameters: a parameter is a variable
2758 that is defined in a basic block that dominates INSTANTIATE_BELOW or
2759 a function parameter. */
2761 tree
2762 instantiate_scev (basic_block instantiate_below, struct loop *evolution_loop,
2763 tree chrec)
2765 tree res;
2766 instantiate_cache_type cache;
2768 if (dump_file && (dump_flags & TDF_SCEV))
2770 fprintf (dump_file, "(instantiate_scev \n");
2771 fprintf (dump_file, " (instantiate_below = %d)\n", instantiate_below->index);
2772 fprintf (dump_file, " (evolution_loop = %d)\n", evolution_loop->num);
2773 fprintf (dump_file, " (chrec = ");
2774 print_generic_expr (dump_file, chrec, 0);
2775 fprintf (dump_file, ")\n");
2778 res = instantiate_scev_r (instantiate_below, evolution_loop,
2779 NULL, chrec, false, cache, 0);
2781 if (dump_file && (dump_flags & TDF_SCEV))
2783 fprintf (dump_file, " (res = ");
2784 print_generic_expr (dump_file, res, 0);
2785 fprintf (dump_file, "))\n");
2788 return res;
2791 /* Similar to instantiate_parameters, but does not introduce the
2792 evolutions in outer loops for LOOP invariants in CHREC, and does not
2793 care about causing overflows, as long as they do not affect value
2794 of an expression. */
2796 tree
2797 resolve_mixers (struct loop *loop, tree chrec)
2799 instantiate_cache_type cache;
2800 tree ret = instantiate_scev_r (block_before_loop (loop), loop, NULL,
2801 chrec, true, cache, 0);
2802 return ret;
2805 /* Entry point for the analysis of the number of iterations pass.
2806 This function tries to safely approximate the number of iterations
2807 the loop will run. When this property is not decidable at compile
2808 time, the result is chrec_dont_know. Otherwise the result is a
2809 scalar or a symbolic parameter. When the number of iterations may
2810 be equal to zero and the property cannot be determined at compile
2811 time, the result is a COND_EXPR that represents in a symbolic form
2812 the conditions under which the number of iterations is not zero.
2814 Example of analysis: suppose that the loop has an exit condition:
2816 "if (b > 49) goto end_loop;"
2818 and that in a previous analysis we have determined that the
2819 variable 'b' has an evolution function:
2821 "EF = {23, +, 5}_2".
2823 When we evaluate the function at the point 5, i.e. the value of the
2824 variable 'b' after 5 iterations in the loop, we have EF (5) = 48,
2825 and EF (6) = 53. In this case the value of 'b' on exit is '53' and
2826 the loop body has been executed 6 times. */
2828 tree
2829 number_of_latch_executions (struct loop *loop)
2831 edge exit;
2832 struct tree_niter_desc niter_desc;
2833 tree may_be_zero;
2834 tree res;
2836 /* Determine whether the number of iterations in loop has already
2837 been computed. */
2838 res = loop->nb_iterations;
2839 if (res)
2840 return res;
2842 may_be_zero = NULL_TREE;
2844 if (dump_file && (dump_flags & TDF_SCEV))
2845 fprintf (dump_file, "(number_of_iterations_in_loop = \n");
2847 res = chrec_dont_know;
2848 exit = single_exit (loop);
2850 if (exit && number_of_iterations_exit (loop, exit, &niter_desc, false))
2852 may_be_zero = niter_desc.may_be_zero;
2853 res = niter_desc.niter;
2856 if (res == chrec_dont_know
2857 || !may_be_zero
2858 || integer_zerop (may_be_zero))
2860 else if (integer_nonzerop (may_be_zero))
2861 res = build_int_cst (TREE_TYPE (res), 0);
2863 else if (COMPARISON_CLASS_P (may_be_zero))
2864 res = fold_build3 (COND_EXPR, TREE_TYPE (res), may_be_zero,
2865 build_int_cst (TREE_TYPE (res), 0), res);
2866 else
2867 res = chrec_dont_know;
2869 if (dump_file && (dump_flags & TDF_SCEV))
2871 fprintf (dump_file, " (set_nb_iterations_in_loop = ");
2872 print_generic_expr (dump_file, res, 0);
2873 fprintf (dump_file, "))\n");
2876 loop->nb_iterations = res;
2877 return res;
2880 /* Returns the number of executions of the exit condition of LOOP,
2881 i.e., the number by one higher than number_of_latch_executions.
2882 Note that unlike number_of_latch_executions, this number does
2883 not necessarily fit in the unsigned variant of the type of
2884 the control variable -- if the number of iterations is a constant,
2885 we return chrec_dont_know if adding one to number_of_latch_executions
2886 overflows; however, in case the number of iterations is symbolic
2887 expression, the caller is responsible for dealing with this
2888 the possible overflow. */
2890 tree
2891 number_of_exit_cond_executions (struct loop *loop)
2893 tree ret = number_of_latch_executions (loop);
2894 tree type = chrec_type (ret);
2896 if (chrec_contains_undetermined (ret))
2897 return ret;
2899 ret = chrec_fold_plus (type, ret, build_int_cst (type, 1));
2900 if (TREE_CODE (ret) == INTEGER_CST
2901 && TREE_OVERFLOW (ret))
2902 return chrec_dont_know;
2904 return ret;
2909 /* Counters for the stats. */
2911 struct chrec_stats
2913 unsigned nb_chrecs;
2914 unsigned nb_affine;
2915 unsigned nb_affine_multivar;
2916 unsigned nb_higher_poly;
2917 unsigned nb_chrec_dont_know;
2918 unsigned nb_undetermined;
2921 /* Reset the counters. */
2923 static inline void
2924 reset_chrecs_counters (struct chrec_stats *stats)
2926 stats->nb_chrecs = 0;
2927 stats->nb_affine = 0;
2928 stats->nb_affine_multivar = 0;
2929 stats->nb_higher_poly = 0;
2930 stats->nb_chrec_dont_know = 0;
2931 stats->nb_undetermined = 0;
2934 /* Dump the contents of a CHREC_STATS structure. */
2936 static void
2937 dump_chrecs_stats (FILE *file, struct chrec_stats *stats)
2939 fprintf (file, "\n(\n");
2940 fprintf (file, "-----------------------------------------\n");
2941 fprintf (file, "%d\taffine univariate chrecs\n", stats->nb_affine);
2942 fprintf (file, "%d\taffine multivariate chrecs\n", stats->nb_affine_multivar);
2943 fprintf (file, "%d\tdegree greater than 2 polynomials\n",
2944 stats->nb_higher_poly);
2945 fprintf (file, "%d\tchrec_dont_know chrecs\n", stats->nb_chrec_dont_know);
2946 fprintf (file, "-----------------------------------------\n");
2947 fprintf (file, "%d\ttotal chrecs\n", stats->nb_chrecs);
2948 fprintf (file, "%d\twith undetermined coefficients\n",
2949 stats->nb_undetermined);
2950 fprintf (file, "-----------------------------------------\n");
2951 fprintf (file, "%d\tchrecs in the scev database\n",
2952 (int) htab_elements (scalar_evolution_info));
2953 fprintf (file, "%d\tsets in the scev database\n", nb_set_scev);
2954 fprintf (file, "%d\tgets in the scev database\n", nb_get_scev);
2955 fprintf (file, "-----------------------------------------\n");
2956 fprintf (file, ")\n\n");
2959 /* Gather statistics about CHREC. */
2961 static void
2962 gather_chrec_stats (tree chrec, struct chrec_stats *stats)
2964 if (dump_file && (dump_flags & TDF_STATS))
2966 fprintf (dump_file, "(classify_chrec ");
2967 print_generic_expr (dump_file, chrec, 0);
2968 fprintf (dump_file, "\n");
2971 stats->nb_chrecs++;
2973 if (chrec == NULL_TREE)
2975 stats->nb_undetermined++;
2976 return;
2979 switch (TREE_CODE (chrec))
2981 case POLYNOMIAL_CHREC:
2982 if (evolution_function_is_affine_p (chrec))
2984 if (dump_file && (dump_flags & TDF_STATS))
2985 fprintf (dump_file, " affine_univariate\n");
2986 stats->nb_affine++;
2988 else if (evolution_function_is_affine_multivariate_p (chrec, 0))
2990 if (dump_file && (dump_flags & TDF_STATS))
2991 fprintf (dump_file, " affine_multivariate\n");
2992 stats->nb_affine_multivar++;
2994 else
2996 if (dump_file && (dump_flags & TDF_STATS))
2997 fprintf (dump_file, " higher_degree_polynomial\n");
2998 stats->nb_higher_poly++;
3001 break;
3003 default:
3004 break;
3007 if (chrec_contains_undetermined (chrec))
3009 if (dump_file && (dump_flags & TDF_STATS))
3010 fprintf (dump_file, " undetermined\n");
3011 stats->nb_undetermined++;
3014 if (dump_file && (dump_flags & TDF_STATS))
3015 fprintf (dump_file, ")\n");
3018 /* Callback for htab_traverse, gathers information on chrecs in the
3019 hashtable. */
3021 static int
3022 gather_stats_on_scev_database_1 (void **slot, void *stats)
3024 struct scev_info_str *entry = (struct scev_info_str *) *slot;
3026 gather_chrec_stats (entry->chrec, (struct chrec_stats *) stats);
3028 return 1;
3031 /* Classify the chrecs of the whole database. */
3033 void
3034 gather_stats_on_scev_database (void)
3036 struct chrec_stats stats;
3038 if (!dump_file)
3039 return;
3041 reset_chrecs_counters (&stats);
3043 htab_traverse (scalar_evolution_info, gather_stats_on_scev_database_1,
3044 &stats);
3046 dump_chrecs_stats (dump_file, &stats);
3051 /* Initializer. */
3053 static void
3054 initialize_scalar_evolutions_analyzer (void)
3056 /* The elements below are unique. */
3057 if (chrec_dont_know == NULL_TREE)
3059 chrec_not_analyzed_yet = NULL_TREE;
3060 chrec_dont_know = make_node (SCEV_NOT_KNOWN);
3061 chrec_known = make_node (SCEV_KNOWN);
3062 TREE_TYPE (chrec_dont_know) = void_type_node;
3063 TREE_TYPE (chrec_known) = void_type_node;
3067 /* Initialize the analysis of scalar evolutions for LOOPS. */
3069 void
3070 scev_initialize (void)
3072 loop_iterator li;
3073 struct loop *loop;
3076 scalar_evolution_info = htab_create_ggc (100, hash_scev_info, eq_scev_info,
3077 del_scev_info);
3079 initialize_scalar_evolutions_analyzer ();
3081 FOR_EACH_LOOP (li, loop, 0)
3083 loop->nb_iterations = NULL_TREE;
3087 /* Return true if SCEV is initialized. */
3089 bool
3090 scev_initialized_p (void)
3092 return scalar_evolution_info != NULL;
3095 /* Cleans up the information cached by the scalar evolutions analysis
3096 in the hash table. */
3098 void
3099 scev_reset_htab (void)
3101 if (!scalar_evolution_info)
3102 return;
3104 htab_empty (scalar_evolution_info);
3107 /* Cleans up the information cached by the scalar evolutions analysis
3108 in the hash table and in the loop->nb_iterations. */
3110 void
3111 scev_reset (void)
3113 loop_iterator li;
3114 struct loop *loop;
3116 scev_reset_htab ();
3118 if (!current_loops)
3119 return;
3121 FOR_EACH_LOOP (li, loop, 0)
3123 loop->nb_iterations = NULL_TREE;
3127 /* Checks whether use of OP in USE_LOOP behaves as a simple affine iv with
3128 respect to WRTO_LOOP and returns its base and step in IV if possible
3129 (see analyze_scalar_evolution_in_loop for more details on USE_LOOP
3130 and WRTO_LOOP). If ALLOW_NONCONSTANT_STEP is true, we want step to be
3131 invariant in LOOP. Otherwise we require it to be an integer constant.
3133 IV->no_overflow is set to true if we are sure the iv cannot overflow (e.g.
3134 because it is computed in signed arithmetics). Consequently, adding an
3135 induction variable
3137 for (i = IV->base; ; i += IV->step)
3139 is only safe if IV->no_overflow is false, or TYPE_OVERFLOW_UNDEFINED is
3140 false for the type of the induction variable, or you can prove that i does
3141 not wrap by some other argument. Otherwise, this might introduce undefined
3142 behavior, and
3144 for (i = iv->base; ; i = (type) ((unsigned type) i + (unsigned type) iv->step))
3146 must be used instead. */
3148 bool
3149 simple_iv (struct loop *wrto_loop, struct loop *use_loop, tree op,
3150 affine_iv *iv, bool allow_nonconstant_step)
3152 tree type, ev;
3153 bool folded_casts;
3155 iv->base = NULL_TREE;
3156 iv->step = NULL_TREE;
3157 iv->no_overflow = false;
3159 type = TREE_TYPE (op);
3160 if (!POINTER_TYPE_P (type)
3161 && !INTEGRAL_TYPE_P (type))
3162 return false;
3164 ev = analyze_scalar_evolution_in_loop (wrto_loop, use_loop, op,
3165 &folded_casts);
3166 if (chrec_contains_undetermined (ev)
3167 || chrec_contains_symbols_defined_in_loop (ev, wrto_loop->num))
3168 return false;
3170 if (tree_does_not_contain_chrecs (ev))
3172 iv->base = ev;
3173 iv->step = build_int_cst (TREE_TYPE (ev), 0);
3174 iv->no_overflow = true;
3175 return true;
3178 if (TREE_CODE (ev) != POLYNOMIAL_CHREC
3179 || CHREC_VARIABLE (ev) != (unsigned) wrto_loop->num)
3180 return false;
3182 iv->step = CHREC_RIGHT (ev);
3183 if ((!allow_nonconstant_step && TREE_CODE (iv->step) != INTEGER_CST)
3184 || tree_contains_chrecs (iv->step, NULL))
3185 return false;
3187 iv->base = CHREC_LEFT (ev);
3188 if (tree_contains_chrecs (iv->base, NULL))
3189 return false;
3191 iv->no_overflow = !folded_casts && TYPE_OVERFLOW_UNDEFINED (type);
3193 return true;
3196 /* Finalize the scalar evolution analysis. */
3198 void
3199 scev_finalize (void)
3201 if (!scalar_evolution_info)
3202 return;
3203 htab_delete (scalar_evolution_info);
3204 scalar_evolution_info = NULL;
3207 /* Returns true if the expression EXPR is considered to be too expensive
3208 for scev_const_prop. */
3210 bool
3211 expression_expensive_p (tree expr)
3213 enum tree_code code;
3215 if (is_gimple_val (expr))
3216 return false;
3218 code = TREE_CODE (expr);
3219 if (code == TRUNC_DIV_EXPR
3220 || code == CEIL_DIV_EXPR
3221 || code == FLOOR_DIV_EXPR
3222 || code == ROUND_DIV_EXPR
3223 || code == TRUNC_MOD_EXPR
3224 || code == CEIL_MOD_EXPR
3225 || code == FLOOR_MOD_EXPR
3226 || code == ROUND_MOD_EXPR
3227 || code == EXACT_DIV_EXPR)
3229 /* Division by power of two is usually cheap, so we allow it.
3230 Forbid anything else. */
3231 if (!integer_pow2p (TREE_OPERAND (expr, 1)))
3232 return true;
3235 switch (TREE_CODE_CLASS (code))
3237 case tcc_binary:
3238 case tcc_comparison:
3239 if (expression_expensive_p (TREE_OPERAND (expr, 1)))
3240 return true;
3242 /* Fallthru. */
3243 case tcc_unary:
3244 return expression_expensive_p (TREE_OPERAND (expr, 0));
3246 default:
3247 return true;
3251 /* Replace ssa names for that scev can prove they are constant by the
3252 appropriate constants. Also perform final value replacement in loops,
3253 in case the replacement expressions are cheap.
3255 We only consider SSA names defined by phi nodes; rest is left to the
3256 ordinary constant propagation pass. */
3258 unsigned int
3259 scev_const_prop (void)
3261 basic_block bb;
3262 tree name, type, ev;
3263 gimple phi, ass;
3264 struct loop *loop, *ex_loop;
3265 bitmap ssa_names_to_remove = NULL;
3266 unsigned i;
3267 loop_iterator li;
3268 gimple_stmt_iterator psi;
3270 if (number_of_loops (cfun) <= 1)
3271 return 0;
3273 FOR_EACH_BB (bb)
3275 loop = bb->loop_father;
3277 for (psi = gsi_start_phis (bb); !gsi_end_p (psi); gsi_next (&psi))
3279 phi = gsi_stmt (psi);
3280 name = PHI_RESULT (phi);
3282 if (virtual_operand_p (name))
3283 continue;
3285 type = TREE_TYPE (name);
3287 if (!POINTER_TYPE_P (type)
3288 && !INTEGRAL_TYPE_P (type))
3289 continue;
3291 ev = resolve_mixers (loop, analyze_scalar_evolution (loop, name));
3292 if (!is_gimple_min_invariant (ev)
3293 || !may_propagate_copy (name, ev))
3294 continue;
3296 /* Replace the uses of the name. */
3297 if (name != ev)
3298 replace_uses_by (name, ev);
3300 if (!ssa_names_to_remove)
3301 ssa_names_to_remove = BITMAP_ALLOC (NULL);
3302 bitmap_set_bit (ssa_names_to_remove, SSA_NAME_VERSION (name));
3306 /* Remove the ssa names that were replaced by constants. We do not
3307 remove them directly in the previous cycle, since this
3308 invalidates scev cache. */
3309 if (ssa_names_to_remove)
3311 bitmap_iterator bi;
3313 EXECUTE_IF_SET_IN_BITMAP (ssa_names_to_remove, 0, i, bi)
3315 gimple_stmt_iterator psi;
3316 name = ssa_name (i);
3317 phi = SSA_NAME_DEF_STMT (name);
3319 gcc_assert (gimple_code (phi) == GIMPLE_PHI);
3320 psi = gsi_for_stmt (phi);
3321 remove_phi_node (&psi, true);
3324 BITMAP_FREE (ssa_names_to_remove);
3325 scev_reset ();
3328 /* Now the regular final value replacement. */
3329 FOR_EACH_LOOP (li, loop, LI_FROM_INNERMOST)
3331 edge exit;
3332 tree def, rslt, niter;
3333 gimple_stmt_iterator bsi;
3335 /* If we do not know exact number of iterations of the loop, we cannot
3336 replace the final value. */
3337 exit = single_exit (loop);
3338 if (!exit)
3339 continue;
3341 niter = number_of_latch_executions (loop);
3342 if (niter == chrec_dont_know)
3343 continue;
3345 /* Ensure that it is possible to insert new statements somewhere. */
3346 if (!single_pred_p (exit->dest))
3347 split_loop_exit_edge (exit);
3348 bsi = gsi_after_labels (exit->dest);
3350 ex_loop = superloop_at_depth (loop,
3351 loop_depth (exit->dest->loop_father) + 1);
3353 for (psi = gsi_start_phis (exit->dest); !gsi_end_p (psi); )
3355 phi = gsi_stmt (psi);
3356 rslt = PHI_RESULT (phi);
3357 def = PHI_ARG_DEF_FROM_EDGE (phi, exit);
3358 if (virtual_operand_p (def))
3360 gsi_next (&psi);
3361 continue;
3364 if (!POINTER_TYPE_P (TREE_TYPE (def))
3365 && !INTEGRAL_TYPE_P (TREE_TYPE (def)))
3367 gsi_next (&psi);
3368 continue;
3371 def = analyze_scalar_evolution_in_loop (ex_loop, loop, def, NULL);
3372 def = compute_overall_effect_of_inner_loop (ex_loop, def);
3373 if (!tree_does_not_contain_chrecs (def)
3374 || chrec_contains_symbols_defined_in_loop (def, ex_loop->num)
3375 /* Moving the computation from the loop may prolong life range
3376 of some ssa names, which may cause problems if they appear
3377 on abnormal edges. */
3378 || contains_abnormal_ssa_name_p (def)
3379 /* Do not emit expensive expressions. The rationale is that
3380 when someone writes a code like
3382 while (n > 45) n -= 45;
3384 he probably knows that n is not large, and does not want it
3385 to be turned into n %= 45. */
3386 || expression_expensive_p (def))
3388 if (dump_file && (dump_flags & TDF_DETAILS))
3390 fprintf (dump_file, "not replacing:\n ");
3391 print_gimple_stmt (dump_file, phi, 0, 0);
3392 fprintf (dump_file, "\n");
3394 gsi_next (&psi);
3395 continue;
3398 /* Eliminate the PHI node and replace it by a computation outside
3399 the loop. */
3400 if (dump_file)
3402 fprintf (dump_file, "\nfinal value replacement:\n ");
3403 print_gimple_stmt (dump_file, phi, 0, 0);
3404 fprintf (dump_file, " with\n ");
3406 def = unshare_expr (def);
3407 remove_phi_node (&psi, false);
3409 def = force_gimple_operand_gsi (&bsi, def, false, NULL_TREE,
3410 true, GSI_SAME_STMT);
3411 ass = gimple_build_assign (rslt, def);
3412 gsi_insert_before (&bsi, ass, GSI_SAME_STMT);
3413 if (dump_file)
3415 print_gimple_stmt (dump_file, ass, 0, 0);
3416 fprintf (dump_file, "\n");
3420 return 0;
3423 #include "gt-tree-scalar-evolution.h"