Also handle ARRAY_REFs in instantiate_scev_r.
[official-gcc/graphite-test-results.git] / gcc / tree-scalar-evolution.c
blob671494caa9c6bfff0563a04eaa316704fc17fcb8
1 /* Scalar evolution detector.
2 Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
3 Free Software Foundation, Inc.
4 Contributed by Sebastian Pop <s.pop@laposte.net>
6 This file is part of GCC.
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 for more details.
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
23 Description:
25 This pass analyzes the evolution of scalar variables in loop
26 structures. The algorithm is based on the SSA representation,
27 and on the loop hierarchy tree. This algorithm is not based on
28 the notion of versions of a variable, as it was the case for the
29 previous implementations of the scalar evolution algorithm, but
30 it assumes that each defined name is unique.
32 The notation used in this file is called "chains of recurrences",
33 and has been proposed by Eugene Zima, Robert Van Engelen, and
34 others for describing induction variables in programs. For example
35 "b -> {0, +, 2}_1" means that the scalar variable "b" is equal to 0
36 when entering in the loop_1 and has a step 2 in this loop, in other
37 words "for (b = 0; b < N; b+=2);". Note that the coefficients of
38 this chain of recurrence (or chrec [shrek]) can contain the name of
39 other variables, in which case they are called parametric chrecs.
40 For example, "b -> {a, +, 2}_1" means that the initial value of "b"
41 is the value of "a". In most of the cases these parametric chrecs
42 are fully instantiated before their use because symbolic names can
43 hide some difficult cases such as self-references described later
44 (see the Fibonacci example).
46 A short sketch of the algorithm is:
48 Given a scalar variable to be analyzed, follow the SSA edge to
49 its definition:
51 - When the definition is a GIMPLE_ASSIGN: if the right hand side
52 (RHS) of the definition cannot be statically analyzed, the answer
53 of the analyzer is: "don't know".
54 Otherwise, for all the variables that are not yet analyzed in the
55 RHS, try to determine their evolution, and finally try to
56 evaluate the operation of the RHS that gives the evolution
57 function of the analyzed variable.
59 - When the definition is a condition-phi-node: determine the
60 evolution function for all the branches of the phi node, and
61 finally merge these evolutions (see chrec_merge).
63 - When the definition is a loop-phi-node: determine its initial
64 condition, that is the SSA edge defined in an outer loop, and
65 keep it symbolic. Then determine the SSA edges that are defined
66 in the body of the loop. Follow the inner edges until ending on
67 another loop-phi-node of the same analyzed loop. If the reached
68 loop-phi-node is not the starting loop-phi-node, then we keep
69 this definition under a symbolic form. If the reached
70 loop-phi-node is the same as the starting one, then we compute a
71 symbolic stride on the return path. The result is then the
72 symbolic chrec {initial_condition, +, symbolic_stride}_loop.
74 Examples:
76 Example 1: Illustration of the basic algorithm.
78 | a = 3
79 | loop_1
80 | b = phi (a, c)
81 | c = b + 1
82 | if (c > 10) exit_loop
83 | endloop
85 Suppose that we want to know the number of iterations of the
86 loop_1. The exit_loop is controlled by a COND_EXPR (c > 10). We
87 ask the scalar evolution analyzer two questions: what's the
88 scalar evolution (scev) of "c", and what's the scev of "10". For
89 "10" the answer is "10" since it is a scalar constant. For the
90 scalar variable "c", it follows the SSA edge to its definition,
91 "c = b + 1", and then asks again what's the scev of "b".
92 Following the SSA edge, we end on a loop-phi-node "b = phi (a,
93 c)", where the initial condition is "a", and the inner loop edge
94 is "c". The initial condition is kept under a symbolic form (it
95 may be the case that the copy constant propagation has done its
96 work and we end with the constant "3" as one of the edges of the
97 loop-phi-node). The update edge is followed to the end of the
98 loop, and until reaching again the starting loop-phi-node: b -> c
99 -> b. At this point we have drawn a path from "b" to "b" from
100 which we compute the stride in the loop: in this example it is
101 "+1". The resulting scev for "b" is "b -> {a, +, 1}_1". Now
102 that the scev for "b" is known, it is possible to compute the
103 scev for "c", that is "c -> {a + 1, +, 1}_1". In order to
104 determine the number of iterations in the loop_1, we have to
105 instantiate_parameters (loop_1, {a + 1, +, 1}_1), that gives after some
106 more analysis the scev {4, +, 1}_1, or in other words, this is
107 the function "f (x) = x + 4", where x is the iteration count of
108 the loop_1. Now we have to solve the inequality "x + 4 > 10",
109 and take the smallest iteration number for which the loop is
110 exited: x = 7. This loop runs from x = 0 to x = 7, and in total
111 there are 8 iterations. In terms of loop normalization, we have
112 created a variable that is implicitly defined, "x" or just "_1",
113 and all the other analyzed scalars of the loop are defined in
114 function of this variable:
116 a -> 3
117 b -> {3, +, 1}_1
118 c -> {4, +, 1}_1
120 or in terms of a C program:
122 | a = 3
123 | for (x = 0; x <= 7; x++)
125 | b = x + 3
126 | c = x + 4
129 Example 2a: Illustration of the algorithm on nested loops.
131 | loop_1
132 | a = phi (1, b)
133 | c = a + 2
134 | loop_2 10 times
135 | b = phi (c, d)
136 | d = b + 3
137 | endloop
138 | endloop
140 For analyzing the scalar evolution of "a", the algorithm follows
141 the SSA edge into the loop's body: "a -> b". "b" is an inner
142 loop-phi-node, and its analysis as in Example 1, gives:
144 b -> {c, +, 3}_2
145 d -> {c + 3, +, 3}_2
147 Following the SSA edge for the initial condition, we end on "c = a
148 + 2", and then on the starting loop-phi-node "a". From this point,
149 the loop stride is computed: back on "c = a + 2" we get a "+2" in
150 the loop_1, then on the loop-phi-node "b" we compute the overall
151 effect of the inner loop that is "b = c + 30", and we get a "+30"
152 in the loop_1. That means that the overall stride in loop_1 is
153 equal to "+32", and the result is:
155 a -> {1, +, 32}_1
156 c -> {3, +, 32}_1
158 Example 2b: Multivariate chains of recurrences.
160 | loop_1
161 | k = phi (0, k + 1)
162 | loop_2 4 times
163 | j = phi (0, j + 1)
164 | loop_3 4 times
165 | i = phi (0, i + 1)
166 | A[j + k] = ...
167 | endloop
168 | endloop
169 | endloop
171 Analyzing the access function of array A with
172 instantiate_parameters (loop_1, "j + k"), we obtain the
173 instantiation and the analysis of the scalar variables "j" and "k"
174 in loop_1. This leads to the scalar evolution {4, +, 1}_1: the end
175 value of loop_2 for "j" is 4, and the evolution of "k" in loop_1 is
176 {0, +, 1}_1. To obtain the evolution function in loop_3 and
177 instantiate the scalar variables up to loop_1, one has to use:
178 instantiate_scev (block_before_loop (loop_1), loop_3, "j + k").
179 The result of this call is {{0, +, 1}_1, +, 1}_2.
181 Example 3: Higher degree polynomials.
183 | loop_1
184 | a = phi (2, b)
185 | c = phi (5, d)
186 | b = a + 1
187 | d = c + a
188 | endloop
190 a -> {2, +, 1}_1
191 b -> {3, +, 1}_1
192 c -> {5, +, a}_1
193 d -> {5 + a, +, a}_1
195 instantiate_parameters (loop_1, {5, +, a}_1) -> {5, +, 2, +, 1}_1
196 instantiate_parameters (loop_1, {5 + a, +, a}_1) -> {7, +, 3, +, 1}_1
198 Example 4: Lucas, Fibonacci, or mixers in general.
200 | loop_1
201 | a = phi (1, b)
202 | c = phi (3, d)
203 | b = c
204 | d = c + a
205 | endloop
207 a -> (1, c)_1
208 c -> {3, +, a}_1
210 The syntax "(1, c)_1" stands for a PEELED_CHREC that has the
211 following semantics: during the first iteration of the loop_1, the
212 variable contains the value 1, and then it contains the value "c".
213 Note that this syntax is close to the syntax of the loop-phi-node:
214 "a -> (1, c)_1" vs. "a = phi (1, c)".
216 The symbolic chrec representation contains all the semantics of the
217 original code. What is more difficult is to use this information.
219 Example 5: Flip-flops, or exchangers.
221 | loop_1
222 | a = phi (1, b)
223 | c = phi (3, d)
224 | b = c
225 | d = a
226 | endloop
228 a -> (1, c)_1
229 c -> (3, a)_1
231 Based on these symbolic chrecs, it is possible to refine this
232 information into the more precise PERIODIC_CHRECs:
234 a -> |1, 3|_1
235 c -> |3, 1|_1
237 This transformation is not yet implemented.
239 Further readings:
241 You can find a more detailed description of the algorithm in:
242 http://icps.u-strasbg.fr/~pop/DEA_03_Pop.pdf
243 http://icps.u-strasbg.fr/~pop/DEA_03_Pop.ps.gz. But note that
244 this is a preliminary report and some of the details of the
245 algorithm have changed. I'm working on a research report that
246 updates the description of the algorithms to reflect the design
247 choices used in this implementation.
249 A set of slides show a high level overview of the algorithm and run
250 an example through the scalar evolution analyzer:
251 http://cri.ensmp.fr/~pop/gcc/mar04/slides.pdf
253 The slides that I have presented at the GCC Summit'04 are available
254 at: http://cri.ensmp.fr/~pop/gcc/20040604/gccsummit-lno-spop.pdf
257 #include "config.h"
258 #include "system.h"
259 #include "coretypes.h"
260 #include "tm.h"
261 #include "ggc.h"
262 #include "tree.h"
263 #include "basic-block.h"
264 #include "tree-pretty-print.h"
265 #include "gimple-pretty-print.h"
266 #include "tree-flow.h"
267 #include "tree-dump.h"
268 #include "timevar.h"
269 #include "cfgloop.h"
270 #include "tree-chrec.h"
271 #include "tree-scalar-evolution.h"
272 #include "tree-pass.h"
273 #include "flags.h"
274 #include "params.h"
276 static tree analyze_scalar_evolution_1 (struct loop *, tree, tree);
278 /* The cached information about an SSA name VAR, claiming that below
279 basic block INSTANTIATED_BELOW, the value of VAR can be expressed
280 as CHREC. */
282 struct GTY(()) scev_info_str {
283 basic_block instantiated_below;
284 tree var;
285 tree chrec;
288 /* Counters for the scev database. */
289 static unsigned nb_set_scev = 0;
290 static unsigned nb_get_scev = 0;
292 /* The following trees are unique elements. Thus the comparison of
293 another element to these elements should be done on the pointer to
294 these trees, and not on their value. */
296 /* The SSA_NAMEs that are not yet analyzed are qualified with NULL_TREE. */
297 tree chrec_not_analyzed_yet;
299 /* Reserved to the cases where the analyzer has detected an
300 undecidable property at compile time. */
301 tree chrec_dont_know;
303 /* When the analyzer has detected that a property will never
304 happen, then it qualifies it with chrec_known. */
305 tree chrec_known;
307 static GTY ((param_is (struct scev_info_str))) htab_t scalar_evolution_info;
310 /* Constructs a new SCEV_INFO_STR structure for VAR and INSTANTIATED_BELOW. */
312 static inline struct scev_info_str *
313 new_scev_info_str (basic_block instantiated_below, tree var)
315 struct scev_info_str *res;
317 res = GGC_NEW (struct scev_info_str);
318 res->var = var;
319 res->chrec = chrec_not_analyzed_yet;
320 res->instantiated_below = instantiated_below;
322 return res;
325 /* Computes a hash function for database element ELT. */
327 static hashval_t
328 hash_scev_info (const void *elt)
330 return SSA_NAME_VERSION (((const struct scev_info_str *) elt)->var);
333 /* Compares database elements E1 and E2. */
335 static int
336 eq_scev_info (const void *e1, const void *e2)
338 const struct scev_info_str *elt1 = (const struct scev_info_str *) e1;
339 const struct scev_info_str *elt2 = (const struct scev_info_str *) e2;
341 return (elt1->var == elt2->var
342 && elt1->instantiated_below == elt2->instantiated_below);
345 /* Deletes database element E. */
347 static void
348 del_scev_info (void *e)
350 ggc_free (e);
353 /* Get the scalar evolution of VAR for INSTANTIATED_BELOW basic block.
354 A first query on VAR returns chrec_not_analyzed_yet. */
356 static tree *
357 find_var_scev_info (basic_block instantiated_below, tree var)
359 struct scev_info_str *res;
360 struct scev_info_str tmp;
361 PTR *slot;
363 tmp.var = var;
364 tmp.instantiated_below = instantiated_below;
365 slot = htab_find_slot (scalar_evolution_info, &tmp, INSERT);
367 if (!*slot)
368 *slot = new_scev_info_str (instantiated_below, var);
369 res = (struct scev_info_str *) *slot;
371 return &res->chrec;
374 /* Return true when CHREC contains symbolic names defined in
375 LOOP_NB. */
377 bool
378 chrec_contains_symbols_defined_in_loop (const_tree chrec, unsigned loop_nb)
380 int i, n;
382 if (chrec == NULL_TREE)
383 return false;
385 if (is_gimple_min_invariant (chrec))
386 return false;
388 if (TREE_CODE (chrec) == SSA_NAME)
390 gimple def;
391 loop_p def_loop, loop;
393 if (SSA_NAME_IS_DEFAULT_DEF (chrec))
394 return false;
396 def = SSA_NAME_DEF_STMT (chrec);
397 def_loop = loop_containing_stmt (def);
398 loop = get_loop (loop_nb);
400 if (def_loop == NULL)
401 return false;
403 if (loop == def_loop || flow_loop_nested_p (loop, def_loop))
404 return true;
406 return false;
409 n = TREE_OPERAND_LENGTH (chrec);
410 for (i = 0; i < n; i++)
411 if (chrec_contains_symbols_defined_in_loop (TREE_OPERAND (chrec, i),
412 loop_nb))
413 return true;
414 return false;
417 /* Return true when PHI is a loop-phi-node. */
419 static bool
420 loop_phi_node_p (gimple phi)
422 /* The implementation of this function is based on the following
423 property: "all the loop-phi-nodes of a loop are contained in the
424 loop's header basic block". */
426 return loop_containing_stmt (phi)->header == gimple_bb (phi);
429 /* Compute the scalar evolution for EVOLUTION_FN after crossing LOOP.
430 In general, in the case of multivariate evolutions we want to get
431 the evolution in different loops. LOOP specifies the level for
432 which to get the evolution.
434 Example:
436 | for (j = 0; j < 100; j++)
438 | for (k = 0; k < 100; k++)
440 | i = k + j; - Here the value of i is a function of j, k.
442 | ... = i - Here the value of i is a function of j.
444 | ... = i - Here the value of i is a scalar.
446 Example:
448 | i_0 = ...
449 | loop_1 10 times
450 | i_1 = phi (i_0, i_2)
451 | i_2 = i_1 + 2
452 | endloop
454 This loop has the same effect as:
455 LOOP_1 has the same effect as:
457 | i_1 = i_0 + 20
459 The overall effect of the loop, "i_0 + 20" in the previous example,
460 is obtained by passing in the parameters: LOOP = 1,
461 EVOLUTION_FN = {i_0, +, 2}_1.
464 tree
465 compute_overall_effect_of_inner_loop (struct loop *loop, tree evolution_fn)
467 bool val = false;
469 if (evolution_fn == chrec_dont_know)
470 return chrec_dont_know;
472 else if (TREE_CODE (evolution_fn) == POLYNOMIAL_CHREC)
474 struct loop *inner_loop = get_chrec_loop (evolution_fn);
476 if (inner_loop == loop
477 || flow_loop_nested_p (loop, inner_loop))
479 tree nb_iter = number_of_latch_executions (inner_loop);
481 if (nb_iter == chrec_dont_know)
482 return chrec_dont_know;
483 else
485 tree res;
487 /* evolution_fn is the evolution function in LOOP. Get
488 its value in the nb_iter-th iteration. */
489 res = chrec_apply (inner_loop->num, evolution_fn, nb_iter);
491 if (chrec_contains_symbols_defined_in_loop (res, loop->num))
492 res = instantiate_parameters (loop, res);
494 /* Continue the computation until ending on a parent of LOOP. */
495 return compute_overall_effect_of_inner_loop (loop, res);
498 else
499 return evolution_fn;
502 /* If the evolution function is an invariant, there is nothing to do. */
503 else if (no_evolution_in_loop_p (evolution_fn, loop->num, &val) && val)
504 return evolution_fn;
506 else
507 return chrec_dont_know;
510 /* Determine whether the CHREC is always positive/negative. If the expression
511 cannot be statically analyzed, return false, otherwise set the answer into
512 VALUE. */
514 bool
515 chrec_is_positive (tree chrec, bool *value)
517 bool value0, value1, value2;
518 tree end_value, nb_iter;
520 switch (TREE_CODE (chrec))
522 case POLYNOMIAL_CHREC:
523 if (!chrec_is_positive (CHREC_LEFT (chrec), &value0)
524 || !chrec_is_positive (CHREC_RIGHT (chrec), &value1))
525 return false;
527 /* FIXME -- overflows. */
528 if (value0 == value1)
530 *value = value0;
531 return true;
534 /* Otherwise the chrec is under the form: "{-197, +, 2}_1",
535 and the proof consists in showing that the sign never
536 changes during the execution of the loop, from 0 to
537 loop->nb_iterations. */
538 if (!evolution_function_is_affine_p (chrec))
539 return false;
541 nb_iter = number_of_latch_executions (get_chrec_loop (chrec));
542 if (chrec_contains_undetermined (nb_iter))
543 return false;
545 #if 0
546 /* TODO -- If the test is after the exit, we may decrease the number of
547 iterations by one. */
548 if (after_exit)
549 nb_iter = chrec_fold_minus (type, nb_iter, build_int_cst (type, 1));
550 #endif
552 end_value = chrec_apply (CHREC_VARIABLE (chrec), chrec, nb_iter);
554 if (!chrec_is_positive (end_value, &value2))
555 return false;
557 *value = value0;
558 return value0 == value1;
560 case INTEGER_CST:
561 *value = (tree_int_cst_sgn (chrec) == 1);
562 return true;
564 default:
565 return false;
569 /* Associate CHREC to SCALAR. */
571 static void
572 set_scalar_evolution (basic_block instantiated_below, tree scalar, tree chrec)
574 tree *scalar_info;
576 if (TREE_CODE (scalar) != SSA_NAME)
577 return;
579 scalar_info = find_var_scev_info (instantiated_below, scalar);
581 if (dump_file)
583 if (dump_flags & TDF_DETAILS)
585 fprintf (dump_file, "(set_scalar_evolution \n");
586 fprintf (dump_file, " instantiated_below = %d \n",
587 instantiated_below->index);
588 fprintf (dump_file, " (scalar = ");
589 print_generic_expr (dump_file, scalar, 0);
590 fprintf (dump_file, ")\n (scalar_evolution = ");
591 print_generic_expr (dump_file, chrec, 0);
592 fprintf (dump_file, "))\n");
594 if (dump_flags & TDF_STATS)
595 nb_set_scev++;
598 *scalar_info = chrec;
601 /* Retrieve the chrec associated to SCALAR instantiated below
602 INSTANTIATED_BELOW block. */
604 static tree
605 get_scalar_evolution (basic_block instantiated_below, tree scalar)
607 tree res;
609 if (dump_file)
611 if (dump_flags & TDF_DETAILS)
613 fprintf (dump_file, "(get_scalar_evolution \n");
614 fprintf (dump_file, " (scalar = ");
615 print_generic_expr (dump_file, scalar, 0);
616 fprintf (dump_file, ")\n");
618 if (dump_flags & TDF_STATS)
619 nb_get_scev++;
622 switch (TREE_CODE (scalar))
624 case SSA_NAME:
625 res = *find_var_scev_info (instantiated_below, scalar);
626 break;
628 case REAL_CST:
629 case FIXED_CST:
630 case INTEGER_CST:
631 res = scalar;
632 break;
634 default:
635 res = chrec_not_analyzed_yet;
636 break;
639 if (dump_file && (dump_flags & TDF_DETAILS))
641 fprintf (dump_file, " (scalar_evolution = ");
642 print_generic_expr (dump_file, res, 0);
643 fprintf (dump_file, "))\n");
646 return res;
649 /* Helper function for add_to_evolution. Returns the evolution
650 function for an assignment of the form "a = b + c", where "a" and
651 "b" are on the strongly connected component. CHREC_BEFORE is the
652 information that we already have collected up to this point.
653 TO_ADD is the evolution of "c".
655 When CHREC_BEFORE has an evolution part in LOOP_NB, add to this
656 evolution the expression TO_ADD, otherwise construct an evolution
657 part for this loop. */
659 static tree
660 add_to_evolution_1 (unsigned loop_nb, tree chrec_before, tree to_add,
661 gimple at_stmt)
663 tree type, left, right;
664 struct loop *loop = get_loop (loop_nb), *chloop;
666 switch (TREE_CODE (chrec_before))
668 case POLYNOMIAL_CHREC:
669 chloop = get_chrec_loop (chrec_before);
670 if (chloop == loop
671 || flow_loop_nested_p (chloop, loop))
673 unsigned var;
675 type = chrec_type (chrec_before);
677 /* When there is no evolution part in this loop, build it. */
678 if (chloop != loop)
680 var = loop_nb;
681 left = chrec_before;
682 right = SCALAR_FLOAT_TYPE_P (type)
683 ? build_real (type, dconst0)
684 : build_int_cst (type, 0);
686 else
688 var = CHREC_VARIABLE (chrec_before);
689 left = CHREC_LEFT (chrec_before);
690 right = CHREC_RIGHT (chrec_before);
693 to_add = chrec_convert (type, to_add, at_stmt);
694 right = chrec_convert_rhs (type, right, at_stmt);
695 right = chrec_fold_plus (chrec_type (right), right, to_add);
696 return build_polynomial_chrec (var, left, right);
698 else
700 gcc_assert (flow_loop_nested_p (loop, chloop));
702 /* Search the evolution in LOOP_NB. */
703 left = add_to_evolution_1 (loop_nb, CHREC_LEFT (chrec_before),
704 to_add, at_stmt);
705 right = CHREC_RIGHT (chrec_before);
706 right = chrec_convert_rhs (chrec_type (left), right, at_stmt);
707 return build_polynomial_chrec (CHREC_VARIABLE (chrec_before),
708 left, right);
711 default:
712 /* These nodes do not depend on a loop. */
713 if (chrec_before == chrec_dont_know)
714 return chrec_dont_know;
716 left = chrec_before;
717 right = chrec_convert_rhs (chrec_type (left), to_add, at_stmt);
718 return build_polynomial_chrec (loop_nb, left, right);
722 /* Add TO_ADD to the evolution part of CHREC_BEFORE in the dimension
723 of LOOP_NB.
725 Description (provided for completeness, for those who read code in
726 a plane, and for my poor 62 bytes brain that would have forgotten
727 all this in the next two or three months):
729 The algorithm of translation of programs from the SSA representation
730 into the chrecs syntax is based on a pattern matching. After having
731 reconstructed the overall tree expression for a loop, there are only
732 two cases that can arise:
734 1. a = loop-phi (init, a + expr)
735 2. a = loop-phi (init, expr)
737 where EXPR is either a scalar constant with respect to the analyzed
738 loop (this is a degree 0 polynomial), or an expression containing
739 other loop-phi definitions (these are higher degree polynomials).
741 Examples:
744 | init = ...
745 | loop_1
746 | a = phi (init, a + 5)
747 | endloop
750 | inita = ...
751 | initb = ...
752 | loop_1
753 | a = phi (inita, 2 * b + 3)
754 | b = phi (initb, b + 1)
755 | endloop
757 For the first case, the semantics of the SSA representation is:
759 | a (x) = init + \sum_{j = 0}^{x - 1} expr (j)
761 that is, there is a loop index "x" that determines the scalar value
762 of the variable during the loop execution. During the first
763 iteration, the value is that of the initial condition INIT, while
764 during the subsequent iterations, it is the sum of the initial
765 condition with the sum of all the values of EXPR from the initial
766 iteration to the before last considered iteration.
768 For the second case, the semantics of the SSA program is:
770 | a (x) = init, if x = 0;
771 | expr (x - 1), otherwise.
773 The second case corresponds to the PEELED_CHREC, whose syntax is
774 close to the syntax of a loop-phi-node:
776 | phi (init, expr) vs. (init, expr)_x
778 The proof of the translation algorithm for the first case is a
779 proof by structural induction based on the degree of EXPR.
781 Degree 0:
782 When EXPR is a constant with respect to the analyzed loop, or in
783 other words when EXPR is a polynomial of degree 0, the evolution of
784 the variable A in the loop is an affine function with an initial
785 condition INIT, and a step EXPR. In order to show this, we start
786 from the semantics of the SSA representation:
788 f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
790 and since "expr (j)" is a constant with respect to "j",
792 f (x) = init + x * expr
794 Finally, based on the semantics of the pure sum chrecs, by
795 identification we get the corresponding chrecs syntax:
797 f (x) = init * \binom{x}{0} + expr * \binom{x}{1}
798 f (x) -> {init, +, expr}_x
800 Higher degree:
801 Suppose that EXPR is a polynomial of degree N with respect to the
802 analyzed loop_x for which we have already determined that it is
803 written under the chrecs syntax:
805 | expr (x) -> {b_0, +, b_1, +, ..., +, b_{n-1}} (x)
807 We start from the semantics of the SSA program:
809 | f (x) = init + \sum_{j = 0}^{x - 1} expr (j)
811 | f (x) = init + \sum_{j = 0}^{x - 1}
812 | (b_0 * \binom{j}{0} + ... + b_{n-1} * \binom{j}{n-1})
814 | f (x) = init + \sum_{j = 0}^{x - 1}
815 | \sum_{k = 0}^{n - 1} (b_k * \binom{j}{k})
817 | f (x) = init + \sum_{k = 0}^{n - 1}
818 | (b_k * \sum_{j = 0}^{x - 1} \binom{j}{k})
820 | f (x) = init + \sum_{k = 0}^{n - 1}
821 | (b_k * \binom{x}{k + 1})
823 | f (x) = init + b_0 * \binom{x}{1} + ...
824 | + b_{n-1} * \binom{x}{n}
826 | f (x) = init * \binom{x}{0} + b_0 * \binom{x}{1} + ...
827 | + b_{n-1} * \binom{x}{n}
830 And finally from the definition of the chrecs syntax, we identify:
831 | f (x) -> {init, +, b_0, +, ..., +, b_{n-1}}_x
833 This shows the mechanism that stands behind the add_to_evolution
834 function. An important point is that the use of symbolic
835 parameters avoids the need of an analysis schedule.
837 Example:
839 | inita = ...
840 | initb = ...
841 | loop_1
842 | a = phi (inita, a + 2 + b)
843 | b = phi (initb, b + 1)
844 | endloop
846 When analyzing "a", the algorithm keeps "b" symbolically:
848 | a -> {inita, +, 2 + b}_1
850 Then, after instantiation, the analyzer ends on the evolution:
852 | a -> {inita, +, 2 + initb, +, 1}_1
856 static tree
857 add_to_evolution (unsigned loop_nb, tree chrec_before, enum tree_code code,
858 tree to_add, gimple at_stmt)
860 tree type = chrec_type (to_add);
861 tree res = NULL_TREE;
863 if (to_add == NULL_TREE)
864 return chrec_before;
866 /* TO_ADD is either a scalar, or a parameter. TO_ADD is not
867 instantiated at this point. */
868 if (TREE_CODE (to_add) == POLYNOMIAL_CHREC)
869 /* This should not happen. */
870 return chrec_dont_know;
872 if (dump_file && (dump_flags & TDF_DETAILS))
874 fprintf (dump_file, "(add_to_evolution \n");
875 fprintf (dump_file, " (loop_nb = %d)\n", loop_nb);
876 fprintf (dump_file, " (chrec_before = ");
877 print_generic_expr (dump_file, chrec_before, 0);
878 fprintf (dump_file, ")\n (to_add = ");
879 print_generic_expr (dump_file, to_add, 0);
880 fprintf (dump_file, ")\n");
883 if (code == MINUS_EXPR)
884 to_add = chrec_fold_multiply (type, to_add, SCALAR_FLOAT_TYPE_P (type)
885 ? build_real (type, dconstm1)
886 : build_int_cst_type (type, -1));
888 res = add_to_evolution_1 (loop_nb, chrec_before, to_add, at_stmt);
890 if (dump_file && (dump_flags & TDF_DETAILS))
892 fprintf (dump_file, " (res = ");
893 print_generic_expr (dump_file, res, 0);
894 fprintf (dump_file, "))\n");
897 return res;
902 /* This section selects the loops that will be good candidates for the
903 scalar evolution analysis. For the moment, greedily select all the
904 loop nests we could analyze. */
906 /* For a loop with a single exit edge, return the COND_EXPR that
907 guards the exit edge. If the expression is too difficult to
908 analyze, then give up. */
910 gimple
911 get_loop_exit_condition (const struct loop *loop)
913 gimple res = NULL;
914 edge exit_edge = single_exit (loop);
916 if (dump_file && (dump_flags & TDF_DETAILS))
917 fprintf (dump_file, "(get_loop_exit_condition \n ");
919 if (exit_edge)
921 gimple stmt;
923 stmt = last_stmt (exit_edge->src);
924 if (gimple_code (stmt) == GIMPLE_COND)
925 res = stmt;
928 if (dump_file && (dump_flags & TDF_DETAILS))
930 print_gimple_stmt (dump_file, res, 0, 0);
931 fprintf (dump_file, ")\n");
934 return res;
937 /* Recursively determine and enqueue the exit conditions for a loop. */
939 static void
940 get_exit_conditions_rec (struct loop *loop,
941 VEC(gimple,heap) **exit_conditions)
943 if (!loop)
944 return;
946 /* Recurse on the inner loops, then on the next (sibling) loops. */
947 get_exit_conditions_rec (loop->inner, exit_conditions);
948 get_exit_conditions_rec (loop->next, exit_conditions);
950 if (single_exit (loop))
952 gimple loop_condition = get_loop_exit_condition (loop);
954 if (loop_condition)
955 VEC_safe_push (gimple, heap, *exit_conditions, loop_condition);
959 /* Select the candidate loop nests for the analysis. This function
960 initializes the EXIT_CONDITIONS array. */
962 static void
963 select_loops_exit_conditions (VEC(gimple,heap) **exit_conditions)
965 struct loop *function_body = current_loops->tree_root;
967 get_exit_conditions_rec (function_body->inner, exit_conditions);
971 /* Depth first search algorithm. */
973 typedef enum t_bool {
974 t_false,
975 t_true,
976 t_dont_know
977 } t_bool;
980 static t_bool follow_ssa_edge (struct loop *loop, gimple, gimple, tree *, int);
982 /* Follow the ssa edge into the binary expression RHS0 CODE RHS1.
983 Return true if the strongly connected component has been found. */
985 static t_bool
986 follow_ssa_edge_binary (struct loop *loop, gimple at_stmt,
987 tree type, tree rhs0, enum tree_code code, tree rhs1,
988 gimple halting_phi, tree *evolution_of_loop, int limit)
990 t_bool res = t_false;
991 tree evol;
993 switch (code)
995 case POINTER_PLUS_EXPR:
996 case PLUS_EXPR:
997 if (TREE_CODE (rhs0) == SSA_NAME)
999 if (TREE_CODE (rhs1) == SSA_NAME)
1001 /* Match an assignment under the form:
1002 "a = b + c". */
1004 /* We want only assignments of form "name + name" contribute to
1005 LIMIT, as the other cases do not necessarily contribute to
1006 the complexity of the expression. */
1007 limit++;
1009 evol = *evolution_of_loop;
1010 res = follow_ssa_edge
1011 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi, &evol, limit);
1013 if (res == t_true)
1014 *evolution_of_loop = add_to_evolution
1015 (loop->num,
1016 chrec_convert (type, evol, at_stmt),
1017 code, rhs1, at_stmt);
1019 else if (res == t_false)
1021 res = follow_ssa_edge
1022 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
1023 evolution_of_loop, limit);
1025 if (res == t_true)
1026 *evolution_of_loop = add_to_evolution
1027 (loop->num,
1028 chrec_convert (type, *evolution_of_loop, at_stmt),
1029 code, rhs0, at_stmt);
1031 else if (res == t_dont_know)
1032 *evolution_of_loop = chrec_dont_know;
1035 else if (res == t_dont_know)
1036 *evolution_of_loop = chrec_dont_know;
1039 else
1041 /* Match an assignment under the form:
1042 "a = b + ...". */
1043 res = follow_ssa_edge
1044 (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
1045 evolution_of_loop, limit);
1046 if (res == t_true)
1047 *evolution_of_loop = add_to_evolution
1048 (loop->num, chrec_convert (type, *evolution_of_loop,
1049 at_stmt),
1050 code, rhs1, at_stmt);
1052 else if (res == t_dont_know)
1053 *evolution_of_loop = chrec_dont_know;
1057 else if (TREE_CODE (rhs1) == SSA_NAME)
1059 /* Match an assignment under the form:
1060 "a = ... + c". */
1061 res = follow_ssa_edge
1062 (loop, SSA_NAME_DEF_STMT (rhs1), halting_phi,
1063 evolution_of_loop, limit);
1064 if (res == t_true)
1065 *evolution_of_loop = add_to_evolution
1066 (loop->num, chrec_convert (type, *evolution_of_loop,
1067 at_stmt),
1068 code, rhs0, at_stmt);
1070 else if (res == t_dont_know)
1071 *evolution_of_loop = chrec_dont_know;
1074 else
1075 /* Otherwise, match an assignment under the form:
1076 "a = ... + ...". */
1077 /* And there is nothing to do. */
1078 res = t_false;
1079 break;
1081 case MINUS_EXPR:
1082 /* This case is under the form "opnd0 = rhs0 - rhs1". */
1083 if (TREE_CODE (rhs0) == SSA_NAME)
1085 /* Match an assignment under the form:
1086 "a = b - ...". */
1088 /* We want only assignments of form "name - name" contribute to
1089 LIMIT, as the other cases do not necessarily contribute to
1090 the complexity of the expression. */
1091 if (TREE_CODE (rhs1) == SSA_NAME)
1092 limit++;
1094 res = follow_ssa_edge (loop, SSA_NAME_DEF_STMT (rhs0), halting_phi,
1095 evolution_of_loop, limit);
1096 if (res == t_true)
1097 *evolution_of_loop = add_to_evolution
1098 (loop->num, chrec_convert (type, *evolution_of_loop, at_stmt),
1099 MINUS_EXPR, rhs1, at_stmt);
1101 else if (res == t_dont_know)
1102 *evolution_of_loop = chrec_dont_know;
1104 else
1105 /* Otherwise, match an assignment under the form:
1106 "a = ... - ...". */
1107 /* And there is nothing to do. */
1108 res = t_false;
1109 break;
1111 default:
1112 res = t_false;
1115 return res;
1118 /* Follow the ssa edge into the expression EXPR.
1119 Return true if the strongly connected component has been found. */
1121 static t_bool
1122 follow_ssa_edge_expr (struct loop *loop, gimple at_stmt, tree expr,
1123 gimple halting_phi, tree *evolution_of_loop, int limit)
1125 enum tree_code code = TREE_CODE (expr);
1126 tree type = TREE_TYPE (expr), rhs0, rhs1;
1127 t_bool res;
1129 /* The EXPR is one of the following cases:
1130 - an SSA_NAME,
1131 - an INTEGER_CST,
1132 - a PLUS_EXPR,
1133 - a POINTER_PLUS_EXPR,
1134 - a MINUS_EXPR,
1135 - an ASSERT_EXPR,
1136 - other cases are not yet handled. */
1138 switch (code)
1140 CASE_CONVERT:
1141 /* This assignment is under the form "a_1 = (cast) rhs. */
1142 res = follow_ssa_edge_expr (loop, at_stmt, TREE_OPERAND (expr, 0),
1143 halting_phi, evolution_of_loop, limit);
1144 *evolution_of_loop = chrec_convert (type, *evolution_of_loop, at_stmt);
1145 break;
1147 case INTEGER_CST:
1148 /* This assignment is under the form "a_1 = 7". */
1149 res = t_false;
1150 break;
1152 case SSA_NAME:
1153 /* This assignment is under the form: "a_1 = b_2". */
1154 res = follow_ssa_edge
1155 (loop, SSA_NAME_DEF_STMT (expr), halting_phi, evolution_of_loop, limit);
1156 break;
1158 case POINTER_PLUS_EXPR:
1159 case PLUS_EXPR:
1160 case MINUS_EXPR:
1161 /* This case is under the form "rhs0 +- rhs1". */
1162 rhs0 = TREE_OPERAND (expr, 0);
1163 rhs1 = TREE_OPERAND (expr, 1);
1164 type = TREE_TYPE (rhs0);
1165 STRIP_USELESS_TYPE_CONVERSION (rhs0);
1166 STRIP_USELESS_TYPE_CONVERSION (rhs1);
1167 res = follow_ssa_edge_binary (loop, at_stmt, type, rhs0, code, rhs1,
1168 halting_phi, evolution_of_loop, limit);
1169 break;
1171 case ASSERT_EXPR:
1172 /* This assignment is of the form: "a_1 = ASSERT_EXPR <a_2, ...>"
1173 It must be handled as a copy assignment of the form a_1 = a_2. */
1174 rhs0 = ASSERT_EXPR_VAR (expr);
1175 if (TREE_CODE (rhs0) == SSA_NAME)
1176 res = follow_ssa_edge (loop, SSA_NAME_DEF_STMT (rhs0),
1177 halting_phi, evolution_of_loop, limit);
1178 else
1179 res = t_false;
1180 break;
1182 default:
1183 res = t_false;
1184 break;
1187 return res;
1190 /* Follow the ssa edge into the right hand side of an assignment STMT.
1191 Return true if the strongly connected component has been found. */
1193 static t_bool
1194 follow_ssa_edge_in_rhs (struct loop *loop, gimple stmt,
1195 gimple halting_phi, tree *evolution_of_loop, int limit)
1197 enum tree_code code = gimple_assign_rhs_code (stmt);
1198 tree type = gimple_expr_type (stmt), rhs1, rhs2;
1199 t_bool res;
1201 switch (code)
1203 CASE_CONVERT:
1204 /* This assignment is under the form "a_1 = (cast) rhs. */
1205 res = follow_ssa_edge_expr (loop, stmt, gimple_assign_rhs1 (stmt),
1206 halting_phi, evolution_of_loop, limit);
1207 *evolution_of_loop = chrec_convert (type, *evolution_of_loop, stmt);
1208 break;
1210 case POINTER_PLUS_EXPR:
1211 case PLUS_EXPR:
1212 case MINUS_EXPR:
1213 rhs1 = gimple_assign_rhs1 (stmt);
1214 rhs2 = gimple_assign_rhs2 (stmt);
1215 type = TREE_TYPE (rhs1);
1216 res = follow_ssa_edge_binary (loop, stmt, type, rhs1, code, rhs2,
1217 halting_phi, evolution_of_loop, limit);
1218 break;
1220 default:
1221 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1222 res = follow_ssa_edge_expr (loop, stmt, gimple_assign_rhs1 (stmt),
1223 halting_phi, evolution_of_loop, limit);
1224 else
1225 res = t_false;
1226 break;
1229 return res;
1232 /* Checks whether the I-th argument of a PHI comes from a backedge. */
1234 static bool
1235 backedge_phi_arg_p (gimple phi, int i)
1237 const_edge e = gimple_phi_arg_edge (phi, i);
1239 /* We would in fact like to test EDGE_DFS_BACK here, but we do not care
1240 about updating it anywhere, and this should work as well most of the
1241 time. */
1242 if (e->flags & EDGE_IRREDUCIBLE_LOOP)
1243 return true;
1245 return false;
1248 /* Helper function for one branch of the condition-phi-node. Return
1249 true if the strongly connected component has been found following
1250 this path. */
1252 static inline t_bool
1253 follow_ssa_edge_in_condition_phi_branch (int i,
1254 struct loop *loop,
1255 gimple condition_phi,
1256 gimple halting_phi,
1257 tree *evolution_of_branch,
1258 tree init_cond, int limit)
1260 tree branch = PHI_ARG_DEF (condition_phi, i);
1261 *evolution_of_branch = chrec_dont_know;
1263 /* Do not follow back edges (they must belong to an irreducible loop, which
1264 we really do not want to worry about). */
1265 if (backedge_phi_arg_p (condition_phi, i))
1266 return t_false;
1268 if (TREE_CODE (branch) == SSA_NAME)
1270 *evolution_of_branch = init_cond;
1271 return follow_ssa_edge (loop, SSA_NAME_DEF_STMT (branch), halting_phi,
1272 evolution_of_branch, limit);
1275 /* This case occurs when one of the condition branches sets
1276 the variable to a constant: i.e. a phi-node like
1277 "a_2 = PHI <a_7(5), 2(6)>;".
1279 FIXME: This case have to be refined correctly:
1280 in some cases it is possible to say something better than
1281 chrec_dont_know, for example using a wrap-around notation. */
1282 return t_false;
1285 /* This function merges the branches of a condition-phi-node in a
1286 loop. */
1288 static t_bool
1289 follow_ssa_edge_in_condition_phi (struct loop *loop,
1290 gimple condition_phi,
1291 gimple halting_phi,
1292 tree *evolution_of_loop, int limit)
1294 int i, n;
1295 tree init = *evolution_of_loop;
1296 tree evolution_of_branch;
1297 t_bool res = follow_ssa_edge_in_condition_phi_branch (0, loop, condition_phi,
1298 halting_phi,
1299 &evolution_of_branch,
1300 init, limit);
1301 if (res == t_false || res == t_dont_know)
1302 return res;
1304 *evolution_of_loop = evolution_of_branch;
1306 n = gimple_phi_num_args (condition_phi);
1307 for (i = 1; i < n; i++)
1309 /* Quickly give up when the evolution of one of the branches is
1310 not known. */
1311 if (*evolution_of_loop == chrec_dont_know)
1312 return t_true;
1314 /* Increase the limit by the PHI argument number to avoid exponential
1315 time and memory complexity. */
1316 res = follow_ssa_edge_in_condition_phi_branch (i, loop, condition_phi,
1317 halting_phi,
1318 &evolution_of_branch,
1319 init, limit + i);
1320 if (res == t_false || res == t_dont_know)
1321 return res;
1323 *evolution_of_loop = chrec_merge (*evolution_of_loop,
1324 evolution_of_branch);
1327 return t_true;
1330 /* Follow an SSA edge in an inner loop. It computes the overall
1331 effect of the loop, and following the symbolic initial conditions,
1332 it follows the edges in the parent loop. The inner loop is
1333 considered as a single statement. */
1335 static t_bool
1336 follow_ssa_edge_inner_loop_phi (struct loop *outer_loop,
1337 gimple loop_phi_node,
1338 gimple halting_phi,
1339 tree *evolution_of_loop, int limit)
1341 struct loop *loop = loop_containing_stmt (loop_phi_node);
1342 tree ev = analyze_scalar_evolution (loop, PHI_RESULT (loop_phi_node));
1344 /* Sometimes, the inner loop is too difficult to analyze, and the
1345 result of the analysis is a symbolic parameter. */
1346 if (ev == PHI_RESULT (loop_phi_node))
1348 t_bool res = t_false;
1349 int i, n = gimple_phi_num_args (loop_phi_node);
1351 for (i = 0; i < n; i++)
1353 tree arg = PHI_ARG_DEF (loop_phi_node, i);
1354 basic_block bb;
1356 /* Follow the edges that exit the inner loop. */
1357 bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1358 if (!flow_bb_inside_loop_p (loop, bb))
1359 res = follow_ssa_edge_expr (outer_loop, loop_phi_node,
1360 arg, halting_phi,
1361 evolution_of_loop, limit);
1362 if (res == t_true)
1363 break;
1366 /* If the path crosses this loop-phi, give up. */
1367 if (res == t_true)
1368 *evolution_of_loop = chrec_dont_know;
1370 return res;
1373 /* Otherwise, compute the overall effect of the inner loop. */
1374 ev = compute_overall_effect_of_inner_loop (loop, ev);
1375 return follow_ssa_edge_expr (outer_loop, loop_phi_node, ev, halting_phi,
1376 evolution_of_loop, limit);
1379 /* Follow an SSA edge from a loop-phi-node to itself, constructing a
1380 path that is analyzed on the return walk. */
1382 static t_bool
1383 follow_ssa_edge (struct loop *loop, gimple def, gimple halting_phi,
1384 tree *evolution_of_loop, int limit)
1386 struct loop *def_loop;
1388 if (gimple_nop_p (def))
1389 return t_false;
1391 /* Give up if the path is longer than the MAX that we allow. */
1392 if (limit > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_SIZE))
1393 return t_dont_know;
1395 def_loop = loop_containing_stmt (def);
1397 switch (gimple_code (def))
1399 case GIMPLE_PHI:
1400 if (!loop_phi_node_p (def))
1401 /* DEF is a condition-phi-node. Follow the branches, and
1402 record their evolutions. Finally, merge the collected
1403 information and set the approximation to the main
1404 variable. */
1405 return follow_ssa_edge_in_condition_phi
1406 (loop, def, halting_phi, evolution_of_loop, limit);
1408 /* When the analyzed phi is the halting_phi, the
1409 depth-first search is over: we have found a path from
1410 the halting_phi to itself in the loop. */
1411 if (def == halting_phi)
1412 return t_true;
1414 /* Otherwise, the evolution of the HALTING_PHI depends
1415 on the evolution of another loop-phi-node, i.e. the
1416 evolution function is a higher degree polynomial. */
1417 if (def_loop == loop)
1418 return t_false;
1420 /* Inner loop. */
1421 if (flow_loop_nested_p (loop, def_loop))
1422 return follow_ssa_edge_inner_loop_phi
1423 (loop, def, halting_phi, evolution_of_loop, limit + 1);
1425 /* Outer loop. */
1426 return t_false;
1428 case GIMPLE_ASSIGN:
1429 return follow_ssa_edge_in_rhs (loop, def, halting_phi,
1430 evolution_of_loop, limit);
1432 default:
1433 /* At this level of abstraction, the program is just a set
1434 of GIMPLE_ASSIGNs and PHI_NODEs. In principle there is no
1435 other node to be handled. */
1436 return t_false;
1442 /* Given a LOOP_PHI_NODE, this function determines the evolution
1443 function from LOOP_PHI_NODE to LOOP_PHI_NODE in the loop. */
1445 static tree
1446 analyze_evolution_in_loop (gimple loop_phi_node,
1447 tree init_cond)
1449 int i, n = gimple_phi_num_args (loop_phi_node);
1450 tree evolution_function = chrec_not_analyzed_yet;
1451 struct loop *loop = loop_containing_stmt (loop_phi_node);
1452 basic_block bb;
1454 if (dump_file && (dump_flags & TDF_DETAILS))
1456 fprintf (dump_file, "(analyze_evolution_in_loop \n");
1457 fprintf (dump_file, " (loop_phi_node = ");
1458 print_gimple_stmt (dump_file, loop_phi_node, 0, 0);
1459 fprintf (dump_file, ")\n");
1462 for (i = 0; i < n; i++)
1464 tree arg = PHI_ARG_DEF (loop_phi_node, i);
1465 gimple ssa_chain;
1466 tree ev_fn;
1467 t_bool res;
1469 /* Select the edges that enter the loop body. */
1470 bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1471 if (!flow_bb_inside_loop_p (loop, bb))
1472 continue;
1474 if (TREE_CODE (arg) == SSA_NAME)
1476 bool val = false;
1478 ssa_chain = SSA_NAME_DEF_STMT (arg);
1480 /* Pass in the initial condition to the follow edge function. */
1481 ev_fn = init_cond;
1482 res = follow_ssa_edge (loop, ssa_chain, loop_phi_node, &ev_fn, 0);
1484 /* If ev_fn has no evolution in the inner loop, and the
1485 init_cond is not equal to ev_fn, then we have an
1486 ambiguity between two possible values, as we cannot know
1487 the number of iterations at this point. */
1488 if (TREE_CODE (ev_fn) != POLYNOMIAL_CHREC
1489 && no_evolution_in_loop_p (ev_fn, loop->num, &val) && val
1490 && !operand_equal_p (init_cond, ev_fn, 0))
1491 ev_fn = chrec_dont_know;
1493 else
1494 res = t_false;
1496 /* When it is impossible to go back on the same
1497 loop_phi_node by following the ssa edges, the
1498 evolution is represented by a peeled chrec, i.e. the
1499 first iteration, EV_FN has the value INIT_COND, then
1500 all the other iterations it has the value of ARG.
1501 For the moment, PEELED_CHREC nodes are not built. */
1502 if (res != t_true)
1503 ev_fn = chrec_dont_know;
1505 /* When there are multiple back edges of the loop (which in fact never
1506 happens currently, but nevertheless), merge their evolutions. */
1507 evolution_function = chrec_merge (evolution_function, ev_fn);
1510 if (dump_file && (dump_flags & TDF_DETAILS))
1512 fprintf (dump_file, " (evolution_function = ");
1513 print_generic_expr (dump_file, evolution_function, 0);
1514 fprintf (dump_file, "))\n");
1517 return evolution_function;
1520 /* Given a loop-phi-node, return the initial conditions of the
1521 variable on entry of the loop. When the CCP has propagated
1522 constants into the loop-phi-node, the initial condition is
1523 instantiated, otherwise the initial condition is kept symbolic.
1524 This analyzer does not analyze the evolution outside the current
1525 loop, and leaves this task to the on-demand tree reconstructor. */
1527 static tree
1528 analyze_initial_condition (gimple loop_phi_node)
1530 int i, n;
1531 tree init_cond = chrec_not_analyzed_yet;
1532 struct loop *loop = loop_containing_stmt (loop_phi_node);
1534 if (dump_file && (dump_flags & TDF_DETAILS))
1536 fprintf (dump_file, "(analyze_initial_condition \n");
1537 fprintf (dump_file, " (loop_phi_node = \n");
1538 print_gimple_stmt (dump_file, loop_phi_node, 0, 0);
1539 fprintf (dump_file, ")\n");
1542 n = gimple_phi_num_args (loop_phi_node);
1543 for (i = 0; i < n; i++)
1545 tree branch = PHI_ARG_DEF (loop_phi_node, i);
1546 basic_block bb = gimple_phi_arg_edge (loop_phi_node, i)->src;
1548 /* When the branch is oriented to the loop's body, it does
1549 not contribute to the initial condition. */
1550 if (flow_bb_inside_loop_p (loop, bb))
1551 continue;
1553 if (init_cond == chrec_not_analyzed_yet)
1555 init_cond = branch;
1556 continue;
1559 if (TREE_CODE (branch) == SSA_NAME)
1561 init_cond = chrec_dont_know;
1562 break;
1565 init_cond = chrec_merge (init_cond, branch);
1568 /* Ooops -- a loop without an entry??? */
1569 if (init_cond == chrec_not_analyzed_yet)
1570 init_cond = chrec_dont_know;
1572 /* During early loop unrolling we do not have fully constant propagated IL.
1573 Handle degenerate PHIs here to not miss important unrollings. */
1574 if (TREE_CODE (init_cond) == SSA_NAME)
1576 gimple def = SSA_NAME_DEF_STMT (init_cond);
1577 tree res;
1578 if (gimple_code (def) == GIMPLE_PHI
1579 && (res = degenerate_phi_result (def)) != NULL_TREE
1580 /* Only allow invariants here, otherwise we may break
1581 loop-closed SSA form. */
1582 && is_gimple_min_invariant (res))
1583 init_cond = res;
1586 if (dump_file && (dump_flags & TDF_DETAILS))
1588 fprintf (dump_file, " (init_cond = ");
1589 print_generic_expr (dump_file, init_cond, 0);
1590 fprintf (dump_file, "))\n");
1593 return init_cond;
1596 /* Analyze the scalar evolution for LOOP_PHI_NODE. */
1598 static tree
1599 interpret_loop_phi (struct loop *loop, gimple loop_phi_node)
1601 tree res;
1602 struct loop *phi_loop = loop_containing_stmt (loop_phi_node);
1603 tree init_cond;
1605 if (phi_loop != loop)
1607 struct loop *subloop;
1608 tree evolution_fn = analyze_scalar_evolution
1609 (phi_loop, PHI_RESULT (loop_phi_node));
1611 /* Dive one level deeper. */
1612 subloop = superloop_at_depth (phi_loop, loop_depth (loop) + 1);
1614 /* Interpret the subloop. */
1615 res = compute_overall_effect_of_inner_loop (subloop, evolution_fn);
1616 return res;
1619 /* Otherwise really interpret the loop phi. */
1620 init_cond = analyze_initial_condition (loop_phi_node);
1621 res = analyze_evolution_in_loop (loop_phi_node, init_cond);
1623 /* Verify we maintained the correct initial condition throughout
1624 possible conversions in the SSA chain. */
1625 if (res != chrec_dont_know)
1627 tree new_init = res;
1628 if (CONVERT_EXPR_P (res)
1629 && TREE_CODE (TREE_OPERAND (res, 0)) == POLYNOMIAL_CHREC)
1630 new_init = fold_convert (TREE_TYPE (res),
1631 CHREC_LEFT (TREE_OPERAND (res, 0)));
1632 else if (TREE_CODE (res) == POLYNOMIAL_CHREC)
1633 new_init = CHREC_LEFT (res);
1634 STRIP_USELESS_TYPE_CONVERSION (new_init);
1635 gcc_assert (TREE_CODE (new_init) != POLYNOMIAL_CHREC);
1636 if (!operand_equal_p (init_cond, new_init, 0))
1637 return chrec_dont_know;
1640 return res;
1643 /* This function merges the branches of a condition-phi-node,
1644 contained in the outermost loop, and whose arguments are already
1645 analyzed. */
1647 static tree
1648 interpret_condition_phi (struct loop *loop, gimple condition_phi)
1650 int i, n = gimple_phi_num_args (condition_phi);
1651 tree res = chrec_not_analyzed_yet;
1653 for (i = 0; i < n; i++)
1655 tree branch_chrec;
1657 if (backedge_phi_arg_p (condition_phi, i))
1659 res = chrec_dont_know;
1660 break;
1663 branch_chrec = analyze_scalar_evolution
1664 (loop, PHI_ARG_DEF (condition_phi, i));
1666 res = chrec_merge (res, branch_chrec);
1669 return res;
1672 /* Interpret the operation RHS1 OP RHS2. If we didn't
1673 analyze this node before, follow the definitions until ending
1674 either on an analyzed GIMPLE_ASSIGN, or on a loop-phi-node. On the
1675 return path, this function propagates evolutions (ala constant copy
1676 propagation). OPND1 is not a GIMPLE expression because we could
1677 analyze the effect of an inner loop: see interpret_loop_phi. */
1679 static tree
1680 interpret_rhs_expr (struct loop *loop, gimple at_stmt,
1681 tree type, tree rhs1, enum tree_code code, tree rhs2)
1683 tree res, chrec1, chrec2;
1685 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1687 if (is_gimple_min_invariant (rhs1))
1688 return chrec_convert (type, rhs1, at_stmt);
1690 if (code == SSA_NAME)
1691 return chrec_convert (type, analyze_scalar_evolution (loop, rhs1),
1692 at_stmt);
1694 if (code == ASSERT_EXPR)
1696 rhs1 = ASSERT_EXPR_VAR (rhs1);
1697 return chrec_convert (type, analyze_scalar_evolution (loop, rhs1),
1698 at_stmt);
1701 return chrec_dont_know;
1704 switch (code)
1706 case POINTER_PLUS_EXPR:
1707 chrec1 = analyze_scalar_evolution (loop, rhs1);
1708 chrec2 = analyze_scalar_evolution (loop, rhs2);
1709 chrec1 = chrec_convert (type, chrec1, at_stmt);
1710 chrec2 = chrec_convert (sizetype, chrec2, at_stmt);
1711 res = chrec_fold_plus (type, chrec1, chrec2);
1712 break;
1714 case PLUS_EXPR:
1715 chrec1 = analyze_scalar_evolution (loop, rhs1);
1716 chrec2 = analyze_scalar_evolution (loop, rhs2);
1717 chrec1 = chrec_convert (type, chrec1, at_stmt);
1718 chrec2 = chrec_convert (type, chrec2, at_stmt);
1719 res = chrec_fold_plus (type, chrec1, chrec2);
1720 break;
1722 case MINUS_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_minus (type, chrec1, chrec2);
1728 break;
1730 case NEGATE_EXPR:
1731 chrec1 = analyze_scalar_evolution (loop, rhs1);
1732 chrec1 = chrec_convert (type, chrec1, at_stmt);
1733 /* TYPE may be integer, real or complex, so use fold_convert. */
1734 res = chrec_fold_multiply (type, chrec1,
1735 fold_convert (type, integer_minus_one_node));
1736 break;
1738 case BIT_NOT_EXPR:
1739 /* Handle ~X as -1 - X. */
1740 chrec1 = analyze_scalar_evolution (loop, rhs1);
1741 chrec1 = chrec_convert (type, chrec1, at_stmt);
1742 res = chrec_fold_minus (type,
1743 fold_convert (type, integer_minus_one_node),
1744 chrec1);
1745 break;
1747 case MULT_EXPR:
1748 chrec1 = analyze_scalar_evolution (loop, rhs1);
1749 chrec2 = analyze_scalar_evolution (loop, rhs2);
1750 chrec1 = chrec_convert (type, chrec1, at_stmt);
1751 chrec2 = chrec_convert (type, chrec2, at_stmt);
1752 res = chrec_fold_multiply (type, chrec1, chrec2);
1753 break;
1755 CASE_CONVERT:
1756 chrec1 = analyze_scalar_evolution (loop, rhs1);
1757 res = chrec_convert (type, chrec1, at_stmt);
1758 break;
1760 default:
1761 res = chrec_dont_know;
1762 break;
1765 return res;
1768 /* Interpret the expression EXPR. */
1770 static tree
1771 interpret_expr (struct loop *loop, gimple at_stmt, tree expr)
1773 enum tree_code code;
1774 tree type = TREE_TYPE (expr), op0, op1;
1776 if (automatically_generated_chrec_p (expr))
1777 return expr;
1779 if (TREE_CODE (expr) == POLYNOMIAL_CHREC)
1780 return chrec_dont_know;
1782 extract_ops_from_tree (expr, &code, &op0, &op1);
1784 return interpret_rhs_expr (loop, at_stmt, type,
1785 op0, code, op1);
1788 /* Interpret the rhs of the assignment STMT. */
1790 static tree
1791 interpret_gimple_assign (struct loop *loop, gimple stmt)
1793 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
1794 enum tree_code code = gimple_assign_rhs_code (stmt);
1796 return interpret_rhs_expr (loop, stmt, type,
1797 gimple_assign_rhs1 (stmt), code,
1798 gimple_assign_rhs2 (stmt));
1803 /* This section contains all the entry points:
1804 - number_of_iterations_in_loop,
1805 - analyze_scalar_evolution,
1806 - instantiate_parameters.
1809 /* Compute and return the evolution function in WRTO_LOOP, the nearest
1810 common ancestor of DEF_LOOP and USE_LOOP. */
1812 static tree
1813 compute_scalar_evolution_in_loop (struct loop *wrto_loop,
1814 struct loop *def_loop,
1815 tree ev)
1817 bool val;
1818 tree res;
1820 if (def_loop == wrto_loop)
1821 return ev;
1823 def_loop = superloop_at_depth (def_loop, loop_depth (wrto_loop) + 1);
1824 res = compute_overall_effect_of_inner_loop (def_loop, ev);
1826 if (no_evolution_in_loop_p (res, wrto_loop->num, &val) && val)
1827 return res;
1829 return analyze_scalar_evolution_1 (wrto_loop, res, chrec_not_analyzed_yet);
1832 /* Helper recursive function. */
1834 static tree
1835 analyze_scalar_evolution_1 (struct loop *loop, tree var, tree res)
1837 tree type = TREE_TYPE (var);
1838 gimple def;
1839 basic_block bb;
1840 struct loop *def_loop;
1842 if (loop == NULL || TREE_CODE (type) == VECTOR_TYPE)
1843 return chrec_dont_know;
1845 if (TREE_CODE (var) != SSA_NAME)
1846 return interpret_expr (loop, NULL, var);
1848 def = SSA_NAME_DEF_STMT (var);
1849 bb = gimple_bb (def);
1850 def_loop = bb ? bb->loop_father : NULL;
1852 if (bb == NULL
1853 || !flow_bb_inside_loop_p (loop, bb))
1855 /* Keep the symbolic form. */
1856 res = var;
1857 goto set_and_end;
1860 if (res != chrec_not_analyzed_yet)
1862 if (loop != bb->loop_father)
1863 res = compute_scalar_evolution_in_loop
1864 (find_common_loop (loop, bb->loop_father), bb->loop_father, res);
1866 goto set_and_end;
1869 if (loop != def_loop)
1871 res = analyze_scalar_evolution_1 (def_loop, var, chrec_not_analyzed_yet);
1872 res = compute_scalar_evolution_in_loop (loop, def_loop, res);
1874 goto set_and_end;
1877 switch (gimple_code (def))
1879 case GIMPLE_ASSIGN:
1880 res = interpret_gimple_assign (loop, def);
1881 break;
1883 case GIMPLE_PHI:
1884 if (loop_phi_node_p (def))
1885 res = interpret_loop_phi (loop, def);
1886 else
1887 res = interpret_condition_phi (loop, def);
1888 break;
1890 default:
1891 res = chrec_dont_know;
1892 break;
1895 set_and_end:
1897 /* Keep the symbolic form. */
1898 if (res == chrec_dont_know)
1899 res = var;
1901 if (loop == def_loop)
1902 set_scalar_evolution (block_before_loop (loop), var, res);
1904 return res;
1907 /* Analyzes and returns the scalar evolution of the ssa_name VAR in
1908 LOOP. LOOP is the loop in which the variable is used.
1910 Example of use: having a pointer VAR to a SSA_NAME node, STMT a
1911 pointer to the statement that uses this variable, in order to
1912 determine the evolution function of the variable, use the following
1913 calls:
1915 loop_p loop = loop_containing_stmt (stmt);
1916 tree chrec_with_symbols = analyze_scalar_evolution (loop, var);
1917 tree chrec_instantiated = instantiate_parameters (loop, chrec_with_symbols);
1920 tree
1921 analyze_scalar_evolution (struct loop *loop, tree var)
1923 tree res;
1925 if (dump_file && (dump_flags & TDF_DETAILS))
1927 fprintf (dump_file, "(analyze_scalar_evolution \n");
1928 fprintf (dump_file, " (loop_nb = %d)\n", loop->num);
1929 fprintf (dump_file, " (scalar = ");
1930 print_generic_expr (dump_file, var, 0);
1931 fprintf (dump_file, ")\n");
1934 res = get_scalar_evolution (block_before_loop (loop), var);
1935 res = analyze_scalar_evolution_1 (loop, var, res);
1937 if (dump_file && (dump_flags & TDF_DETAILS))
1938 fprintf (dump_file, ")\n");
1940 return res;
1943 /* Analyze scalar evolution of use of VERSION in USE_LOOP with respect to
1944 WRTO_LOOP (which should be a superloop of USE_LOOP)
1946 FOLDED_CASTS is set to true if resolve_mixers used
1947 chrec_convert_aggressive (TODO -- not really, we are way too conservative
1948 at the moment in order to keep things simple).
1950 To illustrate the meaning of USE_LOOP and WRTO_LOOP, consider the following
1951 example:
1953 for (i = 0; i < 100; i++) -- loop 1
1955 for (j = 0; j < 100; j++) -- loop 2
1957 k1 = i;
1958 k2 = j;
1960 use2 (k1, k2);
1962 for (t = 0; t < 100; t++) -- loop 3
1963 use3 (k1, k2);
1966 use1 (k1, k2);
1969 Both k1 and k2 are invariants in loop3, thus
1970 analyze_scalar_evolution_in_loop (loop3, loop3, k1) = k1
1971 analyze_scalar_evolution_in_loop (loop3, loop3, k2) = k2
1973 As they are invariant, it does not matter whether we consider their
1974 usage in loop 3 or loop 2, hence
1975 analyze_scalar_evolution_in_loop (loop2, loop3, k1) =
1976 analyze_scalar_evolution_in_loop (loop2, loop2, k1) = i
1977 analyze_scalar_evolution_in_loop (loop2, loop3, k2) =
1978 analyze_scalar_evolution_in_loop (loop2, loop2, k2) = [0,+,1]_2
1980 Similarly for their evolutions with respect to loop 1. The values of K2
1981 in the use in loop 2 vary independently on loop 1, thus we cannot express
1982 the evolution with respect to loop 1:
1983 analyze_scalar_evolution_in_loop (loop1, loop3, k1) =
1984 analyze_scalar_evolution_in_loop (loop1, loop2, k1) = [0,+,1]_1
1985 analyze_scalar_evolution_in_loop (loop1, loop3, k2) =
1986 analyze_scalar_evolution_in_loop (loop1, loop2, k2) = dont_know
1988 The value of k2 in the use in loop 1 is known, though:
1989 analyze_scalar_evolution_in_loop (loop1, loop1, k1) = [0,+,1]_1
1990 analyze_scalar_evolution_in_loop (loop1, loop1, k2) = 100
1993 static tree
1994 analyze_scalar_evolution_in_loop (struct loop *wrto_loop, struct loop *use_loop,
1995 tree version, bool *folded_casts)
1997 bool val = false;
1998 tree ev = version, tmp;
2000 /* We cannot just do
2002 tmp = analyze_scalar_evolution (use_loop, version);
2003 ev = resolve_mixers (wrto_loop, tmp);
2005 as resolve_mixers would query the scalar evolution with respect to
2006 wrto_loop. For example, in the situation described in the function
2007 comment, suppose that wrto_loop = loop1, use_loop = loop3 and
2008 version = k2. Then
2010 analyze_scalar_evolution (use_loop, version) = k2
2012 and resolve_mixers (loop1, k2) finds that the value of k2 in loop 1
2013 is 100, which is a wrong result, since we are interested in the
2014 value in loop 3.
2016 Instead, we need to proceed from use_loop to wrto_loop loop by loop,
2017 each time checking that there is no evolution in the inner loop. */
2019 if (folded_casts)
2020 *folded_casts = false;
2021 while (1)
2023 tmp = analyze_scalar_evolution (use_loop, ev);
2024 ev = resolve_mixers (use_loop, tmp);
2026 if (folded_casts && tmp != ev)
2027 *folded_casts = true;
2029 if (use_loop == wrto_loop)
2030 return ev;
2032 /* If the value of the use changes in the inner loop, we cannot express
2033 its value in the outer loop (we might try to return interval chrec,
2034 but we do not have a user for it anyway) */
2035 if (!no_evolution_in_loop_p (ev, use_loop->num, &val)
2036 || !val)
2037 return chrec_dont_know;
2039 use_loop = loop_outer (use_loop);
2043 /* Returns from CACHE the value for VERSION instantiated below
2044 INSTANTIATED_BELOW block. */
2046 static tree
2047 get_instantiated_value (htab_t cache, basic_block instantiated_below,
2048 tree version)
2050 struct scev_info_str *info, pattern;
2052 pattern.var = version;
2053 pattern.instantiated_below = instantiated_below;
2054 info = (struct scev_info_str *) htab_find (cache, &pattern);
2056 if (info)
2057 return info->chrec;
2058 else
2059 return NULL_TREE;
2062 /* Sets in CACHE the value of VERSION instantiated below basic block
2063 INSTANTIATED_BELOW to VAL. */
2065 static void
2066 set_instantiated_value (htab_t cache, basic_block instantiated_below,
2067 tree version, tree val)
2069 struct scev_info_str *info, pattern;
2070 PTR *slot;
2072 pattern.var = version;
2073 pattern.instantiated_below = instantiated_below;
2074 slot = htab_find_slot (cache, &pattern, INSERT);
2076 if (!*slot)
2077 *slot = new_scev_info_str (instantiated_below, version);
2078 info = (struct scev_info_str *) *slot;
2079 info->chrec = val;
2082 /* Return the closed_loop_phi node for VAR. If there is none, return
2083 NULL_TREE. */
2085 static tree
2086 loop_closed_phi_def (tree var)
2088 struct loop *loop;
2089 edge exit;
2090 gimple phi;
2091 gimple_stmt_iterator psi;
2093 if (var == NULL_TREE
2094 || TREE_CODE (var) != SSA_NAME)
2095 return NULL_TREE;
2097 loop = loop_containing_stmt (SSA_NAME_DEF_STMT (var));
2098 exit = single_exit (loop);
2099 if (!exit)
2100 return NULL_TREE;
2102 for (psi = gsi_start_phis (exit->dest); !gsi_end_p (psi); gsi_next (&psi))
2104 phi = gsi_stmt (psi);
2105 if (PHI_ARG_DEF_FROM_EDGE (phi, exit) == var)
2106 return PHI_RESULT (phi);
2109 return NULL_TREE;
2112 static tree instantiate_scev_r (basic_block, struct loop *, tree, bool,
2113 htab_t, int);
2115 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2116 and EVOLUTION_LOOP, that were left under a symbolic form.
2118 CHREC is an SSA_NAME to be instantiated.
2120 CACHE is the cache of already instantiated values.
2122 FOLD_CONVERSIONS should be set to true when the conversions that
2123 may wrap in signed/pointer type are folded, as long as the value of
2124 the chrec is preserved.
2126 SIZE_EXPR is used for computing the size of the expression to be
2127 instantiated, and to stop if it exceeds some limit. */
2129 static tree
2130 instantiate_scev_name (basic_block instantiate_below,
2131 struct loop *evolution_loop, tree chrec,
2132 bool fold_conversions, htab_t cache, int size_expr)
2134 tree res;
2135 struct loop *def_loop;
2136 basic_block def_bb = gimple_bb (SSA_NAME_DEF_STMT (chrec));
2138 /* A parameter (or loop invariant and we do not want to include
2139 evolutions in outer loops), nothing to do. */
2140 if (!def_bb
2141 || loop_depth (def_bb->loop_father) == 0
2142 || dominated_by_p (CDI_DOMINATORS, instantiate_below, def_bb))
2143 return chrec;
2145 /* We cache the value of instantiated variable to avoid exponential
2146 time complexity due to reevaluations. We also store the convenient
2147 value in the cache in order to prevent infinite recursion -- we do
2148 not want to instantiate the SSA_NAME if it is in a mixer
2149 structure. This is used for avoiding the instantiation of
2150 recursively defined functions, such as:
2152 | a_2 -> {0, +, 1, +, a_2}_1 */
2154 res = get_instantiated_value (cache, instantiate_below, chrec);
2155 if (res)
2156 return res;
2158 res = chrec_dont_know;
2159 set_instantiated_value (cache, instantiate_below, chrec, res);
2161 def_loop = find_common_loop (evolution_loop, def_bb->loop_father);
2163 /* If the analysis yields a parametric chrec, instantiate the
2164 result again. */
2165 res = analyze_scalar_evolution (def_loop, chrec);
2167 /* Don't instantiate default definitions. */
2168 if (TREE_CODE (res) == SSA_NAME
2169 && SSA_NAME_IS_DEFAULT_DEF (res))
2172 /* Don't instantiate loop-closed-ssa phi nodes. */
2173 else if (TREE_CODE (res) == SSA_NAME
2174 && loop_depth (loop_containing_stmt (SSA_NAME_DEF_STMT (res)))
2175 > loop_depth (def_loop))
2177 if (res == chrec)
2178 res = loop_closed_phi_def (chrec);
2179 else
2180 res = chrec;
2182 /* When there is no loop_closed_phi_def, it means that the
2183 variable is not used after the loop: try to still compute the
2184 value of the variable when exiting the loop. */
2185 if (res == NULL_TREE)
2187 loop_p loop = loop_containing_stmt (SSA_NAME_DEF_STMT (chrec));
2188 res = analyze_scalar_evolution (loop, chrec);
2189 res = compute_overall_effect_of_inner_loop (loop, res);
2190 res = instantiate_scev_r (instantiate_below, evolution_loop, res,
2191 fold_conversions, cache, size_expr);
2193 else if (!dominated_by_p (CDI_DOMINATORS, instantiate_below,
2194 gimple_bb (SSA_NAME_DEF_STMT (res))))
2195 res = chrec_dont_know;
2198 else if (res != chrec_dont_know)
2199 res = instantiate_scev_r (instantiate_below, evolution_loop, res,
2200 fold_conversions, cache, size_expr);
2202 /* Store the correct value to the cache. */
2203 set_instantiated_value (cache, instantiate_below, chrec, res);
2204 return res;
2207 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2208 and EVOLUTION_LOOP, that were left under a symbolic form.
2210 CHREC is a polynomial chain of recurrence to be instantiated.
2212 CACHE is the cache of already instantiated values.
2214 FOLD_CONVERSIONS should be set to true when the conversions that
2215 may wrap in signed/pointer type are folded, as long as the value of
2216 the chrec is preserved.
2218 SIZE_EXPR is used for computing the size of the expression to be
2219 instantiated, and to stop if it exceeds some limit. */
2221 static tree
2222 instantiate_scev_poly (basic_block instantiate_below,
2223 struct loop *evolution_loop, tree chrec,
2224 bool fold_conversions, htab_t cache, int size_expr)
2226 tree op1;
2227 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2228 CHREC_LEFT (chrec), fold_conversions, cache,
2229 size_expr);
2230 if (op0 == chrec_dont_know)
2231 return chrec_dont_know;
2233 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2234 CHREC_RIGHT (chrec), fold_conversions, cache,
2235 size_expr);
2236 if (op1 == chrec_dont_know)
2237 return chrec_dont_know;
2239 if (CHREC_LEFT (chrec) != op0
2240 || CHREC_RIGHT (chrec) != op1)
2242 unsigned var = CHREC_VARIABLE (chrec);
2244 /* When the instantiated stride or base has an evolution in an
2245 innermost loop, return chrec_dont_know, as this is not a
2246 valid SCEV representation. In the reduced testcase for
2247 PR40281 we would have {0, +, {1, +, 1}_2}_1 that has no
2248 meaning. */
2249 if ((tree_is_chrec (op0) && CHREC_VARIABLE (op0) > var)
2250 || (tree_is_chrec (op1) && CHREC_VARIABLE (op1) > var))
2251 return chrec_dont_know;
2253 op1 = chrec_convert_rhs (chrec_type (op0), op1, NULL);
2254 chrec = build_polynomial_chrec (var, op0, op1);
2257 return chrec;
2260 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2261 and EVOLUTION_LOOP, that were left under a symbolic form.
2263 "C0 CODE C1" is a binary expression of type TYPE to be instantiated.
2265 CACHE is the cache of already instantiated values.
2267 FOLD_CONVERSIONS should be set to true when the conversions that
2268 may wrap in signed/pointer type are folded, as long as the value of
2269 the chrec is preserved.
2271 SIZE_EXPR is used for computing the size of the expression to be
2272 instantiated, and to stop if it exceeds some limit. */
2274 static tree
2275 instantiate_scev_binary (basic_block instantiate_below,
2276 struct loop *evolution_loop, tree chrec, enum tree_code code,
2277 tree type, tree c0, tree c1,
2278 bool fold_conversions, htab_t cache, int size_expr)
2280 tree op1;
2281 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2282 c0, fold_conversions, cache,
2283 size_expr);
2284 if (op0 == chrec_dont_know)
2285 return chrec_dont_know;
2287 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2288 c1, fold_conversions, cache,
2289 size_expr);
2290 if (op1 == chrec_dont_know)
2291 return chrec_dont_know;
2293 if (c0 != op0
2294 || c1 != op1)
2296 op0 = chrec_convert (type, op0, NULL);
2297 op1 = chrec_convert_rhs (type, op1, NULL);
2299 switch (code)
2301 case POINTER_PLUS_EXPR:
2302 case PLUS_EXPR:
2303 return chrec_fold_plus (type, op0, op1);
2305 case MINUS_EXPR:
2306 return chrec_fold_minus (type, op0, op1);
2308 case MULT_EXPR:
2309 return chrec_fold_multiply (type, op0, op1);
2311 default:
2312 gcc_unreachable ();
2316 return chrec ? chrec : fold_build2 (code, type, c0, c1);
2319 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2320 and EVOLUTION_LOOP, that were left under a symbolic form.
2322 "CHREC" is an array reference to be instantiated.
2324 CACHE is the cache of already instantiated values.
2326 FOLD_CONVERSIONS should be set to true when the conversions that
2327 may wrap in signed/pointer type are folded, as long as the value of
2328 the chrec is preserved.
2330 SIZE_EXPR is used for computing the size of the expression to be
2331 instantiated, and to stop if it exceeds some limit. */
2333 static tree
2334 instantiate_array_ref (basic_block instantiate_below,
2335 struct loop *evolution_loop, tree chrec,
2336 bool fold_conversions, htab_t cache, int size_expr)
2338 tree res;
2339 tree index = TREE_OPERAND (chrec, 1);
2340 tree op1 = instantiate_scev_r (instantiate_below, evolution_loop, index,
2341 fold_conversions, cache, size_expr);
2343 if (op1 == chrec_dont_know)
2344 return chrec_dont_know;
2346 if (chrec && op1 == index)
2347 return chrec;
2349 res = unshare_expr (chrec);
2350 TREE_OPERAND (res, 1) = op1;
2351 return res;
2354 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2355 and EVOLUTION_LOOP, that were left under a symbolic form.
2357 "CHREC" that stands for a convert expression "(TYPE) OP" is to be
2358 instantiated.
2360 CACHE is the cache of already instantiated values.
2362 FOLD_CONVERSIONS should be set to true when the conversions that
2363 may wrap in signed/pointer type are folded, as long as the value of
2364 the chrec is preserved.
2366 SIZE_EXPR is used for computing the size of the expression to be
2367 instantiated, and to stop if it exceeds some limit. */
2369 static tree
2370 instantiate_scev_convert (basic_block instantiate_below,
2371 struct loop *evolution_loop, tree chrec,
2372 tree type, tree op,
2373 bool fold_conversions, htab_t cache, int size_expr)
2375 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop, op,
2376 fold_conversions, cache, size_expr);
2378 if (op0 == chrec_dont_know)
2379 return chrec_dont_know;
2381 if (fold_conversions)
2383 tree tmp = chrec_convert_aggressive (type, op0);
2384 if (tmp)
2385 return tmp;
2388 if (chrec && op0 == op)
2389 return chrec;
2391 /* If we used chrec_convert_aggressive, we can no longer assume that
2392 signed chrecs do not overflow, as chrec_convert does, so avoid
2393 calling it in that case. */
2394 if (fold_conversions)
2395 return fold_convert (type, op0);
2397 return chrec_convert (type, op0, NULL);
2400 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2401 and EVOLUTION_LOOP, that were left under a symbolic form.
2403 CHREC is a BIT_NOT_EXPR or a NEGATE_EXPR expression to be instantiated.
2404 Handle ~X as -1 - X.
2405 Handle -X as -1 * X.
2407 CACHE is the cache of already instantiated values.
2409 FOLD_CONVERSIONS should be set to true when the conversions that
2410 may wrap in signed/pointer type are folded, as long as the value of
2411 the chrec is preserved.
2413 SIZE_EXPR is used for computing the size of the expression to be
2414 instantiated, and to stop if it exceeds some limit. */
2416 static tree
2417 instantiate_scev_not (basic_block instantiate_below,
2418 struct loop *evolution_loop, tree chrec,
2419 enum tree_code code, tree type, tree op,
2420 bool fold_conversions, htab_t cache, int size_expr)
2422 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop, op,
2423 fold_conversions, cache, size_expr);
2425 if (op0 == chrec_dont_know)
2426 return chrec_dont_know;
2428 if (op != op0)
2430 op0 = chrec_convert (type, op0, NULL);
2432 switch (code)
2434 case BIT_NOT_EXPR:
2435 return chrec_fold_minus
2436 (type, fold_convert (type, integer_minus_one_node), op0);
2438 case NEGATE_EXPR:
2439 return chrec_fold_multiply
2440 (type, fold_convert (type, integer_minus_one_node), op0);
2442 default:
2443 gcc_unreachable ();
2447 return chrec ? chrec : fold_build1 (code, type, op0);
2450 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2451 and EVOLUTION_LOOP, that were left under a symbolic form.
2453 CHREC is an expression with 3 operands to be instantiated.
2455 CACHE is the cache of already instantiated values.
2457 FOLD_CONVERSIONS should be set to true when the conversions that
2458 may wrap in signed/pointer type are folded, as long as the value of
2459 the chrec is preserved.
2461 SIZE_EXPR is used for computing the size of the expression to be
2462 instantiated, and to stop if it exceeds some limit. */
2464 static tree
2465 instantiate_scev_3 (basic_block instantiate_below,
2466 struct loop *evolution_loop, tree chrec,
2467 bool fold_conversions, htab_t cache, int size_expr)
2469 tree op1, op2;
2470 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2471 TREE_OPERAND (chrec, 0),
2472 fold_conversions, cache, size_expr);
2473 if (op0 == chrec_dont_know)
2474 return chrec_dont_know;
2476 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2477 TREE_OPERAND (chrec, 1),
2478 fold_conversions, cache, size_expr);
2479 if (op1 == chrec_dont_know)
2480 return chrec_dont_know;
2482 op2 = instantiate_scev_r (instantiate_below, evolution_loop,
2483 TREE_OPERAND (chrec, 2),
2484 fold_conversions, cache, size_expr);
2485 if (op2 == chrec_dont_know)
2486 return chrec_dont_know;
2488 if (op0 == TREE_OPERAND (chrec, 0)
2489 && op1 == TREE_OPERAND (chrec, 1)
2490 && op2 == TREE_OPERAND (chrec, 2))
2491 return chrec;
2493 return fold_build3 (TREE_CODE (chrec),
2494 TREE_TYPE (chrec), op0, op1, op2);
2497 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2498 and EVOLUTION_LOOP, that were left under a symbolic form.
2500 CHREC is an expression with 2 operands to be instantiated.
2502 CACHE is the cache of already instantiated values.
2504 FOLD_CONVERSIONS should be set to true when the conversions that
2505 may wrap in signed/pointer type are folded, as long as the value of
2506 the chrec is preserved.
2508 SIZE_EXPR is used for computing the size of the expression to be
2509 instantiated, and to stop if it exceeds some limit. */
2511 static tree
2512 instantiate_scev_2 (basic_block instantiate_below,
2513 struct loop *evolution_loop, tree chrec,
2514 bool fold_conversions, htab_t cache, int size_expr)
2516 tree op1;
2517 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2518 TREE_OPERAND (chrec, 0),
2519 fold_conversions, cache, size_expr);
2520 if (op0 == chrec_dont_know)
2521 return chrec_dont_know;
2523 op1 = instantiate_scev_r (instantiate_below, evolution_loop,
2524 TREE_OPERAND (chrec, 1),
2525 fold_conversions, cache, size_expr);
2526 if (op1 == chrec_dont_know)
2527 return chrec_dont_know;
2529 if (op0 == TREE_OPERAND (chrec, 0)
2530 && op1 == TREE_OPERAND (chrec, 1))
2531 return chrec;
2533 return fold_build2 (TREE_CODE (chrec), TREE_TYPE (chrec), op0, op1);
2536 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2537 and EVOLUTION_LOOP, that were left under a symbolic form.
2539 CHREC is an expression with 2 operands to be instantiated.
2541 CACHE is the cache of already instantiated values.
2543 FOLD_CONVERSIONS should be set to true when the conversions that
2544 may wrap in signed/pointer type are folded, as long as the value of
2545 the chrec is preserved.
2547 SIZE_EXPR is used for computing the size of the expression to be
2548 instantiated, and to stop if it exceeds some limit. */
2550 static tree
2551 instantiate_scev_1 (basic_block instantiate_below,
2552 struct loop *evolution_loop, tree chrec,
2553 bool fold_conversions, htab_t cache, int size_expr)
2555 tree op0 = instantiate_scev_r (instantiate_below, evolution_loop,
2556 TREE_OPERAND (chrec, 0),
2557 fold_conversions, cache, size_expr);
2559 if (op0 == chrec_dont_know)
2560 return chrec_dont_know;
2562 if (op0 == TREE_OPERAND (chrec, 0))
2563 return chrec;
2565 return fold_build1 (TREE_CODE (chrec), TREE_TYPE (chrec), op0);
2568 /* Analyze all the parameters of the chrec, between INSTANTIATE_BELOW
2569 and EVOLUTION_LOOP, that were left under a symbolic form.
2571 CHREC is the scalar evolution to instantiate.
2573 CACHE is the cache of already instantiated values.
2575 FOLD_CONVERSIONS should be set to true when the conversions that
2576 may wrap in signed/pointer type are folded, as long as the value of
2577 the chrec is preserved.
2579 SIZE_EXPR is used for computing the size of the expression to be
2580 instantiated, and to stop if it exceeds some limit. */
2582 static tree
2583 instantiate_scev_r (basic_block instantiate_below,
2584 struct loop *evolution_loop, tree chrec,
2585 bool fold_conversions, htab_t cache, int size_expr)
2587 /* Give up if the expression is larger than the MAX that we allow. */
2588 if (size_expr++ > PARAM_VALUE (PARAM_SCEV_MAX_EXPR_SIZE))
2589 return chrec_dont_know;
2591 if (automatically_generated_chrec_p (chrec)
2592 || is_gimple_min_invariant (chrec))
2593 return chrec;
2595 switch (TREE_CODE (chrec))
2597 case SSA_NAME:
2598 return instantiate_scev_name (instantiate_below, evolution_loop, chrec,
2599 fold_conversions, cache, size_expr);
2601 case POLYNOMIAL_CHREC:
2602 return instantiate_scev_poly (instantiate_below, evolution_loop, chrec,
2603 fold_conversions, cache, size_expr);
2605 case POINTER_PLUS_EXPR:
2606 case PLUS_EXPR:
2607 case MINUS_EXPR:
2608 case MULT_EXPR:
2609 return instantiate_scev_binary (instantiate_below, evolution_loop, chrec,
2610 TREE_CODE (chrec), chrec_type (chrec),
2611 TREE_OPERAND (chrec, 0),
2612 TREE_OPERAND (chrec, 1),
2613 fold_conversions, cache, size_expr);
2615 CASE_CONVERT:
2616 return instantiate_scev_convert (instantiate_below, evolution_loop, chrec,
2617 TREE_TYPE (chrec), TREE_OPERAND (chrec, 0),
2618 fold_conversions, cache, size_expr);
2620 case NEGATE_EXPR:
2621 case BIT_NOT_EXPR:
2622 return instantiate_scev_not (instantiate_below, evolution_loop, chrec,
2623 TREE_CODE (chrec), TREE_TYPE (chrec),
2624 TREE_OPERAND (chrec, 0),
2625 fold_conversions, cache, size_expr);
2627 case SCEV_NOT_KNOWN:
2628 return chrec_dont_know;
2630 case SCEV_KNOWN:
2631 return chrec_known;
2633 case ARRAY_REF:
2634 return instantiate_array_ref (instantiate_below, evolution_loop, chrec,
2635 fold_conversions, cache, size_expr);
2637 default:
2638 break;
2641 if (VL_EXP_CLASS_P (chrec))
2642 return chrec_dont_know;
2644 switch (TREE_CODE_LENGTH (TREE_CODE (chrec)))
2646 case 3:
2647 return instantiate_scev_3 (instantiate_below, evolution_loop, chrec,
2648 fold_conversions, cache, size_expr);
2650 case 2:
2651 return instantiate_scev_2 (instantiate_below, evolution_loop, chrec,
2652 fold_conversions, cache, size_expr);
2654 case 1:
2655 return instantiate_scev_1 (instantiate_below, evolution_loop, chrec,
2656 fold_conversions, cache, size_expr);
2658 case 0:
2659 return chrec;
2661 default:
2662 break;
2665 /* Too complicated to handle. */
2666 return chrec_dont_know;
2669 /* Analyze all the parameters of the chrec that were left under a
2670 symbolic form. INSTANTIATE_BELOW is the basic block that stops the
2671 recursive instantiation of parameters: a parameter is a variable
2672 that is defined in a basic block that dominates INSTANTIATE_BELOW or
2673 a function parameter. */
2675 tree
2676 instantiate_scev (basic_block instantiate_below, struct loop *evolution_loop,
2677 tree chrec)
2679 tree res;
2680 htab_t cache = htab_create (10, hash_scev_info, eq_scev_info, del_scev_info);
2682 if (dump_file && (dump_flags & TDF_DETAILS))
2684 fprintf (dump_file, "(instantiate_scev \n");
2685 fprintf (dump_file, " (instantiate_below = %d)\n", instantiate_below->index);
2686 fprintf (dump_file, " (evolution_loop = %d)\n", evolution_loop->num);
2687 fprintf (dump_file, " (chrec = ");
2688 print_generic_expr (dump_file, chrec, 0);
2689 fprintf (dump_file, ")\n");
2692 res = instantiate_scev_r (instantiate_below, evolution_loop, chrec, false,
2693 cache, 0);
2695 if (dump_file && (dump_flags & TDF_DETAILS))
2697 fprintf (dump_file, " (res = ");
2698 print_generic_expr (dump_file, res, 0);
2699 fprintf (dump_file, "))\n");
2702 htab_delete (cache);
2704 return res;
2707 /* Similar to instantiate_parameters, but does not introduce the
2708 evolutions in outer loops for LOOP invariants in CHREC, and does not
2709 care about causing overflows, as long as they do not affect value
2710 of an expression. */
2712 tree
2713 resolve_mixers (struct loop *loop, tree chrec)
2715 htab_t cache = htab_create (10, hash_scev_info, eq_scev_info, del_scev_info);
2716 tree ret = instantiate_scev_r (block_before_loop (loop), loop, chrec, true,
2717 cache, 0);
2718 htab_delete (cache);
2719 return ret;
2722 /* Entry point for the analysis of the number of iterations pass.
2723 This function tries to safely approximate the number of iterations
2724 the loop will run. When this property is not decidable at compile
2725 time, the result is chrec_dont_know. Otherwise the result is a
2726 scalar or a symbolic parameter. When the number of iterations may
2727 be equal to zero and the property cannot be determined at compile
2728 time, the result is a COND_EXPR that represents in a symbolic form
2729 the conditions under which the number of iterations is not zero.
2731 Example of analysis: suppose that the loop has an exit condition:
2733 "if (b > 49) goto end_loop;"
2735 and that in a previous analysis we have determined that the
2736 variable 'b' has an evolution function:
2738 "EF = {23, +, 5}_2".
2740 When we evaluate the function at the point 5, i.e. the value of the
2741 variable 'b' after 5 iterations in the loop, we have EF (5) = 48,
2742 and EF (6) = 53. In this case the value of 'b' on exit is '53' and
2743 the loop body has been executed 6 times. */
2745 tree
2746 number_of_latch_executions (struct loop *loop)
2748 edge exit;
2749 struct tree_niter_desc niter_desc;
2750 tree may_be_zero;
2751 tree res;
2753 /* Determine whether the number of iterations in loop has already
2754 been computed. */
2755 res = loop->nb_iterations;
2756 if (res)
2757 return res;
2759 may_be_zero = NULL_TREE;
2761 if (dump_file && (dump_flags & TDF_DETAILS))
2762 fprintf (dump_file, "(number_of_iterations_in_loop = \n");
2764 res = chrec_dont_know;
2765 exit = single_exit (loop);
2767 if (exit && number_of_iterations_exit (loop, exit, &niter_desc, false))
2769 may_be_zero = niter_desc.may_be_zero;
2770 res = niter_desc.niter;
2773 if (res == chrec_dont_know
2774 || !may_be_zero
2775 || integer_zerop (may_be_zero))
2777 else if (integer_nonzerop (may_be_zero))
2778 res = build_int_cst (TREE_TYPE (res), 0);
2780 else if (COMPARISON_CLASS_P (may_be_zero))
2781 res = fold_build3 (COND_EXPR, TREE_TYPE (res), may_be_zero,
2782 build_int_cst (TREE_TYPE (res), 0), res);
2783 else
2784 res = chrec_dont_know;
2786 if (dump_file && (dump_flags & TDF_DETAILS))
2788 fprintf (dump_file, " (set_nb_iterations_in_loop = ");
2789 print_generic_expr (dump_file, res, 0);
2790 fprintf (dump_file, "))\n");
2793 loop->nb_iterations = res;
2794 return res;
2797 /* Returns the number of executions of the exit condition of LOOP,
2798 i.e., the number by one higher than number_of_latch_executions.
2799 Note that unlike number_of_latch_executions, this number does
2800 not necessarily fit in the unsigned variant of the type of
2801 the control variable -- if the number of iterations is a constant,
2802 we return chrec_dont_know if adding one to number_of_latch_executions
2803 overflows; however, in case the number of iterations is symbolic
2804 expression, the caller is responsible for dealing with this
2805 the possible overflow. */
2807 tree
2808 number_of_exit_cond_executions (struct loop *loop)
2810 tree ret = number_of_latch_executions (loop);
2811 tree type = chrec_type (ret);
2813 if (chrec_contains_undetermined (ret))
2814 return ret;
2816 ret = chrec_fold_plus (type, ret, build_int_cst (type, 1));
2817 if (TREE_CODE (ret) == INTEGER_CST
2818 && TREE_OVERFLOW (ret))
2819 return chrec_dont_know;
2821 return ret;
2824 /* One of the drivers for testing the scalar evolutions analysis.
2825 This function computes the number of iterations for all the loops
2826 from the EXIT_CONDITIONS array. */
2828 static void
2829 number_of_iterations_for_all_loops (VEC(gimple,heap) **exit_conditions)
2831 unsigned int i;
2832 unsigned nb_chrec_dont_know_loops = 0;
2833 unsigned nb_static_loops = 0;
2834 gimple cond;
2836 for (i = 0; VEC_iterate (gimple, *exit_conditions, i, cond); i++)
2838 tree res = number_of_latch_executions (loop_containing_stmt (cond));
2839 if (chrec_contains_undetermined (res))
2840 nb_chrec_dont_know_loops++;
2841 else
2842 nb_static_loops++;
2845 if (dump_file)
2847 fprintf (dump_file, "\n(\n");
2848 fprintf (dump_file, "-----------------------------------------\n");
2849 fprintf (dump_file, "%d\tnb_chrec_dont_know_loops\n", nb_chrec_dont_know_loops);
2850 fprintf (dump_file, "%d\tnb_static_loops\n", nb_static_loops);
2851 fprintf (dump_file, "%d\tnb_total_loops\n", number_of_loops ());
2852 fprintf (dump_file, "-----------------------------------------\n");
2853 fprintf (dump_file, ")\n\n");
2855 print_loops (dump_file, 3);
2861 /* Counters for the stats. */
2863 struct chrec_stats
2865 unsigned nb_chrecs;
2866 unsigned nb_affine;
2867 unsigned nb_affine_multivar;
2868 unsigned nb_higher_poly;
2869 unsigned nb_chrec_dont_know;
2870 unsigned nb_undetermined;
2873 /* Reset the counters. */
2875 static inline void
2876 reset_chrecs_counters (struct chrec_stats *stats)
2878 stats->nb_chrecs = 0;
2879 stats->nb_affine = 0;
2880 stats->nb_affine_multivar = 0;
2881 stats->nb_higher_poly = 0;
2882 stats->nb_chrec_dont_know = 0;
2883 stats->nb_undetermined = 0;
2886 /* Dump the contents of a CHREC_STATS structure. */
2888 static void
2889 dump_chrecs_stats (FILE *file, struct chrec_stats *stats)
2891 fprintf (file, "\n(\n");
2892 fprintf (file, "-----------------------------------------\n");
2893 fprintf (file, "%d\taffine univariate chrecs\n", stats->nb_affine);
2894 fprintf (file, "%d\taffine multivariate chrecs\n", stats->nb_affine_multivar);
2895 fprintf (file, "%d\tdegree greater than 2 polynomials\n",
2896 stats->nb_higher_poly);
2897 fprintf (file, "%d\tchrec_dont_know chrecs\n", stats->nb_chrec_dont_know);
2898 fprintf (file, "-----------------------------------------\n");
2899 fprintf (file, "%d\ttotal chrecs\n", stats->nb_chrecs);
2900 fprintf (file, "%d\twith undetermined coefficients\n",
2901 stats->nb_undetermined);
2902 fprintf (file, "-----------------------------------------\n");
2903 fprintf (file, "%d\tchrecs in the scev database\n",
2904 (int) htab_elements (scalar_evolution_info));
2905 fprintf (file, "%d\tsets in the scev database\n", nb_set_scev);
2906 fprintf (file, "%d\tgets in the scev database\n", nb_get_scev);
2907 fprintf (file, "-----------------------------------------\n");
2908 fprintf (file, ")\n\n");
2911 /* Gather statistics about CHREC. */
2913 static void
2914 gather_chrec_stats (tree chrec, struct chrec_stats *stats)
2916 if (dump_file && (dump_flags & TDF_STATS))
2918 fprintf (dump_file, "(classify_chrec ");
2919 print_generic_expr (dump_file, chrec, 0);
2920 fprintf (dump_file, "\n");
2923 stats->nb_chrecs++;
2925 if (chrec == NULL_TREE)
2927 stats->nb_undetermined++;
2928 return;
2931 switch (TREE_CODE (chrec))
2933 case POLYNOMIAL_CHREC:
2934 if (evolution_function_is_affine_p (chrec))
2936 if (dump_file && (dump_flags & TDF_STATS))
2937 fprintf (dump_file, " affine_univariate\n");
2938 stats->nb_affine++;
2940 else if (evolution_function_is_affine_multivariate_p (chrec, 0))
2942 if (dump_file && (dump_flags & TDF_STATS))
2943 fprintf (dump_file, " affine_multivariate\n");
2944 stats->nb_affine_multivar++;
2946 else
2948 if (dump_file && (dump_flags & TDF_STATS))
2949 fprintf (dump_file, " higher_degree_polynomial\n");
2950 stats->nb_higher_poly++;
2953 break;
2955 default:
2956 break;
2959 if (chrec_contains_undetermined (chrec))
2961 if (dump_file && (dump_flags & TDF_STATS))
2962 fprintf (dump_file, " undetermined\n");
2963 stats->nb_undetermined++;
2966 if (dump_file && (dump_flags & TDF_STATS))
2967 fprintf (dump_file, ")\n");
2970 /* One of the drivers for testing the scalar evolutions analysis.
2971 This function analyzes the scalar evolution of all the scalars
2972 defined as loop phi nodes in one of the loops from the
2973 EXIT_CONDITIONS array.
2975 TODO Optimization: A loop is in canonical form if it contains only
2976 a single scalar loop phi node. All the other scalars that have an
2977 evolution in the loop are rewritten in function of this single
2978 index. This allows the parallelization of the loop. */
2980 static void
2981 analyze_scalar_evolution_for_all_loop_phi_nodes (VEC(gimple,heap) **exit_conditions)
2983 unsigned int i;
2984 struct chrec_stats stats;
2985 gimple cond, phi;
2986 gimple_stmt_iterator psi;
2988 reset_chrecs_counters (&stats);
2990 for (i = 0; VEC_iterate (gimple, *exit_conditions, i, cond); i++)
2992 struct loop *loop;
2993 basic_block bb;
2994 tree chrec;
2996 loop = loop_containing_stmt (cond);
2997 bb = loop->header;
2999 for (psi = gsi_start_phis (bb); !gsi_end_p (psi); gsi_next (&psi))
3001 phi = gsi_stmt (psi);
3002 if (is_gimple_reg (PHI_RESULT (phi)))
3004 chrec = instantiate_parameters
3005 (loop,
3006 analyze_scalar_evolution (loop, PHI_RESULT (phi)));
3008 if (dump_file && (dump_flags & TDF_STATS))
3009 gather_chrec_stats (chrec, &stats);
3014 if (dump_file && (dump_flags & TDF_STATS))
3015 dump_chrecs_stats (dump_file, &stats);
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;
3075 scalar_evolution_info = htab_create_alloc (100,
3076 hash_scev_info,
3077 eq_scev_info,
3078 del_scev_info,
3079 ggc_calloc,
3080 ggc_free);
3082 initialize_scalar_evolutions_analyzer ();
3084 FOR_EACH_LOOP (li, loop, 0)
3086 loop->nb_iterations = NULL_TREE;
3090 /* Cleans up the information cached by the scalar evolutions analysis
3091 in the hash table. */
3093 void
3094 scev_reset_htab (void)
3096 if (!scalar_evolution_info)
3097 return;
3099 htab_empty (scalar_evolution_info);
3102 /* Cleans up the information cached by the scalar evolutions analysis
3103 in the hash table and in the loop->nb_iterations. */
3105 void
3106 scev_reset (void)
3108 loop_iterator li;
3109 struct loop *loop;
3111 scev_reset_htab ();
3113 if (!current_loops)
3114 return;
3116 FOR_EACH_LOOP (li, loop, 0)
3118 loop->nb_iterations = NULL_TREE;
3122 /* Checks whether use of OP in USE_LOOP behaves as a simple affine iv with
3123 respect to WRTO_LOOP and returns its base and step in IV if possible
3124 (see analyze_scalar_evolution_in_loop for more details on USE_LOOP
3125 and WRTO_LOOP). If ALLOW_NONCONSTANT_STEP is true, we want step to be
3126 invariant in LOOP. Otherwise we require it to be an integer constant.
3128 IV->no_overflow is set to true if we are sure the iv cannot overflow (e.g.
3129 because it is computed in signed arithmetics). Consequently, adding an
3130 induction variable
3132 for (i = IV->base; ; i += IV->step)
3134 is only safe if IV->no_overflow is false, or TYPE_OVERFLOW_UNDEFINED is
3135 false for the type of the induction variable, or you can prove that i does
3136 not wrap by some other argument. Otherwise, this might introduce undefined
3137 behavior, and
3139 for (i = iv->base; ; i = (type) ((unsigned type) i + (unsigned type) iv->step))
3141 must be used instead. */
3143 bool
3144 simple_iv (struct loop *wrto_loop, struct loop *use_loop, tree op,
3145 affine_iv *iv, bool allow_nonconstant_step)
3147 tree type, ev;
3148 bool folded_casts;
3150 iv->base = NULL_TREE;
3151 iv->step = NULL_TREE;
3152 iv->no_overflow = false;
3154 type = TREE_TYPE (op);
3155 if (TREE_CODE (type) != INTEGER_TYPE
3156 && TREE_CODE (type) != POINTER_TYPE)
3157 return false;
3159 ev = analyze_scalar_evolution_in_loop (wrto_loop, use_loop, op,
3160 &folded_casts);
3161 if (chrec_contains_undetermined (ev)
3162 || chrec_contains_symbols_defined_in_loop (ev, wrto_loop->num))
3163 return false;
3165 if (tree_does_not_contain_chrecs (ev))
3167 iv->base = ev;
3168 iv->step = build_int_cst (TREE_TYPE (ev), 0);
3169 iv->no_overflow = true;
3170 return true;
3173 if (TREE_CODE (ev) != POLYNOMIAL_CHREC
3174 || CHREC_VARIABLE (ev) != (unsigned) wrto_loop->num)
3175 return false;
3177 iv->step = CHREC_RIGHT (ev);
3178 if ((!allow_nonconstant_step && TREE_CODE (iv->step) != INTEGER_CST)
3179 || tree_contains_chrecs (iv->step, NULL))
3180 return false;
3182 iv->base = CHREC_LEFT (ev);
3183 if (tree_contains_chrecs (iv->base, NULL))
3184 return false;
3186 iv->no_overflow = !folded_casts && TYPE_OVERFLOW_UNDEFINED (type);
3188 return true;
3191 /* Runs the analysis of scalar evolutions. */
3193 void
3194 scev_analysis (void)
3196 VEC(gimple,heap) *exit_conditions;
3198 exit_conditions = VEC_alloc (gimple, heap, 37);
3199 select_loops_exit_conditions (&exit_conditions);
3201 if (dump_file && (dump_flags & TDF_STATS))
3202 analyze_scalar_evolution_for_all_loop_phi_nodes (&exit_conditions);
3204 number_of_iterations_for_all_loops (&exit_conditions);
3205 VEC_free (gimple, heap, exit_conditions);
3208 /* Finalize the scalar evolution analysis. */
3210 void
3211 scev_finalize (void)
3213 if (!scalar_evolution_info)
3214 return;
3215 htab_delete (scalar_evolution_info);
3216 scalar_evolution_info = NULL;
3219 /* Returns true if the expression EXPR is considered to be too expensive
3220 for scev_const_prop. */
3222 bool
3223 expression_expensive_p (tree expr)
3225 enum tree_code code;
3227 if (is_gimple_val (expr))
3228 return false;
3230 code = TREE_CODE (expr);
3231 if (code == TRUNC_DIV_EXPR
3232 || code == CEIL_DIV_EXPR
3233 || code == FLOOR_DIV_EXPR
3234 || code == ROUND_DIV_EXPR
3235 || code == TRUNC_MOD_EXPR
3236 || code == CEIL_MOD_EXPR
3237 || code == FLOOR_MOD_EXPR
3238 || code == ROUND_MOD_EXPR
3239 || code == EXACT_DIV_EXPR)
3241 /* Division by power of two is usually cheap, so we allow it.
3242 Forbid anything else. */
3243 if (!integer_pow2p (TREE_OPERAND (expr, 1)))
3244 return true;
3247 switch (TREE_CODE_CLASS (code))
3249 case tcc_binary:
3250 case tcc_comparison:
3251 if (expression_expensive_p (TREE_OPERAND (expr, 1)))
3252 return true;
3254 /* Fallthru. */
3255 case tcc_unary:
3256 return expression_expensive_p (TREE_OPERAND (expr, 0));
3258 default:
3259 return true;
3263 /* Replace ssa names for that scev can prove they are constant by the
3264 appropriate constants. Also perform final value replacement in loops,
3265 in case the replacement expressions are cheap.
3267 We only consider SSA names defined by phi nodes; rest is left to the
3268 ordinary constant propagation pass. */
3270 unsigned int
3271 scev_const_prop (void)
3273 basic_block bb;
3274 tree name, type, ev;
3275 gimple phi, ass;
3276 struct loop *loop, *ex_loop;
3277 bitmap ssa_names_to_remove = NULL;
3278 unsigned i;
3279 loop_iterator li;
3280 gimple_stmt_iterator psi;
3282 if (number_of_loops () <= 1)
3283 return 0;
3285 FOR_EACH_BB (bb)
3287 loop = bb->loop_father;
3289 for (psi = gsi_start_phis (bb); !gsi_end_p (psi); gsi_next (&psi))
3291 phi = gsi_stmt (psi);
3292 name = PHI_RESULT (phi);
3294 if (!is_gimple_reg (name))
3295 continue;
3297 type = TREE_TYPE (name);
3299 if (!POINTER_TYPE_P (type)
3300 && !INTEGRAL_TYPE_P (type))
3301 continue;
3303 ev = resolve_mixers (loop, analyze_scalar_evolution (loop, name));
3304 if (!is_gimple_min_invariant (ev)
3305 || !may_propagate_copy (name, ev))
3306 continue;
3308 /* Replace the uses of the name. */
3309 if (name != ev)
3310 replace_uses_by (name, ev);
3312 if (!ssa_names_to_remove)
3313 ssa_names_to_remove = BITMAP_ALLOC (NULL);
3314 bitmap_set_bit (ssa_names_to_remove, SSA_NAME_VERSION (name));
3318 /* Remove the ssa names that were replaced by constants. We do not
3319 remove them directly in the previous cycle, since this
3320 invalidates scev cache. */
3321 if (ssa_names_to_remove)
3323 bitmap_iterator bi;
3325 EXECUTE_IF_SET_IN_BITMAP (ssa_names_to_remove, 0, i, bi)
3327 gimple_stmt_iterator psi;
3328 name = ssa_name (i);
3329 phi = SSA_NAME_DEF_STMT (name);
3331 gcc_assert (gimple_code (phi) == GIMPLE_PHI);
3332 psi = gsi_for_stmt (phi);
3333 remove_phi_node (&psi, true);
3336 BITMAP_FREE (ssa_names_to_remove);
3337 scev_reset ();
3340 /* Now the regular final value replacement. */
3341 FOR_EACH_LOOP (li, loop, LI_FROM_INNERMOST)
3343 edge exit;
3344 tree def, rslt, niter;
3345 gimple_stmt_iterator bsi;
3347 /* If we do not know exact number of iterations of the loop, we cannot
3348 replace the final value. */
3349 exit = single_exit (loop);
3350 if (!exit)
3351 continue;
3353 niter = number_of_latch_executions (loop);
3354 if (niter == chrec_dont_know)
3355 continue;
3357 /* Ensure that it is possible to insert new statements somewhere. */
3358 if (!single_pred_p (exit->dest))
3359 split_loop_exit_edge (exit);
3360 bsi = gsi_after_labels (exit->dest);
3362 ex_loop = superloop_at_depth (loop,
3363 loop_depth (exit->dest->loop_father) + 1);
3365 for (psi = gsi_start_phis (exit->dest); !gsi_end_p (psi); )
3367 phi = gsi_stmt (psi);
3368 rslt = PHI_RESULT (phi);
3369 def = PHI_ARG_DEF_FROM_EDGE (phi, exit);
3370 if (!is_gimple_reg (def))
3372 gsi_next (&psi);
3373 continue;
3376 if (!POINTER_TYPE_P (TREE_TYPE (def))
3377 && !INTEGRAL_TYPE_P (TREE_TYPE (def)))
3379 gsi_next (&psi);
3380 continue;
3383 def = analyze_scalar_evolution_in_loop (ex_loop, loop, def, NULL);
3384 def = compute_overall_effect_of_inner_loop (ex_loop, def);
3385 if (!tree_does_not_contain_chrecs (def)
3386 || chrec_contains_symbols_defined_in_loop (def, ex_loop->num)
3387 /* Moving the computation from the loop may prolong life range
3388 of some ssa names, which may cause problems if they appear
3389 on abnormal edges. */
3390 || contains_abnormal_ssa_name_p (def)
3391 /* Do not emit expensive expressions. The rationale is that
3392 when someone writes a code like
3394 while (n > 45) n -= 45;
3396 he probably knows that n is not large, and does not want it
3397 to be turned into n %= 45. */
3398 || expression_expensive_p (def))
3400 gsi_next (&psi);
3401 continue;
3404 /* Eliminate the PHI node and replace it by a computation outside
3405 the loop. */
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);
3415 return 0;
3418 #include "gt-tree-scalar-evolution.h"